From b4fc6d845e9f29ff33e3f5733bdfda690c26655b Mon Sep 17 00:00:00 2001 From: Andrey Litvitski Date: Sat, 15 Aug 2026 03:52:53 +0300 Subject: [PATCH 01/12] lil more --- .../manifest.yaml | 204 +++ .../sol.cpp | 37 + .../sol.cs | 39 + .../sol.dart | 42 + .../sol.go | 25 + .../sol.java | 41 + .../sol.kt | 41 + .../sol.py | 31 + .../sol.py2 | 34 + .../sol.rb | 39 + .../sol.rs | 45 + .../sol.swift | 32 + .../sol.ts | 39 + .../manifest.yaml | 303 ++++ .../sol.cpp | 30 + .../sol.cs | 29 + .../sol.dart | 19 + .../sol.go | 41 + .../sol.java | 29 + .../sol.kt | 17 + .../sol.py | 30 + .../sol.py2 | 14 + .../sol.rb | 37 + .../sol.rs | 20 + .../sol.swift | 16 + .../sol.ts | 30 + .../manifest.yaml | 263 ++++ .../sol.cpp | 6 + .../sol.cs | 5 + .../sol.dart | 5 + .../sol.go | 3 + .../sol.java | 5 + .../sol.kt | 5 + .../sol.py | 3 + .../sol.py2 | 8 + .../sol.rb | 6 + .../sol.rs | 5 + .../sol.swift | 5 + .../sol.ts | 3 + .../manifest.yaml | 363 +++++ .../sol.cpp | 14 + .../sol.cs | 13 + .../sol.dart | 13 + .../sol.go | 11 + .../sol.java | 13 + .../sol.kt | 13 + .../sol.py | 8 + .../sol.py2 | 14 + .../sol.rb | 13 + .../sol.rs | 13 + .../sol.swift | 13 + .../sol.ts | 11 + .../manifest.yaml | 225 +++ .../sol.cpp | 25 + .../sol.cs | 33 + .../sol.dart | 26 + .../sol.go | 23 + .../sol.java | 25 + .../sol.kt | 25 + .../sol.py | 18 + .../sol.py2 | 22 + .../sol.rb | 24 + .../sol.rs | 24 + .../sol.swift | 20 + .../sol.ts | 23 + .../manifest.yaml | 273 ++++ .../sol.cpp | 12 + .../sol.cs | 11 + .../sol.dart | 11 + .../sol.go | 9 + .../sol.java | 11 + .../sol.kt | 11 + .../sol.py | 7 + .../sol.py2 | 11 + .../sol.rb | 11 + .../sol.rs | 11 + .../sol.swift | 11 + .../sol.ts | 9 + .../1528. shuffle-string/manifest.yaml | 557 +++++++ tests/1501-2000/1528. shuffle-string/sol.cpp | 10 + tests/1501-2000/1528. shuffle-string/sol.cs | 9 + tests/1501-2000/1528. shuffle-string/sol.dart | 9 + tests/1501-2000/1528. shuffle-string/sol.go | 7 + tests/1501-2000/1528. shuffle-string/sol.java | 9 + tests/1501-2000/1528. shuffle-string/sol.kt | 9 + tests/1501-2000/1528. shuffle-string/sol.py | 8 + tests/1501-2000/1528. shuffle-string/sol.py2 | 11 + tests/1501-2000/1528. shuffle-string/sol.rb | 10 + tests/1501-2000/1528. shuffle-string/sol.rs | 10 + .../1501-2000/1528. shuffle-string/sol.swift | 10 + tests/1501-2000/1528. shuffle-string/sol.ts | 7 + .../1529. minimum-suffix-flips/manifest.yaml | 221 +++ .../1529. minimum-suffix-flips/sol.cpp | 18 + .../1529. minimum-suffix-flips/sol.cs | 17 + .../1529. minimum-suffix-flips/sol.dart | 17 + .../1529. minimum-suffix-flips/sol.go | 15 + .../1529. minimum-suffix-flips/sol.java | 16 + .../1529. minimum-suffix-flips/sol.kt | 16 + .../1529. minimum-suffix-flips/sol.py | 12 + .../1529. minimum-suffix-flips/sol.py2 | 16 + .../1529. minimum-suffix-flips/sol.rb | 16 + .../1529. minimum-suffix-flips/sol.rs | 18 + .../1529. minimum-suffix-flips/sol.swift | 18 + .../1529. minimum-suffix-flips/sol.ts | 15 + .../manifest.yaml | 234 +++ .../sol.cpp | 57 + .../sol.cs | 59 + .../sol.dart | 53 + .../sol.go | 73 + .../sol.java | 66 + .../sol.kt | 51 + .../sol.py | 47 + .../sol.py2 | 46 + .../sol.rb | 53 + .../sol.rs | 28 + .../sol.swift | 17 + .../sol.ts | 58 + .../1531. string-compression-ii/manifest.yaml | 275 ++++ .../1531. string-compression-ii/sol.cpp | 31 + .../1531. string-compression-ii/sol.cs | 30 + .../1531. string-compression-ii/sol.dart | 28 + .../1531. string-compression-ii/sol.go | 43 + .../1531. string-compression-ii/sol.java | 33 + .../1531. string-compression-ii/sol.kt | 32 + .../1531. string-compression-ii/sol.py | 35 + .../1531. string-compression-ii/sol.py2 | 27 + .../1531. string-compression-ii/sol.rb | 41 + .../1531. string-compression-ii/sol.rs | 31 + .../1531. string-compression-ii/sol.swift | 30 + .../1531. string-compression-ii/sol.ts | 27 + .../1534. count-good-triplets/manifest.yaml | 405 +++++ .../1534. count-good-triplets/sol.cpp | 17 + .../1534. count-good-triplets/sol.cs | 16 + .../1534. count-good-triplets/sol.dart | 14 + .../1534. count-good-triplets/sol.go | 21 + .../1534. count-good-triplets/sol.java | 16 + .../1534. count-good-triplets/sol.kt | 16 + .../1534. count-good-triplets/sol.py | 14 + .../1534. count-good-triplets/sol.py2 | 17 + .../1534. count-good-triplets/sol.rb | 19 + .../1534. count-good-triplets/sol.rs | 16 + .../1534. count-good-triplets/sol.swift | 16 + .../1534. count-good-triplets/sol.ts | 23 + .../manifest.yaml | 307 ++++ .../sol.cpp | 17 + .../sol.cs | 16 + .../sol.dart | 16 + .../sol.go | 16 + .../sol.java | 16 + .../sol.kt | 16 + .../sol.py | 91 ++ .../sol.py2 | 18 + .../sol.rb | 17 + .../sol.rs | 16 + .../sol.swift | 16 + .../sol.ts | 14 + .../manifest.yaml | 387 +++++ .../sol.cpp | 35 + .../sol.cs | 36 + .../sol.dart | 36 + .../sol.go | 32 + .../sol.java | 36 + .../sol.kt | 36 + .../sol.py | 29 + .../sol.py2 | 29 + .../sol.rb | 32 + .../sol.rs | 34 + .../sol.swift | 34 + .../sol.ts | 32 + .../1537. get-the-maximum-score/manifest.yaml | 348 +++++ .../1537. get-the-maximum-score/sol.cpp | 29 + .../1537. get-the-maximum-score/sol.cs | 28 + .../1537. get-the-maximum-score/sol.dart | 28 + .../1537. get-the-maximum-score/sol.go | 37 + .../1537. get-the-maximum-score/sol.java | 28 + .../1537. get-the-maximum-score/sol.kt | 33 + .../1537. get-the-maximum-score/sol.py | 31 + .../1537. get-the-maximum-score/sol.py2 | 27 + .../1537. get-the-maximum-score/sol.rb | 29 + .../1537. get-the-maximum-score/sol.rs | 30 + .../1537. get-the-maximum-score/sol.swift | 28 + .../1537. get-the-maximum-score/sol.ts | 31 + .../manifest.yaml | 315 ++++ .../1539. kth-missing-positive-number/sol.cpp | 16 + .../1539. kth-missing-positive-number/sol.cs | 15 + .../sol.dart | 15 + .../1539. kth-missing-positive-number/sol.go | 13 + .../sol.java | 15 + .../1539. kth-missing-positive-number/sol.kt | 16 + .../1539. kth-missing-positive-number/sol.py | 14 + .../1539. kth-missing-positive-number/sol.py2 | 16 + .../1539. kth-missing-positive-number/sol.rb | 13 + .../1539. kth-missing-positive-number/sol.rs | 16 + .../sol.swift | 15 + .../1539. kth-missing-positive-number/sol.ts | 14 + .../manifest.yaml | 346 +++++ .../sol.cpp | 14 + .../sol.cs | 13 + .../sol.dart | 13 + .../sol.go | 17 + .../sol.java | 13 + .../sol.kt | 13 + .../sol.py | 25 + .../sol.py2 | 19 + .../sol.rb | 11 + .../sol.rs | 15 + .../sol.swift | 15 + .../sol.ts | 11 + .../manifest.yaml | 215 +++ .../sol.cpp | 34 + .../sol.cs | 33 + .../sol.dart | 33 + .../sol.go | 31 + .../sol.java | 33 + .../sol.kt | 33 + .../sol.py | 26 + .../sol.py2 | 30 + .../sol.rb | 33 + .../sol.rs | 34 + .../sol.swift | 34 + .../sol.ts | 31 + .../manifest.yaml | 220 +++ .../sol.cpp | 28 + .../sol.cs | 27 + .../sol.dart | 27 + .../sol.go | 29 + .../sol.java | 27 + .../sol.kt | 21 + .../sol.py | 25 + .../sol.py2 | 24 + .../sol.rb | 25 + .../sol.rs | 26 + .../sol.swift | 28 + .../sol.ts | 25 + .../1544. make-the-string-great/manifest.yaml | 216 +++ .../1544. make-the-string-great/sol.cpp | 14 + .../1544. make-the-string-great/sol.cs | 13 + .../1544. make-the-string-great/sol.dart | 14 + .../1544. make-the-string-great/sol.go | 11 + .../1544. make-the-string-great/sol.java | 13 + .../1544. make-the-string-great/sol.kt | 13 + .../1544. make-the-string-great/sol.py | 11 + .../1544. make-the-string-great/sol.py2 | 13 + .../1544. make-the-string-great/sol.rb | 13 + .../1544. make-the-string-great/sol.rs | 15 + .../1544. make-the-string-great/sol.swift | 13 + .../1544. make-the-string-great/sol.ts | 15 + .../manifest.yaml | 202 +++ .../sol.cpp | 21 + .../sol.cs | 20 + .../sol.dart | 20 + .../sol.go | 21 + .../sol.java | 20 + .../sol.kt | 20 + .../sol.py | 15 + .../sol.py2 | 20 + .../sol.rb | 21 + .../sol.rs | 20 + .../sol.swift | 20 + .../sol.ts | 18 + .../manifest.yaml | 299 ++++ .../sol.cpp | 18 + .../sol.cs | 17 + .../sol.dart | 17 + .../sol.go | 15 + .../sol.java | 18 + .../sol.kt | 17 + .../sol.py | 11 + .../sol.py2 | 16 + .../sol.rb | 16 + .../sol.rs | 18 + .../sol.swift | 17 + .../sol.ts | 15 + .../manifest.yaml | 288 ++++ .../1547. minimum-cost-to-cut-a-stick/sol.cpp | 24 + .../1547. minimum-cost-to-cut-a-stick/sol.cs | 26 + .../sol.dart | 20 + .../1547. minimum-cost-to-cut-a-stick/sol.go | 31 + .../sol.java | 27 + .../1547. minimum-cost-to-cut-a-stick/sol.kt | 21 + .../1547. minimum-cost-to-cut-a-stick/sol.py | 29 + .../1547. minimum-cost-to-cut-a-stick/sol.py2 | 22 + .../1547. minimum-cost-to-cut-a-stick/sol.rb | 23 + .../1547. minimum-cost-to-cut-a-stick/sol.rs | 23 + .../sol.swift | 21 + .../1547. minimum-cost-to-cut-a-stick/sol.ts | 18 + .../manifest.yaml | 276 ++++ .../1550. three-consecutive-odds/sol.cpp | 8 + .../1550. three-consecutive-odds/sol.cs | 6 + .../1550. three-consecutive-odds/sol.dart | 6 + .../1550. three-consecutive-odds/sol.go | 7 + .../1550. three-consecutive-odds/sol.java | 7 + .../1550. three-consecutive-odds/sol.kt | 5 + .../1550. three-consecutive-odds/sol.py | 3 + .../1550. three-consecutive-odds/sol.py2 | 7 + .../1550. three-consecutive-odds/sol.rb | 5 + .../1550. three-consecutive-odds/sol.rs | 5 + .../1550. three-consecutive-odds/sol.swift | 5 + .../1550. three-consecutive-odds/sol.ts | 6 + .../manifest.yaml | 208 +++ .../sol.cpp | 6 + .../sol.cs | 5 + .../sol.dart | 5 + .../sol.go | 3 + .../sol.java | 5 + .../sol.kt | 5 + .../sol.py | 11 + .../sol.py2 | 7 + .../sol.rb | 5 + .../sol.rs | 5 + .../sol.swift | 5 + .../sol.ts | 3 + .../manifest.yaml | 323 ++++ .../sol.cpp | 29 + .../sol.cs | 28 + .../sol.dart | 28 + .../sol.go | 26 + .../sol.java | 28 + .../sol.kt | 28 + .../sol.py | 22 + .../sol.py2 | 27 + .../sol.rb | 29 + .../sol.rs | 29 + .../sol.swift | 28 + .../sol.ts | 26 + .../manifest.yaml | 229 +++ .../sol.cpp | 22 + .../sol.cs | 21 + .../sol.dart | 20 + .../sol.go | 26 + .../sol.java | 21 + .../sol.kt | 20 + .../sol.py | 19 + .../sol.py2 | 24 + .../sol.rb | 20 + .../sol.rs | 20 + .../sol.swift | 20 + .../sol.ts | 18 + .../1556. thousand-separator/manifest.yaml | 215 +++ .../1556. thousand-separator/sol.cpp | 18 + .../1501-2000/1556. thousand-separator/sol.cs | 18 + .../1556. thousand-separator/sol.dart | 16 + .../1501-2000/1556. thousand-separator/sol.go | 20 + .../1556. thousand-separator/sol.java | 16 + .../1501-2000/1556. thousand-separator/sol.kt | 16 + .../1501-2000/1556. thousand-separator/sol.py | 6 + .../1556. thousand-separator/sol.py2 | 17 + .../1501-2000/1556. thousand-separator/sol.rb | 16 + .../1501-2000/1556. thousand-separator/sol.rs | 18 + .../1556. thousand-separator/sol.swift | 16 + .../1501-2000/1556. thousand-separator/sol.ts | 14 + .../manifest.yaml | 611 ++++++++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 15 + .../sol.go | 13 + .../sol.java | 15 + .../sol.kt | 9 + .../sol.py | 6 + .../sol.py2 | 11 + .../sol.rb | 10 + .../sol.rs | 9 + .../sol.swift | 15 + .../sol.ts | 13 + .../manifest.yaml | 313 ++++ .../sol.cpp | 15 + .../sol.cs | 14 + .../sol.dart | 14 + .../sol.go | 15 + .../sol.java | 14 + .../sol.kt | 14 + .../sol.py | 14 + .../sol.py2 | 14 + .../sol.rb | 14 + .../sol.rs | 16 + .../sol.swift | 14 + .../sol.ts | 12 + .../manifest.yaml | 373 +++++ .../1559. detect-cycles-in-2d-grid/sol.cpp | 44 + .../1559. detect-cycles-in-2d-grid/sol.cs | 39 + .../1559. detect-cycles-in-2d-grid/sol.dart | 44 + .../1559. detect-cycles-in-2d-grid/sol.go | 37 + .../1559. detect-cycles-in-2d-grid/sol.java | 42 + .../1559. detect-cycles-in-2d-grid/sol.kt | 45 + .../1559. detect-cycles-in-2d-grid/sol.py | 51 + .../1559. detect-cycles-in-2d-grid/sol.py2 | 40 + .../1559. detect-cycles-in-2d-grid/sol.rb | 38 + .../1559. detect-cycles-in-2d-grid/sol.rs | 46 + .../1559. detect-cycles-in-2d-grid/sol.swift | 41 + .../1559. detect-cycles-in-2d-grid/sol.ts | 51 + .../manifest.yaml | 538 +++++++ .../sol.cpp | 14 + .../sol.cs | 14 + .../sol.dart | 11 + .../sol.go | 17 + .../sol.java | 13 + .../sol.kt | 7 + .../sol.py | 8 + .../sol.py2 | 12 + .../sol.rb | 11 + .../sol.rs | 11 + .../sol.swift | 11 + .../sol.ts | 14 + .../manifest.yaml | 380 +++++ .../sol.cpp | 15 + .../sol.cs | 14 + .../sol.dart | 14 + .../sol.go | 12 + .../sol.java | 14 + .../sol.kt | 14 + .../sol.py | 11 + .../sol.py2 | 15 + .../sol.rb | 14 + .../sol.rs | 15 + .../sol.swift | 14 + .../sol.ts | 12 + .../manifest.yaml | 252 +++ .../1562. find-latest-group-of-size-m/sol.cpp | 22 + .../1562. find-latest-group-of-size-m/sol.cs | 21 + .../sol.dart | 21 + .../1562. find-latest-group-of-size-m/sol.go | 25 + .../sol.java | 21 + .../1562. find-latest-group-of-size-m/sol.kt | 23 + .../1562. find-latest-group-of-size-m/sol.py | 25 + .../1562. find-latest-group-of-size-m/sol.py2 | 25 + .../1562. find-latest-group-of-size-m/sol.rb | 22 + .../1562. find-latest-group-of-size-m/sol.rs | 25 + .../sol.swift | 25 + .../1562. find-latest-group-of-size-m/sol.ts | 19 + .../1563. stone-game-v/manifest.yaml | 418 +++++ tests/1501-2000/1563. stone-game-v/sol.cpp | 50 + tests/1501-2000/1563. stone-game-v/sol.cs | 52 + tests/1501-2000/1563. stone-game-v/sol.dart | 48 + tests/1501-2000/1563. stone-game-v/sol.go | 66 + tests/1501-2000/1563. stone-game-v/sol.java | 51 + tests/1501-2000/1563. stone-game-v/sol.kt | 47 + tests/1501-2000/1563. stone-game-v/sol.py | 34 + tests/1501-2000/1563. stone-game-v/sol.py2 | 42 + tests/1501-2000/1563. stone-game-v/sol.rb | 41 + tests/1501-2000/1563. stone-game-v/sol.rs | 49 + tests/1501-2000/1563. stone-game-v/sol.swift | 49 + tests/1501-2000/1563. stone-game-v/sol.ts | 51 + .../manifest.yaml | 354 +++++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 15 + .../sol.go | 15 + .../sol.java | 15 + .../sol.kt | 15 + .../sol.py | 12 + .../sol.py2 | 17 + .../sol.rb | 17 + .../sol.rs | 22 + .../sol.swift | 16 + .../sol.ts | 13 + .../manifest.yaml | 254 +++ .../sol.cpp | 21 + .../sol.cs | 20 + .../sol.dart | 20 + .../sol.go | 28 + .../sol.java | 22 + .../sol.kt | 26 + .../sol.py | 16 + .../sol.py2 | 22 + .../sol.rb | 22 + .../sol.rs | 20 + .../sol.swift | 20 + .../sol.ts | 20 + .../manifest.yaml | 364 +++++ .../sol.cpp | 47 + .../sol.cs | 45 + .../sol.dart | 45 + .../sol.go | 49 + .../sol.java | 48 + .../sol.kt | 45 + .../sol.py | 40 + .../sol.py2 | 39 + .../sol.rb | 45 + .../sol.rs | 51 + .../sol.swift | 50 + .../sol.ts | 54 + .../manifest.yaml | 256 +++ .../sol.cpp | 31 + .../sol.cs | 28 + .../sol.dart | 28 + .../sol.go | 37 + .../sol.java | 27 + .../sol.kt | 29 + .../sol.py | 27 + .../sol.py2 | 27 + .../sol.rb | 27 + .../sol.rs | 30 + .../sol.swift | 30 + .../sol.ts | 28 + .../1572. matrix-diagonal-sum/manifest.yaml | 893 +++++++++++ .../1572. matrix-diagonal-sum/sol.cpp | 15 + .../1572. matrix-diagonal-sum/sol.cs | 14 + .../1572. matrix-diagonal-sum/sol.dart | 14 + .../1572. matrix-diagonal-sum/sol.go | 12 + .../1572. matrix-diagonal-sum/sol.java | 14 + .../1572. matrix-diagonal-sum/sol.kt | 14 + .../1572. matrix-diagonal-sum/sol.py | 13 + .../1572. matrix-diagonal-sum/sol.py2 | 14 + .../1572. matrix-diagonal-sum/sol.rb | 12 + .../1572. matrix-diagonal-sum/sol.rs | 14 + .../1572. matrix-diagonal-sum/sol.swift | 14 + .../1572. matrix-diagonal-sum/sol.ts | 12 + .../manifest.yaml | 185 +++ .../sol.cpp | 31 + .../sol.cs | 27 + .../sol.dart | 27 + .../sol.go | 34 + .../sol.java | 31 + .../sol.kt | 29 + .../sol.py | 29 + .../sol.py2 | 29 + .../sol.rb | 29 + .../sol.rs | 33 + .../sol.swift | 33 + .../sol.ts | 27 + .../manifest.yaml | 252 +++ .../sol.cpp | 22 + .../sol.cs | 21 + .../sol.dart | 21 + .../sol.go | 25 + .../sol.java | 21 + .../sol.kt | 21 + .../sol.py | 18 + .../sol.py2 | 22 + .../sol.rb | 21 + .../sol.rs | 25 + .../sol.swift | 21 + .../sol.ts | 19 + .../manifest.yaml | 415 +++++ .../1575. count-all-possible-routes/sol.cpp | 26 + .../1575. count-all-possible-routes/sol.cs | 25 + .../1575. count-all-possible-routes/sol.dart | 25 + .../1575. count-all-possible-routes/sol.go | 38 + .../1575. count-all-possible-routes/sol.java | 25 + .../1575. count-all-possible-routes/sol.kt | 25 + .../1575. count-all-possible-routes/sol.py | 18 + .../1575. count-all-possible-routes/sol.py2 | 24 + .../1575. count-all-possible-routes/sol.rb | 28 + .../1575. count-all-possible-routes/sol.rs | 25 + .../1575. count-all-possible-routes/sol.swift | 25 + .../1575. count-all-possible-routes/sol.ts | 30 + .../manifest.yaml | 186 +++ .../sol.cpp | 20 + .../sol.cs | 20 + .../sol.dart | 20 + .../sol.go | 24 + .../sol.java | 20 + .../sol.kt | 18 + .../sol.py | 18 + .../sol.py2 | 19 + .../sol.rb | 18 + .../sol.rs | 20 + .../sol.swift | 20 + .../sol.ts | 18 + .../manifest.yaml | 358 +++++ .../sol.cpp | 21 + .../sol.cs | 20 + .../sol.dart | 19 + .../sol.go | 17 + .../sol.java | 20 + .../sol.kt | 19 + .../sol.py | 26 + .../sol.py2 | 20 + .../sol.rb | 21 + .../sol.rs | 21 + .../sol.swift | 19 + .../sol.ts | 17 + .../manifest.yaml | 227 +++ .../sol.cpp | 14 + .../sol.cs | 12 + .../sol.dart | 12 + .../sol.go | 15 + .../sol.java | 13 + .../sol.kt | 12 + .../sol.py | 8 + .../sol.py2 | 8 + .../sol.rb | 14 + .../sol.rs | 15 + .../sol.swift | 15 + .../sol.ts | 10 + .../manifest.yaml | 575 +++++++ .../sol.cpp | 59 + .../sol.cs | 62 + .../sol.dart | 59 + .../sol.go | 69 + .../sol.java | 75 + .../sol.kt | 63 + .../sol.py | 50 + .../sol.py2 | 54 + .../sol.rb | 60 + .../sol.rs | 62 + .../sol.swift | 60 + .../sol.ts | 62 + .../manifest.yaml | 377 +++++ .../sol.cpp | 26 + .../sol.cs | 26 + .../sol.dart | 26 + .../sol.go | 24 + .../sol.java | 26 + .../sol.kt | 27 + .../sol.py | 17 + .../sol.py2 | 21 + .../sol.rb | 24 + .../sol.rs | 27 + .../sol.swift | 26 + .../sol.ts | 25 + .../1583. count-unhappy-friends/manifest.yaml | 556 +++++++ .../1583. count-unhappy-friends/sol.cpp | 33 + .../1583. count-unhappy-friends/sol.cs | 33 + .../1583. count-unhappy-friends/sol.dart | 32 + .../1583. count-unhappy-friends/sol.go | 35 + .../1583. count-unhappy-friends/sol.java | 32 + .../1583. count-unhappy-friends/sol.kt | 32 + .../1583. count-unhappy-friends/sol.py | 39 + .../1583. count-unhappy-friends/sol.py2 | 33 + .../1583. count-unhappy-friends/sol.rb | 34 + .../1583. count-unhappy-friends/sol.rs | 36 + .../1583. count-unhappy-friends/sol.swift | 32 + .../1583. count-unhappy-friends/sol.ts | 36 + .../manifest.yaml | 412 +++++ .../sol.cpp | 34 + .../sol.cs | 28 + .../sol.dart | 30 + .../sol.go | 29 + .../sol.java | 32 + .../sol.kt | 31 + .../sol.py | 31 + .../sol.py2 | 26 + .../sol.rb | 25 + .../sol.rs | 48 + .../sol.swift | 29 + .../sol.ts | 28 + .../manifest.yaml | 223 +++ .../sol.cpp | 24 + .../sol.cs | 22 + .../sol.dart | 21 + .../sol.go | 23 + .../sol.java | 25 + .../sol.kt | 16 + .../sol.py | 15 + .../sol.py2 | 17 + .../sol.rb | 19 + .../sol.rs | 23 + .../sol.swift | 19 + .../sol.ts | 17 + .../manifest.yaml | 404 +++++ .../sol.cpp | 21 + .../sol.cs | 20 + .../sol.dart | 20 + .../sol.go | 21 + .../sol.java | 19 + .../sol.kt | 18 + .../sol.py | 14 + .../sol.py2 | 18 + .../sol.rb | 18 + .../sol.rs | 20 + .../sol.swift | 20 + .../sol.ts | 18 + .../manifest.yaml | 366 +++++ .../sol.cpp | 44 + .../sol.cs | 44 + .../sol.dart | 43 + .../sol.go | 54 + .../sol.java | 50 + .../sol.kt | 40 + .../sol.py | 41 + .../sol.py2 | 38 + .../sol.rb | 41 + .../sol.rs | 43 + .../sol.swift | 40 + .../sol.ts | 38 + .../manifest.yaml | 287 ++++ .../1590. make-sum-divisible-by-p/sol.cpp | 27 + .../1590. make-sum-divisible-by-p/sol.cs | 25 + .../1590. make-sum-divisible-by-p/sol.dart | 24 + .../1590. make-sum-divisible-by-p/sol.go | 32 + .../1590. make-sum-divisible-by-p/sol.java | 26 + .../1590. make-sum-divisible-by-p/sol.kt | 26 + .../1590. make-sum-divisible-by-p/sol.py | 21 + .../1590. make-sum-divisible-by-p/sol.py2 | 26 + .../1590. make-sum-divisible-by-p/sol.rb | 25 + .../1590. make-sum-divisible-by-p/sol.rs | 31 + .../1590. make-sum-divisible-by-p/sol.swift | 26 + .../1590. make-sum-divisible-by-p/sol.ts | 22 + .../1591. strange-printer-ii/manifest.yaml | 435 ++++++ .../1591. strange-printer-ii/sol.cpp | 53 + .../1501-2000/1591. strange-printer-ii/sol.cs | 47 + .../1591. strange-printer-ii/sol.dart | 43 + .../1501-2000/1591. strange-printer-ii/sol.go | 53 + .../1591. strange-printer-ii/sol.java | 49 + .../1501-2000/1591. strange-printer-ii/sol.kt | 39 + .../1501-2000/1591. strange-printer-ii/sol.py | 42 + .../1591. strange-printer-ii/sol.py2 | 34 + .../1501-2000/1591. strange-printer-ii/sol.rb | 38 + .../1501-2000/1591. strange-printer-ii/sol.rs | 46 + .../1591. strange-printer-ii/sol.swift | 43 + .../1501-2000/1591. strange-printer-ii/sol.ts | 47 + .../manifest.yaml | 220 +++ .../sol.cpp | 24 + .../sol.cs | 12 + .../sol.dart | 12 + .../sol.go | 10 + .../sol.java | 12 + .../sol.kt | 12 + .../sol.py | 14 + .../sol.py2 | 13 + .../sol.rb | 10 + .../sol.rs | 14 + .../sol.swift | 12 + .../sol.ts | 10 + .../manifest.yaml | 298 ++++ .../sol.cpp | 23 + .../sol.cs | 22 + .../sol.dart | 25 + .../sol.go | 24 + .../sol.java | 22 + .../sol.kt | 21 + .../sol.py | 23 + .../sol.py2 | 21 + .../sol.rb | 23 + .../sol.rs | 24 + .../sol.swift | 24 + .../sol.ts | 21 + .../manifest.yaml | 317 ++++ .../sol.cpp | 36 + .../sol.cs | 41 + .../sol.dart | 34 + .../sol.go | 50 + .../sol.java | 35 + .../sol.kt | 34 + .../sol.py | 25 + .../sol.py2 | 30 + .../sol.rb | 29 + .../sol.rs | 36 + .../sol.swift | 34 + .../sol.ts | 39 + .../manifest.yaml | 499 ++++++ .../sol.cpp | 31 + .../sol.cs | 49 + .../sol.dart | 32 + .../sol.go | 51 + .../sol.java | 53 + .../sol.kt | 30 + .../sol.py | 17 + .../sol.py2 | 20 + .../sol.rb | 27 + .../sol.rs | 35 + .../sol.swift | 33 + .../sol.ts | 33 + .../1598. crawler-log-folder/manifest.yaml | 322 ++++ .../1598. crawler-log-folder/sol.cpp | 17 + .../1501-2000/1598. crawler-log-folder/sol.cs | 16 + .../1598. crawler-log-folder/sol.dart | 16 + .../1501-2000/1598. crawler-log-folder/sol.go | 19 + .../1598. crawler-log-folder/sol.java | 16 + .../1501-2000/1598. crawler-log-folder/sol.kt | 16 + .../1501-2000/1598. crawler-log-folder/sol.py | 16 + .../1598. crawler-log-folder/sol.py2 | 20 + .../1501-2000/1598. crawler-log-folder/sol.rb | 16 + .../1501-2000/1598. crawler-log-folder/sol.rs | 16 + .../1598. crawler-log-folder/sol.swift | 16 + .../1501-2000/1598. crawler-log-folder/sol.ts | 14 + .../manifest.yaml | 368 +++++ .../sol.cpp | 31 + .../sol.cs | 30 + .../sol.dart | 30 + .../sol.go | 31 + .../sol.java | 30 + .../sol.kt | 30 + .../sol.py | 31 + .../sol.py2 | 31 + .../sol.rb | 30 + .../sol.rs | 30 + .../sol.swift | 30 + .../sol.ts | 32 + .../manifest.yaml | 600 ++++++++ .../sol.cpp | 32 + .../sol.cs | 29 + .../sol.dart | 33 + .../sol.go | 32 + .../sol.java | 29 + .../sol.kt | 29 + .../sol.py | 26 + .../sol.py2 | 29 + .../sol.rb | 29 + .../sol.rs | 32 + .../sol.swift | 29 + .../sol.ts | 31 + .../manifest.yaml | 279 ++++ .../sol.cpp | 28 + .../sol.cs | 30 + .../sol.dart | 26 + .../sol.go | 26 + .../sol.java | 27 + .../sol.kt | 25 + .../sol.py | 27 + .../sol.py2 | 27 + .../sol.rb | 26 + .../sol.rs | 28 + .../sol.swift | 26 + .../sol.ts | 26 + .../manifest.yaml | 203 +++ .../sol.cpp | 17 + .../sol.cs | 17 + .../sol.dart | 16 + .../sol.go | 21 + .../sol.java | 16 + .../sol.kt | 18 + .../sol.py | 20 + .../sol.py2 | 20 + .../sol.rb | 17 + .../sol.rs | 18 + .../sol.swift | 18 + .../sol.ts | 18 + .../manifest.yaml | 438 ++++++ .../sol.cpp | 27 + .../sol.cs | 29 + .../sol.dart | 28 + .../sol.go | 38 + .../sol.java | 27 + .../sol.kt | 22 + .../sol.py | 19 + .../sol.py2 | 22 + .../sol.rb | 24 + .../sol.rs | 30 + .../sol.swift | 23 + .../sol.ts | 31 + .../manifest.yaml | 453 ++++++ .../sol.cpp | 15 + .../sol.cs | 14 + .../sol.dart | 14 + .../sol.go | 16 + .../sol.java | 14 + .../sol.kt | 14 + .../sol.py | 12 + .../sol.py2 | 16 + .../sol.rb | 14 + .../sol.rs | 18 + .../sol.swift | 14 + .../sol.ts | 12 + .../1609. even-odd-tree/manifest.yaml | 230 +++ tests/1501-2000/1609. even-odd-tree/sol.cpp | 34 + tests/1501-2000/1609. even-odd-tree/sol.cs | 35 + tests/1501-2000/1609. even-odd-tree/sol.dart | 31 + tests/1501-2000/1609. even-odd-tree/sol.go | 37 + tests/1501-2000/1609. even-odd-tree/sol.java | 39 + tests/1501-2000/1609. even-odd-tree/sol.kt | 32 + tests/1501-2000/1609. even-odd-tree/sol.py | 30 + tests/1501-2000/1609. even-odd-tree/sol.py2 | 32 + tests/1501-2000/1609. even-odd-tree/sol.rb | 31 + tests/1501-2000/1609. even-odd-tree/sol.rs | 55 + tests/1501-2000/1609. even-odd-tree/sol.swift | 37 + tests/1501-2000/1609. even-odd-tree/sol.ts | 42 + .../manifest.yaml | 542 +++++++ .../sol.cpp | 41 + .../sol.cs | 40 + .../sol.dart | 40 + .../sol.go | 41 + .../sol.java | 47 + .../sol.kt | 40 + .../sol.py | 44 + .../sol.py2 | 38 + .../sol.rb | 37 + .../sol.rs | 43 + .../sol.swift | 36 + .../sol.ts | 37 + .../manifest.yaml | 218 +++ .../sol.cpp | 27 + .../sol.cs | 26 + .../sol.dart | 26 + .../sol.go | 24 + .../sol.java | 26 + .../sol.kt | 26 + .../sol.py | 19 + .../sol.py2 | 23 + .../sol.rb | 26 + .../sol.rs | 26 + .../sol.swift | 28 + .../sol.ts | 24 + .../manifest.yaml | 194 +++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 15 + .../sol.go | 15 + .../sol.java | 15 + .../sol.kt | 15 + .../sol.py | 11 + .../sol.py2 | 15 + .../sol.rb | 15 + .../sol.rs | 15 + .../sol.swift | 15 + .../sol.ts | 13 + .../1615. maximal-network-rank/manifest.yaml | 629 ++++++++ .../1615. maximal-network-rank/sol.cpp | 34 + .../1615. maximal-network-rank/sol.cs | 35 + .../1615. maximal-network-rank/sol.dart | 28 + .../1615. maximal-network-rank/sol.go | 41 + .../1615. maximal-network-rank/sol.java | 35 + .../1615. maximal-network-rank/sol.kt | 28 + .../1615. maximal-network-rank/sol.py | 25 + .../1615. maximal-network-rank/sol.py2 | 21 + .../1615. maximal-network-rank/sol.rb | 23 + .../1615. maximal-network-rank/sol.rs | 25 + .../1615. maximal-network-rank/sol.swift | 22 + .../1615. maximal-network-rank/sol.ts | 20 + .../manifest.yaml | 347 +++++ .../sol.cpp | 26 + .../sol.cs | 24 + .../sol.dart | 16 + .../sol.go | 21 + .../sol.java | 18 + .../sol.kt | 17 + .../sol.py | 19 + .../sol.py2 | 18 + .../sol.rb | 16 + .../sol.rs | 30 + .../sol.swift | 24 + .../sol.ts | 19 + .../manifest.yaml | 517 +++++++ .../sol.cpp | 57 + .../sol.cs | 69 + .../sol.dart | 76 + .../sol.go | 62 + .../sol.java | 59 + .../sol.kt | 57 + .../sol.py | 53 + .../sol.py2 | 52 + .../sol.rb | 51 + .../sol.rs | 60 + .../sol.swift | 58 + .../sol.ts | 63 + .../manifest.yaml | 1182 ++++++++++++++ .../sol.cpp | 13 + .../sol.cs | 12 + .../sol.dart | 12 + .../sol.go | 10 + .../sol.java | 12 + .../sol.kt | 12 + .../sol.py | 7 + .../sol.py2 | 11 + .../sol.rb | 9 + .../sol.rs | 10 + .../sol.swift | 9 + .../sol.ts | 10 + .../manifest.yaml | 479 ++++++ .../sol.cpp | 33 + .../sol.cs | 32 + .../sol.dart | 32 + .../sol.go | 32 + .../sol.java | 32 + .../sol.kt | 32 + .../sol.py | 27 + .../sol.py2 | 26 + .../sol.rb | 28 + .../sol.rs | 34 + .../sol.swift | 32 + .../sol.ts | 34 + .../manifest.yaml | 255 +++ .../sol.cpp | 27 + .../sol.cs | 27 + .../sol.dart | 26 + .../sol.go | 27 + .../sol.java | 27 + .../sol.kt | 26 + .../sol.py | 28 + .../sol.py2 | 28 + .../sol.rb | 29 + .../sol.rs | 28 + .../sol.swift | 26 + .../sol.ts | 24 + .../manifest.yaml | 215 +++ .../sol.cpp | 23 + .../sol.cs | 26 + .../sol.dart | 23 + .../sol.go | 31 + .../sol.java | 24 + .../sol.kt | 22 + .../sol.py | 22 + .../sol.py2 | 22 + .../sol.rb | 20 + .../sol.rs | 27 + .../sol.swift | 24 + .../sol.ts | 21 + .../manifest.yaml | 309 ++++ .../sol.cpp | 19 + .../sol.cs | 22 + .../sol.dart | 18 + .../sol.go | 23 + .../sol.java | 34 + .../sol.kt | 19 + .../sol.py | 29 + .../sol.py2 | 21 + .../sol.rb | 16 + .../sol.rs | 28 + .../sol.swift | 22 + .../sol.ts | 16 + .../manifest.yaml | 331 ++++ .../1626. best-team-with-no-conflicts/sol.cpp | 18 + .../1626. best-team-with-no-conflicts/sol.cs | 18 + .../sol.dart | 16 + .../1626. best-team-with-no-conflicts/sol.go | 35 + .../sol.java | 25 + .../1626. best-team-with-no-conflicts/sol.kt | 17 + .../1626. best-team-with-no-conflicts/sol.py | 9 + .../1626. best-team-with-no-conflicts/sol.py2 | 14 + .../1626. best-team-with-no-conflicts/sol.rb | 15 + .../1626. best-team-with-no-conflicts/sol.rs | 15 + .../sol.swift | 15 + .../1626. best-team-with-no-conflicts/sol.ts | 14 + .../manifest.yaml | 451 ++++++ .../sol.cpp | 50 + .../sol.cs | 50 + .../sol.dart | 42 + .../sol.go | 54 + .../sol.java | 51 + .../sol.kt | 41 + .../sol.py | 38 + .../sol.py2 | 39 + .../sol.rb | 39 + .../sol.rs | 46 + .../sol.swift | 43 + .../sol.ts | 43 + .../1501-2000/1629. slowest-key/manifest.yaml | 231 +++ tests/1501-2000/1629. slowest-key/sol.cpp | 17 + tests/1501-2000/1629. slowest-key/sol.cs | 16 + tests/1501-2000/1629. slowest-key/sol.dart | 18 + tests/1501-2000/1629. slowest-key/sol.go | 16 + tests/1501-2000/1629. slowest-key/sol.java | 16 + tests/1501-2000/1629. slowest-key/sol.kt | 16 + tests/1501-2000/1629. slowest-key/sol.py | 16 + tests/1501-2000/1629. slowest-key/sol.py2 | 17 + tests/1501-2000/1629. slowest-key/sol.rb | 14 + tests/1501-2000/1629. slowest-key/sol.rs | 19 + tests/1501-2000/1629. slowest-key/sol.swift | 19 + tests/1501-2000/1629. slowest-key/sol.ts | 16 + .../1630. arithmetic-subarrays/manifest.yaml | 338 ++++ .../1630. arithmetic-subarrays/sol.cpp | 22 + .../1630. arithmetic-subarrays/sol.cs | 22 + .../1630. arithmetic-subarrays/sol.dart | 20 + .../1630. arithmetic-subarrays/sol.go | 20 + .../1630. arithmetic-subarrays/sol.java | 23 + .../1630. arithmetic-subarrays/sol.kt | 20 + .../1630. arithmetic-subarrays/sol.py | 16 + .../1630. arithmetic-subarrays/sol.py2 | 15 + .../1630. arithmetic-subarrays/sol.rb | 25 + .../1630. arithmetic-subarrays/sol.rs | 21 + .../1630. arithmetic-subarrays/sol.swift | 20 + .../1630. arithmetic-subarrays/sol.ts | 22 + .../manifest.yaml | 378 +++++ .../1631. path-with-minimum-effort/sol.cpp | 28 + .../1631. path-with-minimum-effort/sol.cs | 28 + .../1631. path-with-minimum-effort/sol.dart | 28 + .../1631. path-with-minimum-effort/sol.go | 60 + .../1631. path-with-minimum-effort/sol.java | 27 + .../1631. path-with-minimum-effort/sol.kt | 31 + .../1631. path-with-minimum-effort/sol.py | 42 + .../1631. path-with-minimum-effort/sol.py2 | 25 + .../1631. path-with-minimum-effort/sol.rb | 29 + .../1631. path-with-minimum-effort/sol.rs | 39 + .../1631. path-with-minimum-effort/sol.swift | 32 + .../1631. path-with-minimum-effort/sol.ts | 45 + .../manifest.yaml | 366 +++++ .../1632. rank-transform-of-a-matrix/sol.cpp | 47 + .../1632. rank-transform-of-a-matrix/sol.cs | 46 + .../1632. rank-transform-of-a-matrix/sol.dart | 45 + .../1632. rank-transform-of-a-matrix/sol.go | 52 + .../1632. rank-transform-of-a-matrix/sol.java | 41 + .../1632. rank-transform-of-a-matrix/sol.kt | 42 + .../1632. rank-transform-of-a-matrix/sol.py | 36 + .../1632. rank-transform-of-a-matrix/sol.py2 | 35 + .../1632. rank-transform-of-a-matrix/sol.rb | 43 + .../1632. rank-transform-of-a-matrix/sol.rs | 49 + .../sol.swift | 41 + .../1632. rank-transform-of-a-matrix/sol.ts | 41 + .../manifest.yaml | 225 +++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 14 + .../sol.go | 13 + .../sol.java | 17 + .../sol.kt | 7 + .../sol.py | 7 + .../sol.py2 | 9 + .../sol.rb | 6 + .../sol.rs | 15 + .../sol.swift | 14 + .../sol.ts | 11 + .../manifest.yaml | 439 ++++++ .../sol.cpp | 14 + .../sol.cs | 11 + .../sol.dart | 11 + .../sol.go | 13 + .../sol.java | 11 + .../sol.kt | 11 + .../sol.py | 13 + .../sol.py2 | 12 + .../sol.rb | 11 + .../sol.rs | 14 + .../sol.swift | 11 + .../sol.ts | 9 + .../manifest.yaml | 278 ++++ .../sol.cpp | 28 + .../sol.cs | 27 + .../sol.dart | 27 + .../sol.go | 25 + .../sol.java | 27 + .../sol.kt | 28 + .../sol.py | 24 + .../sol.py2 | 24 + .../sol.rb | 28 + .../sol.rs | 30 + .../sol.swift | 29 + .../sol.ts | 26 + .../manifest.yaml | 302 ++++ .../sol.cpp | 26 + .../sol.cs | 31 + .../sol.dart | 24 + .../sol.go | 37 + .../sol.java | 24 + .../sol.kt | 24 + .../sol.py | 28 + .../sol.py2 | 33 + .../sol.rb | 27 + .../sol.rs | 26 + .../sol.swift | 23 + .../sol.ts | 31 + .../manifest.yaml | 377 +++++ .../sol.cpp | 17 + .../sol.cs | 20 + .../sol.dart | 20 + .../sol.go | 32 + .../sol.java | 26 + .../sol.kt | 16 + .../sol.py | 13 + .../sol.py2 | 18 + .../sol.rb | 16 + .../sol.rs | 16 + .../sol.swift | 16 + .../sol.ts | 14 + .../manifest.yaml | 213 +++ .../1641. count-sorted-vowel-strings/sol.cpp | 27 + .../1641. count-sorted-vowel-strings/sol.cs | 26 + .../1641. count-sorted-vowel-strings/sol.dart | 28 + .../1641. count-sorted-vowel-strings/sol.go | 26 + .../1641. count-sorted-vowel-strings/sol.java | 26 + .../1641. count-sorted-vowel-strings/sol.kt | 24 + .../1641. count-sorted-vowel-strings/sol.py | 17 + .../1641. count-sorted-vowel-strings/sol.py2 | 21 + .../1641. count-sorted-vowel-strings/sol.rb | 22 + .../1641. count-sorted-vowel-strings/sol.rs | 26 + .../sol.swift | 26 + .../1641. count-sorted-vowel-strings/sol.ts | 23 + .../manifest.yaml | 331 ++++ .../sol.cpp | 24 + .../sol.cs | 27 + .../sol.dart | 22 + .../sol.go | 37 + .../sol.java | 22 + .../sol.kt | 23 + .../sol.py | 16 + .../sol.py2 | 23 + .../sol.rb | 23 + .../sol.rs | 26 + .../sol.swift | 39 + .../sol.ts | 49 + .../manifest.yaml | 237 +++ .../1643. kth-smallest-instructions/sol.cpp | 37 + .../1643. kth-smallest-instructions/sol.cs | 35 + .../1643. kth-smallest-instructions/sol.dart | 35 + .../1643. kth-smallest-instructions/sol.go | 37 + .../1643. kth-smallest-instructions/sol.java | 35 + .../1643. kth-smallest-instructions/sol.kt | 37 + .../1643. kth-smallest-instructions/sol.py | 30 + .../1643. kth-smallest-instructions/sol.py2 | 32 + .../1643. kth-smallest-instructions/sol.rb | 37 + .../1643. kth-smallest-instructions/sol.rs | 39 + .../1643. kth-smallest-instructions/sol.swift | 35 + .../1643. kth-smallest-instructions/sol.ts | 33 + .../manifest.yaml | 224 +++ .../sol.cpp | 24 + .../sol.cs | 23 + .../sol.dart | 27 + .../sol.go | 27 + .../sol.java | 27 + .../sol.kt | 23 + .../sol.py | 16 + .../sol.py2 | 20 + .../sol.rb | 21 + .../sol.rs | 24 + .../sol.swift | 23 + .../sol.ts | 21 + .../manifest.yaml | 215 +++ .../sol.cpp | 23 + .../sol.cs | 22 + .../sol.dart | 18 + .../sol.go | 22 + .../sol.java | 22 + .../sol.kt | 16 + .../sol.py | 19 + .../sol.py2 | 16 + .../sol.rb | 16 + .../sol.rs | 19 + .../sol.swift | 18 + .../sol.ts | 16 + .../manifest.yaml | 271 ++++ .../sol.cpp | 34 + .../sol.cs | 32 + .../sol.dart | 34 + .../sol.go | 37 + .../sol.java | 32 + .../sol.kt | 33 + .../sol.py | 28 + .../sol.py2 | 33 + .../sol.rb | 36 + .../sol.rs | 39 + .../sol.swift | 39 + .../sol.ts | 37 + .../manifest.yaml | 271 ++++ .../sol.cpp | 74 + .../sol.cs | 70 + .../sol.dart | 32 + .../sol.go | 72 + .../sol.java | 69 + .../sol.kt | 67 + .../sol.py | 76 + .../sol.py2 | 54 + .../sol.rb | 62 + .../sol.rs | 68 + .../sol.swift | 67 + .../sol.ts | 68 + .../1652. defuse-the-bomb/manifest.yaml | 269 ++++ tests/1501-2000/1652. defuse-the-bomb/sol.cpp | 29 + tests/1501-2000/1652. defuse-the-bomb/sol.cs | 28 + .../1501-2000/1652. defuse-the-bomb/sol.dart | 28 + tests/1501-2000/1652. defuse-the-bomb/sol.go | 41 + .../1501-2000/1652. defuse-the-bomb/sol.java | 28 + tests/1501-2000/1652. defuse-the-bomb/sol.kt | 28 + tests/1501-2000/1652. defuse-the-bomb/sol.py | 25 + tests/1501-2000/1652. defuse-the-bomb/sol.py2 | 15 + tests/1501-2000/1652. defuse-the-bomb/sol.rb | 29 + tests/1501-2000/1652. defuse-the-bomb/sol.rs | 30 + .../1501-2000/1652. defuse-the-bomb/sol.swift | 28 + tests/1501-2000/1652. defuse-the-bomb/sol.ts | 26 + .../manifest.yaml | 194 +++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 15 + .../sol.go | 13 + .../sol.java | 15 + .../sol.kt | 15 + .../sol.py | 12 + .../sol.py2 | 15 + .../sol.rb | 15 + .../sol.rs | 15 + .../sol.swift | 15 + .../sol.ts | 13 + .../manifest.yaml | 344 +++++ .../1654. minimum-jumps-to-reach-home/sol.cpp | 37 + .../1654. minimum-jumps-to-reach-home/sol.cs | 35 + .../sol.dart | 34 + .../1654. minimum-jumps-to-reach-home/sol.go | 52 + .../sol.java | 36 + .../1654. minimum-jumps-to-reach-home/sol.kt | 33 + .../1654. minimum-jumps-to-reach-home/sol.py | 34 + .../1654. minimum-jumps-to-reach-home/sol.py2 | 38 + .../1654. minimum-jumps-to-reach-home/sol.rb | 30 + .../1654. minimum-jumps-to-reach-home/sol.rs | 39 + .../sol.swift | 39 + .../1654. minimum-jumps-to-reach-home/sol.ts | 36 + .../manifest.yaml | 373 +++++ .../sol.cpp | 27 + .../sol.cs | 42 + .../sol.dart | 36 + .../sol.go | 37 + .../sol.java | 35 + .../sol.kt | 28 + .../sol.py | 24 + .../sol.py2 | 23 + .../sol.rb | 25 + .../sol.rs | 44 + .../sol.swift | 35 + .../sol.ts | 33 + .../manifest.yaml | 272 ++++ .../sol.cpp | 26 + .../sol.cs | 16 + .../sol.dart | 16 + .../sol.go | 44 + .../sol.java | 26 + .../sol.kt | 16 + .../sol.py | 16 + .../sol.py2 | 23 + .../sol.rb | 20 + .../sol.rs | 20 + .../sol.swift | 16 + .../sol.ts | 24 + .../manifest.yaml | 281 ++++ .../sol.cpp | 28 + .../sol.cs | 27 + .../sol.dart | 27 + .../sol.go | 38 + .../sol.java | 29 + .../sol.kt | 29 + .../sol.py | 22 + .../sol.py2 | 27 + .../sol.rb | 24 + .../sol.rs | 29 + .../sol.swift | 27 + .../sol.ts | 27 + .../manifest.yaml | 341 ++++ .../1659. maximize-grid-happiness/sol.cpp | 2 + .../1659. maximize-grid-happiness/sol.cs | 1 + .../1659. maximize-grid-happiness/sol.dart | 1 + .../1659. maximize-grid-happiness/sol.go | 1 + .../1659. maximize-grid-happiness/sol.java | 1 + .../1659. maximize-grid-happiness/sol.kt | 1 + .../1659. maximize-grid-happiness/sol.py | 79 + .../1659. maximize-grid-happiness/sol.py2 | 28 + .../1659. maximize-grid-happiness/sol.rb | 6 + .../1659. maximize-grid-happiness/sol.rs | 1 + .../1659. maximize-grid-happiness/sol.swift | 1 + .../1659. maximize-grid-happiness/sol.ts | 55 + .../manifest.yaml | 368 +++++ .../sol.cpp | 14 + .../sol.cs | 7 + .../sol.dart | 7 + .../sol.go | 11 + .../sol.java | 7 + .../sol.kt | 7 + .../sol.py | 9 + .../sol.py2 | 10 + .../sol.rb | 8 + .../sol.rs | 7 + .../sol.swift | 7 + .../sol.ts | 5 + .../manifest.yaml | 222 +++ .../sol.cpp | 17 + .../sol.cs | 17 + .../sol.dart | 16 + .../sol.go | 24 + .../sol.java | 17 + .../sol.kt | 16 + .../sol.py | 18 + .../sol.py2 | 18 + .../sol.rb | 17 + .../sol.rs | 16 + .../sol.swift | 16 + .../sol.ts | 14 + .../manifest.yaml | 232 +++ .../1664. ways-to-make-a-fair-array/sol.cpp | 33 + .../1664. ways-to-make-a-fair-array/sol.cs | 32 + .../1664. ways-to-make-a-fair-array/sol.dart | 32 + .../1664. ways-to-make-a-fair-array/sol.go | 30 + .../1664. ways-to-make-a-fair-array/sol.java | 32 + .../1664. ways-to-make-a-fair-array/sol.kt | 32 + .../1664. ways-to-make-a-fair-array/sol.py | 24 + .../1664. ways-to-make-a-fair-array/sol.py2 | 28 + .../1664. ways-to-make-a-fair-array/sol.rb | 32 + .../1664. ways-to-make-a-fair-array/sol.rs | 32 + .../1664. ways-to-make-a-fair-array/sol.swift | 32 + .../1664. ways-to-make-a-fair-array/sol.ts | 30 + .../manifest.yaml | 337 ++++ .../sol.cpp | 22 + .../sol.cs | 19 + .../sol.dart | 22 + .../sol.go | 24 + .../sol.java | 22 + .../sol.kt | 20 + .../sol.py | 15 + .../sol.py2 | 21 + .../sol.rb | 22 + .../sol.rs | 24 + .../sol.swift | 23 + .../sol.ts | 18 + .../manifest.yaml | 250 +++ .../1668. maximum-repeating-substring/sol.cpp | 12 + .../1668. maximum-repeating-substring/sol.cs | 11 + .../sol.dart | 11 + .../1668. maximum-repeating-substring/sol.go | 9 + .../sol.java | 11 + .../1668. maximum-repeating-substring/sol.kt | 11 + .../1668. maximum-repeating-substring/sol.py | 7 + .../1668. maximum-repeating-substring/sol.py2 | 12 + .../1668. maximum-repeating-substring/sol.rb | 11 + .../1668. maximum-repeating-substring/sol.rs | 11 + .../sol.swift | 11 + .../1668. maximum-repeating-substring/sol.ts | 9 + .../manifest.yaml | 294 ++++ .../sol.cpp | 30 + .../sol.cs | 30 + .../sol.dart | 13 + .../sol.go | 24 + .../sol.java | 29 + .../sol.kt | 28 + .../sol.py | 27 + .../sol.py2 | 26 + .../sol.rb | 26 + .../sol.rs | 44 + .../sol.swift | 29 + .../sol.ts | 34 + .../manifest.yaml | 197 +++ .../sol.cpp | 33 + .../sol.cs | 34 + .../sol.dart | 39 + .../sol.go | 40 + .../sol.java | 34 + .../sol.kt | 32 + .../sol.py | 26 + .../sol.py2 | 26 + .../sol.rb | 32 + .../sol.rs | 32 + .../sol.swift | 32 + .../sol.ts | 30 + .../manifest.yaml | 423 +++++ .../1672. richest-customer-wealth/sol.cpp | 14 + .../1672. richest-customer-wealth/sol.cs | 13 + .../1672. richest-customer-wealth/sol.dart | 10 + .../1672. richest-customer-wealth/sol.go | 13 + .../1672. richest-customer-wealth/sol.java | 13 + .../1672. richest-customer-wealth/sol.kt | 9 + .../1672. richest-customer-wealth/sol.py | 6 + .../1672. richest-customer-wealth/sol.py2 | 10 + .../1672. richest-customer-wealth/sol.rb | 9 + .../1672. richest-customer-wealth/sol.rs | 9 + .../1672. richest-customer-wealth/sol.swift | 9 + .../1672. richest-customer-wealth/sol.ts | 10 + .../manifest.yaml | 321 ++++ .../sol.cpp | 18 + .../sol.cs | 17 + .../sol.dart | 17 + .../sol.go | 15 + .../sol.java | 21 + .../sol.kt | 17 + .../sol.py | 15 + .../sol.py2 | 17 + .../sol.rb | 18 + .../sol.rs | 19 + .../sol.swift | 17 + .../sol.ts | 15 + .../manifest.yaml | 316 ++++ .../sol.cpp | 33 + .../sol.cs | 32 + .../sol.dart | 32 + .../sol.go | 46 + .../sol.java | 32 + .../sol.kt | 32 + .../sol.py | 37 + .../sol.py2 | 33 + .../sol.rb | 33 + .../sol.rs | 32 + .../sol.swift | 32 + .../sol.ts | 30 + .../manifest.yaml | 238 +++ .../1675. minimize-deviation-in-array/sol.cpp | 32 + .../1675. minimize-deviation-in-array/sol.cs | 31 + .../sol.dart | 30 + .../1675. minimize-deviation-in-array/sol.go | 42 + .../sol.java | 32 + .../1675. minimize-deviation-in-array/sol.kt | 30 + .../1675. minimize-deviation-in-array/sol.py | 29 + .../1675. minimize-deviation-in-array/sol.py2 | 32 + .../1675. minimize-deviation-in-array/sol.rb | 49 + .../1675. minimize-deviation-in-array/sol.rs | 35 + .../sol.swift | 31 + .../1675. minimize-deviation-in-array/sol.ts | 51 + .../manifest.yaml | 190 +++ .../1678. goal-parser-interpretation/sol.cpp | 20 + .../1678. goal-parser-interpretation/sol.cs | 19 + .../1678. goal-parser-interpretation/sol.dart | 19 + .../1678. goal-parser-interpretation/sol.go | 17 + .../1678. goal-parser-interpretation/sol.java | 19 + .../1678. goal-parser-interpretation/sol.kt | 19 + .../1678. goal-parser-interpretation/sol.py | 20 + .../1678. goal-parser-interpretation/sol.py2 | 19 + .../1678. goal-parser-interpretation/sol.rb | 19 + .../1678. goal-parser-interpretation/sol.rs | 20 + .../sol.swift | 20 + .../1678. goal-parser-interpretation/sol.ts | 17 + .../manifest.yaml | 325 ++++ .../1679. max-number-of-k-sum-pairs/sol.cpp | 23 + .../1679. max-number-of-k-sum-pairs/sol.cs | 22 + .../1679. max-number-of-k-sum-pairs/sol.dart | 21 + .../1679. max-number-of-k-sum-pairs/sol.go | 20 + .../1679. max-number-of-k-sum-pairs/sol.java | 22 + .../1679. max-number-of-k-sum-pairs/sol.kt | 23 + .../1679. max-number-of-k-sum-pairs/sol.py | 18 + .../1679. max-number-of-k-sum-pairs/sol.py2 | 23 + .../1679. max-number-of-k-sum-pairs/sol.rb | 23 + .../1679. max-number-of-k-sum-pairs/sol.rs | 23 + .../1679. max-number-of-k-sum-pairs/sol.swift | 23 + .../1679. max-number-of-k-sum-pairs/sol.ts | 21 + .../manifest.yaml | 197 +++ .../sol.cpp | 17 + .../sol.cs | 16 + .../sol.dart | 12 + .../sol.go | 14 + .../sol.java | 16 + .../sol.kt | 16 + .../sol.py | 12 + .../sol.py2 | 16 + .../sol.rb | 16 + .../sol.rs | 16 + .../sol.swift | 16 + .../sol.ts | 14 + .../manifest.yaml | 270 ++++ .../1681. minimum-incompatibility/sol.cpp | 59 + .../1681. minimum-incompatibility/sol.cs | 70 + .../1681. minimum-incompatibility/sol.dart | 58 + .../1681. minimum-incompatibility/sol.go | 79 + .../1681. minimum-incompatibility/sol.java | 59 + .../1681. minimum-incompatibility/sol.kt | 51 + .../1681. minimum-incompatibility/sol.py | 46 + .../1681. minimum-incompatibility/sol.py2 | 40 + .../1681. minimum-incompatibility/sol.rb | 46 + .../1681. minimum-incompatibility/sol.rs | 62 + .../1681. minimum-incompatibility/sol.swift | 61 + .../1681. minimum-incompatibility/sol.ts | 66 + .../manifest.yaml | 283 ++++ .../sol.cpp | 18 + .../sol.cs | 17 + .../sol.dart | 10 + .../sol.go | 20 + .../sol.java | 22 + .../sol.kt | 17 + .../sol.py | 13 + .../sol.py2 | 18 + .../sol.rb | 18 + .../sol.rs | 19 + .../sol.swift | 19 + .../sol.ts | 15 + .../manifest.yaml | 298 ++++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 17 + .../sol.go | 16 + .../sol.java | 15 + .../sol.kt | 15 + .../sol.py | 18 + .../sol.py2 | 17 + .../sol.rb | 15 + .../sol.rs | 17 + .../sol.swift | 15 + .../sol.ts | 13 + .../1686. stone-game-vi/manifest.yaml | 356 +++++ tests/1501-2000/1686. stone-game-vi/sol.cpp | 28 + tests/1501-2000/1686. stone-game-vi/sol.cs | 23 + tests/1501-2000/1686. stone-game-vi/sol.dart | 20 + tests/1501-2000/1686. stone-game-vi/sol.go | 31 + tests/1501-2000/1686. stone-game-vi/sol.java | 25 + tests/1501-2000/1686. stone-game-vi/sol.kt | 28 + tests/1501-2000/1686. stone-game-vi/sol.py | 24 + tests/1501-2000/1686. stone-game-vi/sol.py2 | 24 + tests/1501-2000/1686. stone-game-vi/sol.rb | 25 + tests/1501-2000/1686. stone-game-vi/sol.rs | 27 + tests/1501-2000/1686. stone-game-vi/sol.swift | 23 + tests/1501-2000/1686. stone-game-vi/sol.ts | 26 + .../manifest.yaml | 517 +++++++ .../sol.cpp | 40 + .../sol.cs | 39 + .../sol.dart | 38 + .../sol.go | 41 + .../sol.java | 39 + .../sol.kt | 39 + .../sol.py | 37 + .../sol.py2 | 37 + .../sol.rb | 34 + .../sol.rs | 39 + .../sol.swift | 40 + .../sol.ts | 47 + .../manifest.yaml | 208 +++ .../sol.cpp | 6 + .../sol.cs | 5 + .../sol.dart | 5 + .../sol.go | 3 + .../sol.java | 5 + .../sol.kt | 5 + .../sol.py | 3 + .../sol.py2 | 7 + .../sol.rb | 5 + .../sol.rs | 5 + .../sol.swift | 5 + .../sol.ts | 3 + .../manifest.yaml | 192 +++ .../sol.cpp | 10 + .../sol.cs | 9 + .../sol.dart | 10 + .../sol.go | 9 + .../sol.java | 9 + .../sol.kt | 5 + .../sol.py | 3 + .../sol.py2 | 7 + .../sol.rb | 5 + .../sol.rs | 5 + .../sol.swift | 5 + .../sol.ts | 3 + .../1690. stone-game-vii/manifest.yaml | 235 +++ tests/1501-2000/1690. stone-game-vii/sol.cpp | 26 + tests/1501-2000/1690. stone-game-vii/sol.cs | 25 + tests/1501-2000/1690. stone-game-vii/sol.dart | 20 + tests/1501-2000/1690. stone-game-vii/sol.go | 30 + tests/1501-2000/1690. stone-game-vii/sol.java | 25 + tests/1501-2000/1690. stone-game-vii/sol.kt | 25 + tests/1501-2000/1690. stone-game-vii/sol.py | 23 + tests/1501-2000/1690. stone-game-vii/sol.py2 | 24 + tests/1501-2000/1690. stone-game-vii/sol.rb | 25 + tests/1501-2000/1690. stone-game-vii/sol.rs | 25 + .../1501-2000/1690. stone-game-vii/sol.swift | 27 + tests/1501-2000/1690. stone-game-vii/sol.ts | 23 + .../manifest.yaml | 384 +++++ .../sol.cpp | 22 + .../sol.cs | 25 + .../sol.dart | 29 + .../sol.go | 31 + .../sol.java | 25 + .../sol.kt | 19 + .../sol.py | 17 + .../sol.py2 | 17 + .../sol.rb | 17 + .../sol.rs | 26 + .../sol.swift | 26 + .../sol.ts | 25 + .../1694. reformat-phone-number/manifest.yaml | 212 +++ .../1694. reformat-phone-number/sol.cpp | 29 + .../1694. reformat-phone-number/sol.cs | 20 + .../1694. reformat-phone-number/sol.dart | 20 + .../1694. reformat-phone-number/sol.go | 22 + .../1694. reformat-phone-number/sol.java | 19 + .../1694. reformat-phone-number/sol.kt | 20 + .../1694. reformat-phone-number/sol.py | 14 + .../1694. reformat-phone-number/sol.py2 | 18 + .../1694. reformat-phone-number/sol.rb | 20 + .../1694. reformat-phone-number/sol.rs | 21 + .../1694. reformat-phone-number/sol.swift | 20 + .../1694. reformat-phone-number/sol.ts | 18 + .../1695. maximum-erasure-value/manifest.yaml | 234 +++ .../1695. maximum-erasure-value/sol.cpp | 25 + .../1695. maximum-erasure-value/sol.cs | 24 + .../1695. maximum-erasure-value/sol.dart | 26 + .../1695. maximum-erasure-value/sol.go | 24 + .../1695. maximum-erasure-value/sol.java | 24 + .../1695. maximum-erasure-value/sol.kt | 24 + .../1695. maximum-erasure-value/sol.py | 20 + .../1695. maximum-erasure-value/sol.py2 | 24 + .../1695. maximum-erasure-value/sol.rb | 24 + .../1695. maximum-erasure-value/sol.rs | 24 + .../1695. maximum-erasure-value/sol.swift | 24 + .../1695. maximum-erasure-value/sol.ts | 22 + .../1696. jump-game-vi/manifest.yaml | 269 ++++ tests/1501-2000/1696. jump-game-vi/sol.cpp | 21 + tests/1501-2000/1696. jump-game-vi/sol.cs | 20 + tests/1501-2000/1696. jump-game-vi/sol.dart | 20 + tests/1501-2000/1696. jump-game-vi/sol.go | 18 + tests/1501-2000/1696. jump-game-vi/sol.java | 20 + tests/1501-2000/1696. jump-game-vi/sol.kt | 20 + tests/1501-2000/1696. jump-game-vi/sol.py | 30 + tests/1501-2000/1696. jump-game-vi/sol.py2 | 20 + tests/1501-2000/1696. jump-game-vi/sol.rb | 19 + tests/1501-2000/1696. jump-game-vi/sol.rs | 30 + tests/1501-2000/1696. jump-game-vi/sol.swift | 20 + tests/1501-2000/1696. jump-game-vi/sol.ts | 18 + .../manifest.yaml | 643 ++++++++ .../sol.cpp | 55 + .../sol.cs | 51 + .../sol.dart | 49 + .../sol.go | 57 + .../sol.java | 55 + .../sol.kt | 53 + .../sol.py | 46 + .../sol.py2 | 45 + .../sol.rb | 48 + .../sol.rs | 50 + .../sol.swift | 49 + .../sol.ts | 53 + .../manifest.yaml | 379 +++++ .../sol.cpp | 12 + .../sol.cs | 21 + .../sol.dart | 19 + .../sol.go | 21 + .../sol.java | 21 + .../sol.kt | 19 + .../sol.py | 14 + .../sol.py2 | 19 + .../sol.rb | 18 + .../sol.rs | 20 + .../sol.swift | 19 + .../sol.ts | 17 + .../1701. average-waiting-time/manifest.yaml | 315 ++++ .../1701. average-waiting-time/sol.cpp | 19 + .../1701. average-waiting-time/sol.cs | 18 + .../1701. average-waiting-time/sol.dart | 18 + .../1701. average-waiting-time/sol.go | 15 + .../1701. average-waiting-time/sol.java | 18 + .../1701. average-waiting-time/sol.kt | 18 + .../1701. average-waiting-time/sol.py | 11 + .../1701. average-waiting-time/sol.py2 | 16 + .../1701. average-waiting-time/sol.rb | 14 + .../1701. average-waiting-time/sol.rs | 19 + .../1701. average-waiting-time/sol.swift | 18 + .../1701. average-waiting-time/sol.ts | 14 + .../manifest.yaml | 171 +++ .../sol.cpp | 17 + .../sol.cs | 13 + .../sol.dart | 13 + .../sol.go | 13 + .../sol.java | 16 + .../sol.kt | 13 + .../sol.py | 16 + .../sol.py2 | 16 + .../sol.rb | 13 + .../sol.rs | 15 + .../sol.swift | 16 + .../sol.ts | 11 + .../manifest.yaml | 421 +++++ .../sol.cpp | 35 + .../sol.cs | 34 + .../sol.dart | 38 + .../sol.go | 41 + .../sol.java | 34 + .../sol.kt | 34 + .../sol.py | 72 + .../sol.py2 | 34 + .../sol.rb | 39 + .../sol.rs | 32 + .../sol.swift | 38 + .../sol.ts | 32 + .../manifest.yaml | 199 +++ .../sol.cpp | 15 + .../sol.cs | 14 + .../sol.dart | 14 + .../sol.go | 16 + .../sol.java | 18 + .../sol.kt | 14 + .../sol.py | 20 + .../sol.py2 | 16 + .../sol.rb | 14 + .../sol.rs | 15 + .../sol.swift | 15 + .../sol.ts | 12 + .../manifest.yaml | 266 ++++ .../sol.cpp | 31 + .../sol.cs | 25 + .../sol.dart | 27 + .../sol.go | 45 + .../sol.java | 26 + .../sol.kt | 25 + .../sol.py | 21 + .../sol.py2 | 25 + .../sol.rb | 29 + .../sol.rs | 27 + .../sol.swift | 27 + .../sol.ts | 25 + .../manifest.yaml | 370 +++++ .../1706. where-will-the-ball-fall/sol.cpp | 21 + .../1706. where-will-the-ball-fall/sol.cs | 20 + .../1706. where-will-the-ball-fall/sol.dart | 20 + .../1706. where-will-the-ball-fall/sol.go | 19 + .../1706. where-will-the-ball-fall/sol.java | 20 + .../1706. where-will-the-ball-fall/sol.kt | 21 + .../1706. where-will-the-ball-fall/sol.py | 20 + .../1706. where-will-the-ball-fall/sol.py2 | 19 + .../1706. where-will-the-ball-fall/sol.rb | 19 + .../1706. where-will-the-ball-fall/sol.rs | 21 + .../1706. where-will-the-ball-fall/sol.swift | 20 + .../1706. where-will-the-ball-fall/sol.ts | 19 + .../manifest.yaml | 488 ++++++ .../sol.cpp | 53 + .../sol.cs | 52 + .../sol.dart | 55 + .../sol.go | 55 + .../sol.java | 55 + .../sol.kt | 53 + .../sol.py | 49 + .../sol.py2 | 49 + .../sol.rb | 72 + .../sol.rs | 51 + .../sol.swift | 50 + .../sol.ts | 48 + .../manifest.yaml | 423 +++++ .../1710. maximum-units-on-a-truck/sol.cpp | 17 + .../1710. maximum-units-on-a-truck/sol.cs | 14 + .../1710. maximum-units-on-a-truck/sol.dart | 14 + .../1710. maximum-units-on-a-truck/sol.go | 19 + .../1710. maximum-units-on-a-truck/sol.java | 13 + .../1710. maximum-units-on-a-truck/sol.kt | 14 + .../1710. maximum-units-on-a-truck/sol.py | 36 + .../1710. maximum-units-on-a-truck/sol.py2 | 16 + .../1710. maximum-units-on-a-truck/sol.rb | 14 + .../1710. maximum-units-on-a-truck/sol.rs | 15 + .../1710. maximum-units-on-a-truck/sol.swift | 14 + .../1710. maximum-units-on-a-truck/sol.ts | 12 + .../1711. count-good-meals/manifest.yaml | 246 +++ .../1501-2000/1711. count-good-meals/sol.cpp | 25 + tests/1501-2000/1711. count-good-meals/sol.cs | 25 + .../1501-2000/1711. count-good-meals/sol.dart | 24 + tests/1501-2000/1711. count-good-meals/sol.go | 28 + .../1501-2000/1711. count-good-meals/sol.java | 24 + tests/1501-2000/1711. count-good-meals/sol.kt | 21 + tests/1501-2000/1711. count-good-meals/sol.py | 23 + .../1501-2000/1711. count-good-meals/sol.py2 | 23 + tests/1501-2000/1711. count-good-meals/sol.rb | 19 + tests/1501-2000/1711. count-good-meals/sol.rs | 21 + .../1711. count-good-meals/sol.swift | 24 + tests/1501-2000/1711. count-good-meals/sol.ts | 21 + .../manifest.yaml | 237 +++ .../sol.cpp | 51 + .../sol.cs | 49 + .../sol.dart | 49 + .../sol.go | 47 + .../sol.java | 47 + .../sol.kt | 51 + .../sol.py | 27 + .../sol.py2 | 42 + .../sol.rb | 45 + .../sol.rs | 51 + .../sol.swift | 49 + .../sol.ts | 64 + .../manifest.yaml | 312 ++++ .../sol.cpp | 28 + .../sol.cs | 28 + .../sol.dart | 40 + .../sol.go | 25 + .../sol.java | 32 + .../sol.kt | 25 + .../sol.py | 24 + .../sol.py2 | 23 + .../sol.rb | 28 + .../sol.rs | 19 + .../sol.swift | 33 + .../sol.ts | 35 + .../manifest.yaml | 200 +++ .../sol.cpp | 12 + .../sol.cs | 10 + .../sol.dart | 10 + .../sol.go | 9 + .../sol.java | 10 + .../sol.kt | 10 + .../sol.py | 9 + .../sol.py2 | 10 + .../sol.rb | 7 + .../sol.rs | 10 + .../sol.swift | 10 + .../sol.ts | 16 + .../manifest.yaml | 317 ++++ .../sol.cpp | 39 + .../sol.cs | 38 + .../sol.dart | 39 + .../sol.go | 40 + .../sol.java | 38 + .../sol.kt | 42 + .../sol.py | 27 + .../sol.py2 | 33 + .../sol.rb | 36 + .../sol.rs | 42 + .../sol.swift | 42 + .../sol.ts | 38 + .../manifest.yaml | 265 ++++ .../sol.cpp | 46 + .../sol.cs | 44 + .../sol.dart | 38 + .../sol.go | 44 + .../sol.java | 43 + .../sol.kt | 38 + .../sol.py | 37 + .../sol.py2 | 39 + .../sol.rb | 41 + .../sol.rs | 47 + .../sol.swift | 46 + .../sol.ts | 47 + .../manifest.yaml | 429 ++++++ .../sol.cpp | 41 + .../sol.cs | 39 + .../sol.dart | 27 + .../sol.go | 45 + .../sol.java | 40 + .../sol.kt | 24 + .../sol.py | 30 + .../sol.py2 | 31 + .../sol.rb | 26 + .../sol.rs | 27 + .../sol.swift | 25 + .../sol.ts | 39 + .../1720. decode-xored-array/manifest.yaml | 271 ++++ .../1720. decode-xored-array/sol.cpp | 10 + .../1501-2000/1720. decode-xored-array/sol.cs | 10 + .../1720. decode-xored-array/sol.dart | 9 + .../1501-2000/1720. decode-xored-array/sol.go | 8 + .../1720. decode-xored-array/sol.java | 10 + .../1501-2000/1720. decode-xored-array/sol.kt | 10 + .../1501-2000/1720. decode-xored-array/sol.py | 6 + .../1720. decode-xored-array/sol.py2 | 11 + .../1501-2000/1720. decode-xored-array/sol.rb | 10 + .../1501-2000/1720. decode-xored-array/sol.rs | 9 + .../1720. decode-xored-array/sol.swift | 9 + .../1501-2000/1720. decode-xored-array/sol.ts | 7 + .../manifest.yaml | 523 +++++++ .../sol.cpp | 59 + .../sol.cs | 59 + .../sol.dart | 52 + .../sol.go | 53 + .../sol.java | 58 + .../sol.kt | 53 + .../sol.py | 44 + .../sol.py2 | 49 + .../sol.rb | 47 + .../sol.rs | 20 + .../sol.swift | 54 + .../sol.ts | 58 + .../manifest.yaml | 485 ++++++ .../sol.cpp | 47 + .../sol.cs | 50 + .../sol.dart | 48 + .../sol.go | 50 + .../sol.java | 49 + .../sol.kt | 41 + .../sol.py | 36 + .../sol.py2 | 37 + .../sol.rb | 41 + .../sol.rs | 52 + .../sol.swift | 47 + .../sol.ts | 52 + .../manifest.yaml | 244 +++ .../sol.cpp | 35 + .../sol.cs | 35 + .../sol.dart | 36 + .../sol.go | 43 + .../sol.java | 42 + .../sol.kt | 36 + .../sol.py | 37 + .../sol.py2 | 36 + .../sol.rb | 37 + .../sol.rs | 42 + .../sol.swift | 42 + .../sol.ts | 34 + .../manifest.yaml | 407 +++++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 15 + .../sol.go | 23 + .../sol.java | 15 + .../sol.kt | 6 + .../sol.py | 4 + .../sol.py2 | 8 + .../sol.rb | 6 + .../sol.rs | 6 + .../sol.swift | 6 + .../sol.ts | 4 + .../manifest.yaml | 209 +++ .../1726. tuple-with-same-product/sol.cpp | 17 + .../1726. tuple-with-same-product/sol.cs | 16 + .../1726. tuple-with-same-product/sol.dart | 16 + .../1726. tuple-with-same-product/sol.go | 14 + .../1726. tuple-with-same-product/sol.java | 16 + .../1726. tuple-with-same-product/sol.kt | 16 + .../1726. tuple-with-same-product/sol.py | 15 + .../1726. tuple-with-same-product/sol.py2 | 17 + .../1726. tuple-with-same-product/sol.rb | 16 + .../1726. tuple-with-same-product/sol.rs | 18 + .../1726. tuple-with-same-product/sol.swift | 16 + .../1726. tuple-with-same-product/sol.ts | 14 + .../manifest.yaml | 425 +++++ .../sol.cpp | 28 + .../sol.cs | 25 + .../sol.dart | 23 + .../sol.go | 27 + .../sol.java | 30 + .../sol.kt | 23 + .../sol.py | 20 + .../sol.py2 | 21 + .../sol.rb | 21 + .../sol.rs | 26 + .../sol.swift | 23 + .../sol.ts | 21 + .../1728. cat-and-mouse-ii/manifest.yaml | 394 +++++ .../1501-2000/1728. cat-and-mouse-ii/sol.cpp | 75 + tests/1501-2000/1728. cat-and-mouse-ii/sol.cs | 83 + .../1501-2000/1728. cat-and-mouse-ii/sol.dart | 71 + tests/1501-2000/1728. cat-and-mouse-ii/sol.go | 82 + .../1501-2000/1728. cat-and-mouse-ii/sol.java | 83 + tests/1501-2000/1728. cat-and-mouse-ii/sol.kt | 89 ++ tests/1501-2000/1728. cat-and-mouse-ii/sol.py | 45 + .../1501-2000/1728. cat-and-mouse-ii/sol.py2 | 59 + tests/1501-2000/1728. cat-and-mouse-ii/sol.rb | 65 + tests/1501-2000/1728. cat-and-mouse-ii/sol.rs | 95 ++ .../1728. cat-and-mouse-ii/sol.swift | 91 ++ tests/1501-2000/1728. cat-and-mouse-ii/sol.ts | 85 + .../manifest.yaml | 243 +++ .../1732. find-the-highest-altitude/sol.cpp | 12 + .../1732. find-the-highest-altitude/sol.cs | 11 + .../1732. find-the-highest-altitude/sol.dart | 11 + .../1732. find-the-highest-altitude/sol.go | 9 + .../1732. find-the-highest-altitude/sol.java | 11 + .../1732. find-the-highest-altitude/sol.kt | 11 + .../1732. find-the-highest-altitude/sol.py | 10 + .../1732. find-the-highest-altitude/sol.py2 | 12 + .../1732. find-the-highest-altitude/sol.rb | 11 + .../1732. find-the-highest-altitude/sol.rs | 12 + .../1732. find-the-highest-altitude/sol.swift | 12 + .../1732. find-the-highest-altitude/sol.ts | 10 + .../manifest.yaml | 574 +++++++ .../sol.cpp | 42 + .../sol.cs | 41 + .../sol.dart | 35 + .../sol.go | 45 + .../sol.java | 43 + .../sol.kt | 41 + .../sol.py | 30 + .../sol.py2 | 30 + .../sol.rb | 33 + .../sol.rs | 35 + .../sol.swift | 33 + .../sol.ts | 35 + .../manifest.yaml | 642 ++++++++ .../1734. decode-xored-permutation/sol.cpp | 18 + .../1734. decode-xored-permutation/sol.cs | 17 + .../1734. decode-xored-permutation/sol.dart | 17 + .../1734. decode-xored-permutation/sol.go | 19 + .../1734. decode-xored-permutation/sol.java | 17 + .../1734. decode-xored-permutation/sol.kt | 17 + .../1734. decode-xored-permutation/sol.py | 17 + .../1734. decode-xored-permutation/sol.py2 | 18 + .../1734. decode-xored-permutation/sol.rb | 16 + .../1734. decode-xored-permutation/sol.rs | 17 + .../1734. decode-xored-permutation/sol.swift | 17 + .../1734. decode-xored-permutation/sol.ts | 15 + .../manifest.yaml | 328 ++++ .../sol.cpp | 42 + .../sol.cs | 45 + .../sol.dart | 41 + .../sol.go | 46 + .../sol.java | 42 + .../sol.kt | 42 + .../sol.py | 26 + .../sol.py2 | 36 + .../sol.rb | 39 + .../sol.rs | 49 + .../sol.swift | 47 + .../sol.ts | 48 + .../manifest.yaml | 204 +++ .../sol.cpp | 35 + .../sol.cs | 34 + .../sol.dart | 34 + .../sol.go | 32 + .../sol.java | 35 + .../sol.kt | 34 + .../sol.py | 35 + .../sol.py2 | 34 + .../sol.rb | 37 + .../sol.rs | 35 + .../sol.swift | 35 + .../sol.ts | 32 + .../manifest.yaml | 251 +++ .../sol.cpp | 28 + .../sol.cs | 27 + .../sol.dart | 32 + .../sol.go | 36 + .../sol.java | 31 + .../sol.kt | 28 + .../sol.py | 30 + .../sol.py2 | 30 + .../sol.rb | 28 + .../sol.rs | 32 + .../sol.swift | 31 + .../sol.ts | 30 + .../manifest.yaml | 370 +++++ .../sol.cpp | 23 + .../sol.cs | 24 + .../sol.dart | 25 + .../sol.go | 30 + .../sol.java | 24 + .../sol.kt | 24 + .../sol.py | 76 + .../sol.py2 | 23 + .../sol.rb | 19 + .../sol.rs | 25 + .../sol.swift | 25 + .../sol.ts | 17 + .../1739. building-boxes/manifest.yaml | 204 +++ tests/1501-2000/1739. building-boxes/sol.cpp | 15 + tests/1501-2000/1739. building-boxes/sol.cs | 14 + tests/1501-2000/1739. building-boxes/sol.dart | 14 + tests/1501-2000/1739. building-boxes/sol.go | 15 + tests/1501-2000/1739. building-boxes/sol.java | 14 + tests/1501-2000/1739. building-boxes/sol.kt | 15 + tests/1501-2000/1739. building-boxes/sol.py | 16 + tests/1501-2000/1739. building-boxes/sol.py2 | 19 + tests/1501-2000/1739. building-boxes/sol.rb | 17 + tests/1501-2000/1739. building-boxes/sol.rs | 14 + .../1501-2000/1739. building-boxes/sol.swift | 18 + tests/1501-2000/1739. building-boxes/sol.ts | 15 + .../manifest.yaml | 261 ++++ .../sol.cpp | 18 + .../sol.cs | 12 + .../sol.dart | 14 + .../sol.go | 17 + .../sol.java | 17 + .../sol.kt | 12 + .../sol.py | 13 + .../sol.py2 | 15 + .../sol.rb | 13 + .../sol.rs | 13 + .../sol.swift | 12 + .../sol.ts | 12 + .../manifest.yaml | 401 +++++ .../sol.cpp | 36 + .../sol.cs | 35 + .../sol.dart | 35 + .../sol.go | 33 + .../sol.java | 35 + .../sol.kt | 36 + .../sol.py | 31 + .../sol.py2 | 34 + .../sol.rb | 32 + .../sol.rs | 37 + .../sol.swift | 35 + .../sol.ts | 32 + .../manifest.yaml | 487 ++++++ .../sol.cpp | 21 + .../sol.cs | 20 + .../sol.dart | 20 + .../sol.go | 16 + .../sol.java | 20 + .../sol.kt | 20 + .../sol.py | 21 + .../sol.py2 | 19 + .../sol.rb | 20 + .../sol.rs | 20 + .../sol.swift | 20 + .../sol.ts | 18 + .../manifest.yaml | 224 +++ .../1745. palindrome-partitioning-iv/sol.cpp | 24 + .../1745. palindrome-partitioning-iv/sol.cs | 26 + .../1745. palindrome-partitioning-iv/sol.dart | 23 + .../1745. palindrome-partitioning-iv/sol.go | 26 + .../1745. palindrome-partitioning-iv/sol.java | 23 + .../1745. palindrome-partitioning-iv/sol.kt | 23 + .../1745. palindrome-partitioning-iv/sol.py | 17 + .../1745. palindrome-partitioning-iv/sol.py2 | 21 + .../1745. palindrome-partitioning-iv/sol.rb | 23 + .../1745. palindrome-partitioning-iv/sol.rs | 28 + .../sol.swift | 28 + .../1745. palindrome-partitioning-iv/sol.ts | 23 + .../manifest.yaml | 231 +++ .../1748. sum-of-unique-elements/sol.cpp | 14 + .../1748. sum-of-unique-elements/sol.cs | 13 + .../1748. sum-of-unique-elements/sol.dart | 9 + .../1748. sum-of-unique-elements/sol.go | 11 + .../1748. sum-of-unique-elements/sol.java | 13 + .../1748. sum-of-unique-elements/sol.kt | 9 + .../1748. sum-of-unique-elements/sol.py | 7 + .../1748. sum-of-unique-elements/sol.py2 | 11 + .../1748. sum-of-unique-elements/sol.rb | 11 + .../1748. sum-of-unique-elements/sol.rs | 11 + .../1748. sum-of-unique-elements/sol.swift | 9 + .../1748. sum-of-unique-elements/sol.ts | 7 + .../manifest.yaml | 231 +++ .../sol.cpp | 21 + .../sol.cs | 20 + .../sol.dart | 20 + .../sol.go | 26 + .../sol.java | 20 + .../sol.kt | 20 + .../sol.py | 19 + .../sol.py2 | 21 + .../sol.rb | 20 + .../sol.rs | 20 + .../sol.swift | 20 + .../sol.ts | 24 + .../manifest.yaml | 205 +++ .../sol.cpp | 17 + .../sol.cs | 16 + .../sol.dart | 16 + .../sol.go | 17 + .../sol.java | 16 + .../sol.kt | 16 + .../sol.py | 10 + .../sol.py2 | 14 + .../sol.rb | 16 + .../sol.rs | 17 + .../sol.swift | 17 + .../sol.ts | 14 + .../manifest.yaml | 432 ++++++ .../sol.cpp | 36 + .../sol.cs | 32 + .../sol.dart | 34 + .../sol.go | 40 + .../sol.java | 31 + .../sol.kt | 33 + .../sol.py | 41 + .../sol.py2 | 30 + .../sol.rb | 33 + .../sol.rs | 36 + .../sol.swift | 33 + .../sol.ts | 36 + .../manifest.yaml | 217 +++ .../sol.cpp | 13 + .../sol.cs | 12 + .../sol.dart | 12 + .../sol.go | 10 + .../sol.java | 12 + .../sol.kt | 12 + .../sol.py | 11 + .../sol.py2 | 12 + .../sol.rb | 10 + .../sol.rs | 12 + .../sol.swift | 12 + .../sol.ts | 10 + .../manifest.yaml | 304 ++++ .../sol.cpp | 7 + .../sol.cs | 6 + .../sol.dart | 8 + .../sol.go | 14 + .../sol.java | 6 + .../sol.kt | 6 + .../sol.py | 3 + .../sol.py2 | 9 + .../sol.rb | 7 + .../sol.rs | 6 + .../sol.swift | 6 + .../sol.ts | 4 + .../manifest.yaml | 262 ++++ .../sol.cpp | 38 + .../1754. largest-merge-of-two-strings/sol.cs | 37 + .../sol.dart | 37 + .../1754. largest-merge-of-two-strings/sol.go | 35 + .../sol.java | 37 + .../1754. largest-merge-of-two-strings/sol.kt | 39 + .../1754. largest-merge-of-two-strings/sol.py | 35 + .../sol.py2 | 29 + .../1754. largest-merge-of-two-strings/sol.rb | 40 + .../1754. largest-merge-of-two-strings/sol.rs | 41 + .../sol.swift | 39 + .../1754. largest-merge-of-two-strings/sol.ts | 37 + .../manifest.yaml | 275 ++++ .../1755. closest-subsequence-sum/sol.cpp | 32 + .../1755. closest-subsequence-sum/sol.cs | 31 + .../1755. closest-subsequence-sum/sol.dart | 30 + .../1755. closest-subsequence-sum/sol.go | 43 + .../1755. closest-subsequence-sum/sol.java | 32 + .../1755. closest-subsequence-sum/sol.kt | 29 + .../1755. closest-subsequence-sum/sol.py | 20 + .../1755. closest-subsequence-sum/sol.py2 | 24 + .../1755. closest-subsequence-sum/sol.rb | 27 + .../1755. closest-subsequence-sum/sol.rs | 31 + .../1755. closest-subsequence-sum/sol.swift | 29 + .../1755. closest-subsequence-sum/sol.ts | 27 + .../manifest.yaml | 219 +++ .../sol.cpp | 13 + .../sol.cs | 12 + .../sol.dart | 12 + .../sol.go | 15 + .../sol.java | 12 + .../sol.kt | 14 + .../sol.py | 8 + .../sol.py2 | 14 + .../sol.rb | 14 + .../sol.rs | 15 + .../sol.swift | 16 + .../sol.ts | 12 + .../manifest.yaml | 204 +++ .../sol.cpp | 17 + .../sol.cs | 16 + .../sol.dart | 16 + .../sol.go | 14 + .../sol.java | 16 + .../sol.kt | 16 + .../sol.py | 11 + .../sol.py2 | 15 + .../sol.rb | 16 + .../sol.rs | 17 + .../sol.swift | 17 + .../sol.ts | 14 + .../manifest.yaml | 281 ++++ .../sol.cpp | 19 + .../sol.cs | 18 + .../sol.dart | 18 + .../sol.go | 19 + .../sol.java | 14 + .../sol.kt | 14 + .../sol.py | 26 + .../sol.py2 | 16 + .../sol.rb | 16 + .../sol.rs | 16 + .../sol.swift | 19 + .../sol.ts | 17 + .../manifest.yaml | 338 ++++ .../sol.cpp | 23 + .../sol.cs | 22 + .../sol.dart | 23 + .../sol.go | 29 + .../sol.java | 22 + .../sol.kt | 22 + .../sol.py | 39 + .../sol.py2 | 19 + .../sol.rb | 22 + .../sol.rs | 26 + .../sol.swift | 22 + .../sol.ts | 21 + .../manifest.yaml | 204 +++ .../1763. longest-nice-substring/sol.cpp | 34 + .../1763. longest-nice-substring/sol.cs | 33 + .../1763. longest-nice-substring/sol.dart | 33 + .../1763. longest-nice-substring/sol.go | 40 + .../1763. longest-nice-substring/sol.java | 33 + .../1763. longest-nice-substring/sol.kt | 33 + .../1763. longest-nice-substring/sol.py | 35 + .../1763. longest-nice-substring/sol.py2 | 36 + .../1763. longest-nice-substring/sol.rb | 32 + .../1763. longest-nice-substring/sol.rs | 45 + .../1763. longest-nice-substring/sol.swift | 39 + .../1763. longest-nice-substring/sol.ts | 33 + .../manifest.yaml | 284 ++++ .../sol.cpp | 27 + .../sol.cs | 26 + .../sol.dart | 26 + .../sol.go | 26 + .../sol.java | 26 + .../sol.kt | 26 + .../sol.py | 20 + .../sol.py2 | 20 + .../sol.rb | 20 + .../sol.rs | 28 + .../sol.swift | 28 + .../sol.ts | 24 + .../1765. map-of-highest-peak/manifest.yaml | 1368 +++++++++++++++++ .../1765. map-of-highest-peak/sol.cpp | 28 + .../1765. map-of-highest-peak/sol.cs | 31 + .../1765. map-of-highest-peak/sol.dart | 27 + .../1765. map-of-highest-peak/sol.go | 40 + .../1765. map-of-highest-peak/sol.java | 28 + .../1765. map-of-highest-peak/sol.kt | 27 + .../1765. map-of-highest-peak/sol.py | 24 + .../1765. map-of-highest-peak/sol.py2 | 28 + .../1765. map-of-highest-peak/sol.rb | 27 + .../1765. map-of-highest-peak/sol.rs | 27 + .../1765. map-of-highest-peak/sol.swift | 27 + .../1765. map-of-highest-peak/sol.ts | 29 + .../1766. tree-of-coprimes/manifest.yaml | 803 ++++++++++ .../1501-2000/1766. tree-of-coprimes/sol.cpp | 45 + tests/1501-2000/1766. tree-of-coprimes/sol.cs | 52 + .../1501-2000/1766. tree-of-coprimes/sol.dart | 50 + tests/1501-2000/1766. tree-of-coprimes/sol.go | 53 + .../1501-2000/1766. tree-of-coprimes/sol.java | 47 + tests/1501-2000/1766. tree-of-coprimes/sol.kt | 42 + tests/1501-2000/1766. tree-of-coprimes/sol.py | 36 + .../1501-2000/1766. tree-of-coprimes/sol.py2 | 45 + tests/1501-2000/1766. tree-of-coprimes/sol.rb | 47 + tests/1501-2000/1766. tree-of-coprimes/sol.rs | 46 + .../1766. tree-of-coprimes/sol.swift | 47 + tests/1501-2000/1766. tree-of-coprimes/sol.ts | 43 + .../manifest.yaml | 231 +++ .../1768. merge-strings-alternately/sol.cpp | 18 + .../1768. merge-strings-alternately/sol.cs | 16 + .../1768. merge-strings-alternately/sol.dart | 13 + .../1768. merge-strings-alternately/sol.go | 17 + .../1768. merge-strings-alternately/sol.java | 16 + .../1768. merge-strings-alternately/sol.kt | 16 + .../1768. merge-strings-alternately/sol.py | 11 + .../1768. merge-strings-alternately/sol.py2 | 13 + .../1768. merge-strings-alternately/sol.rb | 13 + .../1768. merge-strings-alternately/sol.rs | 27 + .../1768. merge-strings-alternately/sol.swift | 19 + .../1768. merge-strings-alternately/sol.ts | 14 + .../manifest.yaml | 207 +++ .../sol.cpp | 31 + .../sol.cs | 30 + .../sol.dart | 30 + .../sol.go | 28 + .../sol.java | 30 + .../sol.kt | 30 + .../sol.py | 24 + .../sol.py2 | 28 + .../sol.rb | 30 + .../sol.rs | 31 + .../sol.swift | 31 + .../sol.ts | 28 + .../manifest.yaml | 274 ++++ .../sol.cpp | 20 + .../sol.cs | 24 + .../sol.dart | 20 + .../sol.go | 32 + .../sol.java | 21 + .../sol.kt | 20 + .../sol.py | 22 + .../sol.py2 | 15 + .../sol.rb | 20 + .../sol.rs | 20 + .../sol.swift | 20 + .../sol.ts | 20 + .../manifest.yaml | 261 ++++ .../sol.cpp | 33 + .../sol.cs | 38 + .../sol.dart | 32 + .../sol.go | 55 + .../sol.java | 29 + .../sol.kt | 28 + .../sol.py | 24 + .../sol.py2 | 30 + .../sol.rb | 30 + .../sol.rs | 35 + .../sol.swift | 32 + .../sol.ts | 30 + .../manifest.yaml | 714 +++++++++ .../1773. count-items-matching-a-rule/sol.cpp | 14 + .../1773. count-items-matching-a-rule/sol.cs | 13 + .../sol.dart | 13 + .../1773. count-items-matching-a-rule/sol.go | 11 + .../sol.java | 24 + .../1773. count-items-matching-a-rule/sol.kt | 15 + .../1773. count-items-matching-a-rule/sol.py | 9 + .../1773. count-items-matching-a-rule/sol.py2 | 15 + .../1773. count-items-matching-a-rule/sol.rb | 15 + .../1773. count-items-matching-a-rule/sol.rs | 13 + .../sol.swift | 13 + .../1773. count-items-matching-a-rule/sol.ts | 15 + .../1774. closest-dessert-cost/manifest.yaml | 338 ++++ .../1774. closest-dessert-cost/sol.cpp | 42 + .../1774. closest-dessert-cost/sol.cs | 42 + .../1774. closest-dessert-cost/sol.dart | 52 + .../1774. closest-dessert-cost/sol.go | 42 + .../1774. closest-dessert-cost/sol.java | 45 + .../1774. closest-dessert-cost/sol.kt | 42 + .../1774. closest-dessert-cost/sol.py | 38 + .../1774. closest-dessert-cost/sol.py2 | 38 + .../1774. closest-dessert-cost/sol.rb | 38 + .../1774. closest-dessert-cost/sol.rs | 43 + .../1774. closest-dessert-cost/sol.swift | 57 + .../1774. closest-dessert-cost/sol.ts | 51 + .../manifest.yaml | 386 +++++ .../sol.cpp | 38 + .../sol.cs | 32 + .../sol.dart | 36 + .../sol.go | 37 + .../sol.java | 37 + .../sol.kt | 32 + .../sol.py | 50 + .../sol.py2 | 31 + .../sol.rb | 33 + .../sol.rs | 34 + .../sol.swift | 32 + .../sol.ts | 30 + .../1776. car-fleet-ii/manifest.yaml | 352 +++++ tests/1501-2000/1776. car-fleet-ii/sol.cpp | 28 + tests/1501-2000/1776. car-fleet-ii/sol.cs | 29 + tests/1501-2000/1776. car-fleet-ii/sol.dart | 27 + tests/1501-2000/1776. car-fleet-ii/sol.go | 31 + tests/1501-2000/1776. car-fleet-ii/sol.java | 30 + tests/1501-2000/1776. car-fleet-ii/sol.kt | 27 + tests/1501-2000/1776. car-fleet-ii/sol.py | 113 ++ tests/1501-2000/1776. car-fleet-ii/sol.py2 | 23 + tests/1501-2000/1776. car-fleet-ii/sol.rb | 27 + tests/1501-2000/1776. car-fleet-ii/sol.rs | 27 + tests/1501-2000/1776. car-fleet-ii/sol.swift | 27 + tests/1501-2000/1776. car-fleet-ii/sol.ts | 31 + .../manifest.yaml | 379 +++++ .../sol.cpp | 19 + .../sol.cs | 18 + .../sol.dart | 18 + .../sol.go | 22 + .../sol.java | 18 + .../sol.kt | 18 + .../sol.py | 11 + .../sol.py2 | 18 + .../sol.rb | 19 + .../sol.rs | 18 + .../sol.swift | 18 + .../sol.ts | 16 + .../manifest.yaml | 199 +++ .../sol.cpp | 12 + .../sol.cs | 11 + .../sol.dart | 11 + .../sol.go | 9 + .../sol.java | 11 + .../sol.kt | 12 + .../sol.py | 8 + .../sol.py2 | 11 + .../sol.rb | 9 + .../sol.rs | 12 + .../sol.swift | 12 + .../sol.ts | 9 + .../manifest.yaml | 197 +++ .../sol.cpp | 23 + .../sol.cs | 22 + .../sol.dart | 22 + .../sol.go | 20 + .../sol.java | 22 + .../sol.kt | 22 + .../sol.py | 22 + .../sol.py2 | 20 + .../sol.rb | 22 + .../sol.rs | 23 + .../sol.swift | 23 + .../sol.ts | 20 + .../1782. count-pairs-of-nodes/manifest.yaml | 649 ++++++++ .../1782. count-pairs-of-nodes/sol.cpp | 81 + .../1782. count-pairs-of-nodes/sol.cs | 78 + .../1782. count-pairs-of-nodes/sol.dart | 72 + .../1782. count-pairs-of-nodes/sol.go | 75 + .../1782. count-pairs-of-nodes/sol.java | 74 + .../1782. count-pairs-of-nodes/sol.kt | 72 + .../1782. count-pairs-of-nodes/sol.py | 68 + .../1782. count-pairs-of-nodes/sol.py2 | 32 + .../1782. count-pairs-of-nodes/sol.rb | 73 + .../1782. count-pairs-of-nodes/sol.rs | 53 + .../1782. count-pairs-of-nodes/sol.swift | 72 + .../1782. count-pairs-of-nodes/sol.ts | 75 + .../manifest.yaml | 179 +++ .../sol.cpp | 6 + .../sol.cs | 5 + .../sol.dart | 5 + .../sol.go | 3 + .../sol.java | 5 + .../sol.kt | 5 + .../sol.py | 3 + .../sol.py2 | 7 + .../sol.rb | 5 + .../sol.rs | 5 + .../sol.swift | 5 + .../sol.ts | 3 + .../manifest.yaml | 255 +++ .../sol.cpp | 11 + .../sol.cs | 10 + .../sol.dart | 7 + .../sol.go | 11 + .../sol.java | 10 + .../sol.kt | 7 + .../sol.py | 11 + .../sol.py2 | 11 + .../sol.rb | 9 + .../sol.rs | 7 + .../sol.swift | 7 + .../sol.ts | 5 + .../manifest.yaml | 609 ++++++++ .../sol.cpp | 44 + .../sol.cs | 43 + .../sol.dart | 42 + .../sol.go | 54 + .../sol.java | 45 + .../sol.kt | 38 + .../sol.py | 36 + .../sol.py2 | 41 + .../sol.rb | 39 + .../sol.rs | 42 + .../sol.swift | 40 + .../sol.ts | 38 + .../manifest.yaml | 247 +++ .../sol.cpp | 28 + .../sol.cs | 31 + .../sol.dart | 26 + .../sol.go | 39 + .../sol.java | 32 + .../sol.kt | 24 + .../sol.py | 21 + .../sol.py2 | 22 + .../sol.rb | 24 + .../sol.rs | 29 + .../sol.swift | 28 + .../sol.ts | 28 + .../manifest.yaml | 249 +++ .../sol.cpp | 22 + .../sol.cs | 21 + .../sol.dart | 21 + .../sol.go | 23 + .../sol.java | 18 + .../sol.kt | 18 + .../sol.py | 24 + .../sol.py2 | 20 + .../sol.rb | 24 + .../sol.rs | 23 + .../sol.swift | 23 + .../sol.ts | 19 + .../manifest.yaml | 679 ++++++++ .../1791. find-center-of-star-graph/sol.cpp | 11 + .../1791. find-center-of-star-graph/sol.cs | 7 + .../1791. find-center-of-star-graph/sol.dart | 7 + .../1791. find-center-of-star-graph/sol.go | 8 + .../1791. find-center-of-star-graph/sol.java | 10 + .../1791. find-center-of-star-graph/sol.kt | 9 + .../1791. find-center-of-star-graph/sol.py | 10 + .../1791. find-center-of-star-graph/sol.py2 | 11 + .../1791. find-center-of-star-graph/sol.rb | 10 + .../1791. find-center-of-star-graph/sol.rs | 13 + .../1791. find-center-of-star-graph/sol.swift | 7 + .../1791. find-center-of-star-graph/sol.ts | 5 + .../manifest.yaml | 247 +++ .../1792. maximum-average-pass-ratio/sol.cpp | 29 + .../1792. maximum-average-pass-ratio/sol.cs | 30 + .../1792. maximum-average-pass-ratio/sol.dart | 23 + .../1792. maximum-average-pass-ratio/sol.go | 40 + .../1792. maximum-average-pass-ratio/sol.java | 22 + .../1792. maximum-average-pass-ratio/sol.kt | 22 + .../1792. maximum-average-pass-ratio/sol.py | 44 + .../1792. maximum-average-pass-ratio/sol.py2 | 18 + .../1792. maximum-average-pass-ratio/sol.rb | 22 + .../1792. maximum-average-pass-ratio/sol.rs | 53 + .../sol.swift | 76 + .../1792. maximum-average-pass-ratio/sol.ts | 69 + .../manifest.yaml | 226 +++ .../sol.cpp | 25 + .../sol.cs | 24 + .../sol.dart | 24 + .../sol.go | 22 + .../sol.java | 24 + .../sol.kt | 25 + .../sol.py | 20 + .../sol.py2 | 25 + .../sol.rb | 25 + .../sol.rs | 25 + .../sol.swift | 24 + .../sol.ts | 23 + .../manifest.yaml | 210 +++ .../sol.cpp | 22 + .../sol.cs | 20 + .../sol.dart | 11 + .../sol.go | 25 + .../sol.java | 18 + .../sol.kt | 11 + .../sol.py | 16 + .../sol.py2 | 11 + .../sol.rb | 6 + .../sol.rs | 17 + .../sol.swift | 17 + .../sol.ts | 14 + .../manifest.yaml | 221 +++ .../sol.cpp | 14 + .../sol.cs | 13 + .../sol.dart | 13 + .../sol.go | 13 + .../sol.java | 13 + .../sol.kt | 13 + .../sol.py | 15 + .../sol.py2 | 15 + .../sol.rb | 13 + .../sol.rs | 14 + .../sol.swift | 13 + .../sol.ts | 11 + .../manifest.yaml | 244 +++ .../sol.cpp | 24 + .../sol.cs | 39 + .../sol.dart | 29 + .../sol.go | 44 + .../sol.java | 36 + .../sol.kt | 25 + .../sol.py | 33 + .../sol.py2 | 28 + .../sol.rb | 33 + .../sol.rs | 36 + .../sol.swift | 35 + .../sol.ts | 29 + .../manifest.yaml | 300 ++++ .../sol.cpp | 11 + .../sol.cs | 10 + .../sol.dart | 10 + .../sol.go | 14 + .../sol.java | 10 + .../sol.kt | 11 + .../sol.py | 7 + .../sol.py2 | 11 + .../sol.rb | 10 + .../sol.rs | 11 + .../sol.swift | 10 + .../sol.ts | 9 + .../manifest.yaml | 212 +++ .../sol.cpp | 50 + .../sol.cs | 50 + .../sol.dart | 32 + .../sol.go | 70 + .../sol.java | 47 + .../sol.kt | 49 + .../sol.py | 31 + .../sol.py2 | 35 + .../sol.rb | 42 + .../sol.rs | 46 + .../sol.swift | 47 + .../sol.ts | 45 + .../manifest.yaml | 315 ++++ .../sol.cpp | 39 + .../sol.cs | 37 + .../sol.dart | 37 + .../sol.go | 37 + .../sol.java | 37 + .../sol.kt | 39 + .../sol.py | 28 + .../sol.py2 | 34 + .../sol.rb | 37 + .../sol.rs | 39 + .../sol.swift | 37 + .../sol.ts | 42 + .../manifest.yaml | 329 ++++ .../sol.cpp | 43 + .../sol.cs | 48 + .../sol.dart | 44 + .../sol.go | 57 + .../sol.java | 54 + .../sol.kt | 48 + .../sol.py | 40 + .../sol.py2 | 39 + .../sol.rb | 50 + .../sol.rs | 48 + .../sol.swift | 47 + .../sol.ts | 54 + .../manifest.yaml | 277 ++++ .../sol.cpp | 26 + .../sol.cs | 25 + .../sol.dart | 26 + .../sol.go | 24 + .../sol.java | 25 + .../sol.kt | 26 + .../sol.py | 18 + .../sol.py2 | 22 + .../sol.rb | 26 + .../sol.rs | 27 + .../sol.swift | 28 + .../sol.ts | 24 + .../manifest.yaml | 187 +++ .../sol.cpp | 23 + .../sol.cs | 29 + .../sol.dart | 28 + .../sol.go | 32 + .../sol.java | 22 + .../sol.kt | 21 + .../sol.py | 23 + .../sol.py2 | 21 + .../sol.rb | 21 + .../sol.rs | 24 + .../sol.swift | 23 + .../sol.ts | 26 + .../manifest.yaml | 379 +++++ .../sol.cpp | 28 + .../sol.cs | 27 + .../sol.dart | 24 + .../sol.go | 28 + .../sol.java | 26 + .../sol.kt | 24 + .../sol.py | 17 + .../sol.py2 | 22 + .../sol.rb | 26 + .../sol.rs | 28 + .../sol.swift | 28 + .../sol.ts | 25 + .../manifest.yaml | 189 +++ .../sol.cpp | 21 + .../sol.cs | 20 + .../sol.dart | 22 + .../sol.go | 26 + .../sol.java | 25 + .../sol.kt | 25 + .../sol.py | 8 + .../sol.py2 | 16 + .../sol.rb | 15 + .../sol.rs | 26 + .../sol.swift | 29 + .../sol.ts | 21 + .../manifest.yaml | 203 +++ .../sol.cpp | 6 + .../sol.cs | 5 + .../sol.dart | 5 + .../sol.go | 3 + .../sol.java | 5 + .../sol.kt | 5 + .../sol.py | 3 + .../sol.py2 | 7 + .../sol.rb | 5 + .../sol.rs | 6 + .../sol.swift | 6 + .../sol.ts | 3 + .../manifest.yaml | 249 +++ .../1813. sentence-similarity-iii/sol.cpp | 26 + .../1813. sentence-similarity-iii/sol.cs | 22 + .../1813. sentence-similarity-iii/sol.dart | 22 + .../1813. sentence-similarity-iii/sol.go | 20 + .../1813. sentence-similarity-iii/sol.java | 22 + .../1813. sentence-similarity-iii/sol.kt | 25 + .../1813. sentence-similarity-iii/sol.py | 19 + .../1813. sentence-similarity-iii/sol.py2 | 23 + .../1813. sentence-similarity-iii/sol.rb | 23 + .../1813. sentence-similarity-iii/sol.rs | 23 + .../1813. sentence-similarity-iii/sol.swift | 22 + .../1813. sentence-similarity-iii/sol.ts | 23 + .../manifest.yaml | 252 +++ .../sol.cpp | 26 + .../1814. count-nice-pairs-in-an-array/sol.cs | 24 + .../sol.dart | 24 + .../1814. count-nice-pairs-in-an-array/sol.go | 25 + .../sol.java | 24 + .../1814. count-nice-pairs-in-an-array/sol.kt | 25 + .../1814. count-nice-pairs-in-an-array/sol.py | 19 + .../sol.py2 | 23 + .../1814. count-nice-pairs-in-an-array/sol.rb | 24 + .../1814. count-nice-pairs-in-an-array/sol.rs | 27 + .../sol.swift | 25 + .../1814. count-nice-pairs-in-an-array/sol.ts | 22 + .../manifest.yaml | 356 +++++ .../sol.cpp | 63 + .../sol.cs | 62 + .../sol.dart | 60 + .../sol.go | 79 + .../sol.java | 63 + .../sol.kt | 57 + .../sol.py | 56 + .../sol.py2 | 53 + .../sol.rb | 59 + .../sol.rs | 63 + .../sol.swift | 62 + .../sol.ts | 62 + .../1816. truncate-sentence/manifest.yaml | 220 +++ .../1501-2000/1816. truncate-sentence/sol.cpp | 17 + .../1501-2000/1816. truncate-sentence/sol.cs | 6 + .../1816. truncate-sentence/sol.dart | 5 + .../1501-2000/1816. truncate-sentence/sol.go | 7 + .../1816. truncate-sentence/sol.java | 11 + .../1501-2000/1816. truncate-sentence/sol.kt | 5 + .../1501-2000/1816. truncate-sentence/sol.py | 4 + .../1501-2000/1816. truncate-sentence/sol.py2 | 9 + .../1501-2000/1816. truncate-sentence/sol.rb | 6 + .../1501-2000/1816. truncate-sentence/sol.rs | 5 + .../1816. truncate-sentence/sol.swift | 6 + .../1501-2000/1816. truncate-sentence/sol.ts | 3 + .../manifest.yaml | 525 +++++++ .../sol.cpp | 17 + .../sol.cs | 19 + .../sol.dart | 16 + .../sol.go | 19 + .../sol.java | 16 + .../sol.kt | 16 + .../sol.py | 13 + .../sol.py2 | 18 + .../sol.rb | 17 + .../sol.rs | 18 + .../sol.swift | 16 + .../sol.ts | 17 + .../manifest.yaml | 219 +++ .../sol.cpp | 33 + .../sol.cs | 31 + .../sol.dart | 42 + .../sol.go | 41 + .../sol.java | 31 + .../sol.kt | 30 + .../sol.py | 32 + .../sol.py2 | 26 + .../sol.rb | 27 + .../sol.rs | 28 + .../sol.swift | 44 + .../sol.ts | 42 + .../manifest.yaml | 249 +++ .../sol.cpp | 28 + .../sol.cs | 26 + .../sol.dart | 26 + .../sol.go | 30 + .../sol.java | 30 + .../sol.kt | 30 + .../sol.py | 16 + .../sol.py2 | 22 + .../sol.rb | 17 + .../sol.rs | 32 + .../sol.swift | 32 + .../sol.ts | 22 + .../manifest.yaml | 274 ++++ .../sol.cpp | 11 + .../sol.cs | 10 + .../sol.dart | 8 + .../sol.go | 13 + .../sol.java | 10 + .../sol.kt | 8 + .../sol.py | 5 + .../sol.py2 | 9 + .../sol.rb | 6 + .../sol.rs | 13 + .../sol.swift | 9 + .../sol.ts | 5 + .../manifest.yaml | 245 +++ .../sol.cpp | 10 + .../sol.cs | 9 + .../sol.dart | 9 + .../sol.go | 7 + .../sol.java | 9 + .../sol.kt | 9 + .../sol.py | 6 + .../sol.py2 | 11 + .../sol.rb | 7 + .../sol.rs | 9 + .../sol.swift | 10 + .../sol.ts | 7 + .../1824. minimum-sideway-jumps/manifest.yaml | 231 +++ .../1824. minimum-sideway-jumps/sol.cpp | 19 + .../1824. minimum-sideway-jumps/sol.cs | 18 + .../1824. minimum-sideway-jumps/sol.dart | 19 + .../1824. minimum-sideway-jumps/sol.go | 30 + .../1824. minimum-sideway-jumps/sol.java | 18 + .../1824. minimum-sideway-jumps/sol.kt | 18 + .../1824. minimum-sideway-jumps/sol.py | 20 + .../1824. minimum-sideway-jumps/sol.py2 | 20 + .../1824. minimum-sideway-jumps/sol.rb | 18 + .../1824. minimum-sideway-jumps/sol.rs | 21 + .../1824. minimum-sideway-jumps/sol.swift | 18 + .../1824. minimum-sideway-jumps/sol.ts | 16 + .../manifest.yaml | 247 +++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 15 + .../sol.go | 13 + .../sol.java | 15 + .../sol.kt | 15 + .../sol.py | 11 + .../sol.py2 | 15 + .../sol.rb | 15 + .../sol.rs | 15 + .../sol.swift | 15 + .../sol.ts | 13 + .../manifest.yaml | 543 +++++++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 15 + .../sol.go | 13 + .../sol.java | 13 + .../sol.kt | 13 + .../sol.py | 16 + .../sol.py2 | 13 + .../sol.rb | 14 + .../sol.rs | 15 + .../sol.swift | 15 + .../sol.ts | 13 + .../manifest.yaml | 289 ++++ .../1829. maximum-xor-for-each-query/sol.cpp | 14 + .../1829. maximum-xor-for-each-query/sol.cs | 13 + .../1829. maximum-xor-for-each-query/sol.dart | 13 + .../1829. maximum-xor-for-each-query/sol.go | 11 + .../1829. maximum-xor-for-each-query/sol.java | 13 + .../1829. maximum-xor-for-each-query/sol.kt | 13 + .../1829. maximum-xor-for-each-query/sol.py | 14 + .../1829. maximum-xor-for-each-query/sol.py2 | 16 + .../1829. maximum-xor-for-each-query/sol.rb | 13 + .../1829. maximum-xor-for-each-query/sol.rs | 13 + .../sol.swift | 13 + .../1829. maximum-xor-for-each-query/sol.ts | 11 + .../manifest.yaml | 308 ++++ .../sol.cpp | 57 + .../sol.cs | 55 + .../sol.dart | 54 + .../sol.go | 56 + .../sol.java | 55 + .../sol.kt | 54 + .../sol.py | 49 + .../sol.py2 | 53 + .../sol.rb | 59 + .../sol.rs | 60 + .../sol.swift | 60 + .../sol.ts | 59 + .../manifest.yaml | 196 +++ .../sol.cpp | 11 + .../sol.cs | 10 + .../sol.dart | 10 + .../sol.go | 12 + .../sol.java | 10 + .../sol.kt | 10 + .../sol.py | 9 + .../sol.py2 | 13 + .../sol.rb | 10 + .../sol.rs | 10 + .../sol.swift | 10 + .../sol.ts | 8 + .../manifest.yaml | 379 +++++ .../1833. maximum-ice-cream-bars/sol.cpp | 22 + .../1833. maximum-ice-cream-bars/sol.cs | 21 + .../1833. maximum-ice-cream-bars/sol.dart | 26 + .../1833. maximum-ice-cream-bars/sol.go | 24 + .../1833. maximum-ice-cream-bars/sol.java | 24 + .../1833. maximum-ice-cream-bars/sol.kt | 26 + .../1833. maximum-ice-cream-bars/sol.py | 17 + .../1833. maximum-ice-cream-bars/sol.py2 | 23 + .../1833. maximum-ice-cream-bars/sol.rb | 21 + .../1833. maximum-ice-cream-bars/sol.rs | 21 + .../1833. maximum-ice-cream-bars/sol.swift | 26 + .../1833. maximum-ice-cream-bars/sol.ts | 19 + .../1834. single-threaded-cpu/manifest.yaml | 442 ++++++ .../1834. single-threaded-cpu/sol.cpp | 38 + .../1834. single-threaded-cpu/sol.cs | 33 + .../1834. single-threaded-cpu/sol.dart | 53 + .../1834. single-threaded-cpu/sol.go | 54 + .../1834. single-threaded-cpu/sol.java | 39 + .../1834. single-threaded-cpu/sol.kt | 38 + .../1834. single-threaded-cpu/sol.py | 37 + .../1834. single-threaded-cpu/sol.py2 | 30 + .../1834. single-threaded-cpu/sol.rb | 31 + .../1834. single-threaded-cpu/sol.rs | 33 + .../1834. single-threaded-cpu/sol.swift | 36 + .../1834. single-threaded-cpu/sol.ts | 39 + .../manifest.yaml | 314 ++++ .../sol.cpp | 13 + .../sol.cs | 12 + .../sol.dart | 12 + .../sol.go | 10 + .../sol.java | 12 + .../sol.kt | 13 + .../sol.py | 8 + .../sol.py2 | 13 + .../sol.rb | 9 + .../sol.rs | 13 + .../sol.swift | 12 + .../sol.ts | 11 + .../manifest.yaml | 272 ++++ .../1837. sum-of-digits-in-base-k/sol.cpp | 11 + .../1837. sum-of-digits-in-base-k/sol.cs | 10 + .../1837. sum-of-digits-in-base-k/sol.dart | 10 + .../1837. sum-of-digits-in-base-k/sol.go | 8 + .../1837. sum-of-digits-in-base-k/sol.java | 10 + .../1837. sum-of-digits-in-base-k/sol.kt | 11 + .../1837. sum-of-digits-in-base-k/sol.py | 7 + .../1837. sum-of-digits-in-base-k/sol.py2 | 12 + .../1837. sum-of-digits-in-base-k/sol.rb | 11 + .../1837. sum-of-digits-in-base-k/sol.rs | 11 + .../1837. sum-of-digits-in-base-k/sol.swift | 11 + .../1837. sum-of-digits-in-base-k/sol.ts | 8 + .../manifest.yaml | 326 ++++ .../sol.cpp | 22 + .../sol.cs | 21 + .../sol.dart | 23 + .../sol.go | 23 + .../sol.java | 21 + .../sol.kt | 23 + .../sol.py | 17 + .../sol.py2 | 21 + .../sol.rb | 24 + .../sol.rs | 24 + .../sol.swift | 23 + .../sol.ts | 21 + .../manifest.yaml | 305 ++++ .../sol.cpp | 32 + .../sol.cs | 31 + .../sol.dart | 31 + .../sol.go | 31 + .../sol.java | 31 + .../sol.kt | 31 + .../sol.py | 24 + .../sol.py2 | 28 + .../sol.rb | 31 + .../sol.rs | 32 + .../sol.swift | 32 + .../sol.ts | 29 + .../manifest.yaml | 330 ++++ .../1840. maximum-building-height/sol.cpp | 23 + .../1840. maximum-building-height/sol.cs | 23 + .../1840. maximum-building-height/sol.dart | 26 + .../1840. maximum-building-height/sol.go | 34 + .../1840. maximum-building-height/sol.java | 26 + .../1840. maximum-building-height/sol.kt | 23 + .../1840. maximum-building-height/sol.py | 25 + .../1840. maximum-building-height/sol.py2 | 28 + .../1840. maximum-building-height/sol.rb | 26 + .../1840. maximum-building-height/sol.rs | 36 + .../1840. maximum-building-height/sol.swift | 24 + .../1840. maximum-building-height/sol.ts | 24 + .../manifest.yaml | 143 ++ .../sol.cpp | 11 + .../sol.cs | 11 + .../sol.dart | 11 + .../sol.go | 9 + .../sol.java | 11 + .../sol.kt | 11 + .../sol.py | 11 + .../sol.py2 | 12 + .../sol.rb | 11 + .../sol.rs | 12 + .../sol.swift | 11 + .../sol.ts | 9 + .../manifest.yaml | 270 ++++ .../sol.cpp | 11 + .../sol.cs | 10 + .../sol.dart | 10 + .../sol.go | 10 + .../sol.java | 10 + .../sol.kt | 10 + .../sol.py | 11 + .../sol.py2 | 11 + .../sol.rb | 10 + .../sol.rs | 11 + .../sol.swift | 11 + .../sol.ts | 8 + .../1847. closest-room/manifest.yaml | 489 ++++++ tests/1501-2000/1847. closest-room/sol.cpp | 49 + tests/1501-2000/1847. closest-room/sol.cs | 46 + tests/1501-2000/1847. closest-room/sol.dart | 43 + tests/1501-2000/1847. closest-room/sol.go | 67 + tests/1501-2000/1847. closest-room/sol.java | 46 + tests/1501-2000/1847. closest-room/sol.kt | 31 + tests/1501-2000/1847. closest-room/sol.py | 23 + tests/1501-2000/1847. closest-room/sol.py2 | 26 + tests/1501-2000/1847. closest-room/sol.rb | 38 + tests/1501-2000/1847. closest-room/sol.rs | 44 + tests/1501-2000/1847. closest-room/sol.swift | 65 + tests/1501-2000/1847. closest-room/sol.ts | 59 + .../manifest.yaml | 287 ++++ .../sol.cpp | 23 + .../sol.cs | 22 + .../sol.dart | 22 + .../sol.go | 20 + .../sol.java | 22 + .../sol.kt | 22 + .../sol.py | 17 + .../sol.py2 | 22 + .../sol.rb | 16 + .../sol.rs | 22 + .../sol.swift | 22 + .../sol.ts | 20 + .../manifest.yaml | 307 ++++ .../sol.cpp | 26 + .../sol.cs | 24 + .../sol.dart | 24 + .../sol.go | 23 + .../sol.java | 24 + .../sol.kt | 20 + .../sol.py | 26 + .../sol.py2 | 25 + .../sol.rb | 24 + .../sol.rs | 25 + .../sol.swift | 43 + .../sol.ts | 22 + .../manifest.yaml | 268 ++++ .../sol.cpp | 48 + .../sol.cs | 52 + .../sol.dart | 52 + .../sol.go | 54 + .../sol.java | 52 + .../sol.kt | 53 + .../sol.py | 44 + .../sol.py2 | 43 + .../sol.rb | 48 + .../sol.rs | 51 + .../sol.swift | 46 + .../sol.ts | 45 + .../manifest.yaml | 374 +++++ .../sol.cpp | 33 + .../sol.cs | 26 + .../sol.dart | 24 + .../sol.go | 38 + .../sol.java | 28 + .../sol.kt | 24 + .../sol.py | 38 + .../sol.py2 | 23 + .../sol.rb | 24 + .../sol.rs | 31 + .../sol.swift | 25 + .../sol.ts | 20 + .../manifest.yaml | 347 +++++ .../1854. maximum-population-year/sol.cpp | 33 + .../1854. maximum-population-year/sol.cs | 36 + .../1854. maximum-population-year/sol.dart | 36 + .../1854. maximum-population-year/sol.go | 36 + .../1854. maximum-population-year/sol.java | 36 + .../1854. maximum-population-year/sol.kt | 36 + .../1854. maximum-population-year/sol.py | 22 + .../1854. maximum-population-year/sol.py2 | 26 + .../1854. maximum-population-year/sol.rb | 28 + .../1854. maximum-population-year/sol.rs | 32 + .../1854. maximum-population-year/sol.swift | 32 + .../1854. maximum-population-year/sol.ts | 30 + .../manifest.yaml | 226 +++ .../sol.cpp | 17 + .../sol.cs | 16 + .../sol.dart | 16 + .../sol.go | 18 + .../sol.java | 16 + .../sol.kt | 17 + .../sol.py | 15 + .../sol.py2 | 18 + .../sol.rb | 20 + .../sol.rs | 17 + .../sol.swift | 16 + .../sol.ts | 15 + .../manifest.yaml | 248 +++ .../sol.cpp | 34 + .../1856. maximum-subarray-min-product/sol.cs | 34 + .../sol.dart | 32 + .../1856. maximum-subarray-min-product/sol.go | 41 + .../sol.java | 36 + .../1856. maximum-subarray-min-product/sol.kt | 33 + .../1856. maximum-subarray-min-product/sol.py | 37 + .../sol.py2 | 30 + .../1856. maximum-subarray-min-product/sol.rb | 30 + .../1856. maximum-subarray-min-product/sol.rs | 45 + .../sol.swift | 34 + .../1856. maximum-subarray-min-product/sol.ts | 32 + .../manifest.yaml | 435 ++++++ .../sol.cpp | 42 + .../sol.cs | 47 + .../sol.dart | 34 + .../sol.go | 55 + .../sol.java | 46 + .../sol.kt | 44 + .../sol.py | 39 + .../sol.py2 | 44 + .../sol.rb | 50 + .../sol.rs | 41 + .../sol.swift | 48 + .../sol.ts | 41 + .../1859. sorting-the-sentence/manifest.yaml | 182 +++ .../1859. sorting-the-sentence/sol.cpp | 20 + .../1859. sorting-the-sentence/sol.cs | 16 + .../1859. sorting-the-sentence/sol.dart | 13 + .../1859. sorting-the-sentence/sol.go | 14 + .../1859. sorting-the-sentence/sol.java | 16 + .../1859. sorting-the-sentence/sol.kt | 9 + .../1859. sorting-the-sentence/sol.py | 7 + .../1859. sorting-the-sentence/sol.py2 | 10 + .../1859. sorting-the-sentence/sol.rb | 9 + .../1859. sorting-the-sentence/sol.rs | 12 + .../1859. sorting-the-sentence/sol.swift | 11 + .../1859. sorting-the-sentence/sol.ts | 11 + .../manifest.yaml | 264 ++++ .../1860. incremental-memory-leak/sol.cpp | 23 + .../1860. incremental-memory-leak/sol.cs | 22 + .../1860. incremental-memory-leak/sol.dart | 22 + .../1860. incremental-memory-leak/sol.go | 20 + .../1860. incremental-memory-leak/sol.java | 22 + .../1860. incremental-memory-leak/sol.kt | 24 + .../1860. incremental-memory-leak/sol.py | 21 + .../1860. incremental-memory-leak/sol.py2 | 21 + .../1860. incremental-memory-leak/sol.rb | 23 + .../1860. incremental-memory-leak/sol.rs | 24 + .../1860. incremental-memory-leak/sol.swift | 24 + .../1860. incremental-memory-leak/sol.ts | 20 + .../1861. rotating-the-box/manifest.yaml | 268 ++++ .../1501-2000/1861. rotating-the-box/sol.cpp | 21 + tests/1501-2000/1861. rotating-the-box/sol.cs | 23 + .../1501-2000/1861. rotating-the-box/sol.dart | 19 + tests/1501-2000/1861. rotating-the-box/sol.go | 24 + .../1501-2000/1861. rotating-the-box/sol.java | 20 + tests/1501-2000/1861. rotating-the-box/sol.kt | 23 + tests/1501-2000/1861. rotating-the-box/sol.py | 15 + .../1501-2000/1861. rotating-the-box/sol.py2 | 19 + tests/1501-2000/1861. rotating-the-box/sol.rb | 18 + tests/1501-2000/1861. rotating-the-box/sol.rs | 21 + .../1861. rotating-the-box/sol.swift | 20 + tests/1501-2000/1861. rotating-the-box/sol.ts | 20 + .../1862. sum-of-floored-pairs/manifest.yaml | 238 +++ .../1862. sum-of-floored-pairs/sol.cpp | 28 + .../1862. sum-of-floored-pairs/sol.cs | 26 + .../1862. sum-of-floored-pairs/sol.dart | 31 + .../1862. sum-of-floored-pairs/sol.go | 38 + .../1862. sum-of-floored-pairs/sol.java | 27 + .../1862. sum-of-floored-pairs/sol.kt | 26 + .../1862. sum-of-floored-pairs/sol.py | 36 + .../1862. sum-of-floored-pairs/sol.py2 | 31 + .../1862. sum-of-floored-pairs/sol.rb | 28 + .../1862. sum-of-floored-pairs/sol.rs | 32 + .../1862. sum-of-floored-pairs/sol.swift | 30 + .../1862. sum-of-floored-pairs/sol.ts | 28 + .../manifest.yaml | 249 +++ .../sol.cpp | 10 + .../1863. sum-of-all-subset-xor-totals/sol.cs | 9 + .../sol.dart | 9 + .../1863. sum-of-all-subset-xor-totals/sol.go | 7 + .../sol.java | 9 + .../1863. sum-of-all-subset-xor-totals/sol.kt | 9 + .../1863. sum-of-all-subset-xor-totals/sol.py | 6 + .../sol.py2 | 10 + .../1863. sum-of-all-subset-xor-totals/sol.rb | 9 + .../1863. sum-of-all-subset-xor-totals/sol.rs | 9 + .../sol.swift | 9 + .../1863. sum-of-all-subset-xor-totals/sol.ts | 7 + .../manifest.yaml | 237 +++ .../sol.cpp | 24 + .../sol.cs | 23 + .../sol.dart | 23 + .../sol.go | 45 + .../sol.java | 23 + .../sol.kt | 17 + .../sol.py | 28 + .../sol.py2 | 26 + .../sol.rb | 25 + .../sol.rs | 29 + .../sol.swift | 23 + .../sol.ts | 21 + .../manifest.yaml | 240 +++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 15 + .../sol.go | 13 + .../sol.java | 15 + .../sol.kt | 15 + .../sol.py | 11 + .../sol.py2 | 16 + .../sol.rb | 16 + .../sol.rs | 17 + .../sol.swift | 15 + .../sol.ts | 13 + .../manifest.yaml | 224 +++ .../sol.cpp | 21 + .../sol.cs | 20 + .../sol.dart | 20 + .../sol.go | 24 + .../sol.java | 20 + .../sol.kt | 22 + .../sol.py | 16 + .../sol.py2 | 20 + .../sol.rb | 20 + .../sol.rs | 22 + .../sol.swift | 22 + .../sol.ts | 20 + .../manifest.yaml | 293 ++++ .../sol.cpp | 27 + .../sol.cs | 26 + .../sol.dart | 26 + .../sol.go | 26 + .../sol.java | 26 + .../sol.kt | 28 + .../sol.py | 33 + .../sol.py2 | 29 + .../sol.rb | 33 + .../sol.rs | 30 + .../sol.swift | 26 + .../sol.ts | 26 + .../1871. jump-game-vii/manifest.yaml | 367 +++++ tests/1501-2000/1871. jump-game-vii/sol.cpp | 28 + tests/1501-2000/1871. jump-game-vii/sol.cs | 27 + tests/1501-2000/1871. jump-game-vii/sol.dart | 27 + tests/1501-2000/1871. jump-game-vii/sol.go | 27 + tests/1501-2000/1871. jump-game-vii/sol.java | 27 + tests/1501-2000/1871. jump-game-vii/sol.kt | 27 + tests/1501-2000/1871. jump-game-vii/sol.py | 22 + tests/1501-2000/1871. jump-game-vii/sol.py2 | 28 + tests/1501-2000/1871. jump-game-vii/sol.rb | 29 + tests/1501-2000/1871. jump-game-vii/sol.rs | 30 + tests/1501-2000/1871. jump-game-vii/sol.swift | 28 + tests/1501-2000/1871. jump-game-vii/sol.ts | 25 + .../1872. stone-game-viii/manifest.yaml | 325 ++++ tests/1501-2000/1872. stone-game-viii/sol.cpp | 22 + tests/1501-2000/1872. stone-game-viii/sol.cs | 25 + .../1501-2000/1872. stone-game-viii/sol.dart | 13 + tests/1501-2000/1872. stone-game-viii/sol.go | 33 + .../1501-2000/1872. stone-game-viii/sol.java | 18 + tests/1501-2000/1872. stone-game-viii/sol.kt | 14 + tests/1501-2000/1872. stone-game-viii/sol.py | 29 + tests/1501-2000/1872. stone-game-viii/sol.py2 | 14 + tests/1501-2000/1872. stone-game-viii/sol.rb | 10 + tests/1501-2000/1872. stone-game-viii/sol.rs | 25 + .../1501-2000/1872. stone-game-viii/sol.swift | 25 + tests/1501-2000/1872. stone-game-viii/sol.ts | 12 + .../manifest.yaml | 227 +++ .../sol.cpp | 13 + .../sol.cs | 12 + .../sol.dart | 12 + .../sol.go | 10 + .../sol.java | 13 + .../sol.kt | 13 + .../sol.py | 8 + .../sol.py2 | 12 + .../sol.rb | 10 + .../sol.rs | 12 + .../sol.swift | 13 + .../sol.ts | 10 + .../manifest.yaml | 338 ++++ .../sol.cpp | 14 + .../sol.cs | 13 + .../sol.dart | 15 + .../sol.go | 13 + .../sol.java | 13 + .../sol.kt | 14 + .../sol.py | 9 + .../sol.py2 | 14 + .../sol.rb | 14 + .../sol.rs | 15 + .../sol.swift | 14 + .../sol.ts | 12 + .../manifest.yaml | 422 +++++ .../sol.cpp | 32 + .../sol.cs | 30 + .../sol.dart | 30 + .../sol.go | 57 + .../sol.java | 29 + .../sol.kt | 29 + .../sol.py | 54 + .../sol.py2 | 35 + .../sol.rb | 28 + .../sol.rs | 39 + .../sol.swift | 31 + .../sol.ts | 28 + .../manifest.yaml | 447 ++++++ .../sol.cpp | 23 + .../sol.cs | 23 + .../sol.dart | 22 + .../sol.go | 25 + .../sol.java | 23 + .../sol.kt | 22 + .../sol.py | 16 + .../sol.py2 | 22 + .../sol.rb | 21 + .../sol.rs | 22 + .../sol.swift | 22 + .../sol.ts | 25 + .../manifest.yaml | 367 +++++ .../sol.cpp | 13 + .../sol.cs | 12 + .../sol.dart | 12 + .../sol.go | 10 + .../sol.java | 16 + .../sol.kt | 8 + .../sol.py | 7 + .../sol.py2 | 12 + .../sol.rb | 10 + .../sol.rs | 9 + .../sol.swift | 12 + .../sol.ts | 15 + .../manifest.yaml | 265 ++++ .../sol.cpp | 21 + .../sol.cs | 20 + .../sol.dart | 20 + .../sol.go | 18 + .../sol.java | 20 + .../sol.kt | 20 + .../sol.py | 19 + .../sol.py2 | 19 + .../sol.rb | 21 + .../sol.rs | 21 + .../sol.swift | 21 + .../sol.ts | 18 + .../manifest.yaml | 340 ++++ .../1882. process-tasks-using-servers/sol.cpp | 46 + .../1882. process-tasks-using-servers/sol.cs | 43 + .../sol.dart | 47 + .../1882. process-tasks-using-servers/sol.go | 83 + .../sol.java | 40 + .../1882. process-tasks-using-servers/sol.kt | 39 + .../1882. process-tasks-using-servers/sol.py | 34 + .../1882. process-tasks-using-servers/sol.py2 | 35 + .../1882. process-tasks-using-servers/sol.rb | 57 + .../1882. process-tasks-using-servers/sol.rs | 50 + .../sol.swift | 35 + .../1882. process-tasks-using-servers/sol.ts | 59 + .../manifest.yaml | 377 +++++ .../sol.cpp | 28 + .../sol.cs | 28 + .../sol.dart | 26 + .../sol.go | 38 + .../sol.java | 28 + .../sol.kt | 26 + .../sol.py | 21 + .../sol.py2 | 28 + .../sol.rb | 28 + .../sol.rs | 27 + .../sol.swift | 27 + .../sol.ts | 25 + .../manifest.yaml | 218 +++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 15 + .../sol.go | 14 + .../sol.java | 15 + .../sol.kt | 17 + .../sol.py | 18 + .../sol.py2 | 16 + .../sol.rb | 16 + .../sol.rs | 17 + .../sol.swift | 15 + .../sol.ts | 15 + .../manifest.yaml | 662 ++++++++ .../sol.cpp | 22 + .../sol.cs | 40 + .../sol.dart | 20 + .../sol.go | 37 + .../sol.java | 20 + .../sol.kt | 21 + .../sol.py | 8 + .../sol.py2 | 13 + .../sol.rb | 11 + .../sol.rs | 23 + .../sol.swift | 21 + .../sol.ts | 18 + .../manifest.yaml | 256 +++ .../sol.cpp | 19 + .../sol.cs | 18 + .../sol.dart | 18 + .../sol.go | 18 + .../sol.java | 18 + .../sol.kt | 19 + .../sol.py | 12 + .../sol.py2 | 16 + .../sol.rb | 15 + .../sol.rs | 21 + .../sol.swift | 20 + .../sol.ts | 17 + .../manifest.yaml | 228 +++ .../sol.cpp | 31 + .../sol.cs | 30 + .../sol.dart | 31 + .../sol.go | 46 + .../sol.java | 30 + .../sol.kt | 30 + .../sol.py | 24 + .../sol.py2 | 27 + .../sol.rb | 26 + .../sol.rs | 31 + .../sol.swift | 31 + .../sol.ts | 28 + .../manifest.yaml | 315 ++++ .../sol.cpp | 45 + .../sol.cs | 43 + .../sol.dart | 42 + .../sol.go | 54 + .../sol.java | 43 + .../sol.kt | 43 + .../sol.py | 46 + .../sol.py2 | 36 + .../sol.rb | 34 + .../sol.rs | 46 + .../sol.swift | 43 + .../sol.ts | 41 + .../manifest.yaml | 413 +++++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 15 + .../sol.go | 15 + .../sol.java | 15 + .../sol.kt | 16 + .../sol.py | 9 + .../sol.py2 | 16 + .../sol.rb | 14 + .../sol.rs | 17 + .../sol.swift | 19 + .../sol.ts | 12 + .../manifest.yaml | 353 +++++ .../sol.cpp | 13 + .../sol.cs | 12 + .../sol.dart | 11 + .../sol.go | 14 + .../sol.java | 12 + .../sol.kt | 11 + .../sol.py | 8 + .../sol.py2 | 13 + .../sol.rb | 11 + .../sol.rs | 13 + .../sol.swift | 11 + .../sol.ts | 9 + .../1895. largest-magic-square/manifest.yaml | 348 +++++ .../1895. largest-magic-square/sol.cpp | 41 + .../1895. largest-magic-square/sol.cs | 38 + .../1895. largest-magic-square/sol.dart | 38 + .../1895. largest-magic-square/sol.go | 48 + .../1895. largest-magic-square/sol.java | 38 + .../1895. largest-magic-square/sol.kt | 34 + .../1895. largest-magic-square/sol.py | 32 + .../1895. largest-magic-square/sol.py2 | 30 + .../1895. largest-magic-square/sol.rb | 37 + .../1895. largest-magic-square/sol.rs | 34 + .../1895. largest-magic-square/sol.swift | 39 + .../1895. largest-magic-square/sol.ts | 38 + .../manifest.yaml | 240 +++ .../sol.cpp | 36 + .../sol.cs | 35 + .../sol.dart | 45 + .../sol.go | 52 + .../sol.java | 39 + .../sol.kt | 38 + .../sol.py | 38 + .../sol.py2 | 31 + .../sol.rb | 48 + .../sol.rs | 39 + .../sol.swift | 39 + .../sol.ts | 33 + .../manifest.yaml | 246 +++ .../sol.cpp | 18 + .../sol.cs | 17 + .../sol.dart | 17 + .../sol.go | 15 + .../sol.java | 17 + .../sol.kt | 17 + .../sol.py | 11 + .../sol.py2 | 15 + .../sol.rb | 15 + .../sol.rs | 17 + .../sol.swift | 17 + .../sol.ts | 15 + .../manifest.yaml | 439 ++++++ .../sol.cpp | 27 + .../sol.cs | 26 + .../sol.dart | 26 + .../sol.go | 24 + .../sol.java | 26 + .../sol.kt | 28 + .../sol.py | 30 + .../sol.py2 | 29 + .../sol.rb | 30 + .../sol.rs | 32 + .../sol.swift | 29 + .../sol.ts | 25 + .../manifest.yaml | 346 +++++ .../sol.cpp | 35 + .../sol.cs | 32 + .../sol.dart | 32 + .../sol.go | 38 + .../sol.java | 26 + .../sol.kt | 22 + .../sol.py | 25 + .../sol.py2 | 24 + .../sol.rb | 21 + .../sol.rs | 32 + .../sol.swift | 30 + .../sol.ts | 34 + .../manifest.yaml | 318 ++++ .../sol.cpp | 49 + .../sol.cs | 47 + .../sol.dart | 51 + .../sol.go | 60 + .../sol.java | 47 + .../sol.kt | 50 + .../sol.py | 49 + .../sol.py2 | 47 + .../sol.rb | 51 + .../sol.rs | 55 + .../sol.swift | 50 + .../sol.ts | 52 + .../manifest.yaml | 375 +++++ .../1901. find-a-peak-element-ii/sol.cpp | 35 + .../1901. find-a-peak-element-ii/sol.cs | 34 + .../1901. find-a-peak-element-ii/sol.dart | 34 + .../1901. find-a-peak-element-ii/sol.go | 38 + .../1901. find-a-peak-element-ii/sol.java | 34 + .../1901. find-a-peak-element-ii/sol.kt | 35 + .../1901. find-a-peak-element-ii/sol.py | 33 + .../1901. find-a-peak-element-ii/sol.py2 | 33 + .../1901. find-a-peak-element-ii/sol.rb | 37 + .../1901. find-a-peak-element-ii/sol.rs | 35 + .../1901. find-a-peak-element-ii/sol.swift | 35 + .../1901. find-a-peak-element-ii/sol.ts | 33 + .../manifest.yaml | 283 ++++ .../sol.cpp | 11 + .../1903. largest-odd-number-in-string/sol.cs | 10 + .../sol.dart | 10 + .../1903. largest-odd-number-in-string/sol.go | 8 + .../sol.java | 10 + .../1903. largest-odd-number-in-string/sol.kt | 10 + .../1903. largest-odd-number-in-string/sol.py | 6 + .../sol.py2 | 10 + .../1903. largest-odd-number-in-string/sol.rb | 8 + .../1903. largest-odd-number-in-string/sol.rs | 11 + .../sol.swift | 11 + .../1903. largest-odd-number-in-string/sol.ts | 8 + .../manifest.yaml | 329 ++++ .../sol.cpp | 22 + .../sol.cs | 20 + .../sol.dart | 20 + .../sol.go | 22 + .../sol.java | 20 + .../sol.kt | 20 + .../sol.py | 22 + .../sol.py2 | 21 + .../sol.rb | 19 + .../sol.rs | 20 + .../sol.swift | 20 + .../sol.ts | 18 + .../1905. count-sub-islands/manifest.yaml | 500 ++++++ .../1501-2000/1905. count-sub-islands/sol.cpp | 29 + .../1501-2000/1905. count-sub-islands/sol.cs | 29 + .../1905. count-sub-islands/sol.dart | 29 + .../1501-2000/1905. count-sub-islands/sol.go | 33 + .../1905. count-sub-islands/sol.java | 27 + .../1501-2000/1905. count-sub-islands/sol.kt | 28 + .../1501-2000/1905. count-sub-islands/sol.py | 27 + .../1501-2000/1905. count-sub-islands/sol.py2 | 30 + .../1501-2000/1905. count-sub-islands/sol.rb | 30 + .../1501-2000/1905. count-sub-islands/sol.rs | 31 + .../1905. count-sub-islands/sol.swift | 30 + .../1501-2000/1905. count-sub-islands/sol.ts | 28 + .../manifest.yaml | 536 +++++++ .../sol.cpp | 32 + .../sol.cs | 32 + .../sol.dart | 33 + .../sol.go | 46 + .../sol.java | 31 + .../sol.kt | 31 + .../sol.py | 27 + .../sol.py2 | 27 + .../sol.rb | 29 + .../sol.rs | 31 + .../sol.swift | 30 + .../sol.ts | 29 + .../manifest.yaml | 350 +++++ .../sol.cpp | 44 + .../sol.cs | 43 + .../sol.dart | 43 + .../sol.go | 49 + .../sol.java | 43 + .../sol.kt | 43 + .../sol.py | 39 + .../sol.py2 | 43 + .../sol.rb | 45 + .../sol.rs | 55 + .../sol.swift | 43 + .../sol.ts | 43 + .../manifest.yaml | 256 +++ .../sol.cpp | 20 + .../sol.cs | 19 + .../sol.dart | 19 + .../sol.go | 17 + .../sol.java | 19 + .../sol.kt | 19 + .../sol.py | 14 + .../sol.py2 | 19 + .../sol.rb | 20 + .../sol.rs | 20 + .../sol.swift | 19 + .../sol.ts | 23 + .../manifest.yaml | 262 ++++ .../sol.cpp | 47 + .../sol.cs | 53 + .../sol.dart | 13 + .../sol.go | 57 + .../sol.java | 36 + .../sol.kt | 19 + .../sol.py | 33 + .../sol.py2 | 8 + .../sol.rb | 16 + .../sol.rs | 45 + .../sol.swift | 45 + .../sol.ts | 11 + .../manifest.yaml | 257 ++++ .../sol.cpp | 13 + .../sol.cs | 11 + .../sol.dart | 7 + .../sol.go | 7 + .../sol.java | 10 + .../sol.kt | 10 + .../sol.py | 4 + .../sol.py2 | 14 + .../sol.rb | 10 + .../sol.rs | 12 + .../sol.swift | 11 + .../sol.ts | 5 + .../manifest.yaml | 487 ++++++ .../1914. cyclically-rotating-a-grid/sol.cpp | 43 + .../1914. cyclically-rotating-a-grid/sol.cs | 41 + .../1914. cyclically-rotating-a-grid/sol.dart | 35 + .../1914. cyclically-rotating-a-grid/sol.go | 63 + .../1914. cyclically-rotating-a-grid/sol.java | 41 + .../1914. cyclically-rotating-a-grid/sol.kt | 47 + .../1914. cyclically-rotating-a-grid/sol.py | 34 + .../1914. cyclically-rotating-a-grid/sol.py2 | 59 + .../1914. cyclically-rotating-a-grid/sol.rb | 69 + .../1914. cyclically-rotating-a-grid/sol.rs | 73 + .../sol.swift | 73 + .../1914. cyclically-rotating-a-grid/sol.ts | 37 + .../manifest.yaml | 236 +++ .../sol.cpp | 37 + .../sol.cs | 35 + .../sol.dart | 18 + .../sol.go | 31 + .../sol.java | 35 + .../sol.kt | 35 + .../sol.py | 25 + .../sol.py2 | 37 + .../sol.rb | 35 + .../sol.rs | 35 + .../sol.swift | 35 + .../sol.ts | 25 + .../manifest.yaml | 221 +++ .../sol.cpp | 91 ++ .../sol.cs | 87 ++ .../sol.dart | 48 + .../sol.go | 53 + .../sol.java | 86 ++ .../sol.kt | 91 ++ .../sol.py | 21 + .../sol.py2 | 56 + .../sol.rb | 79 + .../sol.rs | 99 ++ .../sol.swift | 101 ++ .../sol.ts | 52 + .../manifest.yaml | 389 +++++ .../sol.cpp | 14 + .../1920. build-array-from-permutation/sol.cs | 13 + .../sol.dart | 13 + .../1920. build-array-from-permutation/sol.go | 11 + .../sol.java | 13 + .../1920. build-array-from-permutation/sol.kt | 13 + .../1920. build-array-from-permutation/sol.py | 9 + .../sol.py2 | 13 + .../1920. build-array-from-permutation/sol.rb | 13 + .../1920. build-array-from-permutation/sol.rs | 14 + .../sol.swift | 14 + .../1920. build-array-from-permutation/sol.ts | 11 + .../manifest.yaml | 473 ++++++ .../sol.cpp | 16 + .../sol.cs | 16 + .../sol.dart | 15 + .../sol.go | 13 + .../sol.java | 16 + .../sol.kt | 12 + .../sol.py | 17 + .../sol.py2 | 15 + .../sol.rb | 14 + .../sol.rs | 15 + .../sol.swift | 15 + .../sol.ts | 13 + .../1922. count-good-numbers/manifest.yaml | 219 +++ .../1922. count-good-numbers/sol.cpp | 27 + .../1501-2000/1922. count-good-numbers/sol.cs | 27 + .../1922. count-good-numbers/sol.dart | 26 + .../1501-2000/1922. count-good-numbers/sol.go | 24 + .../1922. count-good-numbers/sol.java | 26 + .../1501-2000/1922. count-good-numbers/sol.kt | 26 + .../1501-2000/1922. count-good-numbers/sol.py | 24 + .../1922. count-good-numbers/sol.py2 | 24 + .../1501-2000/1922. count-good-numbers/sol.rb | 25 + .../1501-2000/1922. count-good-numbers/sol.rs | 26 + .../1922. count-good-numbers/sol.swift | 26 + .../1501-2000/1922. count-good-numbers/sol.ts | 24 + .../manifest.yaml | 337 ++++ .../1923. longest-common-subpath/sol.cpp | 100 ++ .../1923. longest-common-subpath/sol.cs | 99 ++ .../1923. longest-common-subpath/sol.dart | 98 ++ .../1923. longest-common-subpath/sol.go | 109 ++ .../1923. longest-common-subpath/sol.java | 103 ++ .../1923. longest-common-subpath/sol.kt | 97 ++ .../1923. longest-common-subpath/sol.py | 95 ++ .../1923. longest-common-subpath/sol.py2 | 82 + .../1923. longest-common-subpath/sol.rb | 90 ++ .../1923. longest-common-subpath/sol.rs | 103 ++ .../1923. longest-common-subpath/sol.swift | 95 ++ .../1923. longest-common-subpath/sol.ts | 95 ++ .../manifest.yaml | 200 +++ .../1925. count-square-sum-triples/sol.cpp | 27 + .../1925. count-square-sum-triples/sol.cs | 25 + .../1925. count-square-sum-triples/sol.dart | 25 + .../1925. count-square-sum-triples/sol.go | 26 + .../1925. count-square-sum-triples/sol.java | 25 + .../1925. count-square-sum-triples/sol.kt | 29 + .../1925. count-square-sum-triples/sol.py | 17 + .../1925. count-square-sum-triples/sol.py2 | 21 + .../1925. count-square-sum-triples/sol.rb | 21 + .../1925. count-square-sum-triples/sol.rs | 34 + .../1925. count-square-sum-triples/sol.swift | 33 + .../1925. count-square-sum-triples/sol.ts | 23 + .../manifest.yaml | 378 +++++ .../sol.cpp | 24 + .../sol.cs | 23 + .../sol.dart | 24 + .../sol.go | 29 + .../sol.java | 24 + .../sol.kt | 25 + .../sol.py | 45 + .../sol.py2 | 26 + .../sol.rb | 23 + .../sol.rs | 26 + .../sol.swift | 27 + .../sol.ts | 35 + tests/1501-2000/1927. sum-game/manifest.yaml | 209 +++ tests/1501-2000/1927. sum-game/sol.cpp | 21 + tests/1501-2000/1927. sum-game/sol.cs | 20 + tests/1501-2000/1927. sum-game/sol.dart | 26 + tests/1501-2000/1927. sum-game/sol.go | 24 + tests/1501-2000/1927. sum-game/sol.java | 22 + tests/1501-2000/1927. sum-game/sol.kt | 24 + tests/1501-2000/1927. sum-game/sol.py | 24 + tests/1501-2000/1927. sum-game/sol.py2 | 24 + tests/1501-2000/1927. sum-game/sol.rb | 28 + tests/1501-2000/1927. sum-game/sol.rs | 29 + tests/1501-2000/1927. sum-game/sol.swift | 27 + tests/1501-2000/1927. sum-game/sol.ts | 20 + .../manifest.yaml | 448 ++++++ .../sol.cpp | 33 + .../sol.cs | 37 + .../sol.dart | 40 + .../sol.go | 54 + .../sol.java | 37 + .../sol.kt | 31 + .../sol.py | 60 + .../sol.py2 | 33 + .../sol.rb | 31 + .../sol.rs | 48 + .../sol.swift | 38 + .../sol.ts | 46 + .../manifest.yaml | 886 +++++++++++ .../1929. concatenation-of-array/sol.cpp | 11 + .../1929. concatenation-of-array/sol.cs | 10 + .../1929. concatenation-of-array/sol.dart | 10 + .../1929. concatenation-of-array/sol.go | 8 + .../1929. concatenation-of-array/sol.java | 10 + .../1929. concatenation-of-array/sol.kt | 10 + .../1929. concatenation-of-array/sol.py | 10 + .../1929. concatenation-of-array/sol.py2 | 11 + .../1929. concatenation-of-array/sol.rb | 10 + .../1929. concatenation-of-array/sol.rs | 10 + .../1929. concatenation-of-array/sol.swift | 10 + .../1929. concatenation-of-array/sol.ts | 8 + .../manifest.yaml | 305 ++++ .../sol.cpp | 26 + .../sol.cs | 35 + .../sol.dart | 25 + .../sol.go | 29 + .../sol.java | 29 + .../sol.kt | 25 + .../sol.py | 21 + .../sol.py2 | 25 + .../sol.rb | 26 + .../sol.rs | 28 + .../sol.swift | 28 + .../sol.ts | 23 + .../manifest.yaml | 295 ++++ .../sol.cpp | 53 + .../sol.cs | 52 + .../sol.dart | 60 + .../sol.go | 63 + .../sol.java | 52 + .../sol.kt | 52 + .../sol.py | 36 + .../sol.py2 | 41 + .../sol.rb | 49 + .../sol.rs | 62 + .../sol.swift | 60 + .../sol.ts | 56 + .../manifest.yaml | 236 +++ .../sol.cpp | 28 + .../sol.cs | 25 + .../sol.dart | 26 + .../sol.go | 24 + .../sol.java | 25 + .../sol.kt | 25 + .../sol.py | 20 + .../sol.py2 | 24 + .../sol.rb | 24 + .../sol.rs | 25 + .../sol.swift | 26 + .../sol.ts | 24 + .../manifest.yaml | 314 ++++ .../1936. add-minimum-number-of-rungs/sol.cpp | 14 + .../1936. add-minimum-number-of-rungs/sol.cs | 13 + .../sol.dart | 13 + .../1936. add-minimum-number-of-rungs/sol.go | 11 + .../sol.java | 13 + .../1936. add-minimum-number-of-rungs/sol.kt | 13 + .../1936. add-minimum-number-of-rungs/sol.py | 16 + .../1936. add-minimum-number-of-rungs/sol.py2 | 14 + .../1936. add-minimum-number-of-rungs/sol.rb | 14 + .../1936. add-minimum-number-of-rungs/sol.rs | 13 + .../sol.swift | 13 + .../1936. add-minimum-number-of-rungs/sol.ts | 11 + .../manifest.yaml | 356 +++++ .../sol.cpp | 33 + .../sol.cs | 33 + .../sol.dart | 36 + .../sol.go | 46 + .../sol.java | 35 + .../sol.kt | 32 + .../sol.py | 29 + .../sol.py2 | 30 + .../sol.rb | 32 + .../sol.rs | 32 + .../sol.swift | 32 + .../sol.ts | 30 + .../manifest.yaml | 816 ++++++++++ .../sol.cpp | 71 + .../sol.cs | 72 + .../sol.dart | 67 + .../sol.go | 79 + .../sol.java | 73 + .../sol.kt | 66 + .../sol.py | 80 + .../sol.py2 | 63 + .../sol.rb | 72 + .../sol.rs | 94 ++ .../sol.swift | 75 + .../sol.ts | 70 + .../manifest.yaml | 220 +++ .../sol.cpp | 14 + .../sol.cs | 9 + .../sol.dart | 10 + .../sol.go | 11 + .../sol.java | 9 + .../sol.kt | 9 + .../sol.py | 10 + .../sol.py2 | 10 + .../sol.rb | 7 + .../sol.rs | 13 + .../sol.swift | 9 + .../sol.ts | 7 + .../manifest.yaml | 236 +++ .../sol.cpp | 24 + .../sol.cs | 23 + .../sol.dart | 23 + .../sol.go | 23 + .../sol.java | 23 + .../sol.kt | 23 + .../sol.py | 17 + .../sol.py2 | 22 + .../sol.rb | 24 + .../sol.rs | 24 + .../sol.swift | 23 + .../sol.ts | 21 + .../1943. describe-the-painting/manifest.yaml | 323 ++++ .../1943. describe-the-painting/sol.cpp | 25 + .../1943. describe-the-painting/sol.cs | 24 + .../1943. describe-the-painting/sol.dart | 24 + .../1943. describe-the-painting/sol.go | 24 + .../1943. describe-the-painting/sol.java | 24 + .../1943. describe-the-painting/sol.kt | 24 + .../1943. describe-the-painting/sol.py | 30 + .../1943. describe-the-painting/sol.py2 | 22 + .../1943. describe-the-painting/sol.rb | 22 + .../1943. describe-the-painting/sol.rs | 24 + .../1943. describe-the-painting/sol.swift | 24 + .../1943. describe-the-painting/sol.ts | 22 + .../manifest.yaml | 331 ++++ .../sol.cpp | 27 + .../sol.cs | 26 + .../sol.dart | 26 + .../sol.go | 24 + .../sol.java | 26 + .../sol.kt | 26 + .../sol.py | 21 + .../sol.py2 | 24 + .../sol.rb | 24 + .../sol.rs | 26 + .../sol.swift | 26 + .../sol.ts | 24 + .../manifest.yaml | 371 +++++ .../sol.cpp | 17 + .../sol.cs | 16 + .../sol.dart | 16 + .../sol.go | 15 + .../sol.java | 16 + .../sol.kt | 12 + .../sol.py | 10 + .../sol.py2 | 13 + .../sol.rb | 10 + .../sol.rs | 13 + .../sol.swift | 16 + .../sol.ts | 14 + .../manifest.yaml | 280 ++++ .../sol.cpp | 19 + .../sol.cs | 18 + .../sol.dart | 18 + .../sol.go | 16 + .../sol.java | 18 + .../sol.kt | 18 + .../sol.py | 14 + .../sol.py2 | 19 + .../sol.rb | 19 + .../sol.rs | 18 + .../sol.swift | 18 + .../sol.ts | 16 + .../manifest.yaml | 511 ++++++ .../sol.cpp | 19 + .../sol.cs | 29 + .../sol.dart | 31 + .../sol.go | 31 + .../sol.java | 41 + .../sol.kt | 32 + .../sol.py | 24 + .../sol.py2 | 18 + .../sol.rb | 15 + .../sol.rs | 35 + .../sol.swift | 33 + .../sol.ts | 36 + .../manifest.yaml | 448 ++++++ .../sol.cpp | 70 + .../sol.cs | 78 + .../sol.dart | 69 + .../sol.go | 81 + .../sol.java | 82 + .../sol.kt | 65 + .../sol.py | 52 + .../sol.py2 | 55 + .../sol.rb | 57 + .../sol.rs | 83 + .../sol.swift | 73 + .../sol.ts | 79 + .../1952. three-divisors/manifest.yaml | 303 ++++ tests/1501-2000/1952. three-divisors/sol.cpp | 12 + tests/1501-2000/1952. three-divisors/sol.cs | 11 + tests/1501-2000/1952. three-divisors/sol.dart | 11 + tests/1501-2000/1952. three-divisors/sol.go | 9 + tests/1501-2000/1952. three-divisors/sol.java | 11 + tests/1501-2000/1952. three-divisors/sol.kt | 11 + tests/1501-2000/1952. three-divisors/sol.py | 8 + tests/1501-2000/1952. three-divisors/sol.py2 | 11 + tests/1501-2000/1952. three-divisors/sol.rb | 9 + tests/1501-2000/1952. three-divisors/sol.rs | 11 + .../1501-2000/1952. three-divisors/sol.swift | 11 + tests/1501-2000/1952. three-divisors/sol.ts | 9 + .../manifest.yaml | 260 ++++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 15 + .../sol.go | 14 + .../sol.java | 12 + .../sol.kt | 11 + .../sol.py | 12 + .../sol.py2 | 12 + .../sol.rb | 11 + .../sol.rs | 11 + .../sol.swift | 11 + .../sol.ts | 9 + .../manifest.yaml | 222 +++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 15 + .../sol.go | 13 + .../sol.java | 15 + .../sol.kt | 16 + .../sol.py | 11 + .../sol.py2 | 15 + .../sol.rb | 15 + .../sol.rs | 16 + .../sol.swift | 15 + .../sol.ts | 14 + .../manifest.yaml | 256 +++ .../sol.cpp | 17 + .../sol.cs | 16 + .../sol.dart | 16 + .../sol.go | 14 + .../sol.java | 16 + .../sol.kt | 16 + .../sol.py | 16 + .../sol.py2 | 16 + .../sol.rb | 16 + .../sol.rs | 18 + .../sol.swift | 16 + .../sol.ts | 16 + .../manifest.yaml | 232 +++ .../sol.cpp | 24 + .../sol.cs | 23 + .../sol.dart | 22 + .../sol.go | 24 + .../sol.java | 23 + .../sol.kt | 23 + .../sol.py | 18 + .../sol.py2 | 24 + .../sol.rb | 22 + .../sol.rs | 26 + .../sol.swift | 22 + .../sol.ts | 20 + .../manifest.yaml | 590 +++++++ .../1958. check-if-move-is-legal/sol.cpp | 25 + .../1958. check-if-move-is-legal/sol.cs | 28 + .../1958. check-if-move-is-legal/sol.dart | 28 + .../1958. check-if-move-is-legal/sol.go | 25 + .../1958. check-if-move-is-legal/sol.java | 24 + .../1958. check-if-move-is-legal/sol.kt | 28 + .../1958. check-if-move-is-legal/sol.py | 34 + .../1958. check-if-move-is-legal/sol.py2 | 27 + .../1958. check-if-move-is-legal/sol.rb | 29 + .../1958. check-if-move-is-legal/sol.rs | 24 + .../1958. check-if-move-is-legal/sol.swift | 24 + .../1958. check-if-move-is-legal/sol.ts | 43 + .../manifest.yaml | 961 ++++++++++++ .../sol.cpp | 31 + .../sol.cs | 30 + .../sol.dart | 31 + .../sol.go | 36 + .../sol.java | 32 + .../sol.kt | 30 + .../sol.py | 30 + .../sol.py2 | 27 + .../sol.rb | 30 + .../sol.rs | 33 + .../sol.swift | 30 + .../sol.ts | 27 + .../manifest.yaml | 227 +++ .../sol.cpp | 81 + .../sol.cs | 80 + .../sol.dart | 83 + .../sol.go | 97 ++ .../sol.java | 80 + .../sol.kt | 80 + .../sol.py | 64 + .../sol.py2 | 70 + .../sol.rb | 79 + .../sol.rs | 83 + .../sol.swift | 81 + .../sol.ts | 76 + .../manifest.yaml | 324 ++++ .../sol.cpp | 13 + .../sol.cs | 12 + .../sol.dart | 12 + .../sol.go | 12 + .../sol.java | 12 + .../sol.kt | 12 + .../sol.py | 10 + .../sol.py2 | 15 + .../sol.rb | 13 + .../sol.rs | 14 + .../sol.swift | 12 + .../sol.ts | 10 + .../manifest.yaml | 320 ++++ .../sol.cpp | 17 + .../sol.cs | 31 + .../sol.dart | 24 + .../sol.go | 27 + .../sol.java | 16 + .../sol.kt | 14 + .../sol.py | 17 + .../sol.py2 | 15 + .../sol.rb | 20 + .../sol.rs | 16 + .../sol.swift | 21 + .../sol.ts | 24 + .../manifest.yaml | 194 +++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 15 + .../sol.go | 13 + .../sol.java | 15 + .../sol.kt | 15 + .../sol.py | 10 + .../sol.py2 | 14 + .../sol.rb | 15 + .../sol.rs | 15 + .../sol.swift | 15 + .../sol.ts | 13 + .../manifest.yaml | 232 +++ .../sol.cpp | 18 + .../sol.cs | 30 + .../sol.dart | 30 + .../sol.go | 27 + .../sol.java | 32 + .../sol.kt | 31 + .../sol.py | 14 + .../sol.py2 | 18 + .../sol.rb | 16 + .../sol.rs | 30 + .../sol.swift | 29 + .../sol.ts | 28 + .../manifest.yaml | 326 ++++ .../sol.cpp | 12 + .../sol.cs | 11 + .../sol.dart | 11 + .../sol.go | 9 + .../sol.java | 11 + .../sol.kt | 11 + .../sol.py | 7 + .../sol.py2 | 12 + .../sol.rb | 12 + .../sol.rs | 11 + .../sol.swift | 11 + .../sol.ts | 9 + .../manifest.yaml | 357 +++++ .../sol.cpp | 17 + .../sol.cs | 16 + .../sol.dart | 16 + .../sol.go | 16 + .../sol.java | 14 + .../sol.kt | 16 + .../sol.py | 12 + .../sol.py2 | 12 + .../sol.rb | 15 + .../sol.rs | 19 + .../sol.swift | 22 + .../sol.ts | 14 + .../manifest.yaml | 221 +++ .../sol.cpp | 24 + .../sol.cs | 23 + .../sol.dart | 22 + .../sol.go | 21 + .../sol.java | 23 + .../sol.kt | 24 + .../sol.py | 21 + .../sol.py2 | 21 + .../sol.rb | 20 + .../sol.rs | 23 + .../sol.swift | 23 + .../sol.ts | 21 + .../manifest.yaml | 675 ++++++++ .../sol.cpp | 57 + .../sol.cs | 56 + .../sol.dart | 56 + .../sol.go | 63 + .../sol.java | 59 + .../sol.kt | 62 + .../sol.py | 52 + .../sol.py2 | 47 + .../sol.rb | 54 + .../sol.rs | 64 + .../sol.swift | 56 + .../sol.ts | 72 + .../manifest.yaml | 613 ++++++++ .../sol.cpp | 27 + .../1971. find-if-path-exists-in-graph/sol.cs | 28 + .../sol.dart | 25 + .../1971. find-if-path-exists-in-graph/sol.go | 27 + .../sol.java | 25 + .../1971. find-if-path-exists-in-graph/sol.kt | 24 + .../1971. find-if-path-exists-in-graph/sol.py | 59 + .../sol.py2 | 31 + .../1971. find-if-path-exists-in-graph/sol.rb | 26 + .../1971. find-if-path-exists-in-graph/sol.rs | 25 + .../sol.swift | 23 + .../1971. find-if-path-exists-in-graph/sol.ts | 28 + .../manifest.yaml | 226 +++ .../sol.cpp | 16 + .../sol.cs | 15 + .../sol.dart | 16 + .../sol.go | 20 + .../sol.java | 15 + .../sol.kt | 15 + .../sol.py | 12 + .../sol.py2 | 16 + .../sol.rb | 15 + .../sol.rs | 15 + .../sol.swift | 15 + .../sol.ts | 14 + .../1975. maximum-matrix-sum/manifest.yaml | 397 +++++ .../1975. maximum-matrix-sum/sol.cpp | 17 + .../1501-2000/1975. maximum-matrix-sum/sol.cs | 16 + .../1975. maximum-matrix-sum/sol.dart | 16 + .../1501-2000/1975. maximum-matrix-sum/sol.go | 24 + .../1975. maximum-matrix-sum/sol.java | 16 + .../1501-2000/1975. maximum-matrix-sum/sol.kt | 16 + .../1501-2000/1975. maximum-matrix-sum/sol.py | 15 + .../1975. maximum-matrix-sum/sol.py2 | 17 + .../1501-2000/1975. maximum-matrix-sum/sol.rb | 18 + .../1501-2000/1975. maximum-matrix-sum/sol.rs | 22 + .../1975. maximum-matrix-sum/sol.swift | 16 + .../1501-2000/1975. maximum-matrix-sum/sol.ts | 14 + .../manifest.yaml | 780 ++++++++++ .../sol.cpp | 40 + .../sol.cs | 46 + .../sol.dart | 43 + .../sol.go | 66 + .../sol.java | 48 + .../sol.kt | 39 + .../sol.py | 36 + .../sol.py2 | 30 + .../sol.rb | 41 + .../sol.rs | 60 + .../sol.swift | 41 + .../sol.ts | 35 + .../manifest.yaml | 306 ++++ .../sol.cpp | 32 + .../sol.cs | 31 + .../sol.dart | 30 + .../sol.go | 32 + .../sol.java | 31 + .../sol.kt | 31 + .../sol.py | 25 + .../sol.py2 | 23 + .../sol.rb | 29 + .../sol.rs | 31 + .../sol.swift | 50 + .../sol.ts | 34 + .../manifest.yaml | 241 +++ .../sol.cpp | 18 + .../sol.cs | 16 + .../sol.dart | 16 + .../sol.go | 20 + .../sol.java | 20 + .../sol.kt | 18 + .../sol.py | 6 + .../sol.py2 | 12 + .../sol.rb | 10 + .../sol.rs | 16 + .../sol.swift | 18 + .../sol.ts | 14 + .../manifest.yaml | 472 ++++++ .../1980. find-unique-binary-string/sol.cpp | 10 + .../1980. find-unique-binary-string/sol.cs | 9 + .../1980. find-unique-binary-string/sol.dart | 9 + .../1980. find-unique-binary-string/sol.go | 11 + .../1980. find-unique-binary-string/sol.java | 10 + .../1980. find-unique-binary-string/sol.kt | 5 + .../1980. find-unique-binary-string/sol.py | 3 + .../1980. find-unique-binary-string/sol.py2 | 7 + .../1980. find-unique-binary-string/sol.rb | 5 + .../1980. find-unique-binary-string/sol.rs | 7 + .../1980. find-unique-binary-string/sol.swift | 8 + .../1980. find-unique-binary-string/sol.ts | 3 + .../manifest.yaml | 419 +++++ .../sol.cpp | 31 + .../sol.cs | 33 + .../sol.dart | 31 + .../sol.go | 45 + .../sol.java | 32 + .../sol.kt | 29 + .../sol.py | 26 + .../sol.py2 | 31 + .../sol.rb | 30 + .../sol.rs | 38 + .../sol.swift | 39 + .../sol.ts | 28 + .../manifest.yaml | 254 +++ .../sol.cpp | 41 + .../1982. find-array-given-subset-sums/sol.cs | 37 + .../sol.dart | 36 + .../1982. find-array-given-subset-sums/sol.go | 41 + .../sol.java | 34 + .../1982. find-array-given-subset-sums/sol.kt | 34 + .../1982. find-array-given-subset-sums/sol.py | 36 + .../sol.py2 | 34 + .../1982. find-array-given-subset-sums/sol.rb | 34 + .../1982. find-array-given-subset-sums/sol.rs | 36 + .../sol.swift | 35 + .../1982. find-array-given-subset-sums/sol.ts | 31 + .../manifest.yaml | 403 +++++ .../sol.cpp | 12 + .../sol.cs | 11 + .../sol.dart | 11 + .../sol.go | 11 + .../sol.java | 11 + .../sol.kt | 11 + .../sol.py | 8 + .../sol.py2 | 13 + .../sol.rb | 11 + .../sol.rs | 13 + .../sol.swift | 11 + .../sol.ts | 9 + .../manifest.yaml | 684 +++++++++ .../sol.cpp | 10 + .../sol.cs | 9 + .../sol.dart | 9 + .../sol.go | 7 + .../sol.java | 9 + .../sol.kt | 6 + .../sol.py | 5 + .../sol.py2 | 9 + .../sol.rb | 7 + .../sol.rs | 7 + .../sol.swift | 9 + .../sol.ts | 6 + .../manifest.yaml | 381 +++++ .../sol.cpp | 38 + .../sol.cs | 38 + .../sol.dart | 39 + .../sol.go | 46 + .../sol.java | 41 + .../sol.kt | 38 + .../sol.py | 45 + .../sol.py2 | 39 + .../sol.rb | 39 + .../sol.rs | 39 + .../sol.swift | 37 + .../sol.ts | 38 + .../manifest.yaml | 229 +++ .../sol.cpp | 17 + .../sol.cs | 16 + .../sol.dart | 15 + .../sol.go | 14 + .../sol.java | 15 + .../sol.kt | 16 + .../sol.py | 11 + .../sol.py2 | 15 + .../sol.rb | 16 + .../sol.rs | 17 + .../sol.swift | 17 + .../sol.ts | 15 + .../manifest.yaml | 323 ++++ .../sol.cpp | 18 + .../sol.cs | 15 + .../sol.dart | 15 + .../sol.go | 19 + .../sol.java | 17 + .../sol.kt | 15 + .../sol.py | 17 + .../sol.py2 | 17 + .../sol.rb | 15 + .../sol.rs | 17 + .../sol.swift | 17 + .../sol.ts | 13 + .../manifest.yaml | 372 +++++ .../1992. find-all-groups-of-farmland/sol.cpp | 40 + .../1992. find-all-groups-of-farmland/sol.cs | 40 + .../sol.dart | 39 + .../1992. find-all-groups-of-farmland/sol.go | 40 + .../sol.java | 40 + .../1992. find-all-groups-of-farmland/sol.kt | 40 + .../1992. find-all-groups-of-farmland/sol.py | 78 + .../1992. find-all-groups-of-farmland/sol.py2 | 30 + .../1992. find-all-groups-of-farmland/sol.rb | 35 + .../1992. find-all-groups-of-farmland/sol.rs | 41 + .../sol.swift | 39 + .../1992. find-all-groups-of-farmland/sol.ts | 44 + .../manifest.yaml | 292 ++++ .../1994. the-number-of-good-subsets/sol.cpp | 31 + .../1994. the-number-of-good-subsets/sol.cs | 30 + .../1994. the-number-of-good-subsets/sol.dart | 33 + .../1994. the-number-of-good-subsets/sol.go | 30 + .../1994. the-number-of-good-subsets/sol.java | 30 + .../1994. the-number-of-good-subsets/sol.kt | 33 + .../1994. the-number-of-good-subsets/sol.py | 43 + .../1994. the-number-of-good-subsets/sol.py2 | 32 + .../1994. the-number-of-good-subsets/sol.rb | 31 + .../1994. the-number-of-good-subsets/sol.rs | 31 + .../sol.swift | 30 + .../1994. the-number-of-good-subsets/sol.ts | 37 + .../manifest.yaml | 242 +++ .../1995. count-special-quadruplets/sol.cpp | 16 + .../1995. count-special-quadruplets/sol.cs | 18 + .../1995. count-special-quadruplets/sol.dart | 18 + .../1995. count-special-quadruplets/sol.go | 16 + .../1995. count-special-quadruplets/sol.java | 15 + .../1995. count-special-quadruplets/sol.kt | 16 + .../1995. count-special-quadruplets/sol.py | 10 + .../1995. count-special-quadruplets/sol.py2 | 13 + .../1995. count-special-quadruplets/sol.rb | 16 + .../1995. count-special-quadruplets/sol.rs | 18 + .../1995. count-special-quadruplets/sol.swift | 18 + .../1995. count-special-quadruplets/sol.ts | 16 + .../manifest.yaml | 441 ++++++ .../sol.cpp | 22 + .../sol.cs | 18 + .../sol.dart | 18 + .../sol.go | 21 + .../sol.java | 18 + .../sol.kt | 18 + .../sol.py | 18 + .../sol.py2 | 18 + .../sol.rb | 18 + .../sol.rs | 21 + .../sol.swift | 21 + .../sol.ts | 16 + .../manifest.yaml | 397 +++++ .../sol.cpp | 14 + .../sol.cs | 13 + .../sol.dart | 13 + .../sol.go | 11 + .../sol.java | 13 + .../sol.kt | 13 + .../sol.py | 14 + .../sol.py2 | 14 + .../sol.rb | 13 + .../sol.rs | 13 + .../sol.swift | 13 + .../sol.ts | 11 + .../1998. gcd-sort-of-an-array/manifest.yaml | 267 ++++ .../1998. gcd-sort-of-an-array/sol.cpp | 30 + .../1998. gcd-sort-of-an-array/sol.cs | 18 + .../1998. gcd-sort-of-an-array/sol.dart | 22 + .../1998. gcd-sort-of-an-array/sol.go | 17 + .../1998. gcd-sort-of-an-array/sol.java | 68 + .../1998. gcd-sort-of-an-array/sol.kt | 55 + .../1998. gcd-sort-of-an-array/sol.py | 46 + .../1998. gcd-sort-of-an-array/sol.py2 | 42 + .../1998. gcd-sort-of-an-array/sol.rb | 37 + .../1998. gcd-sort-of-an-array/sol.rs | 66 + .../1998. gcd-sort-of-an-array/sol.swift | 60 + .../1998. gcd-sort-of-an-array/sol.ts | 58 + .../manifest.yaml | 325 ++++ .../2000. reverse-prefix-of-word/sol.cpp | 11 + .../2000. reverse-prefix-of-word/sol.cs | 11 + .../2000. reverse-prefix-of-word/sol.dart | 11 + .../2000. reverse-prefix-of-word/sol.go | 17 + .../2000. reverse-prefix-of-word/sol.java | 13 + .../2000. reverse-prefix-of-word/sol.kt | 12 + .../2000. reverse-prefix-of-word/sol.py | 17 + .../2000. reverse-prefix-of-word/sol.py2 | 11 + .../2000. reverse-prefix-of-word/sol.rb | 5 + .../2000. reverse-prefix-of-word/sol.rs | 19 + .../2000. reverse-prefix-of-word/sol.swift | 15 + .../2000. reverse-prefix-of-word/sol.ts | 9 + .../manifest.yaml | 504 ++++++ .../sol.cpp | 33 + .../sol.cs | 25 + .../sol.dart | 37 + .../sol.go | 21 + .../sol.java | 25 + .../sol.kt | 28 + .../sol.py | 25 + .../sol.py2 | 23 + .../sol.rb | 22 + .../sol.rs | 28 + .../sol.swift | 32 + .../sol.ts | 20 + .../manifest.yaml | 226 +++ .../sol.cpp | 37 + .../sol.cs | 41 + .../sol.dart | 36 + .../sol.go | 48 + .../sol.java | 34 + .../sol.kt | 32 + .../sol.py | 29 + .../sol.py2 | 29 + .../sol.rb | 35 + .../sol.rs | 34 + .../sol.swift | 35 + .../sol.ts | 33 + .../manifest.yaml | 290 ++++ .../sol.cpp | 44 + .../sol.cs | 49 + .../sol.dart | 42 + .../sol.go | 46 + .../sol.java | 47 + .../sol.kt | 45 + .../sol.py | 45 + .../sol.py2 | 43 + .../sol.rb | 41 + .../sol.rs | 48 + .../sol.swift | 48 + .../sol.ts | 48 + .../manifest.yaml | 403 +++++ .../sol.cpp | 15 + .../sol.cs | 13 + .../sol.dart | 13 + .../sol.go | 11 + .../sol.java | 13 + .../sol.kt | 9 + .../sol.py | 4 + .../sol.py2 | 10 + .../sol.rb | 7 + .../sol.rs | 10 + .../sol.swift | 13 + .../sol.ts | 11 + .../manifest.yaml | 288 ++++ .../sol.cpp | 23 + .../sol.cs | 22 + .../sol.dart | 22 + .../sol.go | 26 + .../sol.java | 26 + .../sol.kt | 22 + .../sol.py | 23 + .../sol.py2 | 23 + .../sol.rb | 20 + .../sol.rs | 29 + .../sol.swift | 22 + .../sol.ts | 20 + .../manifest.yaml | 380 +++++ .../2008. maximum-earnings-from-taxi/sol.cpp | 36 + .../2008. maximum-earnings-from-taxi/sol.cs | 31 + .../2008. maximum-earnings-from-taxi/sol.dart | 28 + .../2008. maximum-earnings-from-taxi/sol.go | 29 + .../2008. maximum-earnings-from-taxi/sol.java | 34 + .../2008. maximum-earnings-from-taxi/sol.kt | 31 + .../2008. maximum-earnings-from-taxi/sol.py | 21 + .../2008. maximum-earnings-from-taxi/sol.py2 | 20 + .../2008. maximum-earnings-from-taxi/sol.rb | 19 + .../2008. maximum-earnings-from-taxi/sol.rs | 32 + .../sol.swift | 29 + .../2008. maximum-earnings-from-taxi/sol.ts | 13 + .../manifest.yaml | 231 +++ .../sol.cpp | 21 + .../sol.cs | 18 + .../sol.dart | 18 + .../sol.go | 26 + .../sol.java | 18 + .../sol.kt | 18 + .../sol.py | 17 + .../sol.py2 | 18 + .../sol.rb | 18 + .../sol.rs | 19 + .../sol.swift | 18 + .../sol.ts | 19 + .../manifest.yaml | 587 +++++++ .../sol.cpp | 10 + .../sol.cs | 9 + .../sol.dart | 5 + .../sol.go | 11 + .../sol.java | 9 + .../sol.kt | 7 + .../sol.py | 3 + .../sol.py2 | 7 + .../sol.rb | 5 + .../sol.rs | 5 + .../sol.swift | 5 + .../sol.ts | 3 + .../manifest.yaml | 266 ++++ .../2012. sum-of-beauty-in-the-array/sol.cpp | 24 + .../2012. sum-of-beauty-in-the-array/sol.cs | 24 + .../2012. sum-of-beauty-in-the-array/sol.dart | 24 + .../2012. sum-of-beauty-in-the-array/sol.go | 30 + .../2012. sum-of-beauty-in-the-array/sol.java | 24 + .../2012. sum-of-beauty-in-the-array/sol.kt | 24 + .../2012. sum-of-beauty-in-the-array/sol.py | 23 + .../2012. sum-of-beauty-in-the-array/sol.py2 | 22 + .../2012. sum-of-beauty-in-the-array/sol.rb | 24 + .../2012. sum-of-beauty-in-the-array/sol.rs | 24 + .../sol.swift | 24 + .../2012. sum-of-beauty-in-the-array/sol.ts | 22 + .../manifest.yaml | 267 ++++ .../sol.cpp | 36 + .../sol.cs | 36 + .../sol.dart | 33 + .../sol.go | 34 + .../sol.java | 36 + .../sol.kt | 34 + .../sol.py | 24 + .../sol.py2 | 30 + .../sol.rb | 34 + .../sol.rs | 36 + .../sol.swift | 37 + .../sol.ts | 31 + .../manifest.yaml | 265 ++++ .../sol.cpp | 15 + .../sol.cs | 14 + .../sol.dart | 14 + .../sol.go | 14 + .../sol.java | 14 + .../sol.kt | 14 + .../sol.py | 12 + .../sol.py2 | 14 + .../sol.rb | 14 + .../sol.rs | 14 + .../sol.swift | 14 + .../sol.ts | 12 + tests/2001-2500/2017. grid-game/manifest.yaml | 271 ++++ tests/2001-2500/2017. grid-game/sol.cpp | 19 + tests/2001-2500/2017. grid-game/sol.cs | 18 + tests/2001-2500/2017. grid-game/sol.dart | 18 + tests/2001-2500/2017. grid-game/sol.go | 22 + tests/2001-2500/2017. grid-game/sol.java | 18 + tests/2001-2500/2017. grid-game/sol.kt | 15 + tests/2001-2500/2017. grid-game/sol.py | 12 + tests/2001-2500/2017. grid-game/sol.py2 | 16 + tests/2001-2500/2017. grid-game/sol.rb | 15 + tests/2001-2500/2017. grid-game/sol.rs | 16 + tests/2001-2500/2017. grid-game/sol.swift | 16 + tests/2001-2500/2017. grid-game/sol.ts | 13 + .../manifest.yaml | 380 +++++ .../sol.cpp | 52 + .../sol.cs | 31 + .../sol.dart | 30 + .../sol.go | 62 + .../sol.java | 30 + .../sol.kt | 31 + .../sol.py | 32 + .../sol.py2 | 31 + .../sol.rb | 29 + .../sol.rs | 52 + .../sol.swift | 53 + .../sol.ts | 32 + .../manifest.yaml | 245 +++ .../sol.cpp | 68 + .../sol.cs | 67 + .../sol.dart | 63 + .../sol.go | 81 + .../sol.java | 73 + .../sol.kt | 60 + .../sol.py | 27 + .../sol.py2 | 36 + .../sol.rb | 38 + .../sol.rs | 80 + .../sol.swift | 71 + .../sol.ts | 66 + .../manifest.yaml | 1205 +++++++++++++++ .../sol.cpp | 15 + .../sol.cs | 14 + .../sol.dart | 14 + .../sol.go | 16 + .../sol.java | 14 + .../sol.kt | 14 + .../sol.py | 14 + .../sol.py2 | 20 + .../sol.rb | 19 + .../sol.rs | 17 + .../sol.swift | 15 + .../sol.ts | 16 + .../manifest.yaml | 385 +++++ .../sol.cpp | 25 + .../sol.cs | 24 + .../sol.dart | 24 + .../sol.go | 22 + .../sol.java | 24 + .../sol.kt | 21 + .../sol.py | 24 + .../sol.py2 | 22 + .../sol.rb | 22 + .../sol.rs | 26 + .../sol.swift | 25 + .../sol.ts | 22 + .../manifest.yaml | 264 ++++ .../sol.cpp | 31 + .../sol.cs | 30 + .../sol.dart | 30 + .../sol.go | 30 + .../sol.java | 30 + .../sol.kt | 30 + .../sol.py | 22 + .../sol.py2 | 27 + .../sol.rb | 31 + .../sol.rs | 31 + .../sol.swift | 31 + .../sol.ts | 28 + 4771 files changed, 237103 insertions(+) create mode 100644 tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/manifest.yaml create mode 100644 tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.cpp create mode 100644 tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.cs create mode 100644 tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.dart create mode 100644 tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.go create mode 100644 tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.java create mode 100644 tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.kt create mode 100644 tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.py create mode 100644 tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.py2 create mode 100644 tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.rb create mode 100644 tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.rs create mode 100644 tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.swift create mode 100644 tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.ts create mode 100644 tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/manifest.yaml create mode 100644 tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.cpp create mode 100644 tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.cs create mode 100644 tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.dart create mode 100644 tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.go create mode 100644 tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.java create mode 100644 tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.kt create mode 100644 tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.py create mode 100644 tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.py2 create mode 100644 tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.rb create mode 100644 tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.rs create mode 100644 tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.swift create mode 100644 tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.ts create mode 100644 tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/manifest.yaml create mode 100644 tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.cpp create mode 100644 tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.cs create mode 100644 tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.dart create mode 100644 tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.go create mode 100644 tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.java create mode 100644 tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.kt create mode 100644 tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.py create mode 100644 tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.py2 create mode 100644 tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.rb create mode 100644 tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.rs create mode 100644 tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.swift create mode 100644 tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.ts create mode 100644 tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/manifest.yaml create mode 100644 tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.cpp create mode 100644 tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.cs create mode 100644 tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.dart create mode 100644 tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.go create mode 100644 tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.java create mode 100644 tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.kt create mode 100644 tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.py create mode 100644 tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.py2 create mode 100644 tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.rb create mode 100644 tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.rs create mode 100644 tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.swift create mode 100644 tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.ts create mode 100644 tests/1501-2000/1525. number-of-good-ways-to-split-a-string/manifest.yaml create mode 100644 tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.cpp create mode 100644 tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.cs create mode 100644 tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.dart create mode 100644 tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.go create mode 100644 tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.java create mode 100644 tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.kt create mode 100644 tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.py create mode 100644 tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.py2 create mode 100644 tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.rb create mode 100644 tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.rs create mode 100644 tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.swift create mode 100644 tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.ts create mode 100644 tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/manifest.yaml create mode 100644 tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.cpp create mode 100644 tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.cs create mode 100644 tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.dart create mode 100644 tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.go create mode 100644 tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.java create mode 100644 tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.kt create mode 100644 tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.py create mode 100644 tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.py2 create mode 100644 tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.rb create mode 100644 tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.rs create mode 100644 tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.swift create mode 100644 tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.ts create mode 100644 tests/1501-2000/1528. shuffle-string/manifest.yaml create mode 100644 tests/1501-2000/1528. shuffle-string/sol.cpp create mode 100644 tests/1501-2000/1528. shuffle-string/sol.cs create mode 100644 tests/1501-2000/1528. shuffle-string/sol.dart create mode 100644 tests/1501-2000/1528. shuffle-string/sol.go create mode 100644 tests/1501-2000/1528. shuffle-string/sol.java create mode 100644 tests/1501-2000/1528. shuffle-string/sol.kt create mode 100644 tests/1501-2000/1528. shuffle-string/sol.py create mode 100644 tests/1501-2000/1528. shuffle-string/sol.py2 create mode 100644 tests/1501-2000/1528. shuffle-string/sol.rb create mode 100644 tests/1501-2000/1528. shuffle-string/sol.rs create mode 100644 tests/1501-2000/1528. shuffle-string/sol.swift create mode 100644 tests/1501-2000/1528. shuffle-string/sol.ts create mode 100644 tests/1501-2000/1529. minimum-suffix-flips/manifest.yaml create mode 100644 tests/1501-2000/1529. minimum-suffix-flips/sol.cpp create mode 100644 tests/1501-2000/1529. minimum-suffix-flips/sol.cs create mode 100644 tests/1501-2000/1529. minimum-suffix-flips/sol.dart create mode 100644 tests/1501-2000/1529. minimum-suffix-flips/sol.go create mode 100644 tests/1501-2000/1529. minimum-suffix-flips/sol.java create mode 100644 tests/1501-2000/1529. minimum-suffix-flips/sol.kt create mode 100644 tests/1501-2000/1529. minimum-suffix-flips/sol.py create mode 100644 tests/1501-2000/1529. minimum-suffix-flips/sol.py2 create mode 100644 tests/1501-2000/1529. minimum-suffix-flips/sol.rb create mode 100644 tests/1501-2000/1529. minimum-suffix-flips/sol.rs create mode 100644 tests/1501-2000/1529. minimum-suffix-flips/sol.swift create mode 100644 tests/1501-2000/1529. minimum-suffix-flips/sol.ts create mode 100644 tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/manifest.yaml create mode 100644 tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.cpp create mode 100644 tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.cs create mode 100644 tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.dart create mode 100644 tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.go create mode 100644 tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.java create mode 100644 tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.kt create mode 100644 tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.py create mode 100644 tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.py2 create mode 100644 tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.rb create mode 100644 tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.rs create mode 100644 tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.swift create mode 100644 tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.ts create mode 100644 tests/1501-2000/1531. string-compression-ii/manifest.yaml create mode 100644 tests/1501-2000/1531. string-compression-ii/sol.cpp create mode 100644 tests/1501-2000/1531. string-compression-ii/sol.cs create mode 100644 tests/1501-2000/1531. string-compression-ii/sol.dart create mode 100644 tests/1501-2000/1531. string-compression-ii/sol.go create mode 100644 tests/1501-2000/1531. string-compression-ii/sol.java create mode 100644 tests/1501-2000/1531. string-compression-ii/sol.kt create mode 100644 tests/1501-2000/1531. string-compression-ii/sol.py create mode 100644 tests/1501-2000/1531. string-compression-ii/sol.py2 create mode 100644 tests/1501-2000/1531. string-compression-ii/sol.rb create mode 100644 tests/1501-2000/1531. string-compression-ii/sol.rs create mode 100644 tests/1501-2000/1531. string-compression-ii/sol.swift create mode 100644 tests/1501-2000/1531. string-compression-ii/sol.ts create mode 100644 tests/1501-2000/1534. count-good-triplets/manifest.yaml create mode 100644 tests/1501-2000/1534. count-good-triplets/sol.cpp create mode 100644 tests/1501-2000/1534. count-good-triplets/sol.cs create mode 100644 tests/1501-2000/1534. count-good-triplets/sol.dart create mode 100644 tests/1501-2000/1534. count-good-triplets/sol.go create mode 100644 tests/1501-2000/1534. count-good-triplets/sol.java create mode 100644 tests/1501-2000/1534. count-good-triplets/sol.kt create mode 100644 tests/1501-2000/1534. count-good-triplets/sol.py create mode 100644 tests/1501-2000/1534. count-good-triplets/sol.py2 create mode 100644 tests/1501-2000/1534. count-good-triplets/sol.rb create mode 100644 tests/1501-2000/1534. count-good-triplets/sol.rs create mode 100644 tests/1501-2000/1534. count-good-triplets/sol.swift create mode 100644 tests/1501-2000/1534. count-good-triplets/sol.ts create mode 100644 tests/1501-2000/1535. find-the-winner-of-an-array-game/manifest.yaml create mode 100644 tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.cpp create mode 100644 tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.cs create mode 100644 tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.dart create mode 100644 tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.go create mode 100644 tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.java create mode 100644 tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.kt create mode 100644 tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.py create mode 100644 tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.py2 create mode 100644 tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.rb create mode 100644 tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.rs create mode 100644 tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.swift create mode 100644 tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.ts create mode 100644 tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/manifest.yaml create mode 100644 tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.cpp create mode 100644 tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.cs create mode 100644 tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.dart create mode 100644 tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.go create mode 100644 tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.java create mode 100644 tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.kt create mode 100644 tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.py create mode 100644 tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.py2 create mode 100644 tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.rb create mode 100644 tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.rs create mode 100644 tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.swift create mode 100644 tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.ts create mode 100644 tests/1501-2000/1537. get-the-maximum-score/manifest.yaml create mode 100644 tests/1501-2000/1537. get-the-maximum-score/sol.cpp create mode 100644 tests/1501-2000/1537. get-the-maximum-score/sol.cs create mode 100644 tests/1501-2000/1537. get-the-maximum-score/sol.dart create mode 100644 tests/1501-2000/1537. get-the-maximum-score/sol.go create mode 100644 tests/1501-2000/1537. get-the-maximum-score/sol.java create mode 100644 tests/1501-2000/1537. get-the-maximum-score/sol.kt create mode 100644 tests/1501-2000/1537. get-the-maximum-score/sol.py create mode 100644 tests/1501-2000/1537. get-the-maximum-score/sol.py2 create mode 100644 tests/1501-2000/1537. get-the-maximum-score/sol.rb create mode 100644 tests/1501-2000/1537. get-the-maximum-score/sol.rs create mode 100644 tests/1501-2000/1537. get-the-maximum-score/sol.swift create mode 100644 tests/1501-2000/1537. get-the-maximum-score/sol.ts create mode 100644 tests/1501-2000/1539. kth-missing-positive-number/manifest.yaml create mode 100644 tests/1501-2000/1539. kth-missing-positive-number/sol.cpp create mode 100644 tests/1501-2000/1539. kth-missing-positive-number/sol.cs create mode 100644 tests/1501-2000/1539. kth-missing-positive-number/sol.dart create mode 100644 tests/1501-2000/1539. kth-missing-positive-number/sol.go create mode 100644 tests/1501-2000/1539. kth-missing-positive-number/sol.java create mode 100644 tests/1501-2000/1539. kth-missing-positive-number/sol.kt create mode 100644 tests/1501-2000/1539. kth-missing-positive-number/sol.py create mode 100644 tests/1501-2000/1539. kth-missing-positive-number/sol.py2 create mode 100644 tests/1501-2000/1539. kth-missing-positive-number/sol.rb create mode 100644 tests/1501-2000/1539. kth-missing-positive-number/sol.rs create mode 100644 tests/1501-2000/1539. kth-missing-positive-number/sol.swift create mode 100644 tests/1501-2000/1539. kth-missing-positive-number/sol.ts create mode 100644 tests/1501-2000/1540. can-convert-string-in-k-moves/manifest.yaml create mode 100644 tests/1501-2000/1540. can-convert-string-in-k-moves/sol.cpp create mode 100644 tests/1501-2000/1540. can-convert-string-in-k-moves/sol.cs create mode 100644 tests/1501-2000/1540. can-convert-string-in-k-moves/sol.dart create mode 100644 tests/1501-2000/1540. can-convert-string-in-k-moves/sol.go create mode 100644 tests/1501-2000/1540. can-convert-string-in-k-moves/sol.java create mode 100644 tests/1501-2000/1540. can-convert-string-in-k-moves/sol.kt create mode 100644 tests/1501-2000/1540. can-convert-string-in-k-moves/sol.py create mode 100644 tests/1501-2000/1540. can-convert-string-in-k-moves/sol.py2 create mode 100644 tests/1501-2000/1540. can-convert-string-in-k-moves/sol.rb create mode 100644 tests/1501-2000/1540. can-convert-string-in-k-moves/sol.rs create mode 100644 tests/1501-2000/1540. can-convert-string-in-k-moves/sol.swift create mode 100644 tests/1501-2000/1540. can-convert-string-in-k-moves/sol.ts create mode 100644 tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/manifest.yaml create mode 100644 tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.cpp create mode 100644 tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.cs create mode 100644 tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.dart create mode 100644 tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.go create mode 100644 tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.java create mode 100644 tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.kt create mode 100644 tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.py create mode 100644 tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.py2 create mode 100644 tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.rb create mode 100644 tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.rs create mode 100644 tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.swift create mode 100644 tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.ts create mode 100644 tests/1501-2000/1542. find-longest-awesome-substring/manifest.yaml create mode 100644 tests/1501-2000/1542. find-longest-awesome-substring/sol.cpp create mode 100644 tests/1501-2000/1542. find-longest-awesome-substring/sol.cs create mode 100644 tests/1501-2000/1542. find-longest-awesome-substring/sol.dart create mode 100644 tests/1501-2000/1542. find-longest-awesome-substring/sol.go create mode 100644 tests/1501-2000/1542. find-longest-awesome-substring/sol.java create mode 100644 tests/1501-2000/1542. find-longest-awesome-substring/sol.kt create mode 100644 tests/1501-2000/1542. find-longest-awesome-substring/sol.py create mode 100644 tests/1501-2000/1542. find-longest-awesome-substring/sol.py2 create mode 100644 tests/1501-2000/1542. find-longest-awesome-substring/sol.rb create mode 100644 tests/1501-2000/1542. find-longest-awesome-substring/sol.rs create mode 100644 tests/1501-2000/1542. find-longest-awesome-substring/sol.swift create mode 100644 tests/1501-2000/1542. find-longest-awesome-substring/sol.ts create mode 100644 tests/1501-2000/1544. make-the-string-great/manifest.yaml create mode 100644 tests/1501-2000/1544. make-the-string-great/sol.cpp create mode 100644 tests/1501-2000/1544. make-the-string-great/sol.cs create mode 100644 tests/1501-2000/1544. make-the-string-great/sol.dart create mode 100644 tests/1501-2000/1544. make-the-string-great/sol.go create mode 100644 tests/1501-2000/1544. make-the-string-great/sol.java create mode 100644 tests/1501-2000/1544. make-the-string-great/sol.kt create mode 100644 tests/1501-2000/1544. make-the-string-great/sol.py create mode 100644 tests/1501-2000/1544. make-the-string-great/sol.py2 create mode 100644 tests/1501-2000/1544. make-the-string-great/sol.rb create mode 100644 tests/1501-2000/1544. make-the-string-great/sol.rs create mode 100644 tests/1501-2000/1544. make-the-string-great/sol.swift create mode 100644 tests/1501-2000/1544. make-the-string-great/sol.ts create mode 100644 tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/manifest.yaml create mode 100644 tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.cpp create mode 100644 tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.cs create mode 100644 tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.dart create mode 100644 tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.go create mode 100644 tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.java create mode 100644 tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.kt create mode 100644 tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.py create mode 100644 tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.py2 create mode 100644 tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.rb create mode 100644 tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.rs create mode 100644 tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.swift create mode 100644 tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.ts create mode 100644 tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/manifest.yaml create mode 100644 tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.cpp create mode 100644 tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.cs create mode 100644 tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.dart create mode 100644 tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.go create mode 100644 tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.java create mode 100644 tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.kt create mode 100644 tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.py create mode 100644 tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.py2 create mode 100644 tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.rb create mode 100644 tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.rs create mode 100644 tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.swift create mode 100644 tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.ts create mode 100644 tests/1501-2000/1547. minimum-cost-to-cut-a-stick/manifest.yaml create mode 100644 tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.cpp create mode 100644 tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.cs create mode 100644 tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.dart create mode 100644 tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.go create mode 100644 tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.java create mode 100644 tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.kt create mode 100644 tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.py create mode 100644 tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.py2 create mode 100644 tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.rb create mode 100644 tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.rs create mode 100644 tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.swift create mode 100644 tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.ts create mode 100644 tests/1501-2000/1550. three-consecutive-odds/manifest.yaml create mode 100644 tests/1501-2000/1550. three-consecutive-odds/sol.cpp create mode 100644 tests/1501-2000/1550. three-consecutive-odds/sol.cs create mode 100644 tests/1501-2000/1550. three-consecutive-odds/sol.dart create mode 100644 tests/1501-2000/1550. three-consecutive-odds/sol.go create mode 100644 tests/1501-2000/1550. three-consecutive-odds/sol.java create mode 100644 tests/1501-2000/1550. three-consecutive-odds/sol.kt create mode 100644 tests/1501-2000/1550. three-consecutive-odds/sol.py create mode 100644 tests/1501-2000/1550. three-consecutive-odds/sol.py2 create mode 100644 tests/1501-2000/1550. three-consecutive-odds/sol.rb create mode 100644 tests/1501-2000/1550. three-consecutive-odds/sol.rs create mode 100644 tests/1501-2000/1550. three-consecutive-odds/sol.swift create mode 100644 tests/1501-2000/1550. three-consecutive-odds/sol.ts create mode 100644 tests/1501-2000/1551. minimum-operations-to-make-array-equal/manifest.yaml create mode 100644 tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.cpp create mode 100644 tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.cs create mode 100644 tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.dart create mode 100644 tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.go create mode 100644 tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.java create mode 100644 tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.kt create mode 100644 tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.py create mode 100644 tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.py2 create mode 100644 tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.rb create mode 100644 tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.rs create mode 100644 tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.swift create mode 100644 tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.ts create mode 100644 tests/1501-2000/1552. magnetic-force-between-two-balls/manifest.yaml create mode 100644 tests/1501-2000/1552. magnetic-force-between-two-balls/sol.cpp create mode 100644 tests/1501-2000/1552. magnetic-force-between-two-balls/sol.cs create mode 100644 tests/1501-2000/1552. magnetic-force-between-two-balls/sol.dart create mode 100644 tests/1501-2000/1552. magnetic-force-between-two-balls/sol.go create mode 100644 tests/1501-2000/1552. magnetic-force-between-two-balls/sol.java create mode 100644 tests/1501-2000/1552. magnetic-force-between-two-balls/sol.kt create mode 100644 tests/1501-2000/1552. magnetic-force-between-two-balls/sol.py create mode 100644 tests/1501-2000/1552. magnetic-force-between-two-balls/sol.py2 create mode 100644 tests/1501-2000/1552. magnetic-force-between-two-balls/sol.rb create mode 100644 tests/1501-2000/1552. magnetic-force-between-two-balls/sol.rs create mode 100644 tests/1501-2000/1552. magnetic-force-between-two-balls/sol.swift create mode 100644 tests/1501-2000/1552. magnetic-force-between-two-balls/sol.ts create mode 100644 tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/manifest.yaml create mode 100644 tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.cpp create mode 100644 tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.cs create mode 100644 tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.dart create mode 100644 tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.go create mode 100644 tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.java create mode 100644 tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.kt create mode 100644 tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.py create mode 100644 tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.py2 create mode 100644 tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.rb create mode 100644 tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.rs create mode 100644 tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.swift create mode 100644 tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.ts create mode 100644 tests/1501-2000/1556. thousand-separator/manifest.yaml create mode 100644 tests/1501-2000/1556. thousand-separator/sol.cpp create mode 100644 tests/1501-2000/1556. thousand-separator/sol.cs create mode 100644 tests/1501-2000/1556. thousand-separator/sol.dart create mode 100644 tests/1501-2000/1556. thousand-separator/sol.go create mode 100644 tests/1501-2000/1556. thousand-separator/sol.java create mode 100644 tests/1501-2000/1556. thousand-separator/sol.kt create mode 100644 tests/1501-2000/1556. thousand-separator/sol.py create mode 100644 tests/1501-2000/1556. thousand-separator/sol.py2 create mode 100644 tests/1501-2000/1556. thousand-separator/sol.rb create mode 100644 tests/1501-2000/1556. thousand-separator/sol.rs create mode 100644 tests/1501-2000/1556. thousand-separator/sol.swift create mode 100644 tests/1501-2000/1556. thousand-separator/sol.ts create mode 100644 tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/manifest.yaml create mode 100644 tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.cpp create mode 100644 tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.cs create mode 100644 tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.dart create mode 100644 tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.go create mode 100644 tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.java create mode 100644 tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.kt create mode 100644 tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.py create mode 100644 tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.py2 create mode 100644 tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.rb create mode 100644 tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.rs create mode 100644 tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.swift create mode 100644 tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.ts create mode 100644 tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/manifest.yaml create mode 100644 tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.cpp create mode 100644 tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.cs create mode 100644 tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.dart create mode 100644 tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.go create mode 100644 tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.java create mode 100644 tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.kt create mode 100644 tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.py create mode 100644 tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.py2 create mode 100644 tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.rb create mode 100644 tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.rs create mode 100644 tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.swift create mode 100644 tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.ts create mode 100644 tests/1501-2000/1559. detect-cycles-in-2d-grid/manifest.yaml create mode 100644 tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.cpp create mode 100644 tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.cs create mode 100644 tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.dart create mode 100644 tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.go create mode 100644 tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.java create mode 100644 tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.kt create mode 100644 tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.py create mode 100644 tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.py2 create mode 100644 tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.rb create mode 100644 tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.rs create mode 100644 tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.swift create mode 100644 tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.ts create mode 100644 tests/1501-2000/1560. most-visited-sector-in-a-circular-track/manifest.yaml create mode 100644 tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.cpp create mode 100644 tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.cs create mode 100644 tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.dart create mode 100644 tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.go create mode 100644 tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.java create mode 100644 tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.kt create mode 100644 tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.py create mode 100644 tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.py2 create mode 100644 tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.rb create mode 100644 tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.rs create mode 100644 tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.swift create mode 100644 tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.ts create mode 100644 tests/1501-2000/1561. maximum-number-of-coins-you-can-get/manifest.yaml create mode 100644 tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.cpp create mode 100644 tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.cs create mode 100644 tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.dart create mode 100644 tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.go create mode 100644 tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.java create mode 100644 tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.kt create mode 100644 tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.py create mode 100644 tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.py2 create mode 100644 tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.rb create mode 100644 tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.rs create mode 100644 tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.swift create mode 100644 tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.ts create mode 100644 tests/1501-2000/1562. find-latest-group-of-size-m/manifest.yaml create mode 100644 tests/1501-2000/1562. find-latest-group-of-size-m/sol.cpp create mode 100644 tests/1501-2000/1562. find-latest-group-of-size-m/sol.cs create mode 100644 tests/1501-2000/1562. find-latest-group-of-size-m/sol.dart create mode 100644 tests/1501-2000/1562. find-latest-group-of-size-m/sol.go create mode 100644 tests/1501-2000/1562. find-latest-group-of-size-m/sol.java create mode 100644 tests/1501-2000/1562. find-latest-group-of-size-m/sol.kt create mode 100644 tests/1501-2000/1562. find-latest-group-of-size-m/sol.py create mode 100644 tests/1501-2000/1562. find-latest-group-of-size-m/sol.py2 create mode 100644 tests/1501-2000/1562. find-latest-group-of-size-m/sol.rb create mode 100644 tests/1501-2000/1562. find-latest-group-of-size-m/sol.rs create mode 100644 tests/1501-2000/1562. find-latest-group-of-size-m/sol.swift create mode 100644 tests/1501-2000/1562. find-latest-group-of-size-m/sol.ts create mode 100644 tests/1501-2000/1563. stone-game-v/manifest.yaml create mode 100644 tests/1501-2000/1563. stone-game-v/sol.cpp create mode 100644 tests/1501-2000/1563. stone-game-v/sol.cs create mode 100644 tests/1501-2000/1563. stone-game-v/sol.dart create mode 100644 tests/1501-2000/1563. stone-game-v/sol.go create mode 100644 tests/1501-2000/1563. stone-game-v/sol.java create mode 100644 tests/1501-2000/1563. stone-game-v/sol.kt create mode 100644 tests/1501-2000/1563. stone-game-v/sol.py create mode 100644 tests/1501-2000/1563. stone-game-v/sol.py2 create mode 100644 tests/1501-2000/1563. stone-game-v/sol.rb create mode 100644 tests/1501-2000/1563. stone-game-v/sol.rs create mode 100644 tests/1501-2000/1563. stone-game-v/sol.swift create mode 100644 tests/1501-2000/1563. stone-game-v/sol.ts create mode 100644 tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/manifest.yaml create mode 100644 tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.cpp create mode 100644 tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.cs create mode 100644 tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.dart create mode 100644 tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.go create mode 100644 tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.java create mode 100644 tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.kt create mode 100644 tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.py create mode 100644 tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.py2 create mode 100644 tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.rb create mode 100644 tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.rs create mode 100644 tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.swift create mode 100644 tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.ts create mode 100644 tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/manifest.yaml create mode 100644 tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.cpp create mode 100644 tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.cs create mode 100644 tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.dart create mode 100644 tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.go create mode 100644 tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.java create mode 100644 tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.kt create mode 100644 tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.py create mode 100644 tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.py2 create mode 100644 tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.rb create mode 100644 tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.rs create mode 100644 tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.swift create mode 100644 tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.ts create mode 100644 tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/manifest.yaml create mode 100644 tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.cpp create mode 100644 tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.cs create mode 100644 tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.dart create mode 100644 tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.go create mode 100644 tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.java create mode 100644 tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.kt create mode 100644 tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.py create mode 100644 tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.py2 create mode 100644 tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.rb create mode 100644 tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.rs create mode 100644 tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.swift create mode 100644 tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.ts create mode 100644 tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/manifest.yaml create mode 100644 tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.cpp create mode 100644 tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.cs create mode 100644 tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.dart create mode 100644 tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.go create mode 100644 tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.java create mode 100644 tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.kt create mode 100644 tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.py create mode 100644 tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.py2 create mode 100644 tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.rb create mode 100644 tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.rs create mode 100644 tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.swift create mode 100644 tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.ts create mode 100644 tests/1501-2000/1572. matrix-diagonal-sum/manifest.yaml create mode 100644 tests/1501-2000/1572. matrix-diagonal-sum/sol.cpp create mode 100644 tests/1501-2000/1572. matrix-diagonal-sum/sol.cs create mode 100644 tests/1501-2000/1572. matrix-diagonal-sum/sol.dart create mode 100644 tests/1501-2000/1572. matrix-diagonal-sum/sol.go create mode 100644 tests/1501-2000/1572. matrix-diagonal-sum/sol.java create mode 100644 tests/1501-2000/1572. matrix-diagonal-sum/sol.kt create mode 100644 tests/1501-2000/1572. matrix-diagonal-sum/sol.py create mode 100644 tests/1501-2000/1572. matrix-diagonal-sum/sol.py2 create mode 100644 tests/1501-2000/1572. matrix-diagonal-sum/sol.rb create mode 100644 tests/1501-2000/1572. matrix-diagonal-sum/sol.rs create mode 100644 tests/1501-2000/1572. matrix-diagonal-sum/sol.swift create mode 100644 tests/1501-2000/1572. matrix-diagonal-sum/sol.ts create mode 100644 tests/1501-2000/1573. number-of-ways-to-split-a-string/manifest.yaml create mode 100644 tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.cpp create mode 100644 tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.cs create mode 100644 tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.dart create mode 100644 tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.go create mode 100644 tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.java create mode 100644 tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.kt create mode 100644 tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.py create mode 100644 tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.py2 create mode 100644 tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.rb create mode 100644 tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.rs create mode 100644 tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.swift create mode 100644 tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.ts create mode 100644 tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/manifest.yaml create mode 100644 tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.cpp create mode 100644 tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.cs create mode 100644 tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.dart create mode 100644 tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.go create mode 100644 tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.java create mode 100644 tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.kt create mode 100644 tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.py create mode 100644 tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.py2 create mode 100644 tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.rb create mode 100644 tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.rs create mode 100644 tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.swift create mode 100644 tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.ts create mode 100644 tests/1501-2000/1575. count-all-possible-routes/manifest.yaml create mode 100644 tests/1501-2000/1575. count-all-possible-routes/sol.cpp create mode 100644 tests/1501-2000/1575. count-all-possible-routes/sol.cs create mode 100644 tests/1501-2000/1575. count-all-possible-routes/sol.dart create mode 100644 tests/1501-2000/1575. count-all-possible-routes/sol.go create mode 100644 tests/1501-2000/1575. count-all-possible-routes/sol.java create mode 100644 tests/1501-2000/1575. count-all-possible-routes/sol.kt create mode 100644 tests/1501-2000/1575. count-all-possible-routes/sol.py create mode 100644 tests/1501-2000/1575. count-all-possible-routes/sol.py2 create mode 100644 tests/1501-2000/1575. count-all-possible-routes/sol.rb create mode 100644 tests/1501-2000/1575. count-all-possible-routes/sol.rs create mode 100644 tests/1501-2000/1575. count-all-possible-routes/sol.swift create mode 100644 tests/1501-2000/1575. count-all-possible-routes/sol.ts create mode 100644 tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/manifest.yaml create mode 100644 tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.cpp create mode 100644 tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.cs create mode 100644 tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.dart create mode 100644 tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.go create mode 100644 tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.java create mode 100644 tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.kt create mode 100644 tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.py create mode 100644 tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.py2 create mode 100644 tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.rb create mode 100644 tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.rs create mode 100644 tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.swift create mode 100644 tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.ts create mode 100644 tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/manifest.yaml create mode 100644 tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.cpp create mode 100644 tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.cs create mode 100644 tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.dart create mode 100644 tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.go create mode 100644 tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.java create mode 100644 tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.kt create mode 100644 tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.py create mode 100644 tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.py2 create mode 100644 tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.rb create mode 100644 tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.rs create mode 100644 tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.swift create mode 100644 tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.ts create mode 100644 tests/1501-2000/1578. minimum-time-to-make-rope-colorful/manifest.yaml create mode 100644 tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.cpp create mode 100644 tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.cs create mode 100644 tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.dart create mode 100644 tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.go create mode 100644 tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.java create mode 100644 tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.kt create mode 100644 tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.py create mode 100644 tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.py2 create mode 100644 tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.rb create mode 100644 tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.rs create mode 100644 tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.swift create mode 100644 tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.ts create mode 100644 tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/manifest.yaml create mode 100644 tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.cpp create mode 100644 tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.cs create mode 100644 tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.dart create mode 100644 tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.go create mode 100644 tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.java create mode 100644 tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.kt create mode 100644 tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.py create mode 100644 tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.py2 create mode 100644 tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.rb create mode 100644 tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.rs create mode 100644 tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.swift create mode 100644 tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.ts create mode 100644 tests/1501-2000/1582. special-positions-in-a-binary-matrix/manifest.yaml create mode 100644 tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.cpp create mode 100644 tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.cs create mode 100644 tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.dart create mode 100644 tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.go create mode 100644 tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.java create mode 100644 tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.kt create mode 100644 tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.py create mode 100644 tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.py2 create mode 100644 tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.rb create mode 100644 tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.rs create mode 100644 tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.swift create mode 100644 tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.ts create mode 100644 tests/1501-2000/1583. count-unhappy-friends/manifest.yaml create mode 100644 tests/1501-2000/1583. count-unhappy-friends/sol.cpp create mode 100644 tests/1501-2000/1583. count-unhappy-friends/sol.cs create mode 100644 tests/1501-2000/1583. count-unhappy-friends/sol.dart create mode 100644 tests/1501-2000/1583. count-unhappy-friends/sol.go create mode 100644 tests/1501-2000/1583. count-unhappy-friends/sol.java create mode 100644 tests/1501-2000/1583. count-unhappy-friends/sol.kt create mode 100644 tests/1501-2000/1583. count-unhappy-friends/sol.py create mode 100644 tests/1501-2000/1583. count-unhappy-friends/sol.py2 create mode 100644 tests/1501-2000/1583. count-unhappy-friends/sol.rb create mode 100644 tests/1501-2000/1583. count-unhappy-friends/sol.rs create mode 100644 tests/1501-2000/1583. count-unhappy-friends/sol.swift create mode 100644 tests/1501-2000/1583. count-unhappy-friends/sol.ts create mode 100644 tests/1501-2000/1584. min-cost-to-connect-all-points/manifest.yaml create mode 100644 tests/1501-2000/1584. min-cost-to-connect-all-points/sol.cpp create mode 100644 tests/1501-2000/1584. min-cost-to-connect-all-points/sol.cs create mode 100644 tests/1501-2000/1584. min-cost-to-connect-all-points/sol.dart create mode 100644 tests/1501-2000/1584. min-cost-to-connect-all-points/sol.go create mode 100644 tests/1501-2000/1584. min-cost-to-connect-all-points/sol.java create mode 100644 tests/1501-2000/1584. min-cost-to-connect-all-points/sol.kt create mode 100644 tests/1501-2000/1584. min-cost-to-connect-all-points/sol.py create mode 100644 tests/1501-2000/1584. min-cost-to-connect-all-points/sol.py2 create mode 100644 tests/1501-2000/1584. min-cost-to-connect-all-points/sol.rb create mode 100644 tests/1501-2000/1584. min-cost-to-connect-all-points/sol.rs create mode 100644 tests/1501-2000/1584. min-cost-to-connect-all-points/sol.swift create mode 100644 tests/1501-2000/1584. min-cost-to-connect-all-points/sol.ts create mode 100644 tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/manifest.yaml create mode 100644 tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.cpp create mode 100644 tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.cs create mode 100644 tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.dart create mode 100644 tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.go create mode 100644 tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.java create mode 100644 tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.kt create mode 100644 tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.py create mode 100644 tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.py2 create mode 100644 tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.rb create mode 100644 tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.rs create mode 100644 tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.swift create mode 100644 tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.ts create mode 100644 tests/1501-2000/1588. sum-of-all-odd-length-subarrays/manifest.yaml create mode 100644 tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.cpp create mode 100644 tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.cs create mode 100644 tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.dart create mode 100644 tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.go create mode 100644 tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.java create mode 100644 tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.kt create mode 100644 tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.py create mode 100644 tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.py2 create mode 100644 tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.rb create mode 100644 tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.rs create mode 100644 tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.swift create mode 100644 tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.ts create mode 100644 tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/manifest.yaml create mode 100644 tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.cpp create mode 100644 tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.cs create mode 100644 tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.dart create mode 100644 tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.go create mode 100644 tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.java create mode 100644 tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.kt create mode 100644 tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.py create mode 100644 tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.py2 create mode 100644 tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.rb create mode 100644 tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.rs create mode 100644 tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.swift create mode 100644 tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.ts create mode 100644 tests/1501-2000/1590. make-sum-divisible-by-p/manifest.yaml create mode 100644 tests/1501-2000/1590. make-sum-divisible-by-p/sol.cpp create mode 100644 tests/1501-2000/1590. make-sum-divisible-by-p/sol.cs create mode 100644 tests/1501-2000/1590. make-sum-divisible-by-p/sol.dart create mode 100644 tests/1501-2000/1590. make-sum-divisible-by-p/sol.go create mode 100644 tests/1501-2000/1590. make-sum-divisible-by-p/sol.java create mode 100644 tests/1501-2000/1590. make-sum-divisible-by-p/sol.kt create mode 100644 tests/1501-2000/1590. make-sum-divisible-by-p/sol.py create mode 100644 tests/1501-2000/1590. make-sum-divisible-by-p/sol.py2 create mode 100644 tests/1501-2000/1590. make-sum-divisible-by-p/sol.rb create mode 100644 tests/1501-2000/1590. make-sum-divisible-by-p/sol.rs create mode 100644 tests/1501-2000/1590. make-sum-divisible-by-p/sol.swift create mode 100644 tests/1501-2000/1590. make-sum-divisible-by-p/sol.ts create mode 100644 tests/1501-2000/1591. strange-printer-ii/manifest.yaml create mode 100644 tests/1501-2000/1591. strange-printer-ii/sol.cpp create mode 100644 tests/1501-2000/1591. strange-printer-ii/sol.cs create mode 100644 tests/1501-2000/1591. strange-printer-ii/sol.dart create mode 100644 tests/1501-2000/1591. strange-printer-ii/sol.go create mode 100644 tests/1501-2000/1591. strange-printer-ii/sol.java create mode 100644 tests/1501-2000/1591. strange-printer-ii/sol.kt create mode 100644 tests/1501-2000/1591. strange-printer-ii/sol.py create mode 100644 tests/1501-2000/1591. strange-printer-ii/sol.py2 create mode 100644 tests/1501-2000/1591. strange-printer-ii/sol.rb create mode 100644 tests/1501-2000/1591. strange-printer-ii/sol.rs create mode 100644 tests/1501-2000/1591. strange-printer-ii/sol.swift create mode 100644 tests/1501-2000/1591. strange-printer-ii/sol.ts create mode 100644 tests/1501-2000/1592. rearrange-spaces-between-words/manifest.yaml create mode 100644 tests/1501-2000/1592. rearrange-spaces-between-words/sol.cpp create mode 100644 tests/1501-2000/1592. rearrange-spaces-between-words/sol.cs create mode 100644 tests/1501-2000/1592. rearrange-spaces-between-words/sol.dart create mode 100644 tests/1501-2000/1592. rearrange-spaces-between-words/sol.go create mode 100644 tests/1501-2000/1592. rearrange-spaces-between-words/sol.java create mode 100644 tests/1501-2000/1592. rearrange-spaces-between-words/sol.kt create mode 100644 tests/1501-2000/1592. rearrange-spaces-between-words/sol.py create mode 100644 tests/1501-2000/1592. rearrange-spaces-between-words/sol.py2 create mode 100644 tests/1501-2000/1592. rearrange-spaces-between-words/sol.rb create mode 100644 tests/1501-2000/1592. rearrange-spaces-between-words/sol.rs create mode 100644 tests/1501-2000/1592. rearrange-spaces-between-words/sol.swift create mode 100644 tests/1501-2000/1592. rearrange-spaces-between-words/sol.ts create mode 100644 tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/manifest.yaml create mode 100644 tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.cpp create mode 100644 tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.cs create mode 100644 tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.dart create mode 100644 tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.go create mode 100644 tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.java create mode 100644 tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.kt create mode 100644 tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.py create mode 100644 tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.py2 create mode 100644 tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.rb create mode 100644 tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.rs create mode 100644 tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.swift create mode 100644 tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.ts create mode 100644 tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/manifest.yaml create mode 100644 tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.cpp create mode 100644 tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.cs create mode 100644 tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.dart create mode 100644 tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.go create mode 100644 tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.java create mode 100644 tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.kt create mode 100644 tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.py create mode 100644 tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.py2 create mode 100644 tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.rb create mode 100644 tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.rs create mode 100644 tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.swift create mode 100644 tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.ts create mode 100644 tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/manifest.yaml create mode 100644 tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.cpp create mode 100644 tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.cs create mode 100644 tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.dart create mode 100644 tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.go create mode 100644 tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.java create mode 100644 tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.kt create mode 100644 tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.py create mode 100644 tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.py2 create mode 100644 tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.rb create mode 100644 tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.rs create mode 100644 tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.swift create mode 100644 tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.ts create mode 100644 tests/1501-2000/1598. crawler-log-folder/manifest.yaml create mode 100644 tests/1501-2000/1598. crawler-log-folder/sol.cpp create mode 100644 tests/1501-2000/1598. crawler-log-folder/sol.cs create mode 100644 tests/1501-2000/1598. crawler-log-folder/sol.dart create mode 100644 tests/1501-2000/1598. crawler-log-folder/sol.go create mode 100644 tests/1501-2000/1598. crawler-log-folder/sol.java create mode 100644 tests/1501-2000/1598. crawler-log-folder/sol.kt create mode 100644 tests/1501-2000/1598. crawler-log-folder/sol.py create mode 100644 tests/1501-2000/1598. crawler-log-folder/sol.py2 create mode 100644 tests/1501-2000/1598. crawler-log-folder/sol.rb create mode 100644 tests/1501-2000/1598. crawler-log-folder/sol.rs create mode 100644 tests/1501-2000/1598. crawler-log-folder/sol.swift create mode 100644 tests/1501-2000/1598. crawler-log-folder/sol.ts create mode 100644 tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/manifest.yaml create mode 100644 tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.cpp create mode 100644 tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.cs create mode 100644 tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.dart create mode 100644 tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.go create mode 100644 tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.java create mode 100644 tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.kt create mode 100644 tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.py create mode 100644 tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.py2 create mode 100644 tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.rb create mode 100644 tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.rs create mode 100644 tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.swift create mode 100644 tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.ts create mode 100644 tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/manifest.yaml create mode 100644 tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.cpp create mode 100644 tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.cs create mode 100644 tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.dart create mode 100644 tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.go create mode 100644 tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.java create mode 100644 tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.kt create mode 100644 tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.py create mode 100644 tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.py2 create mode 100644 tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.rb create mode 100644 tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.rs create mode 100644 tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.swift create mode 100644 tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.ts create mode 100644 tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/manifest.yaml create mode 100644 tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.cpp create mode 100644 tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.cs create mode 100644 tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.dart create mode 100644 tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.go create mode 100644 tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.java create mode 100644 tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.kt create mode 100644 tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.py create mode 100644 tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.py2 create mode 100644 tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.rb create mode 100644 tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.rs create mode 100644 tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.swift create mode 100644 tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.ts create mode 100644 tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/manifest.yaml create mode 100644 tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.cpp create mode 100644 tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.cs create mode 100644 tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.dart create mode 100644 tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.go create mode 100644 tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.java create mode 100644 tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.kt create mode 100644 tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.py create mode 100644 tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.py2 create mode 100644 tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.rb create mode 100644 tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.rs create mode 100644 tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.swift create mode 100644 tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.ts create mode 100644 tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/manifest.yaml create mode 100644 tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.cpp create mode 100644 tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.cs create mode 100644 tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.dart create mode 100644 tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.go create mode 100644 tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.java create mode 100644 tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.kt create mode 100644 tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.py create mode 100644 tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.py2 create mode 100644 tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.rb create mode 100644 tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.rs create mode 100644 tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.swift create mode 100644 tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.ts create mode 100644 tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/manifest.yaml create mode 100644 tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.cpp create mode 100644 tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.cs create mode 100644 tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.dart create mode 100644 tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.go create mode 100644 tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.java create mode 100644 tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.kt create mode 100644 tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.py create mode 100644 tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.py2 create mode 100644 tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.rb create mode 100644 tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.rs create mode 100644 tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.swift create mode 100644 tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.ts create mode 100644 tests/1501-2000/1609. even-odd-tree/manifest.yaml create mode 100644 tests/1501-2000/1609. even-odd-tree/sol.cpp create mode 100644 tests/1501-2000/1609. even-odd-tree/sol.cs create mode 100644 tests/1501-2000/1609. even-odd-tree/sol.dart create mode 100644 tests/1501-2000/1609. even-odd-tree/sol.go create mode 100644 tests/1501-2000/1609. even-odd-tree/sol.java create mode 100644 tests/1501-2000/1609. even-odd-tree/sol.kt create mode 100644 tests/1501-2000/1609. even-odd-tree/sol.py create mode 100644 tests/1501-2000/1609. even-odd-tree/sol.py2 create mode 100644 tests/1501-2000/1609. even-odd-tree/sol.rb create mode 100644 tests/1501-2000/1609. even-odd-tree/sol.rs create mode 100644 tests/1501-2000/1609. even-odd-tree/sol.swift create mode 100644 tests/1501-2000/1609. even-odd-tree/sol.ts create mode 100644 tests/1501-2000/1610. maximum-number-of-visible-points/manifest.yaml create mode 100644 tests/1501-2000/1610. maximum-number-of-visible-points/sol.cpp create mode 100644 tests/1501-2000/1610. maximum-number-of-visible-points/sol.cs create mode 100644 tests/1501-2000/1610. maximum-number-of-visible-points/sol.dart create mode 100644 tests/1501-2000/1610. maximum-number-of-visible-points/sol.go create mode 100644 tests/1501-2000/1610. maximum-number-of-visible-points/sol.java create mode 100644 tests/1501-2000/1610. maximum-number-of-visible-points/sol.kt create mode 100644 tests/1501-2000/1610. maximum-number-of-visible-points/sol.py create mode 100644 tests/1501-2000/1610. maximum-number-of-visible-points/sol.py2 create mode 100644 tests/1501-2000/1610. maximum-number-of-visible-points/sol.rb create mode 100644 tests/1501-2000/1610. maximum-number-of-visible-points/sol.rs create mode 100644 tests/1501-2000/1610. maximum-number-of-visible-points/sol.swift create mode 100644 tests/1501-2000/1610. maximum-number-of-visible-points/sol.ts create mode 100644 tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/manifest.yaml create mode 100644 tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.cpp create mode 100644 tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.cs create mode 100644 tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.dart create mode 100644 tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.go create mode 100644 tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.java create mode 100644 tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.kt create mode 100644 tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.py create mode 100644 tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.py2 create mode 100644 tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.rb create mode 100644 tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.rs create mode 100644 tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.swift create mode 100644 tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.ts create mode 100644 tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/manifest.yaml create mode 100644 tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.cpp create mode 100644 tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.cs create mode 100644 tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.dart create mode 100644 tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.go create mode 100644 tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.java create mode 100644 tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.kt create mode 100644 tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.py create mode 100644 tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.py2 create mode 100644 tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.rb create mode 100644 tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.rs create mode 100644 tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.swift create mode 100644 tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.ts create mode 100644 tests/1501-2000/1615. maximal-network-rank/manifest.yaml create mode 100644 tests/1501-2000/1615. maximal-network-rank/sol.cpp create mode 100644 tests/1501-2000/1615. maximal-network-rank/sol.cs create mode 100644 tests/1501-2000/1615. maximal-network-rank/sol.dart create mode 100644 tests/1501-2000/1615. maximal-network-rank/sol.go create mode 100644 tests/1501-2000/1615. maximal-network-rank/sol.java create mode 100644 tests/1501-2000/1615. maximal-network-rank/sol.kt create mode 100644 tests/1501-2000/1615. maximal-network-rank/sol.py create mode 100644 tests/1501-2000/1615. maximal-network-rank/sol.py2 create mode 100644 tests/1501-2000/1615. maximal-network-rank/sol.rb create mode 100644 tests/1501-2000/1615. maximal-network-rank/sol.rs create mode 100644 tests/1501-2000/1615. maximal-network-rank/sol.swift create mode 100644 tests/1501-2000/1615. maximal-network-rank/sol.ts create mode 100644 tests/1501-2000/1616. split-two-strings-to-make-palindrome/manifest.yaml create mode 100644 tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.cpp create mode 100644 tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.cs create mode 100644 tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.dart create mode 100644 tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.go create mode 100644 tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.java create mode 100644 tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.kt create mode 100644 tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.py create mode 100644 tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.py2 create mode 100644 tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.rb create mode 100644 tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.rs create mode 100644 tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.swift create mode 100644 tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.ts create mode 100644 tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/manifest.yaml create mode 100644 tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.cpp create mode 100644 tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.cs create mode 100644 tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.dart create mode 100644 tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.go create mode 100644 tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.java create mode 100644 tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.kt create mode 100644 tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.py create mode 100644 tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.py2 create mode 100644 tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.rb create mode 100644 tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.rs create mode 100644 tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.swift create mode 100644 tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.ts create mode 100644 tests/1501-2000/1619. mean-of-array-after-removing-some-elements/manifest.yaml create mode 100644 tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.cpp create mode 100644 tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.cs create mode 100644 tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.dart create mode 100644 tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.go create mode 100644 tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.java create mode 100644 tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.kt create mode 100644 tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.py create mode 100644 tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.py2 create mode 100644 tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.rb create mode 100644 tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.rs create mode 100644 tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.swift create mode 100644 tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.ts create mode 100644 tests/1501-2000/1620. coordinate-with-maximum-network-quality/manifest.yaml create mode 100644 tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.cpp create mode 100644 tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.cs create mode 100644 tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.dart create mode 100644 tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.go create mode 100644 tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.java create mode 100644 tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.kt create mode 100644 tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.py create mode 100644 tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.py2 create mode 100644 tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.rb create mode 100644 tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.rs create mode 100644 tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.swift create mode 100644 tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.ts create mode 100644 tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/manifest.yaml create mode 100644 tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.cpp create mode 100644 tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.cs create mode 100644 tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.dart create mode 100644 tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.go create mode 100644 tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.java create mode 100644 tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.kt create mode 100644 tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.py create mode 100644 tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.py2 create mode 100644 tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.rb create mode 100644 tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.rs create mode 100644 tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.swift create mode 100644 tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.ts create mode 100644 tests/1501-2000/1624. largest-substring-between-two-equal-characters/manifest.yaml create mode 100644 tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.cpp create mode 100644 tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.cs create mode 100644 tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.dart create mode 100644 tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.go create mode 100644 tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.java create mode 100644 tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.kt create mode 100644 tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.py create mode 100644 tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.py2 create mode 100644 tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.rb create mode 100644 tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.rs create mode 100644 tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.swift create mode 100644 tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.ts create mode 100644 tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/manifest.yaml create mode 100644 tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.cpp create mode 100644 tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.cs create mode 100644 tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.dart create mode 100644 tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.go create mode 100644 tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.java create mode 100644 tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.kt create mode 100644 tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.py create mode 100644 tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.py2 create mode 100644 tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.rb create mode 100644 tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.rs create mode 100644 tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.swift create mode 100644 tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.ts create mode 100644 tests/1501-2000/1626. best-team-with-no-conflicts/manifest.yaml create mode 100644 tests/1501-2000/1626. best-team-with-no-conflicts/sol.cpp create mode 100644 tests/1501-2000/1626. best-team-with-no-conflicts/sol.cs create mode 100644 tests/1501-2000/1626. best-team-with-no-conflicts/sol.dart create mode 100644 tests/1501-2000/1626. best-team-with-no-conflicts/sol.go create mode 100644 tests/1501-2000/1626. best-team-with-no-conflicts/sol.java create mode 100644 tests/1501-2000/1626. best-team-with-no-conflicts/sol.kt create mode 100644 tests/1501-2000/1626. best-team-with-no-conflicts/sol.py create mode 100644 tests/1501-2000/1626. best-team-with-no-conflicts/sol.py2 create mode 100644 tests/1501-2000/1626. best-team-with-no-conflicts/sol.rb create mode 100644 tests/1501-2000/1626. best-team-with-no-conflicts/sol.rs create mode 100644 tests/1501-2000/1626. best-team-with-no-conflicts/sol.swift create mode 100644 tests/1501-2000/1626. best-team-with-no-conflicts/sol.ts create mode 100644 tests/1501-2000/1627. graph-connectivity-with-threshold/manifest.yaml create mode 100644 tests/1501-2000/1627. graph-connectivity-with-threshold/sol.cpp create mode 100644 tests/1501-2000/1627. graph-connectivity-with-threshold/sol.cs create mode 100644 tests/1501-2000/1627. graph-connectivity-with-threshold/sol.dart create mode 100644 tests/1501-2000/1627. graph-connectivity-with-threshold/sol.go create mode 100644 tests/1501-2000/1627. graph-connectivity-with-threshold/sol.java create mode 100644 tests/1501-2000/1627. graph-connectivity-with-threshold/sol.kt create mode 100644 tests/1501-2000/1627. graph-connectivity-with-threshold/sol.py create mode 100644 tests/1501-2000/1627. graph-connectivity-with-threshold/sol.py2 create mode 100644 tests/1501-2000/1627. graph-connectivity-with-threshold/sol.rb create mode 100644 tests/1501-2000/1627. graph-connectivity-with-threshold/sol.rs create mode 100644 tests/1501-2000/1627. graph-connectivity-with-threshold/sol.swift create mode 100644 tests/1501-2000/1627. graph-connectivity-with-threshold/sol.ts create mode 100644 tests/1501-2000/1629. slowest-key/manifest.yaml create mode 100644 tests/1501-2000/1629. slowest-key/sol.cpp create mode 100644 tests/1501-2000/1629. slowest-key/sol.cs create mode 100644 tests/1501-2000/1629. slowest-key/sol.dart create mode 100644 tests/1501-2000/1629. slowest-key/sol.go create mode 100644 tests/1501-2000/1629. slowest-key/sol.java create mode 100644 tests/1501-2000/1629. slowest-key/sol.kt create mode 100644 tests/1501-2000/1629. slowest-key/sol.py create mode 100644 tests/1501-2000/1629. slowest-key/sol.py2 create mode 100644 tests/1501-2000/1629. slowest-key/sol.rb create mode 100644 tests/1501-2000/1629. slowest-key/sol.rs create mode 100644 tests/1501-2000/1629. slowest-key/sol.swift create mode 100644 tests/1501-2000/1629. slowest-key/sol.ts create mode 100644 tests/1501-2000/1630. arithmetic-subarrays/manifest.yaml create mode 100644 tests/1501-2000/1630. arithmetic-subarrays/sol.cpp create mode 100644 tests/1501-2000/1630. arithmetic-subarrays/sol.cs create mode 100644 tests/1501-2000/1630. arithmetic-subarrays/sol.dart create mode 100644 tests/1501-2000/1630. arithmetic-subarrays/sol.go create mode 100644 tests/1501-2000/1630. arithmetic-subarrays/sol.java create mode 100644 tests/1501-2000/1630. arithmetic-subarrays/sol.kt create mode 100644 tests/1501-2000/1630. arithmetic-subarrays/sol.py create mode 100644 tests/1501-2000/1630. arithmetic-subarrays/sol.py2 create mode 100644 tests/1501-2000/1630. arithmetic-subarrays/sol.rb create mode 100644 tests/1501-2000/1630. arithmetic-subarrays/sol.rs create mode 100644 tests/1501-2000/1630. arithmetic-subarrays/sol.swift create mode 100644 tests/1501-2000/1630. arithmetic-subarrays/sol.ts create mode 100644 tests/1501-2000/1631. path-with-minimum-effort/manifest.yaml create mode 100644 tests/1501-2000/1631. path-with-minimum-effort/sol.cpp create mode 100644 tests/1501-2000/1631. path-with-minimum-effort/sol.cs create mode 100644 tests/1501-2000/1631. path-with-minimum-effort/sol.dart create mode 100644 tests/1501-2000/1631. path-with-minimum-effort/sol.go create mode 100644 tests/1501-2000/1631. path-with-minimum-effort/sol.java create mode 100644 tests/1501-2000/1631. path-with-minimum-effort/sol.kt create mode 100644 tests/1501-2000/1631. path-with-minimum-effort/sol.py create mode 100644 tests/1501-2000/1631. path-with-minimum-effort/sol.py2 create mode 100644 tests/1501-2000/1631. path-with-minimum-effort/sol.rb create mode 100644 tests/1501-2000/1631. path-with-minimum-effort/sol.rs create mode 100644 tests/1501-2000/1631. path-with-minimum-effort/sol.swift create mode 100644 tests/1501-2000/1631. path-with-minimum-effort/sol.ts create mode 100644 tests/1501-2000/1632. rank-transform-of-a-matrix/manifest.yaml create mode 100644 tests/1501-2000/1632. rank-transform-of-a-matrix/sol.cpp create mode 100644 tests/1501-2000/1632. rank-transform-of-a-matrix/sol.cs create mode 100644 tests/1501-2000/1632. rank-transform-of-a-matrix/sol.dart create mode 100644 tests/1501-2000/1632. rank-transform-of-a-matrix/sol.go create mode 100644 tests/1501-2000/1632. rank-transform-of-a-matrix/sol.java create mode 100644 tests/1501-2000/1632. rank-transform-of-a-matrix/sol.kt create mode 100644 tests/1501-2000/1632. rank-transform-of-a-matrix/sol.py create mode 100644 tests/1501-2000/1632. rank-transform-of-a-matrix/sol.py2 create mode 100644 tests/1501-2000/1632. rank-transform-of-a-matrix/sol.rb create mode 100644 tests/1501-2000/1632. rank-transform-of-a-matrix/sol.rs create mode 100644 tests/1501-2000/1632. rank-transform-of-a-matrix/sol.swift create mode 100644 tests/1501-2000/1632. rank-transform-of-a-matrix/sol.ts create mode 100644 tests/1501-2000/1636. sort-array-by-increasing-frequency/manifest.yaml create mode 100644 tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.cpp create mode 100644 tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.cs create mode 100644 tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.dart create mode 100644 tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.go create mode 100644 tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.java create mode 100644 tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.kt create mode 100644 tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.py create mode 100644 tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.py2 create mode 100644 tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.rb create mode 100644 tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.rs create mode 100644 tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.swift create mode 100644 tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.ts create mode 100644 tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/manifest.yaml create mode 100644 tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.cpp create mode 100644 tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.cs create mode 100644 tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.dart create mode 100644 tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.go create mode 100644 tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.java create mode 100644 tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.kt create mode 100644 tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.py create mode 100644 tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.py2 create mode 100644 tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.rb create mode 100644 tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.rs create mode 100644 tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.swift create mode 100644 tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.ts create mode 100644 tests/1501-2000/1638. count-substrings-that-differ-by-one-character/manifest.yaml create mode 100644 tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.cpp create mode 100644 tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.cs create mode 100644 tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.dart create mode 100644 tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.go create mode 100644 tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.java create mode 100644 tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.kt create mode 100644 tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.py create mode 100644 tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.py2 create mode 100644 tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.rb create mode 100644 tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.rs create mode 100644 tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.swift create mode 100644 tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.ts create mode 100644 tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/manifest.yaml create mode 100644 tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.cpp create mode 100644 tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.cs create mode 100644 tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.dart create mode 100644 tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.go create mode 100644 tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.java create mode 100644 tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.kt create mode 100644 tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.py create mode 100644 tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.py2 create mode 100644 tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.rb create mode 100644 tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.rs create mode 100644 tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.swift create mode 100644 tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.ts create mode 100644 tests/1501-2000/1640. check-array-formation-through-concatenation/manifest.yaml create mode 100644 tests/1501-2000/1640. check-array-formation-through-concatenation/sol.cpp create mode 100644 tests/1501-2000/1640. check-array-formation-through-concatenation/sol.cs create mode 100644 tests/1501-2000/1640. check-array-formation-through-concatenation/sol.dart create mode 100644 tests/1501-2000/1640. check-array-formation-through-concatenation/sol.go create mode 100644 tests/1501-2000/1640. check-array-formation-through-concatenation/sol.java create mode 100644 tests/1501-2000/1640. check-array-formation-through-concatenation/sol.kt create mode 100644 tests/1501-2000/1640. check-array-formation-through-concatenation/sol.py create mode 100644 tests/1501-2000/1640. check-array-formation-through-concatenation/sol.py2 create mode 100644 tests/1501-2000/1640. check-array-formation-through-concatenation/sol.rb create mode 100644 tests/1501-2000/1640. check-array-formation-through-concatenation/sol.rs create mode 100644 tests/1501-2000/1640. check-array-formation-through-concatenation/sol.swift create mode 100644 tests/1501-2000/1640. check-array-formation-through-concatenation/sol.ts create mode 100644 tests/1501-2000/1641. count-sorted-vowel-strings/manifest.yaml create mode 100644 tests/1501-2000/1641. count-sorted-vowel-strings/sol.cpp create mode 100644 tests/1501-2000/1641. count-sorted-vowel-strings/sol.cs create mode 100644 tests/1501-2000/1641. count-sorted-vowel-strings/sol.dart create mode 100644 tests/1501-2000/1641. count-sorted-vowel-strings/sol.go create mode 100644 tests/1501-2000/1641. count-sorted-vowel-strings/sol.java create mode 100644 tests/1501-2000/1641. count-sorted-vowel-strings/sol.kt create mode 100644 tests/1501-2000/1641. count-sorted-vowel-strings/sol.py create mode 100644 tests/1501-2000/1641. count-sorted-vowel-strings/sol.py2 create mode 100644 tests/1501-2000/1641. count-sorted-vowel-strings/sol.rb create mode 100644 tests/1501-2000/1641. count-sorted-vowel-strings/sol.rs create mode 100644 tests/1501-2000/1641. count-sorted-vowel-strings/sol.swift create mode 100644 tests/1501-2000/1641. count-sorted-vowel-strings/sol.ts create mode 100644 tests/1501-2000/1642. furthest-building-you-can-reach/manifest.yaml create mode 100644 tests/1501-2000/1642. furthest-building-you-can-reach/sol.cpp create mode 100644 tests/1501-2000/1642. furthest-building-you-can-reach/sol.cs create mode 100644 tests/1501-2000/1642. furthest-building-you-can-reach/sol.dart create mode 100644 tests/1501-2000/1642. furthest-building-you-can-reach/sol.go create mode 100644 tests/1501-2000/1642. furthest-building-you-can-reach/sol.java create mode 100644 tests/1501-2000/1642. furthest-building-you-can-reach/sol.kt create mode 100644 tests/1501-2000/1642. furthest-building-you-can-reach/sol.py create mode 100644 tests/1501-2000/1642. furthest-building-you-can-reach/sol.py2 create mode 100644 tests/1501-2000/1642. furthest-building-you-can-reach/sol.rb create mode 100644 tests/1501-2000/1642. furthest-building-you-can-reach/sol.rs create mode 100644 tests/1501-2000/1642. furthest-building-you-can-reach/sol.swift create mode 100644 tests/1501-2000/1642. furthest-building-you-can-reach/sol.ts create mode 100644 tests/1501-2000/1643. kth-smallest-instructions/manifest.yaml create mode 100644 tests/1501-2000/1643. kth-smallest-instructions/sol.cpp create mode 100644 tests/1501-2000/1643. kth-smallest-instructions/sol.cs create mode 100644 tests/1501-2000/1643. kth-smallest-instructions/sol.dart create mode 100644 tests/1501-2000/1643. kth-smallest-instructions/sol.go create mode 100644 tests/1501-2000/1643. kth-smallest-instructions/sol.java create mode 100644 tests/1501-2000/1643. kth-smallest-instructions/sol.kt create mode 100644 tests/1501-2000/1643. kth-smallest-instructions/sol.py create mode 100644 tests/1501-2000/1643. kth-smallest-instructions/sol.py2 create mode 100644 tests/1501-2000/1643. kth-smallest-instructions/sol.rb create mode 100644 tests/1501-2000/1643. kth-smallest-instructions/sol.rs create mode 100644 tests/1501-2000/1643. kth-smallest-instructions/sol.swift create mode 100644 tests/1501-2000/1643. kth-smallest-instructions/sol.ts create mode 100644 tests/1501-2000/1646. get-maximum-in-generated-array/manifest.yaml create mode 100644 tests/1501-2000/1646. get-maximum-in-generated-array/sol.cpp create mode 100644 tests/1501-2000/1646. get-maximum-in-generated-array/sol.cs create mode 100644 tests/1501-2000/1646. get-maximum-in-generated-array/sol.dart create mode 100644 tests/1501-2000/1646. get-maximum-in-generated-array/sol.go create mode 100644 tests/1501-2000/1646. get-maximum-in-generated-array/sol.java create mode 100644 tests/1501-2000/1646. get-maximum-in-generated-array/sol.kt create mode 100644 tests/1501-2000/1646. get-maximum-in-generated-array/sol.py create mode 100644 tests/1501-2000/1646. get-maximum-in-generated-array/sol.py2 create mode 100644 tests/1501-2000/1646. get-maximum-in-generated-array/sol.rb create mode 100644 tests/1501-2000/1646. get-maximum-in-generated-array/sol.rs create mode 100644 tests/1501-2000/1646. get-maximum-in-generated-array/sol.swift create mode 100644 tests/1501-2000/1646. get-maximum-in-generated-array/sol.ts create mode 100644 tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/manifest.yaml create mode 100644 tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.cpp create mode 100644 tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.cs create mode 100644 tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.dart create mode 100644 tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.go create mode 100644 tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.java create mode 100644 tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.kt create mode 100644 tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.py create mode 100644 tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.py2 create mode 100644 tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.rb create mode 100644 tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.rs create mode 100644 tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.swift create mode 100644 tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.ts create mode 100644 tests/1501-2000/1648. sell-diminishing-valued-colored-balls/manifest.yaml create mode 100644 tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.cpp create mode 100644 tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.cs create mode 100644 tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.dart create mode 100644 tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.go create mode 100644 tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.java create mode 100644 tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.kt create mode 100644 tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.py create mode 100644 tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.py2 create mode 100644 tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.rb create mode 100644 tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.rs create mode 100644 tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.swift create mode 100644 tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.ts create mode 100644 tests/1501-2000/1649. create-sorted-array-through-instructions/manifest.yaml create mode 100644 tests/1501-2000/1649. create-sorted-array-through-instructions/sol.cpp create mode 100644 tests/1501-2000/1649. create-sorted-array-through-instructions/sol.cs create mode 100644 tests/1501-2000/1649. create-sorted-array-through-instructions/sol.dart create mode 100644 tests/1501-2000/1649. create-sorted-array-through-instructions/sol.go create mode 100644 tests/1501-2000/1649. create-sorted-array-through-instructions/sol.java create mode 100644 tests/1501-2000/1649. create-sorted-array-through-instructions/sol.kt create mode 100644 tests/1501-2000/1649. create-sorted-array-through-instructions/sol.py create mode 100644 tests/1501-2000/1649. create-sorted-array-through-instructions/sol.py2 create mode 100644 tests/1501-2000/1649. create-sorted-array-through-instructions/sol.rb create mode 100644 tests/1501-2000/1649. create-sorted-array-through-instructions/sol.rs create mode 100644 tests/1501-2000/1649. create-sorted-array-through-instructions/sol.swift create mode 100644 tests/1501-2000/1649. create-sorted-array-through-instructions/sol.ts create mode 100644 tests/1501-2000/1652. defuse-the-bomb/manifest.yaml create mode 100644 tests/1501-2000/1652. defuse-the-bomb/sol.cpp create mode 100644 tests/1501-2000/1652. defuse-the-bomb/sol.cs create mode 100644 tests/1501-2000/1652. defuse-the-bomb/sol.dart create mode 100644 tests/1501-2000/1652. defuse-the-bomb/sol.go create mode 100644 tests/1501-2000/1652. defuse-the-bomb/sol.java create mode 100644 tests/1501-2000/1652. defuse-the-bomb/sol.kt create mode 100644 tests/1501-2000/1652. defuse-the-bomb/sol.py create mode 100644 tests/1501-2000/1652. defuse-the-bomb/sol.py2 create mode 100644 tests/1501-2000/1652. defuse-the-bomb/sol.rb create mode 100644 tests/1501-2000/1652. defuse-the-bomb/sol.rs create mode 100644 tests/1501-2000/1652. defuse-the-bomb/sol.swift create mode 100644 tests/1501-2000/1652. defuse-the-bomb/sol.ts create mode 100644 tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/manifest.yaml create mode 100644 tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.cpp create mode 100644 tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.cs create mode 100644 tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.dart create mode 100644 tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.go create mode 100644 tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.java create mode 100644 tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.kt create mode 100644 tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.py create mode 100644 tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.py2 create mode 100644 tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.rb create mode 100644 tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.rs create mode 100644 tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.swift create mode 100644 tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.ts create mode 100644 tests/1501-2000/1654. minimum-jumps-to-reach-home/manifest.yaml create mode 100644 tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.cpp create mode 100644 tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.cs create mode 100644 tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.dart create mode 100644 tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.go create mode 100644 tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.java create mode 100644 tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.kt create mode 100644 tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.py create mode 100644 tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.py2 create mode 100644 tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.rb create mode 100644 tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.rs create mode 100644 tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.swift create mode 100644 tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.ts create mode 100644 tests/1501-2000/1655. distribute-repeating-integers/manifest.yaml create mode 100644 tests/1501-2000/1655. distribute-repeating-integers/sol.cpp create mode 100644 tests/1501-2000/1655. distribute-repeating-integers/sol.cs create mode 100644 tests/1501-2000/1655. distribute-repeating-integers/sol.dart create mode 100644 tests/1501-2000/1655. distribute-repeating-integers/sol.go create mode 100644 tests/1501-2000/1655. distribute-repeating-integers/sol.java create mode 100644 tests/1501-2000/1655. distribute-repeating-integers/sol.kt create mode 100644 tests/1501-2000/1655. distribute-repeating-integers/sol.py create mode 100644 tests/1501-2000/1655. distribute-repeating-integers/sol.py2 create mode 100644 tests/1501-2000/1655. distribute-repeating-integers/sol.rb create mode 100644 tests/1501-2000/1655. distribute-repeating-integers/sol.rs create mode 100644 tests/1501-2000/1655. distribute-repeating-integers/sol.swift create mode 100644 tests/1501-2000/1655. distribute-repeating-integers/sol.ts create mode 100644 tests/1501-2000/1657. determine-if-two-strings-are-close/manifest.yaml create mode 100644 tests/1501-2000/1657. determine-if-two-strings-are-close/sol.cpp create mode 100644 tests/1501-2000/1657. determine-if-two-strings-are-close/sol.cs create mode 100644 tests/1501-2000/1657. determine-if-two-strings-are-close/sol.dart create mode 100644 tests/1501-2000/1657. determine-if-two-strings-are-close/sol.go create mode 100644 tests/1501-2000/1657. determine-if-two-strings-are-close/sol.java create mode 100644 tests/1501-2000/1657. determine-if-two-strings-are-close/sol.kt create mode 100644 tests/1501-2000/1657. determine-if-two-strings-are-close/sol.py create mode 100644 tests/1501-2000/1657. determine-if-two-strings-are-close/sol.py2 create mode 100644 tests/1501-2000/1657. determine-if-two-strings-are-close/sol.rb create mode 100644 tests/1501-2000/1657. determine-if-two-strings-are-close/sol.rs create mode 100644 tests/1501-2000/1657. determine-if-two-strings-are-close/sol.swift create mode 100644 tests/1501-2000/1657. determine-if-two-strings-are-close/sol.ts create mode 100644 tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/manifest.yaml create mode 100644 tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.cpp create mode 100644 tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.cs create mode 100644 tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.dart create mode 100644 tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.go create mode 100644 tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.java create mode 100644 tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.kt create mode 100644 tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.py create mode 100644 tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.py2 create mode 100644 tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.rb create mode 100644 tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.rs create mode 100644 tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.swift create mode 100644 tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.ts create mode 100644 tests/1501-2000/1659. maximize-grid-happiness/manifest.yaml create mode 100644 tests/1501-2000/1659. maximize-grid-happiness/sol.cpp create mode 100644 tests/1501-2000/1659. maximize-grid-happiness/sol.cs create mode 100644 tests/1501-2000/1659. maximize-grid-happiness/sol.dart create mode 100644 tests/1501-2000/1659. maximize-grid-happiness/sol.go create mode 100644 tests/1501-2000/1659. maximize-grid-happiness/sol.java create mode 100644 tests/1501-2000/1659. maximize-grid-happiness/sol.kt create mode 100644 tests/1501-2000/1659. maximize-grid-happiness/sol.py create mode 100644 tests/1501-2000/1659. maximize-grid-happiness/sol.py2 create mode 100644 tests/1501-2000/1659. maximize-grid-happiness/sol.rb create mode 100644 tests/1501-2000/1659. maximize-grid-happiness/sol.rs create mode 100644 tests/1501-2000/1659. maximize-grid-happiness/sol.swift create mode 100644 tests/1501-2000/1659. maximize-grid-happiness/sol.ts create mode 100644 tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/manifest.yaml create mode 100644 tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.cpp create mode 100644 tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.cs create mode 100644 tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.dart create mode 100644 tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.go create mode 100644 tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.java create mode 100644 tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.kt create mode 100644 tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.py create mode 100644 tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.py2 create mode 100644 tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.rb create mode 100644 tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.rs create mode 100644 tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.swift create mode 100644 tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.ts create mode 100644 tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/manifest.yaml create mode 100644 tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.cpp create mode 100644 tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.cs create mode 100644 tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.dart create mode 100644 tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.go create mode 100644 tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.java create mode 100644 tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.kt create mode 100644 tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.py create mode 100644 tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.py2 create mode 100644 tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.rb create mode 100644 tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.rs create mode 100644 tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.swift create mode 100644 tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.ts create mode 100644 tests/1501-2000/1664. ways-to-make-a-fair-array/manifest.yaml create mode 100644 tests/1501-2000/1664. ways-to-make-a-fair-array/sol.cpp create mode 100644 tests/1501-2000/1664. ways-to-make-a-fair-array/sol.cs create mode 100644 tests/1501-2000/1664. ways-to-make-a-fair-array/sol.dart create mode 100644 tests/1501-2000/1664. ways-to-make-a-fair-array/sol.go create mode 100644 tests/1501-2000/1664. ways-to-make-a-fair-array/sol.java create mode 100644 tests/1501-2000/1664. ways-to-make-a-fair-array/sol.kt create mode 100644 tests/1501-2000/1664. ways-to-make-a-fair-array/sol.py create mode 100644 tests/1501-2000/1664. ways-to-make-a-fair-array/sol.py2 create mode 100644 tests/1501-2000/1664. ways-to-make-a-fair-array/sol.rb create mode 100644 tests/1501-2000/1664. ways-to-make-a-fair-array/sol.rs create mode 100644 tests/1501-2000/1664. ways-to-make-a-fair-array/sol.swift create mode 100644 tests/1501-2000/1664. ways-to-make-a-fair-array/sol.ts create mode 100644 tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/manifest.yaml create mode 100644 tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.cpp create mode 100644 tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.cs create mode 100644 tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.dart create mode 100644 tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.go create mode 100644 tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.java create mode 100644 tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.kt create mode 100644 tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.py create mode 100644 tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.py2 create mode 100644 tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.rb create mode 100644 tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.rs create mode 100644 tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.swift create mode 100644 tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.ts create mode 100644 tests/1501-2000/1668. maximum-repeating-substring/manifest.yaml create mode 100644 tests/1501-2000/1668. maximum-repeating-substring/sol.cpp create mode 100644 tests/1501-2000/1668. maximum-repeating-substring/sol.cs create mode 100644 tests/1501-2000/1668. maximum-repeating-substring/sol.dart create mode 100644 tests/1501-2000/1668. maximum-repeating-substring/sol.go create mode 100644 tests/1501-2000/1668. maximum-repeating-substring/sol.java create mode 100644 tests/1501-2000/1668. maximum-repeating-substring/sol.kt create mode 100644 tests/1501-2000/1668. maximum-repeating-substring/sol.py create mode 100644 tests/1501-2000/1668. maximum-repeating-substring/sol.py2 create mode 100644 tests/1501-2000/1668. maximum-repeating-substring/sol.rb create mode 100644 tests/1501-2000/1668. maximum-repeating-substring/sol.rs create mode 100644 tests/1501-2000/1668. maximum-repeating-substring/sol.swift create mode 100644 tests/1501-2000/1668. maximum-repeating-substring/sol.ts create mode 100644 tests/1501-2000/1669. merge-in-between-linked-lists/manifest.yaml create mode 100644 tests/1501-2000/1669. merge-in-between-linked-lists/sol.cpp create mode 100644 tests/1501-2000/1669. merge-in-between-linked-lists/sol.cs create mode 100644 tests/1501-2000/1669. merge-in-between-linked-lists/sol.dart create mode 100644 tests/1501-2000/1669. merge-in-between-linked-lists/sol.go create mode 100644 tests/1501-2000/1669. merge-in-between-linked-lists/sol.java create mode 100644 tests/1501-2000/1669. merge-in-between-linked-lists/sol.kt create mode 100644 tests/1501-2000/1669. merge-in-between-linked-lists/sol.py create mode 100644 tests/1501-2000/1669. merge-in-between-linked-lists/sol.py2 create mode 100644 tests/1501-2000/1669. merge-in-between-linked-lists/sol.rb create mode 100644 tests/1501-2000/1669. merge-in-between-linked-lists/sol.rs create mode 100644 tests/1501-2000/1669. merge-in-between-linked-lists/sol.swift create mode 100644 tests/1501-2000/1669. merge-in-between-linked-lists/sol.ts create mode 100644 tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/manifest.yaml create mode 100644 tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.cpp create mode 100644 tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.cs create mode 100644 tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.dart create mode 100644 tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.go create mode 100644 tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.java create mode 100644 tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.kt create mode 100644 tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.py create mode 100644 tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.py2 create mode 100644 tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.rb create mode 100644 tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.rs create mode 100644 tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.swift create mode 100644 tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.ts create mode 100644 tests/1501-2000/1672. richest-customer-wealth/manifest.yaml create mode 100644 tests/1501-2000/1672. richest-customer-wealth/sol.cpp create mode 100644 tests/1501-2000/1672. richest-customer-wealth/sol.cs create mode 100644 tests/1501-2000/1672. richest-customer-wealth/sol.dart create mode 100644 tests/1501-2000/1672. richest-customer-wealth/sol.go create mode 100644 tests/1501-2000/1672. richest-customer-wealth/sol.java create mode 100644 tests/1501-2000/1672. richest-customer-wealth/sol.kt create mode 100644 tests/1501-2000/1672. richest-customer-wealth/sol.py create mode 100644 tests/1501-2000/1672. richest-customer-wealth/sol.py2 create mode 100644 tests/1501-2000/1672. richest-customer-wealth/sol.rb create mode 100644 tests/1501-2000/1672. richest-customer-wealth/sol.rs create mode 100644 tests/1501-2000/1672. richest-customer-wealth/sol.swift create mode 100644 tests/1501-2000/1672. richest-customer-wealth/sol.ts create mode 100644 tests/1501-2000/1673. find-the-most-competitive-subsequence/manifest.yaml create mode 100644 tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.cpp create mode 100644 tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.cs create mode 100644 tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.dart create mode 100644 tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.go create mode 100644 tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.java create mode 100644 tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.kt create mode 100644 tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.py create mode 100644 tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.py2 create mode 100644 tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.rb create mode 100644 tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.rs create mode 100644 tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.swift create mode 100644 tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.ts create mode 100644 tests/1501-2000/1674. minimum-moves-to-make-array-complementary/manifest.yaml create mode 100644 tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.cpp create mode 100644 tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.cs create mode 100644 tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.dart create mode 100644 tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.go create mode 100644 tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.java create mode 100644 tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.kt create mode 100644 tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.py create mode 100644 tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.py2 create mode 100644 tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.rb create mode 100644 tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.rs create mode 100644 tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.swift create mode 100644 tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.ts create mode 100644 tests/1501-2000/1675. minimize-deviation-in-array/manifest.yaml create mode 100644 tests/1501-2000/1675. minimize-deviation-in-array/sol.cpp create mode 100644 tests/1501-2000/1675. minimize-deviation-in-array/sol.cs create mode 100644 tests/1501-2000/1675. minimize-deviation-in-array/sol.dart create mode 100644 tests/1501-2000/1675. minimize-deviation-in-array/sol.go create mode 100644 tests/1501-2000/1675. minimize-deviation-in-array/sol.java create mode 100644 tests/1501-2000/1675. minimize-deviation-in-array/sol.kt create mode 100644 tests/1501-2000/1675. minimize-deviation-in-array/sol.py create mode 100644 tests/1501-2000/1675. minimize-deviation-in-array/sol.py2 create mode 100644 tests/1501-2000/1675. minimize-deviation-in-array/sol.rb create mode 100644 tests/1501-2000/1675. minimize-deviation-in-array/sol.rs create mode 100644 tests/1501-2000/1675. minimize-deviation-in-array/sol.swift create mode 100644 tests/1501-2000/1675. minimize-deviation-in-array/sol.ts create mode 100644 tests/1501-2000/1678. goal-parser-interpretation/manifest.yaml create mode 100644 tests/1501-2000/1678. goal-parser-interpretation/sol.cpp create mode 100644 tests/1501-2000/1678. goal-parser-interpretation/sol.cs create mode 100644 tests/1501-2000/1678. goal-parser-interpretation/sol.dart create mode 100644 tests/1501-2000/1678. goal-parser-interpretation/sol.go create mode 100644 tests/1501-2000/1678. goal-parser-interpretation/sol.java create mode 100644 tests/1501-2000/1678. goal-parser-interpretation/sol.kt create mode 100644 tests/1501-2000/1678. goal-parser-interpretation/sol.py create mode 100644 tests/1501-2000/1678. goal-parser-interpretation/sol.py2 create mode 100644 tests/1501-2000/1678. goal-parser-interpretation/sol.rb create mode 100644 tests/1501-2000/1678. goal-parser-interpretation/sol.rs create mode 100644 tests/1501-2000/1678. goal-parser-interpretation/sol.swift create mode 100644 tests/1501-2000/1678. goal-parser-interpretation/sol.ts create mode 100644 tests/1501-2000/1679. max-number-of-k-sum-pairs/manifest.yaml create mode 100644 tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.cpp create mode 100644 tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.cs create mode 100644 tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.dart create mode 100644 tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.go create mode 100644 tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.java create mode 100644 tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.kt create mode 100644 tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.py create mode 100644 tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.py2 create mode 100644 tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.rb create mode 100644 tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.rs create mode 100644 tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.swift create mode 100644 tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.ts create mode 100644 tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/manifest.yaml create mode 100644 tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.cpp create mode 100644 tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.cs create mode 100644 tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.dart create mode 100644 tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.go create mode 100644 tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.java create mode 100644 tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.kt create mode 100644 tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.py create mode 100644 tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.py2 create mode 100644 tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.rb create mode 100644 tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.rs create mode 100644 tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.swift create mode 100644 tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.ts create mode 100644 tests/1501-2000/1681. minimum-incompatibility/manifest.yaml create mode 100644 tests/1501-2000/1681. minimum-incompatibility/sol.cpp create mode 100644 tests/1501-2000/1681. minimum-incompatibility/sol.cs create mode 100644 tests/1501-2000/1681. minimum-incompatibility/sol.dart create mode 100644 tests/1501-2000/1681. minimum-incompatibility/sol.go create mode 100644 tests/1501-2000/1681. minimum-incompatibility/sol.java create mode 100644 tests/1501-2000/1681. minimum-incompatibility/sol.kt create mode 100644 tests/1501-2000/1681. minimum-incompatibility/sol.py create mode 100644 tests/1501-2000/1681. minimum-incompatibility/sol.py2 create mode 100644 tests/1501-2000/1681. minimum-incompatibility/sol.rb create mode 100644 tests/1501-2000/1681. minimum-incompatibility/sol.rs create mode 100644 tests/1501-2000/1681. minimum-incompatibility/sol.swift create mode 100644 tests/1501-2000/1681. minimum-incompatibility/sol.ts create mode 100644 tests/1501-2000/1684. count-the-number-of-consistent-strings/manifest.yaml create mode 100644 tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.cpp create mode 100644 tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.cs create mode 100644 tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.dart create mode 100644 tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.go create mode 100644 tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.java create mode 100644 tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.kt create mode 100644 tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.py create mode 100644 tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.py2 create mode 100644 tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.rb create mode 100644 tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.rs create mode 100644 tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.swift create mode 100644 tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.ts create mode 100644 tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/manifest.yaml create mode 100644 tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.cpp create mode 100644 tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.cs create mode 100644 tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.dart create mode 100644 tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.go create mode 100644 tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.java create mode 100644 tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.kt create mode 100644 tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.py create mode 100644 tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.py2 create mode 100644 tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.rb create mode 100644 tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.rs create mode 100644 tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.swift create mode 100644 tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.ts create mode 100644 tests/1501-2000/1686. stone-game-vi/manifest.yaml create mode 100644 tests/1501-2000/1686. stone-game-vi/sol.cpp create mode 100644 tests/1501-2000/1686. stone-game-vi/sol.cs create mode 100644 tests/1501-2000/1686. stone-game-vi/sol.dart create mode 100644 tests/1501-2000/1686. stone-game-vi/sol.go create mode 100644 tests/1501-2000/1686. stone-game-vi/sol.java create mode 100644 tests/1501-2000/1686. stone-game-vi/sol.kt create mode 100644 tests/1501-2000/1686. stone-game-vi/sol.py create mode 100644 tests/1501-2000/1686. stone-game-vi/sol.py2 create mode 100644 tests/1501-2000/1686. stone-game-vi/sol.rb create mode 100644 tests/1501-2000/1686. stone-game-vi/sol.rs create mode 100644 tests/1501-2000/1686. stone-game-vi/sol.swift create mode 100644 tests/1501-2000/1686. stone-game-vi/sol.ts create mode 100644 tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/manifest.yaml create mode 100644 tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.cpp create mode 100644 tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.cs create mode 100644 tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.dart create mode 100644 tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.go create mode 100644 tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.java create mode 100644 tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.kt create mode 100644 tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.py create mode 100644 tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.py2 create mode 100644 tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.rb create mode 100644 tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.rs create mode 100644 tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.swift create mode 100644 tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.ts create mode 100644 tests/1501-2000/1688. count-of-matches-in-tournament/manifest.yaml create mode 100644 tests/1501-2000/1688. count-of-matches-in-tournament/sol.cpp create mode 100644 tests/1501-2000/1688. count-of-matches-in-tournament/sol.cs create mode 100644 tests/1501-2000/1688. count-of-matches-in-tournament/sol.dart create mode 100644 tests/1501-2000/1688. count-of-matches-in-tournament/sol.go create mode 100644 tests/1501-2000/1688. count-of-matches-in-tournament/sol.java create mode 100644 tests/1501-2000/1688. count-of-matches-in-tournament/sol.kt create mode 100644 tests/1501-2000/1688. count-of-matches-in-tournament/sol.py create mode 100644 tests/1501-2000/1688. count-of-matches-in-tournament/sol.py2 create mode 100644 tests/1501-2000/1688. count-of-matches-in-tournament/sol.rb create mode 100644 tests/1501-2000/1688. count-of-matches-in-tournament/sol.rs create mode 100644 tests/1501-2000/1688. count-of-matches-in-tournament/sol.swift create mode 100644 tests/1501-2000/1688. count-of-matches-in-tournament/sol.ts create mode 100644 tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/manifest.yaml create mode 100644 tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.cpp create mode 100644 tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.cs create mode 100644 tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.dart create mode 100644 tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.go create mode 100644 tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.java create mode 100644 tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.kt create mode 100644 tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.py create mode 100644 tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.py2 create mode 100644 tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.rb create mode 100644 tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.rs create mode 100644 tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.swift create mode 100644 tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.ts create mode 100644 tests/1501-2000/1690. stone-game-vii/manifest.yaml create mode 100644 tests/1501-2000/1690. stone-game-vii/sol.cpp create mode 100644 tests/1501-2000/1690. stone-game-vii/sol.cs create mode 100644 tests/1501-2000/1690. stone-game-vii/sol.dart create mode 100644 tests/1501-2000/1690. stone-game-vii/sol.go create mode 100644 tests/1501-2000/1690. stone-game-vii/sol.java create mode 100644 tests/1501-2000/1690. stone-game-vii/sol.kt create mode 100644 tests/1501-2000/1690. stone-game-vii/sol.py create mode 100644 tests/1501-2000/1690. stone-game-vii/sol.py2 create mode 100644 tests/1501-2000/1690. stone-game-vii/sol.rb create mode 100644 tests/1501-2000/1690. stone-game-vii/sol.rs create mode 100644 tests/1501-2000/1690. stone-game-vii/sol.swift create mode 100644 tests/1501-2000/1690. stone-game-vii/sol.ts create mode 100644 tests/1501-2000/1691. maximum-height-by-stacking-cuboids/manifest.yaml create mode 100644 tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.cpp create mode 100644 tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.cs create mode 100644 tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.dart create mode 100644 tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.go create mode 100644 tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.java create mode 100644 tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.kt create mode 100644 tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.py create mode 100644 tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.py2 create mode 100644 tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.rb create mode 100644 tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.rs create mode 100644 tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.swift create mode 100644 tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.ts create mode 100644 tests/1501-2000/1694. reformat-phone-number/manifest.yaml create mode 100644 tests/1501-2000/1694. reformat-phone-number/sol.cpp create mode 100644 tests/1501-2000/1694. reformat-phone-number/sol.cs create mode 100644 tests/1501-2000/1694. reformat-phone-number/sol.dart create mode 100644 tests/1501-2000/1694. reformat-phone-number/sol.go create mode 100644 tests/1501-2000/1694. reformat-phone-number/sol.java create mode 100644 tests/1501-2000/1694. reformat-phone-number/sol.kt create mode 100644 tests/1501-2000/1694. reformat-phone-number/sol.py create mode 100644 tests/1501-2000/1694. reformat-phone-number/sol.py2 create mode 100644 tests/1501-2000/1694. reformat-phone-number/sol.rb create mode 100644 tests/1501-2000/1694. reformat-phone-number/sol.rs create mode 100644 tests/1501-2000/1694. reformat-phone-number/sol.swift create mode 100644 tests/1501-2000/1694. reformat-phone-number/sol.ts create mode 100644 tests/1501-2000/1695. maximum-erasure-value/manifest.yaml create mode 100644 tests/1501-2000/1695. maximum-erasure-value/sol.cpp create mode 100644 tests/1501-2000/1695. maximum-erasure-value/sol.cs create mode 100644 tests/1501-2000/1695. maximum-erasure-value/sol.dart create mode 100644 tests/1501-2000/1695. maximum-erasure-value/sol.go create mode 100644 tests/1501-2000/1695. maximum-erasure-value/sol.java create mode 100644 tests/1501-2000/1695. maximum-erasure-value/sol.kt create mode 100644 tests/1501-2000/1695. maximum-erasure-value/sol.py create mode 100644 tests/1501-2000/1695. maximum-erasure-value/sol.py2 create mode 100644 tests/1501-2000/1695. maximum-erasure-value/sol.rb create mode 100644 tests/1501-2000/1695. maximum-erasure-value/sol.rs create mode 100644 tests/1501-2000/1695. maximum-erasure-value/sol.swift create mode 100644 tests/1501-2000/1695. maximum-erasure-value/sol.ts create mode 100644 tests/1501-2000/1696. jump-game-vi/manifest.yaml create mode 100644 tests/1501-2000/1696. jump-game-vi/sol.cpp create mode 100644 tests/1501-2000/1696. jump-game-vi/sol.cs create mode 100644 tests/1501-2000/1696. jump-game-vi/sol.dart create mode 100644 tests/1501-2000/1696. jump-game-vi/sol.go create mode 100644 tests/1501-2000/1696. jump-game-vi/sol.java create mode 100644 tests/1501-2000/1696. jump-game-vi/sol.kt create mode 100644 tests/1501-2000/1696. jump-game-vi/sol.py create mode 100644 tests/1501-2000/1696. jump-game-vi/sol.py2 create mode 100644 tests/1501-2000/1696. jump-game-vi/sol.rb create mode 100644 tests/1501-2000/1696. jump-game-vi/sol.rs create mode 100644 tests/1501-2000/1696. jump-game-vi/sol.swift create mode 100644 tests/1501-2000/1696. jump-game-vi/sol.ts create mode 100644 tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/manifest.yaml create mode 100644 tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.cpp create mode 100644 tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.cs create mode 100644 tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.dart create mode 100644 tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.go create mode 100644 tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.java create mode 100644 tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.kt create mode 100644 tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.py create mode 100644 tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.py2 create mode 100644 tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.rb create mode 100644 tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.rs create mode 100644 tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.swift create mode 100644 tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.ts create mode 100644 tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/manifest.yaml create mode 100644 tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.cpp create mode 100644 tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.cs create mode 100644 tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.dart create mode 100644 tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.go create mode 100644 tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.java create mode 100644 tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.kt create mode 100644 tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.py create mode 100644 tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.py2 create mode 100644 tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.rb create mode 100644 tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.rs create mode 100644 tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.swift create mode 100644 tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.ts create mode 100644 tests/1501-2000/1701. average-waiting-time/manifest.yaml create mode 100644 tests/1501-2000/1701. average-waiting-time/sol.cpp create mode 100644 tests/1501-2000/1701. average-waiting-time/sol.cs create mode 100644 tests/1501-2000/1701. average-waiting-time/sol.dart create mode 100644 tests/1501-2000/1701. average-waiting-time/sol.go create mode 100644 tests/1501-2000/1701. average-waiting-time/sol.java create mode 100644 tests/1501-2000/1701. average-waiting-time/sol.kt create mode 100644 tests/1501-2000/1701. average-waiting-time/sol.py create mode 100644 tests/1501-2000/1701. average-waiting-time/sol.py2 create mode 100644 tests/1501-2000/1701. average-waiting-time/sol.rb create mode 100644 tests/1501-2000/1701. average-waiting-time/sol.rs create mode 100644 tests/1501-2000/1701. average-waiting-time/sol.swift create mode 100644 tests/1501-2000/1701. average-waiting-time/sol.ts create mode 100644 tests/1501-2000/1702. maximum-binary-string-after-change/manifest.yaml create mode 100644 tests/1501-2000/1702. maximum-binary-string-after-change/sol.cpp create mode 100644 tests/1501-2000/1702. maximum-binary-string-after-change/sol.cs create mode 100644 tests/1501-2000/1702. maximum-binary-string-after-change/sol.dart create mode 100644 tests/1501-2000/1702. maximum-binary-string-after-change/sol.go create mode 100644 tests/1501-2000/1702. maximum-binary-string-after-change/sol.java create mode 100644 tests/1501-2000/1702. maximum-binary-string-after-change/sol.kt create mode 100644 tests/1501-2000/1702. maximum-binary-string-after-change/sol.py create mode 100644 tests/1501-2000/1702. maximum-binary-string-after-change/sol.py2 create mode 100644 tests/1501-2000/1702. maximum-binary-string-after-change/sol.rb create mode 100644 tests/1501-2000/1702. maximum-binary-string-after-change/sol.rs create mode 100644 tests/1501-2000/1702. maximum-binary-string-after-change/sol.swift create mode 100644 tests/1501-2000/1702. maximum-binary-string-after-change/sol.ts create mode 100644 tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/manifest.yaml create mode 100644 tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.cpp create mode 100644 tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.cs create mode 100644 tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.dart create mode 100644 tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.go create mode 100644 tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.java create mode 100644 tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.kt create mode 100644 tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.py create mode 100644 tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.py2 create mode 100644 tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.rb create mode 100644 tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.rs create mode 100644 tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.swift create mode 100644 tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.ts create mode 100644 tests/1501-2000/1704. determine-if-string-halves-are-alike/manifest.yaml create mode 100644 tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.cpp create mode 100644 tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.cs create mode 100644 tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.dart create mode 100644 tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.go create mode 100644 tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.java create mode 100644 tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.kt create mode 100644 tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.py create mode 100644 tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.py2 create mode 100644 tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.rb create mode 100644 tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.rs create mode 100644 tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.swift create mode 100644 tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.ts create mode 100644 tests/1501-2000/1705. maximum-number-of-eaten-apples/manifest.yaml create mode 100644 tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.cpp create mode 100644 tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.cs create mode 100644 tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.dart create mode 100644 tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.go create mode 100644 tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.java create mode 100644 tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.kt create mode 100644 tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.py create mode 100644 tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.py2 create mode 100644 tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.rb create mode 100644 tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.rs create mode 100644 tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.swift create mode 100644 tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.ts create mode 100644 tests/1501-2000/1706. where-will-the-ball-fall/manifest.yaml create mode 100644 tests/1501-2000/1706. where-will-the-ball-fall/sol.cpp create mode 100644 tests/1501-2000/1706. where-will-the-ball-fall/sol.cs create mode 100644 tests/1501-2000/1706. where-will-the-ball-fall/sol.dart create mode 100644 tests/1501-2000/1706. where-will-the-ball-fall/sol.go create mode 100644 tests/1501-2000/1706. where-will-the-ball-fall/sol.java create mode 100644 tests/1501-2000/1706. where-will-the-ball-fall/sol.kt create mode 100644 tests/1501-2000/1706. where-will-the-ball-fall/sol.py create mode 100644 tests/1501-2000/1706. where-will-the-ball-fall/sol.py2 create mode 100644 tests/1501-2000/1706. where-will-the-ball-fall/sol.rb create mode 100644 tests/1501-2000/1706. where-will-the-ball-fall/sol.rs create mode 100644 tests/1501-2000/1706. where-will-the-ball-fall/sol.swift create mode 100644 tests/1501-2000/1706. where-will-the-ball-fall/sol.ts create mode 100644 tests/1501-2000/1707. maximum-xor-with-an-element-from-array/manifest.yaml create mode 100644 tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.cpp create mode 100644 tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.cs create mode 100644 tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.dart create mode 100644 tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.go create mode 100644 tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.java create mode 100644 tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.kt create mode 100644 tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.py create mode 100644 tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.py2 create mode 100644 tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.rb create mode 100644 tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.rs create mode 100644 tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.swift create mode 100644 tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.ts create mode 100644 tests/1501-2000/1710. maximum-units-on-a-truck/manifest.yaml create mode 100644 tests/1501-2000/1710. maximum-units-on-a-truck/sol.cpp create mode 100644 tests/1501-2000/1710. maximum-units-on-a-truck/sol.cs create mode 100644 tests/1501-2000/1710. maximum-units-on-a-truck/sol.dart create mode 100644 tests/1501-2000/1710. maximum-units-on-a-truck/sol.go create mode 100644 tests/1501-2000/1710. maximum-units-on-a-truck/sol.java create mode 100644 tests/1501-2000/1710. maximum-units-on-a-truck/sol.kt create mode 100644 tests/1501-2000/1710. maximum-units-on-a-truck/sol.py create mode 100644 tests/1501-2000/1710. maximum-units-on-a-truck/sol.py2 create mode 100644 tests/1501-2000/1710. maximum-units-on-a-truck/sol.rb create mode 100644 tests/1501-2000/1710. maximum-units-on-a-truck/sol.rs create mode 100644 tests/1501-2000/1710. maximum-units-on-a-truck/sol.swift create mode 100644 tests/1501-2000/1710. maximum-units-on-a-truck/sol.ts create mode 100644 tests/1501-2000/1711. count-good-meals/manifest.yaml create mode 100644 tests/1501-2000/1711. count-good-meals/sol.cpp create mode 100644 tests/1501-2000/1711. count-good-meals/sol.cs create mode 100644 tests/1501-2000/1711. count-good-meals/sol.dart create mode 100644 tests/1501-2000/1711. count-good-meals/sol.go create mode 100644 tests/1501-2000/1711. count-good-meals/sol.java create mode 100644 tests/1501-2000/1711. count-good-meals/sol.kt create mode 100644 tests/1501-2000/1711. count-good-meals/sol.py create mode 100644 tests/1501-2000/1711. count-good-meals/sol.py2 create mode 100644 tests/1501-2000/1711. count-good-meals/sol.rb create mode 100644 tests/1501-2000/1711. count-good-meals/sol.rs create mode 100644 tests/1501-2000/1711. count-good-meals/sol.swift create mode 100644 tests/1501-2000/1711. count-good-meals/sol.ts create mode 100644 tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/manifest.yaml create mode 100644 tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.cpp create mode 100644 tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.cs create mode 100644 tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.dart create mode 100644 tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.go create mode 100644 tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.java create mode 100644 tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.kt create mode 100644 tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.py create mode 100644 tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.py2 create mode 100644 tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.rb create mode 100644 tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.rs create mode 100644 tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.swift create mode 100644 tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.ts create mode 100644 tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/manifest.yaml create mode 100644 tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.cpp create mode 100644 tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.cs create mode 100644 tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.dart create mode 100644 tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.go create mode 100644 tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.java create mode 100644 tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.kt create mode 100644 tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.py create mode 100644 tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.py2 create mode 100644 tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.rb create mode 100644 tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.rs create mode 100644 tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.swift create mode 100644 tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.ts create mode 100644 tests/1501-2000/1716. calculate-money-in-leetcode-bank/manifest.yaml create mode 100644 tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.cpp create mode 100644 tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.cs create mode 100644 tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.dart create mode 100644 tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.go create mode 100644 tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.java create mode 100644 tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.kt create mode 100644 tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.py create mode 100644 tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.py2 create mode 100644 tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.rb create mode 100644 tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.rs create mode 100644 tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.swift create mode 100644 tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.ts create mode 100644 tests/1501-2000/1717. maximum-score-from-removing-substrings/manifest.yaml create mode 100644 tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.cpp create mode 100644 tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.cs create mode 100644 tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.dart create mode 100644 tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.go create mode 100644 tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.java create mode 100644 tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.kt create mode 100644 tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.py create mode 100644 tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.py2 create mode 100644 tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.rb create mode 100644 tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.rs create mode 100644 tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.swift create mode 100644 tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.ts create mode 100644 tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/manifest.yaml create mode 100644 tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.cpp create mode 100644 tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.cs create mode 100644 tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.dart create mode 100644 tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.go create mode 100644 tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.java create mode 100644 tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.kt create mode 100644 tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.py create mode 100644 tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.py2 create mode 100644 tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.rb create mode 100644 tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.rs create mode 100644 tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.swift create mode 100644 tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.ts create mode 100644 tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/manifest.yaml create mode 100644 tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.cpp create mode 100644 tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.cs create mode 100644 tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.dart create mode 100644 tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.go create mode 100644 tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.java create mode 100644 tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.kt create mode 100644 tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.py create mode 100644 tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.py2 create mode 100644 tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.rb create mode 100644 tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.rs create mode 100644 tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.swift create mode 100644 tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.ts create mode 100644 tests/1501-2000/1720. decode-xored-array/manifest.yaml create mode 100644 tests/1501-2000/1720. decode-xored-array/sol.cpp create mode 100644 tests/1501-2000/1720. decode-xored-array/sol.cs create mode 100644 tests/1501-2000/1720. decode-xored-array/sol.dart create mode 100644 tests/1501-2000/1720. decode-xored-array/sol.go create mode 100644 tests/1501-2000/1720. decode-xored-array/sol.java create mode 100644 tests/1501-2000/1720. decode-xored-array/sol.kt create mode 100644 tests/1501-2000/1720. decode-xored-array/sol.py create mode 100644 tests/1501-2000/1720. decode-xored-array/sol.py2 create mode 100644 tests/1501-2000/1720. decode-xored-array/sol.rb create mode 100644 tests/1501-2000/1720. decode-xored-array/sol.rs create mode 100644 tests/1501-2000/1720. decode-xored-array/sol.swift create mode 100644 tests/1501-2000/1720. decode-xored-array/sol.ts create mode 100644 tests/1501-2000/1721. swapping-nodes-in-a-linked-list/manifest.yaml create mode 100644 tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.cpp create mode 100644 tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.cs create mode 100644 tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.dart create mode 100644 tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.go create mode 100644 tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.java create mode 100644 tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.kt create mode 100644 tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.py create mode 100644 tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.py2 create mode 100644 tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.rb create mode 100644 tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.rs create mode 100644 tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.swift create mode 100644 tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.ts create mode 100644 tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/manifest.yaml create mode 100644 tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.cpp create mode 100644 tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.cs create mode 100644 tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.dart create mode 100644 tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.go create mode 100644 tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.java create mode 100644 tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.kt create mode 100644 tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.py create mode 100644 tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.py2 create mode 100644 tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.rb create mode 100644 tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.rs create mode 100644 tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.swift create mode 100644 tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.ts create mode 100644 tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/manifest.yaml create mode 100644 tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.cpp create mode 100644 tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.cs create mode 100644 tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.dart create mode 100644 tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.go create mode 100644 tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.java create mode 100644 tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.kt create mode 100644 tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.py create mode 100644 tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.py2 create mode 100644 tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.rb create mode 100644 tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.rs create mode 100644 tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.swift create mode 100644 tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.ts create mode 100644 tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/manifest.yaml create mode 100644 tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.cpp create mode 100644 tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.cs create mode 100644 tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.dart create mode 100644 tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.go create mode 100644 tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.java create mode 100644 tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.kt create mode 100644 tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.py create mode 100644 tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.py2 create mode 100644 tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.rb create mode 100644 tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.rs create mode 100644 tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.swift create mode 100644 tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.ts create mode 100644 tests/1501-2000/1726. tuple-with-same-product/manifest.yaml create mode 100644 tests/1501-2000/1726. tuple-with-same-product/sol.cpp create mode 100644 tests/1501-2000/1726. tuple-with-same-product/sol.cs create mode 100644 tests/1501-2000/1726. tuple-with-same-product/sol.dart create mode 100644 tests/1501-2000/1726. tuple-with-same-product/sol.go create mode 100644 tests/1501-2000/1726. tuple-with-same-product/sol.java create mode 100644 tests/1501-2000/1726. tuple-with-same-product/sol.kt create mode 100644 tests/1501-2000/1726. tuple-with-same-product/sol.py create mode 100644 tests/1501-2000/1726. tuple-with-same-product/sol.py2 create mode 100644 tests/1501-2000/1726. tuple-with-same-product/sol.rb create mode 100644 tests/1501-2000/1726. tuple-with-same-product/sol.rs create mode 100644 tests/1501-2000/1726. tuple-with-same-product/sol.swift create mode 100644 tests/1501-2000/1726. tuple-with-same-product/sol.ts create mode 100644 tests/1501-2000/1727. largest-submatrix-with-rearrangements/manifest.yaml create mode 100644 tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.cpp create mode 100644 tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.cs create mode 100644 tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.dart create mode 100644 tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.go create mode 100644 tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.java create mode 100644 tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.kt create mode 100644 tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.py create mode 100644 tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.py2 create mode 100644 tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.rb create mode 100644 tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.rs create mode 100644 tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.swift create mode 100644 tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.ts create mode 100644 tests/1501-2000/1728. cat-and-mouse-ii/manifest.yaml create mode 100644 tests/1501-2000/1728. cat-and-mouse-ii/sol.cpp create mode 100644 tests/1501-2000/1728. cat-and-mouse-ii/sol.cs create mode 100644 tests/1501-2000/1728. cat-and-mouse-ii/sol.dart create mode 100644 tests/1501-2000/1728. cat-and-mouse-ii/sol.go create mode 100644 tests/1501-2000/1728. cat-and-mouse-ii/sol.java create mode 100644 tests/1501-2000/1728. cat-and-mouse-ii/sol.kt create mode 100644 tests/1501-2000/1728. cat-and-mouse-ii/sol.py create mode 100644 tests/1501-2000/1728. cat-and-mouse-ii/sol.py2 create mode 100644 tests/1501-2000/1728. cat-and-mouse-ii/sol.rb create mode 100644 tests/1501-2000/1728. cat-and-mouse-ii/sol.rs create mode 100644 tests/1501-2000/1728. cat-and-mouse-ii/sol.swift create mode 100644 tests/1501-2000/1728. cat-and-mouse-ii/sol.ts create mode 100644 tests/1501-2000/1732. find-the-highest-altitude/manifest.yaml create mode 100644 tests/1501-2000/1732. find-the-highest-altitude/sol.cpp create mode 100644 tests/1501-2000/1732. find-the-highest-altitude/sol.cs create mode 100644 tests/1501-2000/1732. find-the-highest-altitude/sol.dart create mode 100644 tests/1501-2000/1732. find-the-highest-altitude/sol.go create mode 100644 tests/1501-2000/1732. find-the-highest-altitude/sol.java create mode 100644 tests/1501-2000/1732. find-the-highest-altitude/sol.kt create mode 100644 tests/1501-2000/1732. find-the-highest-altitude/sol.py create mode 100644 tests/1501-2000/1732. find-the-highest-altitude/sol.py2 create mode 100644 tests/1501-2000/1732. find-the-highest-altitude/sol.rb create mode 100644 tests/1501-2000/1732. find-the-highest-altitude/sol.rs create mode 100644 tests/1501-2000/1732. find-the-highest-altitude/sol.swift create mode 100644 tests/1501-2000/1732. find-the-highest-altitude/sol.ts create mode 100644 tests/1501-2000/1733. minimum-number-of-people-to-teach/manifest.yaml create mode 100644 tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.cpp create mode 100644 tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.cs create mode 100644 tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.dart create mode 100644 tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.go create mode 100644 tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.java create mode 100644 tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.kt create mode 100644 tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.py create mode 100644 tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.py2 create mode 100644 tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.rb create mode 100644 tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.rs create mode 100644 tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.swift create mode 100644 tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.ts create mode 100644 tests/1501-2000/1734. decode-xored-permutation/manifest.yaml create mode 100644 tests/1501-2000/1734. decode-xored-permutation/sol.cpp create mode 100644 tests/1501-2000/1734. decode-xored-permutation/sol.cs create mode 100644 tests/1501-2000/1734. decode-xored-permutation/sol.dart create mode 100644 tests/1501-2000/1734. decode-xored-permutation/sol.go create mode 100644 tests/1501-2000/1734. decode-xored-permutation/sol.java create mode 100644 tests/1501-2000/1734. decode-xored-permutation/sol.kt create mode 100644 tests/1501-2000/1734. decode-xored-permutation/sol.py create mode 100644 tests/1501-2000/1734. decode-xored-permutation/sol.py2 create mode 100644 tests/1501-2000/1734. decode-xored-permutation/sol.rb create mode 100644 tests/1501-2000/1734. decode-xored-permutation/sol.rs create mode 100644 tests/1501-2000/1734. decode-xored-permutation/sol.swift create mode 100644 tests/1501-2000/1734. decode-xored-permutation/sol.ts create mode 100644 tests/1501-2000/1735. count-ways-to-make-array-with-product/manifest.yaml create mode 100644 tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.cpp create mode 100644 tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.cs create mode 100644 tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.dart create mode 100644 tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.go create mode 100644 tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.java create mode 100644 tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.kt create mode 100644 tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.py create mode 100644 tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.py2 create mode 100644 tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.rb create mode 100644 tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.rs create mode 100644 tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.swift create mode 100644 tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.ts create mode 100644 tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/manifest.yaml create mode 100644 tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.cpp create mode 100644 tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.cs create mode 100644 tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.dart create mode 100644 tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.go create mode 100644 tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.java create mode 100644 tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.kt create mode 100644 tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.py create mode 100644 tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.py2 create mode 100644 tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.rb create mode 100644 tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.rs create mode 100644 tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.swift create mode 100644 tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.ts create mode 100644 tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/manifest.yaml create mode 100644 tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.cpp create mode 100644 tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.cs create mode 100644 tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.dart create mode 100644 tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.go create mode 100644 tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.java create mode 100644 tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.kt create mode 100644 tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.py create mode 100644 tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.py2 create mode 100644 tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.rb create mode 100644 tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.rs create mode 100644 tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.swift create mode 100644 tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.ts create mode 100644 tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/manifest.yaml create mode 100644 tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.cpp create mode 100644 tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.cs create mode 100644 tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.dart create mode 100644 tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.go create mode 100644 tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.java create mode 100644 tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.kt create mode 100644 tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.py create mode 100644 tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.py2 create mode 100644 tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.rb create mode 100644 tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.rs create mode 100644 tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.swift create mode 100644 tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.ts create mode 100644 tests/1501-2000/1739. building-boxes/manifest.yaml create mode 100644 tests/1501-2000/1739. building-boxes/sol.cpp create mode 100644 tests/1501-2000/1739. building-boxes/sol.cs create mode 100644 tests/1501-2000/1739. building-boxes/sol.dart create mode 100644 tests/1501-2000/1739. building-boxes/sol.go create mode 100644 tests/1501-2000/1739. building-boxes/sol.java create mode 100644 tests/1501-2000/1739. building-boxes/sol.kt create mode 100644 tests/1501-2000/1739. building-boxes/sol.py create mode 100644 tests/1501-2000/1739. building-boxes/sol.py2 create mode 100644 tests/1501-2000/1739. building-boxes/sol.rb create mode 100644 tests/1501-2000/1739. building-boxes/sol.rs create mode 100644 tests/1501-2000/1739. building-boxes/sol.swift create mode 100644 tests/1501-2000/1739. building-boxes/sol.ts create mode 100644 tests/1501-2000/1742. maximum-number-of-balls-in-a-box/manifest.yaml create mode 100644 tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.cpp create mode 100644 tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.cs create mode 100644 tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.dart create mode 100644 tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.go create mode 100644 tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.java create mode 100644 tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.kt create mode 100644 tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.py create mode 100644 tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.py2 create mode 100644 tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.rb create mode 100644 tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.rs create mode 100644 tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.swift create mode 100644 tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.ts create mode 100644 tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/manifest.yaml create mode 100644 tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.cpp create mode 100644 tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.cs create mode 100644 tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.dart create mode 100644 tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.go create mode 100644 tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.java create mode 100644 tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.kt create mode 100644 tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.py create mode 100644 tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.py2 create mode 100644 tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.rb create mode 100644 tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.rs create mode 100644 tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.swift create mode 100644 tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.ts create mode 100644 tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/manifest.yaml create mode 100644 tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.cpp create mode 100644 tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.cs create mode 100644 tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.dart create mode 100644 tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.go create mode 100644 tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.java create mode 100644 tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.kt create mode 100644 tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.py create mode 100644 tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.py2 create mode 100644 tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.rb create mode 100644 tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.rs create mode 100644 tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.swift create mode 100644 tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.ts create mode 100644 tests/1501-2000/1745. palindrome-partitioning-iv/manifest.yaml create mode 100644 tests/1501-2000/1745. palindrome-partitioning-iv/sol.cpp create mode 100644 tests/1501-2000/1745. palindrome-partitioning-iv/sol.cs create mode 100644 tests/1501-2000/1745. palindrome-partitioning-iv/sol.dart create mode 100644 tests/1501-2000/1745. palindrome-partitioning-iv/sol.go create mode 100644 tests/1501-2000/1745. palindrome-partitioning-iv/sol.java create mode 100644 tests/1501-2000/1745. palindrome-partitioning-iv/sol.kt create mode 100644 tests/1501-2000/1745. palindrome-partitioning-iv/sol.py create mode 100644 tests/1501-2000/1745. palindrome-partitioning-iv/sol.py2 create mode 100644 tests/1501-2000/1745. palindrome-partitioning-iv/sol.rb create mode 100644 tests/1501-2000/1745. palindrome-partitioning-iv/sol.rs create mode 100644 tests/1501-2000/1745. palindrome-partitioning-iv/sol.swift create mode 100644 tests/1501-2000/1745. palindrome-partitioning-iv/sol.ts create mode 100644 tests/1501-2000/1748. sum-of-unique-elements/manifest.yaml create mode 100644 tests/1501-2000/1748. sum-of-unique-elements/sol.cpp create mode 100644 tests/1501-2000/1748. sum-of-unique-elements/sol.cs create mode 100644 tests/1501-2000/1748. sum-of-unique-elements/sol.dart create mode 100644 tests/1501-2000/1748. sum-of-unique-elements/sol.go create mode 100644 tests/1501-2000/1748. sum-of-unique-elements/sol.java create mode 100644 tests/1501-2000/1748. sum-of-unique-elements/sol.kt create mode 100644 tests/1501-2000/1748. sum-of-unique-elements/sol.py create mode 100644 tests/1501-2000/1748. sum-of-unique-elements/sol.py2 create mode 100644 tests/1501-2000/1748. sum-of-unique-elements/sol.rb create mode 100644 tests/1501-2000/1748. sum-of-unique-elements/sol.rs create mode 100644 tests/1501-2000/1748. sum-of-unique-elements/sol.swift create mode 100644 tests/1501-2000/1748. sum-of-unique-elements/sol.ts create mode 100644 tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/manifest.yaml create mode 100644 tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.cpp create mode 100644 tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.cs create mode 100644 tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.dart create mode 100644 tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.go create mode 100644 tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.java create mode 100644 tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.kt create mode 100644 tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.py create mode 100644 tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.py2 create mode 100644 tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.rb create mode 100644 tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.rs create mode 100644 tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.swift create mode 100644 tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.ts create mode 100644 tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/manifest.yaml create mode 100644 tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.cpp create mode 100644 tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.cs create mode 100644 tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.dart create mode 100644 tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.go create mode 100644 tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.java create mode 100644 tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.kt create mode 100644 tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.py create mode 100644 tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.py2 create mode 100644 tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.rb create mode 100644 tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.rs create mode 100644 tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.swift create mode 100644 tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.ts create mode 100644 tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/manifest.yaml create mode 100644 tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.cpp create mode 100644 tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.cs create mode 100644 tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.dart create mode 100644 tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.go create mode 100644 tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.java create mode 100644 tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.kt create mode 100644 tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.py create mode 100644 tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.py2 create mode 100644 tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.rb create mode 100644 tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.rs create mode 100644 tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.swift create mode 100644 tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.ts create mode 100644 tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/manifest.yaml create mode 100644 tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.cpp create mode 100644 tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.cs create mode 100644 tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.dart create mode 100644 tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.go create mode 100644 tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.java create mode 100644 tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.kt create mode 100644 tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.py create mode 100644 tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.py2 create mode 100644 tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.rb create mode 100644 tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.rs create mode 100644 tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.swift create mode 100644 tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.ts create mode 100644 tests/1501-2000/1753. maximum-score-from-removing-stones/manifest.yaml create mode 100644 tests/1501-2000/1753. maximum-score-from-removing-stones/sol.cpp create mode 100644 tests/1501-2000/1753. maximum-score-from-removing-stones/sol.cs create mode 100644 tests/1501-2000/1753. maximum-score-from-removing-stones/sol.dart create mode 100644 tests/1501-2000/1753. maximum-score-from-removing-stones/sol.go create mode 100644 tests/1501-2000/1753. maximum-score-from-removing-stones/sol.java create mode 100644 tests/1501-2000/1753. maximum-score-from-removing-stones/sol.kt create mode 100644 tests/1501-2000/1753. maximum-score-from-removing-stones/sol.py create mode 100644 tests/1501-2000/1753. maximum-score-from-removing-stones/sol.py2 create mode 100644 tests/1501-2000/1753. maximum-score-from-removing-stones/sol.rb create mode 100644 tests/1501-2000/1753. maximum-score-from-removing-stones/sol.rs create mode 100644 tests/1501-2000/1753. maximum-score-from-removing-stones/sol.swift create mode 100644 tests/1501-2000/1753. maximum-score-from-removing-stones/sol.ts create mode 100644 tests/1501-2000/1754. largest-merge-of-two-strings/manifest.yaml create mode 100644 tests/1501-2000/1754. largest-merge-of-two-strings/sol.cpp create mode 100644 tests/1501-2000/1754. largest-merge-of-two-strings/sol.cs create mode 100644 tests/1501-2000/1754. largest-merge-of-two-strings/sol.dart create mode 100644 tests/1501-2000/1754. largest-merge-of-two-strings/sol.go create mode 100644 tests/1501-2000/1754. largest-merge-of-two-strings/sol.java create mode 100644 tests/1501-2000/1754. largest-merge-of-two-strings/sol.kt create mode 100644 tests/1501-2000/1754. largest-merge-of-two-strings/sol.py create mode 100644 tests/1501-2000/1754. largest-merge-of-two-strings/sol.py2 create mode 100644 tests/1501-2000/1754. largest-merge-of-two-strings/sol.rb create mode 100644 tests/1501-2000/1754. largest-merge-of-two-strings/sol.rs create mode 100644 tests/1501-2000/1754. largest-merge-of-two-strings/sol.swift create mode 100644 tests/1501-2000/1754. largest-merge-of-two-strings/sol.ts create mode 100644 tests/1501-2000/1755. closest-subsequence-sum/manifest.yaml create mode 100644 tests/1501-2000/1755. closest-subsequence-sum/sol.cpp create mode 100644 tests/1501-2000/1755. closest-subsequence-sum/sol.cs create mode 100644 tests/1501-2000/1755. closest-subsequence-sum/sol.dart create mode 100644 tests/1501-2000/1755. closest-subsequence-sum/sol.go create mode 100644 tests/1501-2000/1755. closest-subsequence-sum/sol.java create mode 100644 tests/1501-2000/1755. closest-subsequence-sum/sol.kt create mode 100644 tests/1501-2000/1755. closest-subsequence-sum/sol.py create mode 100644 tests/1501-2000/1755. closest-subsequence-sum/sol.py2 create mode 100644 tests/1501-2000/1755. closest-subsequence-sum/sol.rb create mode 100644 tests/1501-2000/1755. closest-subsequence-sum/sol.rs create mode 100644 tests/1501-2000/1755. closest-subsequence-sum/sol.swift create mode 100644 tests/1501-2000/1755. closest-subsequence-sum/sol.ts create mode 100644 tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/manifest.yaml create mode 100644 tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.cpp create mode 100644 tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.cs create mode 100644 tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.dart create mode 100644 tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.go create mode 100644 tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.java create mode 100644 tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.kt create mode 100644 tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.py create mode 100644 tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.py2 create mode 100644 tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.rb create mode 100644 tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.rs create mode 100644 tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.swift create mode 100644 tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.ts create mode 100644 tests/1501-2000/1759. count-number-of-homogenous-substrings/manifest.yaml create mode 100644 tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.cpp create mode 100644 tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.cs create mode 100644 tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.dart create mode 100644 tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.go create mode 100644 tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.java create mode 100644 tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.kt create mode 100644 tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.py create mode 100644 tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.py2 create mode 100644 tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.rb create mode 100644 tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.rs create mode 100644 tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.swift create mode 100644 tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.ts create mode 100644 tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/manifest.yaml create mode 100644 tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.cpp create mode 100644 tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.cs create mode 100644 tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.dart create mode 100644 tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.go create mode 100644 tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.java create mode 100644 tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.kt create mode 100644 tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.py create mode 100644 tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.py2 create mode 100644 tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.rb create mode 100644 tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.rs create mode 100644 tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.swift create mode 100644 tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.ts create mode 100644 tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/manifest.yaml create mode 100644 tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.cpp create mode 100644 tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.cs create mode 100644 tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.dart create mode 100644 tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.go create mode 100644 tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.java create mode 100644 tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.kt create mode 100644 tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.py create mode 100644 tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.py2 create mode 100644 tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.rb create mode 100644 tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.rs create mode 100644 tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.swift create mode 100644 tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.ts create mode 100644 tests/1501-2000/1763. longest-nice-substring/manifest.yaml create mode 100644 tests/1501-2000/1763. longest-nice-substring/sol.cpp create mode 100644 tests/1501-2000/1763. longest-nice-substring/sol.cs create mode 100644 tests/1501-2000/1763. longest-nice-substring/sol.dart create mode 100644 tests/1501-2000/1763. longest-nice-substring/sol.go create mode 100644 tests/1501-2000/1763. longest-nice-substring/sol.java create mode 100644 tests/1501-2000/1763. longest-nice-substring/sol.kt create mode 100644 tests/1501-2000/1763. longest-nice-substring/sol.py create mode 100644 tests/1501-2000/1763. longest-nice-substring/sol.py2 create mode 100644 tests/1501-2000/1763. longest-nice-substring/sol.rb create mode 100644 tests/1501-2000/1763. longest-nice-substring/sol.rs create mode 100644 tests/1501-2000/1763. longest-nice-substring/sol.swift create mode 100644 tests/1501-2000/1763. longest-nice-substring/sol.ts create mode 100644 tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/manifest.yaml create mode 100644 tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.cpp create mode 100644 tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.cs create mode 100644 tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.dart create mode 100644 tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.go create mode 100644 tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.java create mode 100644 tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.kt create mode 100644 tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.py create mode 100644 tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.py2 create mode 100644 tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.rb create mode 100644 tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.rs create mode 100644 tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.swift create mode 100644 tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.ts create mode 100644 tests/1501-2000/1765. map-of-highest-peak/manifest.yaml create mode 100644 tests/1501-2000/1765. map-of-highest-peak/sol.cpp create mode 100644 tests/1501-2000/1765. map-of-highest-peak/sol.cs create mode 100644 tests/1501-2000/1765. map-of-highest-peak/sol.dart create mode 100644 tests/1501-2000/1765. map-of-highest-peak/sol.go create mode 100644 tests/1501-2000/1765. map-of-highest-peak/sol.java create mode 100644 tests/1501-2000/1765. map-of-highest-peak/sol.kt create mode 100644 tests/1501-2000/1765. map-of-highest-peak/sol.py create mode 100644 tests/1501-2000/1765. map-of-highest-peak/sol.py2 create mode 100644 tests/1501-2000/1765. map-of-highest-peak/sol.rb create mode 100644 tests/1501-2000/1765. map-of-highest-peak/sol.rs create mode 100644 tests/1501-2000/1765. map-of-highest-peak/sol.swift create mode 100644 tests/1501-2000/1765. map-of-highest-peak/sol.ts create mode 100644 tests/1501-2000/1766. tree-of-coprimes/manifest.yaml create mode 100644 tests/1501-2000/1766. tree-of-coprimes/sol.cpp create mode 100644 tests/1501-2000/1766. tree-of-coprimes/sol.cs create mode 100644 tests/1501-2000/1766. tree-of-coprimes/sol.dart create mode 100644 tests/1501-2000/1766. tree-of-coprimes/sol.go create mode 100644 tests/1501-2000/1766. tree-of-coprimes/sol.java create mode 100644 tests/1501-2000/1766. tree-of-coprimes/sol.kt create mode 100644 tests/1501-2000/1766. tree-of-coprimes/sol.py create mode 100644 tests/1501-2000/1766. tree-of-coprimes/sol.py2 create mode 100644 tests/1501-2000/1766. tree-of-coprimes/sol.rb create mode 100644 tests/1501-2000/1766. tree-of-coprimes/sol.rs create mode 100644 tests/1501-2000/1766. tree-of-coprimes/sol.swift create mode 100644 tests/1501-2000/1766. tree-of-coprimes/sol.ts create mode 100644 tests/1501-2000/1768. merge-strings-alternately/manifest.yaml create mode 100644 tests/1501-2000/1768. merge-strings-alternately/sol.cpp create mode 100644 tests/1501-2000/1768. merge-strings-alternately/sol.cs create mode 100644 tests/1501-2000/1768. merge-strings-alternately/sol.dart create mode 100644 tests/1501-2000/1768. merge-strings-alternately/sol.go create mode 100644 tests/1501-2000/1768. merge-strings-alternately/sol.java create mode 100644 tests/1501-2000/1768. merge-strings-alternately/sol.kt create mode 100644 tests/1501-2000/1768. merge-strings-alternately/sol.py create mode 100644 tests/1501-2000/1768. merge-strings-alternately/sol.py2 create mode 100644 tests/1501-2000/1768. merge-strings-alternately/sol.rb create mode 100644 tests/1501-2000/1768. merge-strings-alternately/sol.rs create mode 100644 tests/1501-2000/1768. merge-strings-alternately/sol.swift create mode 100644 tests/1501-2000/1768. merge-strings-alternately/sol.ts create mode 100644 tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/manifest.yaml create mode 100644 tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.cpp create mode 100644 tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.cs create mode 100644 tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.dart create mode 100644 tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.go create mode 100644 tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.java create mode 100644 tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.kt create mode 100644 tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.py create mode 100644 tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.py2 create mode 100644 tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.rb create mode 100644 tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.rs create mode 100644 tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.swift create mode 100644 tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.ts create mode 100644 tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/manifest.yaml create mode 100644 tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.cpp create mode 100644 tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.cs create mode 100644 tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.dart create mode 100644 tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.go create mode 100644 tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.java create mode 100644 tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.kt create mode 100644 tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.py create mode 100644 tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.py2 create mode 100644 tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.rb create mode 100644 tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.rs create mode 100644 tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.swift create mode 100644 tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.ts create mode 100644 tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/manifest.yaml create mode 100644 tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.cpp create mode 100644 tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.cs create mode 100644 tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.dart create mode 100644 tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.go create mode 100644 tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.java create mode 100644 tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.kt create mode 100644 tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.py create mode 100644 tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.py2 create mode 100644 tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.rb create mode 100644 tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.rs create mode 100644 tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.swift create mode 100644 tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.ts create mode 100644 tests/1501-2000/1773. count-items-matching-a-rule/manifest.yaml create mode 100644 tests/1501-2000/1773. count-items-matching-a-rule/sol.cpp create mode 100644 tests/1501-2000/1773. count-items-matching-a-rule/sol.cs create mode 100644 tests/1501-2000/1773. count-items-matching-a-rule/sol.dart create mode 100644 tests/1501-2000/1773. count-items-matching-a-rule/sol.go create mode 100644 tests/1501-2000/1773. count-items-matching-a-rule/sol.java create mode 100644 tests/1501-2000/1773. count-items-matching-a-rule/sol.kt create mode 100644 tests/1501-2000/1773. count-items-matching-a-rule/sol.py create mode 100644 tests/1501-2000/1773. count-items-matching-a-rule/sol.py2 create mode 100644 tests/1501-2000/1773. count-items-matching-a-rule/sol.rb create mode 100644 tests/1501-2000/1773. count-items-matching-a-rule/sol.rs create mode 100644 tests/1501-2000/1773. count-items-matching-a-rule/sol.swift create mode 100644 tests/1501-2000/1773. count-items-matching-a-rule/sol.ts create mode 100644 tests/1501-2000/1774. closest-dessert-cost/manifest.yaml create mode 100644 tests/1501-2000/1774. closest-dessert-cost/sol.cpp create mode 100644 tests/1501-2000/1774. closest-dessert-cost/sol.cs create mode 100644 tests/1501-2000/1774. closest-dessert-cost/sol.dart create mode 100644 tests/1501-2000/1774. closest-dessert-cost/sol.go create mode 100644 tests/1501-2000/1774. closest-dessert-cost/sol.java create mode 100644 tests/1501-2000/1774. closest-dessert-cost/sol.kt create mode 100644 tests/1501-2000/1774. closest-dessert-cost/sol.py create mode 100644 tests/1501-2000/1774. closest-dessert-cost/sol.py2 create mode 100644 tests/1501-2000/1774. closest-dessert-cost/sol.rb create mode 100644 tests/1501-2000/1774. closest-dessert-cost/sol.rs create mode 100644 tests/1501-2000/1774. closest-dessert-cost/sol.swift create mode 100644 tests/1501-2000/1774. closest-dessert-cost/sol.ts create mode 100644 tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/manifest.yaml create mode 100644 tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.cpp create mode 100644 tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.cs create mode 100644 tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.dart create mode 100644 tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.go create mode 100644 tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.java create mode 100644 tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.kt create mode 100644 tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.py create mode 100644 tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.py2 create mode 100644 tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.rb create mode 100644 tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.rs create mode 100644 tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.swift create mode 100644 tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.ts create mode 100644 tests/1501-2000/1776. car-fleet-ii/manifest.yaml create mode 100644 tests/1501-2000/1776. car-fleet-ii/sol.cpp create mode 100644 tests/1501-2000/1776. car-fleet-ii/sol.cs create mode 100644 tests/1501-2000/1776. car-fleet-ii/sol.dart create mode 100644 tests/1501-2000/1776. car-fleet-ii/sol.go create mode 100644 tests/1501-2000/1776. car-fleet-ii/sol.java create mode 100644 tests/1501-2000/1776. car-fleet-ii/sol.kt create mode 100644 tests/1501-2000/1776. car-fleet-ii/sol.py create mode 100644 tests/1501-2000/1776. car-fleet-ii/sol.py2 create mode 100644 tests/1501-2000/1776. car-fleet-ii/sol.rb create mode 100644 tests/1501-2000/1776. car-fleet-ii/sol.rs create mode 100644 tests/1501-2000/1776. car-fleet-ii/sol.swift create mode 100644 tests/1501-2000/1776. car-fleet-ii/sol.ts create mode 100644 tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/manifest.yaml create mode 100644 tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.cpp create mode 100644 tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.cs create mode 100644 tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.dart create mode 100644 tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.go create mode 100644 tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.java create mode 100644 tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.kt create mode 100644 tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.py create mode 100644 tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.py2 create mode 100644 tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.rb create mode 100644 tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.rs create mode 100644 tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.swift create mode 100644 tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.ts create mode 100644 tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/manifest.yaml create mode 100644 tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.cpp create mode 100644 tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.cs create mode 100644 tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.dart create mode 100644 tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.go create mode 100644 tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.java create mode 100644 tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.kt create mode 100644 tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.py create mode 100644 tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.py2 create mode 100644 tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.rb create mode 100644 tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.rs create mode 100644 tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.swift create mode 100644 tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.ts create mode 100644 tests/1501-2000/1781. sum-of-beauty-of-all-substrings/manifest.yaml create mode 100644 tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.cpp create mode 100644 tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.cs create mode 100644 tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.dart create mode 100644 tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.go create mode 100644 tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.java create mode 100644 tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.kt create mode 100644 tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.py create mode 100644 tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.py2 create mode 100644 tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.rb create mode 100644 tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.rs create mode 100644 tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.swift create mode 100644 tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.ts create mode 100644 tests/1501-2000/1782. count-pairs-of-nodes/manifest.yaml create mode 100644 tests/1501-2000/1782. count-pairs-of-nodes/sol.cpp create mode 100644 tests/1501-2000/1782. count-pairs-of-nodes/sol.cs create mode 100644 tests/1501-2000/1782. count-pairs-of-nodes/sol.dart create mode 100644 tests/1501-2000/1782. count-pairs-of-nodes/sol.go create mode 100644 tests/1501-2000/1782. count-pairs-of-nodes/sol.java create mode 100644 tests/1501-2000/1782. count-pairs-of-nodes/sol.kt create mode 100644 tests/1501-2000/1782. count-pairs-of-nodes/sol.py create mode 100644 tests/1501-2000/1782. count-pairs-of-nodes/sol.py2 create mode 100644 tests/1501-2000/1782. count-pairs-of-nodes/sol.rb create mode 100644 tests/1501-2000/1782. count-pairs-of-nodes/sol.rs create mode 100644 tests/1501-2000/1782. count-pairs-of-nodes/sol.swift create mode 100644 tests/1501-2000/1782. count-pairs-of-nodes/sol.ts create mode 100644 tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/manifest.yaml create mode 100644 tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.cpp create mode 100644 tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.cs create mode 100644 tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.dart create mode 100644 tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.go create mode 100644 tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.java create mode 100644 tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.kt create mode 100644 tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.py create mode 100644 tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.py2 create mode 100644 tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.rb create mode 100644 tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.rs create mode 100644 tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.swift create mode 100644 tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.ts create mode 100644 tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/manifest.yaml create mode 100644 tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.cpp create mode 100644 tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.cs create mode 100644 tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.dart create mode 100644 tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.go create mode 100644 tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.java create mode 100644 tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.kt create mode 100644 tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.py create mode 100644 tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.py2 create mode 100644 tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.rb create mode 100644 tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.rs create mode 100644 tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.swift create mode 100644 tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.ts create mode 100644 tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/manifest.yaml create mode 100644 tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.cpp create mode 100644 tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.cs create mode 100644 tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.dart create mode 100644 tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.go create mode 100644 tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.java create mode 100644 tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.kt create mode 100644 tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.py create mode 100644 tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.py2 create mode 100644 tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.rb create mode 100644 tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.rs create mode 100644 tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.swift create mode 100644 tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.ts create mode 100644 tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/manifest.yaml create mode 100644 tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.cpp create mode 100644 tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.cs create mode 100644 tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.dart create mode 100644 tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.go create mode 100644 tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.java create mode 100644 tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.kt create mode 100644 tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.py create mode 100644 tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.py2 create mode 100644 tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.rb create mode 100644 tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.rs create mode 100644 tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.swift create mode 100644 tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.ts create mode 100644 tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/manifest.yaml create mode 100644 tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.cpp create mode 100644 tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.cs create mode 100644 tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.dart create mode 100644 tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.go create mode 100644 tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.java create mode 100644 tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.kt create mode 100644 tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.py create mode 100644 tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.py2 create mode 100644 tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.rb create mode 100644 tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.rs create mode 100644 tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.swift create mode 100644 tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.ts create mode 100644 tests/1501-2000/1791. find-center-of-star-graph/manifest.yaml create mode 100644 tests/1501-2000/1791. find-center-of-star-graph/sol.cpp create mode 100644 tests/1501-2000/1791. find-center-of-star-graph/sol.cs create mode 100644 tests/1501-2000/1791. find-center-of-star-graph/sol.dart create mode 100644 tests/1501-2000/1791. find-center-of-star-graph/sol.go create mode 100644 tests/1501-2000/1791. find-center-of-star-graph/sol.java create mode 100644 tests/1501-2000/1791. find-center-of-star-graph/sol.kt create mode 100644 tests/1501-2000/1791. find-center-of-star-graph/sol.py create mode 100644 tests/1501-2000/1791. find-center-of-star-graph/sol.py2 create mode 100644 tests/1501-2000/1791. find-center-of-star-graph/sol.rb create mode 100644 tests/1501-2000/1791. find-center-of-star-graph/sol.rs create mode 100644 tests/1501-2000/1791. find-center-of-star-graph/sol.swift create mode 100644 tests/1501-2000/1791. find-center-of-star-graph/sol.ts create mode 100644 tests/1501-2000/1792. maximum-average-pass-ratio/manifest.yaml create mode 100644 tests/1501-2000/1792. maximum-average-pass-ratio/sol.cpp create mode 100644 tests/1501-2000/1792. maximum-average-pass-ratio/sol.cs create mode 100644 tests/1501-2000/1792. maximum-average-pass-ratio/sol.dart create mode 100644 tests/1501-2000/1792. maximum-average-pass-ratio/sol.go create mode 100644 tests/1501-2000/1792. maximum-average-pass-ratio/sol.java create mode 100644 tests/1501-2000/1792. maximum-average-pass-ratio/sol.kt create mode 100644 tests/1501-2000/1792. maximum-average-pass-ratio/sol.py create mode 100644 tests/1501-2000/1792. maximum-average-pass-ratio/sol.py2 create mode 100644 tests/1501-2000/1792. maximum-average-pass-ratio/sol.rb create mode 100644 tests/1501-2000/1792. maximum-average-pass-ratio/sol.rs create mode 100644 tests/1501-2000/1792. maximum-average-pass-ratio/sol.swift create mode 100644 tests/1501-2000/1792. maximum-average-pass-ratio/sol.ts create mode 100644 tests/1501-2000/1793. maximum-score-of-a-good-subarray/manifest.yaml create mode 100644 tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.cpp create mode 100644 tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.cs create mode 100644 tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.dart create mode 100644 tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.go create mode 100644 tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.java create mode 100644 tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.kt create mode 100644 tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.py create mode 100644 tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.py2 create mode 100644 tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.rb create mode 100644 tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.rs create mode 100644 tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.swift create mode 100644 tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.ts create mode 100644 tests/1501-2000/1796. second-largest-digit-in-a-string/manifest.yaml create mode 100644 tests/1501-2000/1796. second-largest-digit-in-a-string/sol.cpp create mode 100644 tests/1501-2000/1796. second-largest-digit-in-a-string/sol.cs create mode 100644 tests/1501-2000/1796. second-largest-digit-in-a-string/sol.dart create mode 100644 tests/1501-2000/1796. second-largest-digit-in-a-string/sol.go create mode 100644 tests/1501-2000/1796. second-largest-digit-in-a-string/sol.java create mode 100644 tests/1501-2000/1796. second-largest-digit-in-a-string/sol.kt create mode 100644 tests/1501-2000/1796. second-largest-digit-in-a-string/sol.py create mode 100644 tests/1501-2000/1796. second-largest-digit-in-a-string/sol.py2 create mode 100644 tests/1501-2000/1796. second-largest-digit-in-a-string/sol.rb create mode 100644 tests/1501-2000/1796. second-largest-digit-in-a-string/sol.rs create mode 100644 tests/1501-2000/1796. second-largest-digit-in-a-string/sol.swift create mode 100644 tests/1501-2000/1796. second-largest-digit-in-a-string/sol.ts create mode 100644 tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/manifest.yaml create mode 100644 tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.cpp create mode 100644 tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.cs create mode 100644 tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.dart create mode 100644 tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.go create mode 100644 tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.java create mode 100644 tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.kt create mode 100644 tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.py create mode 100644 tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.py2 create mode 100644 tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.rb create mode 100644 tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.rs create mode 100644 tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.swift create mode 100644 tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.ts create mode 100644 tests/1501-2000/1799. maximize-score-after-n-operations/manifest.yaml create mode 100644 tests/1501-2000/1799. maximize-score-after-n-operations/sol.cpp create mode 100644 tests/1501-2000/1799. maximize-score-after-n-operations/sol.cs create mode 100644 tests/1501-2000/1799. maximize-score-after-n-operations/sol.dart create mode 100644 tests/1501-2000/1799. maximize-score-after-n-operations/sol.go create mode 100644 tests/1501-2000/1799. maximize-score-after-n-operations/sol.java create mode 100644 tests/1501-2000/1799. maximize-score-after-n-operations/sol.kt create mode 100644 tests/1501-2000/1799. maximize-score-after-n-operations/sol.py create mode 100644 tests/1501-2000/1799. maximize-score-after-n-operations/sol.py2 create mode 100644 tests/1501-2000/1799. maximize-score-after-n-operations/sol.rb create mode 100644 tests/1501-2000/1799. maximize-score-after-n-operations/sol.rs create mode 100644 tests/1501-2000/1799. maximize-score-after-n-operations/sol.swift create mode 100644 tests/1501-2000/1799. maximize-score-after-n-operations/sol.ts create mode 100644 tests/1501-2000/1800. maximum-ascending-subarray-sum/manifest.yaml create mode 100644 tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.cpp create mode 100644 tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.cs create mode 100644 tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.dart create mode 100644 tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.go create mode 100644 tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.java create mode 100644 tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.kt create mode 100644 tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.py create mode 100644 tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.py2 create mode 100644 tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.rb create mode 100644 tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.rs create mode 100644 tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.swift create mode 100644 tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.ts create mode 100644 tests/1501-2000/1801. number-of-orders-in-the-backlog/manifest.yaml create mode 100644 tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.cpp create mode 100644 tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.cs create mode 100644 tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.dart create mode 100644 tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.go create mode 100644 tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.java create mode 100644 tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.kt create mode 100644 tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.py create mode 100644 tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.py2 create mode 100644 tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.rb create mode 100644 tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.rs create mode 100644 tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.swift create mode 100644 tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.ts create mode 100644 tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/manifest.yaml create mode 100644 tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.cpp create mode 100644 tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.cs create mode 100644 tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.dart create mode 100644 tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.go create mode 100644 tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.java create mode 100644 tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.kt create mode 100644 tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.py create mode 100644 tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.py2 create mode 100644 tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.rb create mode 100644 tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.rs create mode 100644 tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.swift create mode 100644 tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.ts create mode 100644 tests/1501-2000/1803. count-pairs-with-xor-in-a-range/manifest.yaml create mode 100644 tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.cpp create mode 100644 tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.cs create mode 100644 tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.dart create mode 100644 tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.go create mode 100644 tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.java create mode 100644 tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.kt create mode 100644 tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.py create mode 100644 tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.py2 create mode 100644 tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.rb create mode 100644 tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.rs create mode 100644 tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.swift create mode 100644 tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.ts create mode 100644 tests/1501-2000/1805. number-of-different-integers-in-a-string/manifest.yaml create mode 100644 tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.cpp create mode 100644 tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.cs create mode 100644 tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.dart create mode 100644 tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.go create mode 100644 tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.java create mode 100644 tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.kt create mode 100644 tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.py create mode 100644 tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.py2 create mode 100644 tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.rb create mode 100644 tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.rs create mode 100644 tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.swift create mode 100644 tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.ts create mode 100644 tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/manifest.yaml create mode 100644 tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.cpp create mode 100644 tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.cs create mode 100644 tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.dart create mode 100644 tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.go create mode 100644 tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.java create mode 100644 tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.kt create mode 100644 tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.py create mode 100644 tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.py2 create mode 100644 tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.rb create mode 100644 tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.rs create mode 100644 tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.swift create mode 100644 tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.ts create mode 100644 tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/manifest.yaml create mode 100644 tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.cpp create mode 100644 tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.cs create mode 100644 tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.dart create mode 100644 tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.go create mode 100644 tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.java create mode 100644 tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.kt create mode 100644 tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.py create mode 100644 tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.py2 create mode 100644 tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.rb create mode 100644 tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.rs create mode 100644 tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.swift create mode 100644 tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.ts create mode 100644 tests/1501-2000/1808. maximize-number-of-nice-divisors/manifest.yaml create mode 100644 tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.cpp create mode 100644 tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.cs create mode 100644 tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.dart create mode 100644 tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.go create mode 100644 tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.java create mode 100644 tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.kt create mode 100644 tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.py create mode 100644 tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.py2 create mode 100644 tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.rb create mode 100644 tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.rs create mode 100644 tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.swift create mode 100644 tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.ts create mode 100644 tests/1501-2000/1812. determine-color-of-a-chessboard-square/manifest.yaml create mode 100644 tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.cpp create mode 100644 tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.cs create mode 100644 tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.dart create mode 100644 tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.go create mode 100644 tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.java create mode 100644 tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.kt create mode 100644 tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.py create mode 100644 tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.py2 create mode 100644 tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.rb create mode 100644 tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.rs create mode 100644 tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.swift create mode 100644 tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.ts create mode 100644 tests/1501-2000/1813. sentence-similarity-iii/manifest.yaml create mode 100644 tests/1501-2000/1813. sentence-similarity-iii/sol.cpp create mode 100644 tests/1501-2000/1813. sentence-similarity-iii/sol.cs create mode 100644 tests/1501-2000/1813. sentence-similarity-iii/sol.dart create mode 100644 tests/1501-2000/1813. sentence-similarity-iii/sol.go create mode 100644 tests/1501-2000/1813. sentence-similarity-iii/sol.java create mode 100644 tests/1501-2000/1813. sentence-similarity-iii/sol.kt create mode 100644 tests/1501-2000/1813. sentence-similarity-iii/sol.py create mode 100644 tests/1501-2000/1813. sentence-similarity-iii/sol.py2 create mode 100644 tests/1501-2000/1813. sentence-similarity-iii/sol.rb create mode 100644 tests/1501-2000/1813. sentence-similarity-iii/sol.rs create mode 100644 tests/1501-2000/1813. sentence-similarity-iii/sol.swift create mode 100644 tests/1501-2000/1813. sentence-similarity-iii/sol.ts create mode 100644 tests/1501-2000/1814. count-nice-pairs-in-an-array/manifest.yaml create mode 100644 tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.cpp create mode 100644 tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.cs create mode 100644 tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.dart create mode 100644 tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.go create mode 100644 tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.java create mode 100644 tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.kt create mode 100644 tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.py create mode 100644 tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.py2 create mode 100644 tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.rb create mode 100644 tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.rs create mode 100644 tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.swift create mode 100644 tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.ts create mode 100644 tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/manifest.yaml create mode 100644 tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.cpp create mode 100644 tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.cs create mode 100644 tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.dart create mode 100644 tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.go create mode 100644 tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.java create mode 100644 tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.kt create mode 100644 tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.py create mode 100644 tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.py2 create mode 100644 tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.rb create mode 100644 tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.rs create mode 100644 tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.swift create mode 100644 tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.ts create mode 100644 tests/1501-2000/1816. truncate-sentence/manifest.yaml create mode 100644 tests/1501-2000/1816. truncate-sentence/sol.cpp create mode 100644 tests/1501-2000/1816. truncate-sentence/sol.cs create mode 100644 tests/1501-2000/1816. truncate-sentence/sol.dart create mode 100644 tests/1501-2000/1816. truncate-sentence/sol.go create mode 100644 tests/1501-2000/1816. truncate-sentence/sol.java create mode 100644 tests/1501-2000/1816. truncate-sentence/sol.kt create mode 100644 tests/1501-2000/1816. truncate-sentence/sol.py create mode 100644 tests/1501-2000/1816. truncate-sentence/sol.py2 create mode 100644 tests/1501-2000/1816. truncate-sentence/sol.rb create mode 100644 tests/1501-2000/1816. truncate-sentence/sol.rs create mode 100644 tests/1501-2000/1816. truncate-sentence/sol.swift create mode 100644 tests/1501-2000/1816. truncate-sentence/sol.ts create mode 100644 tests/1501-2000/1817. finding-the-users-active-minutes/manifest.yaml create mode 100644 tests/1501-2000/1817. finding-the-users-active-minutes/sol.cpp create mode 100644 tests/1501-2000/1817. finding-the-users-active-minutes/sol.cs create mode 100644 tests/1501-2000/1817. finding-the-users-active-minutes/sol.dart create mode 100644 tests/1501-2000/1817. finding-the-users-active-minutes/sol.go create mode 100644 tests/1501-2000/1817. finding-the-users-active-minutes/sol.java create mode 100644 tests/1501-2000/1817. finding-the-users-active-minutes/sol.kt create mode 100644 tests/1501-2000/1817. finding-the-users-active-minutes/sol.py create mode 100644 tests/1501-2000/1817. finding-the-users-active-minutes/sol.py2 create mode 100644 tests/1501-2000/1817. finding-the-users-active-minutes/sol.rb create mode 100644 tests/1501-2000/1817. finding-the-users-active-minutes/sol.rs create mode 100644 tests/1501-2000/1817. finding-the-users-active-minutes/sol.swift create mode 100644 tests/1501-2000/1817. finding-the-users-active-minutes/sol.ts create mode 100644 tests/1501-2000/1818. minimum-absolute-sum-difference/manifest.yaml create mode 100644 tests/1501-2000/1818. minimum-absolute-sum-difference/sol.cpp create mode 100644 tests/1501-2000/1818. minimum-absolute-sum-difference/sol.cs create mode 100644 tests/1501-2000/1818. minimum-absolute-sum-difference/sol.dart create mode 100644 tests/1501-2000/1818. minimum-absolute-sum-difference/sol.go create mode 100644 tests/1501-2000/1818. minimum-absolute-sum-difference/sol.java create mode 100644 tests/1501-2000/1818. minimum-absolute-sum-difference/sol.kt create mode 100644 tests/1501-2000/1818. minimum-absolute-sum-difference/sol.py create mode 100644 tests/1501-2000/1818. minimum-absolute-sum-difference/sol.py2 create mode 100644 tests/1501-2000/1818. minimum-absolute-sum-difference/sol.rb create mode 100644 tests/1501-2000/1818. minimum-absolute-sum-difference/sol.rs create mode 100644 tests/1501-2000/1818. minimum-absolute-sum-difference/sol.swift create mode 100644 tests/1501-2000/1818. minimum-absolute-sum-difference/sol.ts create mode 100644 tests/1501-2000/1819. number-of-different-subsequences-gcds/manifest.yaml create mode 100644 tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.cpp create mode 100644 tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.cs create mode 100644 tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.dart create mode 100644 tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.go create mode 100644 tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.java create mode 100644 tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.kt create mode 100644 tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.py create mode 100644 tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.py2 create mode 100644 tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.rb create mode 100644 tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.rs create mode 100644 tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.swift create mode 100644 tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.ts create mode 100644 tests/1501-2000/1822. sign-of-the-product-of-an-array/manifest.yaml create mode 100644 tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.cpp create mode 100644 tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.cs create mode 100644 tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.dart create mode 100644 tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.go create mode 100644 tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.java create mode 100644 tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.kt create mode 100644 tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.py create mode 100644 tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.py2 create mode 100644 tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.rb create mode 100644 tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.rs create mode 100644 tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.swift create mode 100644 tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.ts create mode 100644 tests/1501-2000/1823. find-the-winner-of-the-circular-game/manifest.yaml create mode 100644 tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.cpp create mode 100644 tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.cs create mode 100644 tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.dart create mode 100644 tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.go create mode 100644 tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.java create mode 100644 tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.kt create mode 100644 tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.py create mode 100644 tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.py2 create mode 100644 tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.rb create mode 100644 tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.rs create mode 100644 tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.swift create mode 100644 tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.ts create mode 100644 tests/1501-2000/1824. minimum-sideway-jumps/manifest.yaml create mode 100644 tests/1501-2000/1824. minimum-sideway-jumps/sol.cpp create mode 100644 tests/1501-2000/1824. minimum-sideway-jumps/sol.cs create mode 100644 tests/1501-2000/1824. minimum-sideway-jumps/sol.dart create mode 100644 tests/1501-2000/1824. minimum-sideway-jumps/sol.go create mode 100644 tests/1501-2000/1824. minimum-sideway-jumps/sol.java create mode 100644 tests/1501-2000/1824. minimum-sideway-jumps/sol.kt create mode 100644 tests/1501-2000/1824. minimum-sideway-jumps/sol.py create mode 100644 tests/1501-2000/1824. minimum-sideway-jumps/sol.py2 create mode 100644 tests/1501-2000/1824. minimum-sideway-jumps/sol.rb create mode 100644 tests/1501-2000/1824. minimum-sideway-jumps/sol.rs create mode 100644 tests/1501-2000/1824. minimum-sideway-jumps/sol.swift create mode 100644 tests/1501-2000/1824. minimum-sideway-jumps/sol.ts create mode 100644 tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/manifest.yaml create mode 100644 tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.cpp create mode 100644 tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.cs create mode 100644 tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.dart create mode 100644 tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.go create mode 100644 tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.java create mode 100644 tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.kt create mode 100644 tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.py create mode 100644 tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.py2 create mode 100644 tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.rb create mode 100644 tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.rs create mode 100644 tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.swift create mode 100644 tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.ts create mode 100644 tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/manifest.yaml create mode 100644 tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.cpp create mode 100644 tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.cs create mode 100644 tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.dart create mode 100644 tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.go create mode 100644 tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.java create mode 100644 tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.kt create mode 100644 tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.py create mode 100644 tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.py2 create mode 100644 tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.rb create mode 100644 tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.rs create mode 100644 tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.swift create mode 100644 tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.ts create mode 100644 tests/1501-2000/1829. maximum-xor-for-each-query/manifest.yaml create mode 100644 tests/1501-2000/1829. maximum-xor-for-each-query/sol.cpp create mode 100644 tests/1501-2000/1829. maximum-xor-for-each-query/sol.cs create mode 100644 tests/1501-2000/1829. maximum-xor-for-each-query/sol.dart create mode 100644 tests/1501-2000/1829. maximum-xor-for-each-query/sol.go create mode 100644 tests/1501-2000/1829. maximum-xor-for-each-query/sol.java create mode 100644 tests/1501-2000/1829. maximum-xor-for-each-query/sol.kt create mode 100644 tests/1501-2000/1829. maximum-xor-for-each-query/sol.py create mode 100644 tests/1501-2000/1829. maximum-xor-for-each-query/sol.py2 create mode 100644 tests/1501-2000/1829. maximum-xor-for-each-query/sol.rb create mode 100644 tests/1501-2000/1829. maximum-xor-for-each-query/sol.rs create mode 100644 tests/1501-2000/1829. maximum-xor-for-each-query/sol.swift create mode 100644 tests/1501-2000/1829. maximum-xor-for-each-query/sol.ts create mode 100644 tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/manifest.yaml create mode 100644 tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.cpp create mode 100644 tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.cs create mode 100644 tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.dart create mode 100644 tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.go create mode 100644 tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.java create mode 100644 tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.kt create mode 100644 tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.py create mode 100644 tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.py2 create mode 100644 tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.rb create mode 100644 tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.rs create mode 100644 tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.swift create mode 100644 tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.ts create mode 100644 tests/1501-2000/1832. check-if-the-sentence-is-pangram/manifest.yaml create mode 100644 tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.cpp create mode 100644 tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.cs create mode 100644 tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.dart create mode 100644 tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.go create mode 100644 tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.java create mode 100644 tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.kt create mode 100644 tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.py create mode 100644 tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.py2 create mode 100644 tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.rb create mode 100644 tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.rs create mode 100644 tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.swift create mode 100644 tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.ts create mode 100644 tests/1501-2000/1833. maximum-ice-cream-bars/manifest.yaml create mode 100644 tests/1501-2000/1833. maximum-ice-cream-bars/sol.cpp create mode 100644 tests/1501-2000/1833. maximum-ice-cream-bars/sol.cs create mode 100644 tests/1501-2000/1833. maximum-ice-cream-bars/sol.dart create mode 100644 tests/1501-2000/1833. maximum-ice-cream-bars/sol.go create mode 100644 tests/1501-2000/1833. maximum-ice-cream-bars/sol.java create mode 100644 tests/1501-2000/1833. maximum-ice-cream-bars/sol.kt create mode 100644 tests/1501-2000/1833. maximum-ice-cream-bars/sol.py create mode 100644 tests/1501-2000/1833. maximum-ice-cream-bars/sol.py2 create mode 100644 tests/1501-2000/1833. maximum-ice-cream-bars/sol.rb create mode 100644 tests/1501-2000/1833. maximum-ice-cream-bars/sol.rs create mode 100644 tests/1501-2000/1833. maximum-ice-cream-bars/sol.swift create mode 100644 tests/1501-2000/1833. maximum-ice-cream-bars/sol.ts create mode 100644 tests/1501-2000/1834. single-threaded-cpu/manifest.yaml create mode 100644 tests/1501-2000/1834. single-threaded-cpu/sol.cpp create mode 100644 tests/1501-2000/1834. single-threaded-cpu/sol.cs create mode 100644 tests/1501-2000/1834. single-threaded-cpu/sol.dart create mode 100644 tests/1501-2000/1834. single-threaded-cpu/sol.go create mode 100644 tests/1501-2000/1834. single-threaded-cpu/sol.java create mode 100644 tests/1501-2000/1834. single-threaded-cpu/sol.kt create mode 100644 tests/1501-2000/1834. single-threaded-cpu/sol.py create mode 100644 tests/1501-2000/1834. single-threaded-cpu/sol.py2 create mode 100644 tests/1501-2000/1834. single-threaded-cpu/sol.rb create mode 100644 tests/1501-2000/1834. single-threaded-cpu/sol.rs create mode 100644 tests/1501-2000/1834. single-threaded-cpu/sol.swift create mode 100644 tests/1501-2000/1834. single-threaded-cpu/sol.ts create mode 100644 tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/manifest.yaml create mode 100644 tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.cpp create mode 100644 tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.cs create mode 100644 tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.dart create mode 100644 tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.go create mode 100644 tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.java create mode 100644 tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.kt create mode 100644 tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.py create mode 100644 tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.py2 create mode 100644 tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.rb create mode 100644 tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.rs create mode 100644 tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.swift create mode 100644 tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.ts create mode 100644 tests/1501-2000/1837. sum-of-digits-in-base-k/manifest.yaml create mode 100644 tests/1501-2000/1837. sum-of-digits-in-base-k/sol.cpp create mode 100644 tests/1501-2000/1837. sum-of-digits-in-base-k/sol.cs create mode 100644 tests/1501-2000/1837. sum-of-digits-in-base-k/sol.dart create mode 100644 tests/1501-2000/1837. sum-of-digits-in-base-k/sol.go create mode 100644 tests/1501-2000/1837. sum-of-digits-in-base-k/sol.java create mode 100644 tests/1501-2000/1837. sum-of-digits-in-base-k/sol.kt create mode 100644 tests/1501-2000/1837. sum-of-digits-in-base-k/sol.py create mode 100644 tests/1501-2000/1837. sum-of-digits-in-base-k/sol.py2 create mode 100644 tests/1501-2000/1837. sum-of-digits-in-base-k/sol.rb create mode 100644 tests/1501-2000/1837. sum-of-digits-in-base-k/sol.rs create mode 100644 tests/1501-2000/1837. sum-of-digits-in-base-k/sol.swift create mode 100644 tests/1501-2000/1837. sum-of-digits-in-base-k/sol.ts create mode 100644 tests/1501-2000/1838. frequency-of-the-most-frequent-element/manifest.yaml create mode 100644 tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.cpp create mode 100644 tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.cs create mode 100644 tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.dart create mode 100644 tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.go create mode 100644 tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.java create mode 100644 tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.kt create mode 100644 tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.py create mode 100644 tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.py2 create mode 100644 tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.rb create mode 100644 tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.rs create mode 100644 tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.swift create mode 100644 tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.ts create mode 100644 tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/manifest.yaml create mode 100644 tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.cpp create mode 100644 tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.cs create mode 100644 tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.dart create mode 100644 tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.go create mode 100644 tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.java create mode 100644 tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.kt create mode 100644 tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.py create mode 100644 tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.py2 create mode 100644 tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.rb create mode 100644 tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.rs create mode 100644 tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.swift create mode 100644 tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.ts create mode 100644 tests/1501-2000/1840. maximum-building-height/manifest.yaml create mode 100644 tests/1501-2000/1840. maximum-building-height/sol.cpp create mode 100644 tests/1501-2000/1840. maximum-building-height/sol.cs create mode 100644 tests/1501-2000/1840. maximum-building-height/sol.dart create mode 100644 tests/1501-2000/1840. maximum-building-height/sol.go create mode 100644 tests/1501-2000/1840. maximum-building-height/sol.java create mode 100644 tests/1501-2000/1840. maximum-building-height/sol.kt create mode 100644 tests/1501-2000/1840. maximum-building-height/sol.py create mode 100644 tests/1501-2000/1840. maximum-building-height/sol.py2 create mode 100644 tests/1501-2000/1840. maximum-building-height/sol.rb create mode 100644 tests/1501-2000/1840. maximum-building-height/sol.rs create mode 100644 tests/1501-2000/1840. maximum-building-height/sol.swift create mode 100644 tests/1501-2000/1840. maximum-building-height/sol.ts create mode 100644 tests/1501-2000/1844. replace-all-digits-with-characters/manifest.yaml create mode 100644 tests/1501-2000/1844. replace-all-digits-with-characters/sol.cpp create mode 100644 tests/1501-2000/1844. replace-all-digits-with-characters/sol.cs create mode 100644 tests/1501-2000/1844. replace-all-digits-with-characters/sol.dart create mode 100644 tests/1501-2000/1844. replace-all-digits-with-characters/sol.go create mode 100644 tests/1501-2000/1844. replace-all-digits-with-characters/sol.java create mode 100644 tests/1501-2000/1844. replace-all-digits-with-characters/sol.kt create mode 100644 tests/1501-2000/1844. replace-all-digits-with-characters/sol.py create mode 100644 tests/1501-2000/1844. replace-all-digits-with-characters/sol.py2 create mode 100644 tests/1501-2000/1844. replace-all-digits-with-characters/sol.rb create mode 100644 tests/1501-2000/1844. replace-all-digits-with-characters/sol.rs create mode 100644 tests/1501-2000/1844. replace-all-digits-with-characters/sol.swift create mode 100644 tests/1501-2000/1844. replace-all-digits-with-characters/sol.ts create mode 100644 tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/manifest.yaml create mode 100644 tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.cpp create mode 100644 tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.cs create mode 100644 tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.dart create mode 100644 tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.go create mode 100644 tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.java create mode 100644 tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.kt create mode 100644 tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.py create mode 100644 tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.py2 create mode 100644 tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.rb create mode 100644 tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.rs create mode 100644 tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.swift create mode 100644 tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.ts create mode 100644 tests/1501-2000/1847. closest-room/manifest.yaml create mode 100644 tests/1501-2000/1847. closest-room/sol.cpp create mode 100644 tests/1501-2000/1847. closest-room/sol.cs create mode 100644 tests/1501-2000/1847. closest-room/sol.dart create mode 100644 tests/1501-2000/1847. closest-room/sol.go create mode 100644 tests/1501-2000/1847. closest-room/sol.java create mode 100644 tests/1501-2000/1847. closest-room/sol.kt create mode 100644 tests/1501-2000/1847. closest-room/sol.py create mode 100644 tests/1501-2000/1847. closest-room/sol.py2 create mode 100644 tests/1501-2000/1847. closest-room/sol.rb create mode 100644 tests/1501-2000/1847. closest-room/sol.rs create mode 100644 tests/1501-2000/1847. closest-room/sol.swift create mode 100644 tests/1501-2000/1847. closest-room/sol.ts create mode 100644 tests/1501-2000/1848. minimum-distance-to-the-target-element/manifest.yaml create mode 100644 tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.cpp create mode 100644 tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.cs create mode 100644 tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.dart create mode 100644 tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.go create mode 100644 tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.java create mode 100644 tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.kt create mode 100644 tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py create mode 100644 tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py2 create mode 100644 tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.rb create mode 100644 tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.rs create mode 100644 tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.swift create mode 100644 tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.ts create mode 100644 tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/manifest.yaml create mode 100644 tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.cpp create mode 100644 tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.cs create mode 100644 tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.dart create mode 100644 tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.go create mode 100644 tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.java create mode 100644 tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.kt create mode 100644 tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.py create mode 100644 tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.py2 create mode 100644 tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.rb create mode 100644 tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.rs create mode 100644 tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.swift create mode 100644 tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.ts create mode 100644 tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/manifest.yaml create mode 100644 tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.cpp create mode 100644 tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.cs create mode 100644 tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.dart create mode 100644 tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.go create mode 100644 tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.java create mode 100644 tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.kt create mode 100644 tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.py create mode 100644 tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.py2 create mode 100644 tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.rb create mode 100644 tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.rs create mode 100644 tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.swift create mode 100644 tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.ts create mode 100644 tests/1501-2000/1851. minimum-interval-to-include-each-query/manifest.yaml create mode 100644 tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.cpp create mode 100644 tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.cs create mode 100644 tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.dart create mode 100644 tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.go create mode 100644 tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.java create mode 100644 tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.kt create mode 100644 tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.py create mode 100644 tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.py2 create mode 100644 tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.rb create mode 100644 tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.rs create mode 100644 tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.swift create mode 100644 tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.ts create mode 100644 tests/1501-2000/1854. maximum-population-year/manifest.yaml create mode 100644 tests/1501-2000/1854. maximum-population-year/sol.cpp create mode 100644 tests/1501-2000/1854. maximum-population-year/sol.cs create mode 100644 tests/1501-2000/1854. maximum-population-year/sol.dart create mode 100644 tests/1501-2000/1854. maximum-population-year/sol.go create mode 100644 tests/1501-2000/1854. maximum-population-year/sol.java create mode 100644 tests/1501-2000/1854. maximum-population-year/sol.kt create mode 100644 tests/1501-2000/1854. maximum-population-year/sol.py create mode 100644 tests/1501-2000/1854. maximum-population-year/sol.py2 create mode 100644 tests/1501-2000/1854. maximum-population-year/sol.rb create mode 100644 tests/1501-2000/1854. maximum-population-year/sol.rs create mode 100644 tests/1501-2000/1854. maximum-population-year/sol.swift create mode 100644 tests/1501-2000/1854. maximum-population-year/sol.ts create mode 100644 tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/manifest.yaml create mode 100644 tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.cpp create mode 100644 tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.cs create mode 100644 tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.dart create mode 100644 tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.go create mode 100644 tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.java create mode 100644 tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.kt create mode 100644 tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.py create mode 100644 tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.py2 create mode 100644 tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.rb create mode 100644 tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.rs create mode 100644 tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.swift create mode 100644 tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.ts create mode 100644 tests/1501-2000/1856. maximum-subarray-min-product/manifest.yaml create mode 100644 tests/1501-2000/1856. maximum-subarray-min-product/sol.cpp create mode 100644 tests/1501-2000/1856. maximum-subarray-min-product/sol.cs create mode 100644 tests/1501-2000/1856. maximum-subarray-min-product/sol.dart create mode 100644 tests/1501-2000/1856. maximum-subarray-min-product/sol.go create mode 100644 tests/1501-2000/1856. maximum-subarray-min-product/sol.java create mode 100644 tests/1501-2000/1856. maximum-subarray-min-product/sol.kt create mode 100644 tests/1501-2000/1856. maximum-subarray-min-product/sol.py create mode 100644 tests/1501-2000/1856. maximum-subarray-min-product/sol.py2 create mode 100644 tests/1501-2000/1856. maximum-subarray-min-product/sol.rb create mode 100644 tests/1501-2000/1856. maximum-subarray-min-product/sol.rs create mode 100644 tests/1501-2000/1856. maximum-subarray-min-product/sol.swift create mode 100644 tests/1501-2000/1856. maximum-subarray-min-product/sol.ts create mode 100644 tests/1501-2000/1857. largest-color-value-in-a-directed-graph/manifest.yaml create mode 100644 tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.cpp create mode 100644 tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.cs create mode 100644 tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.dart create mode 100644 tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.go create mode 100644 tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.java create mode 100644 tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.kt create mode 100644 tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.py create mode 100644 tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.py2 create mode 100644 tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.rb create mode 100644 tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.rs create mode 100644 tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.swift create mode 100644 tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.ts create mode 100644 tests/1501-2000/1859. sorting-the-sentence/manifest.yaml create mode 100644 tests/1501-2000/1859. sorting-the-sentence/sol.cpp create mode 100644 tests/1501-2000/1859. sorting-the-sentence/sol.cs create mode 100644 tests/1501-2000/1859. sorting-the-sentence/sol.dart create mode 100644 tests/1501-2000/1859. sorting-the-sentence/sol.go create mode 100644 tests/1501-2000/1859. sorting-the-sentence/sol.java create mode 100644 tests/1501-2000/1859. sorting-the-sentence/sol.kt create mode 100644 tests/1501-2000/1859. sorting-the-sentence/sol.py create mode 100644 tests/1501-2000/1859. sorting-the-sentence/sol.py2 create mode 100644 tests/1501-2000/1859. sorting-the-sentence/sol.rb create mode 100644 tests/1501-2000/1859. sorting-the-sentence/sol.rs create mode 100644 tests/1501-2000/1859. sorting-the-sentence/sol.swift create mode 100644 tests/1501-2000/1859. sorting-the-sentence/sol.ts create mode 100644 tests/1501-2000/1860. incremental-memory-leak/manifest.yaml create mode 100644 tests/1501-2000/1860. incremental-memory-leak/sol.cpp create mode 100644 tests/1501-2000/1860. incremental-memory-leak/sol.cs create mode 100644 tests/1501-2000/1860. incremental-memory-leak/sol.dart create mode 100644 tests/1501-2000/1860. incremental-memory-leak/sol.go create mode 100644 tests/1501-2000/1860. incremental-memory-leak/sol.java create mode 100644 tests/1501-2000/1860. incremental-memory-leak/sol.kt create mode 100644 tests/1501-2000/1860. incremental-memory-leak/sol.py create mode 100644 tests/1501-2000/1860. incremental-memory-leak/sol.py2 create mode 100644 tests/1501-2000/1860. incremental-memory-leak/sol.rb create mode 100644 tests/1501-2000/1860. incremental-memory-leak/sol.rs create mode 100644 tests/1501-2000/1860. incremental-memory-leak/sol.swift create mode 100644 tests/1501-2000/1860. incremental-memory-leak/sol.ts create mode 100644 tests/1501-2000/1861. rotating-the-box/manifest.yaml create mode 100644 tests/1501-2000/1861. rotating-the-box/sol.cpp create mode 100644 tests/1501-2000/1861. rotating-the-box/sol.cs create mode 100644 tests/1501-2000/1861. rotating-the-box/sol.dart create mode 100644 tests/1501-2000/1861. rotating-the-box/sol.go create mode 100644 tests/1501-2000/1861. rotating-the-box/sol.java create mode 100644 tests/1501-2000/1861. rotating-the-box/sol.kt create mode 100644 tests/1501-2000/1861. rotating-the-box/sol.py create mode 100644 tests/1501-2000/1861. rotating-the-box/sol.py2 create mode 100644 tests/1501-2000/1861. rotating-the-box/sol.rb create mode 100644 tests/1501-2000/1861. rotating-the-box/sol.rs create mode 100644 tests/1501-2000/1861. rotating-the-box/sol.swift create mode 100644 tests/1501-2000/1861. rotating-the-box/sol.ts create mode 100644 tests/1501-2000/1862. sum-of-floored-pairs/manifest.yaml create mode 100644 tests/1501-2000/1862. sum-of-floored-pairs/sol.cpp create mode 100644 tests/1501-2000/1862. sum-of-floored-pairs/sol.cs create mode 100644 tests/1501-2000/1862. sum-of-floored-pairs/sol.dart create mode 100644 tests/1501-2000/1862. sum-of-floored-pairs/sol.go create mode 100644 tests/1501-2000/1862. sum-of-floored-pairs/sol.java create mode 100644 tests/1501-2000/1862. sum-of-floored-pairs/sol.kt create mode 100644 tests/1501-2000/1862. sum-of-floored-pairs/sol.py create mode 100644 tests/1501-2000/1862. sum-of-floored-pairs/sol.py2 create mode 100644 tests/1501-2000/1862. sum-of-floored-pairs/sol.rb create mode 100644 tests/1501-2000/1862. sum-of-floored-pairs/sol.rs create mode 100644 tests/1501-2000/1862. sum-of-floored-pairs/sol.swift create mode 100644 tests/1501-2000/1862. sum-of-floored-pairs/sol.ts create mode 100644 tests/1501-2000/1863. sum-of-all-subset-xor-totals/manifest.yaml create mode 100644 tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.cpp create mode 100644 tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.cs create mode 100644 tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.dart create mode 100644 tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.go create mode 100644 tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.java create mode 100644 tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.kt create mode 100644 tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.py create mode 100644 tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.py2 create mode 100644 tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.rb create mode 100644 tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.rs create mode 100644 tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.swift create mode 100644 tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.ts create mode 100644 tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/manifest.yaml create mode 100644 tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.cpp create mode 100644 tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.cs create mode 100644 tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.dart create mode 100644 tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.go create mode 100644 tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.java create mode 100644 tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.kt create mode 100644 tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.py create mode 100644 tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.py2 create mode 100644 tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.rb create mode 100644 tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.rs create mode 100644 tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.swift create mode 100644 tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.ts create mode 100644 tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/manifest.yaml create mode 100644 tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.cpp create mode 100644 tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.cs create mode 100644 tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.dart create mode 100644 tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.go create mode 100644 tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.java create mode 100644 tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.kt create mode 100644 tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.py create mode 100644 tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.py2 create mode 100644 tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.rb create mode 100644 tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.rs create mode 100644 tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.swift create mode 100644 tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.ts create mode 100644 tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/manifest.yaml create mode 100644 tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.cpp create mode 100644 tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.cs create mode 100644 tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.dart create mode 100644 tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.go create mode 100644 tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.java create mode 100644 tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.kt create mode 100644 tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.py create mode 100644 tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.py2 create mode 100644 tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.rb create mode 100644 tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.rs create mode 100644 tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.swift create mode 100644 tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.ts create mode 100644 tests/1501-2000/1870. minimum-speed-to-arrive-on-time/manifest.yaml create mode 100644 tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.cpp create mode 100644 tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.cs create mode 100644 tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.dart create mode 100644 tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.go create mode 100644 tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.java create mode 100644 tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.kt create mode 100644 tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.py create mode 100644 tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.py2 create mode 100644 tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.rb create mode 100644 tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.rs create mode 100644 tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.swift create mode 100644 tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.ts create mode 100644 tests/1501-2000/1871. jump-game-vii/manifest.yaml create mode 100644 tests/1501-2000/1871. jump-game-vii/sol.cpp create mode 100644 tests/1501-2000/1871. jump-game-vii/sol.cs create mode 100644 tests/1501-2000/1871. jump-game-vii/sol.dart create mode 100644 tests/1501-2000/1871. jump-game-vii/sol.go create mode 100644 tests/1501-2000/1871. jump-game-vii/sol.java create mode 100644 tests/1501-2000/1871. jump-game-vii/sol.kt create mode 100644 tests/1501-2000/1871. jump-game-vii/sol.py create mode 100644 tests/1501-2000/1871. jump-game-vii/sol.py2 create mode 100644 tests/1501-2000/1871. jump-game-vii/sol.rb create mode 100644 tests/1501-2000/1871. jump-game-vii/sol.rs create mode 100644 tests/1501-2000/1871. jump-game-vii/sol.swift create mode 100644 tests/1501-2000/1871. jump-game-vii/sol.ts create mode 100644 tests/1501-2000/1872. stone-game-viii/manifest.yaml create mode 100644 tests/1501-2000/1872. stone-game-viii/sol.cpp create mode 100644 tests/1501-2000/1872. stone-game-viii/sol.cs create mode 100644 tests/1501-2000/1872. stone-game-viii/sol.dart create mode 100644 tests/1501-2000/1872. stone-game-viii/sol.go create mode 100644 tests/1501-2000/1872. stone-game-viii/sol.java create mode 100644 tests/1501-2000/1872. stone-game-viii/sol.kt create mode 100644 tests/1501-2000/1872. stone-game-viii/sol.py create mode 100644 tests/1501-2000/1872. stone-game-viii/sol.py2 create mode 100644 tests/1501-2000/1872. stone-game-viii/sol.rb create mode 100644 tests/1501-2000/1872. stone-game-viii/sol.rs create mode 100644 tests/1501-2000/1872. stone-game-viii/sol.swift create mode 100644 tests/1501-2000/1872. stone-game-viii/sol.ts create mode 100644 tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/manifest.yaml create mode 100644 tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.cpp create mode 100644 tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.cs create mode 100644 tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.dart create mode 100644 tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.go create mode 100644 tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.java create mode 100644 tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.kt create mode 100644 tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.py create mode 100644 tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.py2 create mode 100644 tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.rb create mode 100644 tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.rs create mode 100644 tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.swift create mode 100644 tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.ts create mode 100644 tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/manifest.yaml create mode 100644 tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.cpp create mode 100644 tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.cs create mode 100644 tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.dart create mode 100644 tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.go create mode 100644 tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.java create mode 100644 tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.kt create mode 100644 tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.py create mode 100644 tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.py2 create mode 100644 tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.rb create mode 100644 tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.rs create mode 100644 tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.swift create mode 100644 tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.ts create mode 100644 tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/manifest.yaml create mode 100644 tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.cpp create mode 100644 tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.cs create mode 100644 tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.dart create mode 100644 tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.go create mode 100644 tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.java create mode 100644 tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.kt create mode 100644 tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.py create mode 100644 tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.py2 create mode 100644 tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.rb create mode 100644 tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.rs create mode 100644 tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.swift create mode 100644 tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.ts create mode 100644 tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/manifest.yaml create mode 100644 tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.cpp create mode 100644 tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.cs create mode 100644 tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.dart create mode 100644 tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.go create mode 100644 tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.java create mode 100644 tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.kt create mode 100644 tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.py create mode 100644 tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.py2 create mode 100644 tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.rb create mode 100644 tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.rs create mode 100644 tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.swift create mode 100644 tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.ts create mode 100644 tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/manifest.yaml create mode 100644 tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.cpp create mode 100644 tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.cs create mode 100644 tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.dart create mode 100644 tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.go create mode 100644 tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.java create mode 100644 tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.kt create mode 100644 tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.py create mode 100644 tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.py2 create mode 100644 tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.rb create mode 100644 tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.rs create mode 100644 tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.swift create mode 100644 tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.ts create mode 100644 tests/1501-2000/1881. maximum-value-after-insertion/manifest.yaml create mode 100644 tests/1501-2000/1881. maximum-value-after-insertion/sol.cpp create mode 100644 tests/1501-2000/1881. maximum-value-after-insertion/sol.cs create mode 100644 tests/1501-2000/1881. maximum-value-after-insertion/sol.dart create mode 100644 tests/1501-2000/1881. maximum-value-after-insertion/sol.go create mode 100644 tests/1501-2000/1881. maximum-value-after-insertion/sol.java create mode 100644 tests/1501-2000/1881. maximum-value-after-insertion/sol.kt create mode 100644 tests/1501-2000/1881. maximum-value-after-insertion/sol.py create mode 100644 tests/1501-2000/1881. maximum-value-after-insertion/sol.py2 create mode 100644 tests/1501-2000/1881. maximum-value-after-insertion/sol.rb create mode 100644 tests/1501-2000/1881. maximum-value-after-insertion/sol.rs create mode 100644 tests/1501-2000/1881. maximum-value-after-insertion/sol.swift create mode 100644 tests/1501-2000/1881. maximum-value-after-insertion/sol.ts create mode 100644 tests/1501-2000/1882. process-tasks-using-servers/manifest.yaml create mode 100644 tests/1501-2000/1882. process-tasks-using-servers/sol.cpp create mode 100644 tests/1501-2000/1882. process-tasks-using-servers/sol.cs create mode 100644 tests/1501-2000/1882. process-tasks-using-servers/sol.dart create mode 100644 tests/1501-2000/1882. process-tasks-using-servers/sol.go create mode 100644 tests/1501-2000/1882. process-tasks-using-servers/sol.java create mode 100644 tests/1501-2000/1882. process-tasks-using-servers/sol.kt create mode 100644 tests/1501-2000/1882. process-tasks-using-servers/sol.py create mode 100644 tests/1501-2000/1882. process-tasks-using-servers/sol.py2 create mode 100644 tests/1501-2000/1882. process-tasks-using-servers/sol.rb create mode 100644 tests/1501-2000/1882. process-tasks-using-servers/sol.rs create mode 100644 tests/1501-2000/1882. process-tasks-using-servers/sol.swift create mode 100644 tests/1501-2000/1882. process-tasks-using-servers/sol.ts create mode 100644 tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/manifest.yaml create mode 100644 tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.cpp create mode 100644 tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.cs create mode 100644 tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.dart create mode 100644 tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.go create mode 100644 tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.java create mode 100644 tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.kt create mode 100644 tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.py create mode 100644 tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.py2 create mode 100644 tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.rb create mode 100644 tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.rs create mode 100644 tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.swift create mode 100644 tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.ts create mode 100644 tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/manifest.yaml create mode 100644 tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.cpp create mode 100644 tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.cs create mode 100644 tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.dart create mode 100644 tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.go create mode 100644 tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.java create mode 100644 tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.kt create mode 100644 tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.py create mode 100644 tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.py2 create mode 100644 tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.rb create mode 100644 tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.rs create mode 100644 tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.swift create mode 100644 tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.ts create mode 100644 tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/manifest.yaml create mode 100644 tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.cpp create mode 100644 tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.cs create mode 100644 tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.dart create mode 100644 tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.go create mode 100644 tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.java create mode 100644 tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.kt create mode 100644 tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.py create mode 100644 tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.py2 create mode 100644 tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.rb create mode 100644 tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.rs create mode 100644 tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.swift create mode 100644 tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.ts create mode 100644 tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/manifest.yaml create mode 100644 tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.cpp create mode 100644 tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.cs create mode 100644 tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.dart create mode 100644 tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.go create mode 100644 tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.java create mode 100644 tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.kt create mode 100644 tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.py create mode 100644 tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.py2 create mode 100644 tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.rb create mode 100644 tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.rs create mode 100644 tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.swift create mode 100644 tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.ts create mode 100644 tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/manifest.yaml create mode 100644 tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.cpp create mode 100644 tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.cs create mode 100644 tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.dart create mode 100644 tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.go create mode 100644 tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.java create mode 100644 tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.kt create mode 100644 tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.py create mode 100644 tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.py2 create mode 100644 tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.rb create mode 100644 tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.rs create mode 100644 tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.swift create mode 100644 tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.ts create mode 100644 tests/1501-2000/1889. minimum-space-wasted-from-packaging/manifest.yaml create mode 100644 tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.cpp create mode 100644 tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.cs create mode 100644 tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.dart create mode 100644 tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.go create mode 100644 tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.java create mode 100644 tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.kt create mode 100644 tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.py create mode 100644 tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.py2 create mode 100644 tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.rb create mode 100644 tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.rs create mode 100644 tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.swift create mode 100644 tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.ts create mode 100644 tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/manifest.yaml create mode 100644 tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.cpp create mode 100644 tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.cs create mode 100644 tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.dart create mode 100644 tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.go create mode 100644 tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.java create mode 100644 tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.kt create mode 100644 tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.py create mode 100644 tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.py2 create mode 100644 tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.rb create mode 100644 tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.rs create mode 100644 tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.swift create mode 100644 tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.ts create mode 100644 tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/manifest.yaml create mode 100644 tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.cpp create mode 100644 tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.cs create mode 100644 tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.dart create mode 100644 tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.go create mode 100644 tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.java create mode 100644 tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.kt create mode 100644 tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.py create mode 100644 tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.py2 create mode 100644 tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.rb create mode 100644 tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.rs create mode 100644 tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.swift create mode 100644 tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.ts create mode 100644 tests/1501-2000/1895. largest-magic-square/manifest.yaml create mode 100644 tests/1501-2000/1895. largest-magic-square/sol.cpp create mode 100644 tests/1501-2000/1895. largest-magic-square/sol.cs create mode 100644 tests/1501-2000/1895. largest-magic-square/sol.dart create mode 100644 tests/1501-2000/1895. largest-magic-square/sol.go create mode 100644 tests/1501-2000/1895. largest-magic-square/sol.java create mode 100644 tests/1501-2000/1895. largest-magic-square/sol.kt create mode 100644 tests/1501-2000/1895. largest-magic-square/sol.py create mode 100644 tests/1501-2000/1895. largest-magic-square/sol.py2 create mode 100644 tests/1501-2000/1895. largest-magic-square/sol.rb create mode 100644 tests/1501-2000/1895. largest-magic-square/sol.rs create mode 100644 tests/1501-2000/1895. largest-magic-square/sol.swift create mode 100644 tests/1501-2000/1895. largest-magic-square/sol.ts create mode 100644 tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/manifest.yaml create mode 100644 tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.cpp create mode 100644 tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.cs create mode 100644 tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.dart create mode 100644 tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.go create mode 100644 tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.java create mode 100644 tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.kt create mode 100644 tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.py create mode 100644 tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.py2 create mode 100644 tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.rb create mode 100644 tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.rs create mode 100644 tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.swift create mode 100644 tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.ts create mode 100644 tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/manifest.yaml create mode 100644 tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.cpp create mode 100644 tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.cs create mode 100644 tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.dart create mode 100644 tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.go create mode 100644 tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.java create mode 100644 tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.kt create mode 100644 tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.py create mode 100644 tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.py2 create mode 100644 tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.rb create mode 100644 tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.rs create mode 100644 tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.swift create mode 100644 tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.ts create mode 100644 tests/1501-2000/1898. maximum-number-of-removable-characters/manifest.yaml create mode 100644 tests/1501-2000/1898. maximum-number-of-removable-characters/sol.cpp create mode 100644 tests/1501-2000/1898. maximum-number-of-removable-characters/sol.cs create mode 100644 tests/1501-2000/1898. maximum-number-of-removable-characters/sol.dart create mode 100644 tests/1501-2000/1898. maximum-number-of-removable-characters/sol.go create mode 100644 tests/1501-2000/1898. maximum-number-of-removable-characters/sol.java create mode 100644 tests/1501-2000/1898. maximum-number-of-removable-characters/sol.kt create mode 100644 tests/1501-2000/1898. maximum-number-of-removable-characters/sol.py create mode 100644 tests/1501-2000/1898. maximum-number-of-removable-characters/sol.py2 create mode 100644 tests/1501-2000/1898. maximum-number-of-removable-characters/sol.rb create mode 100644 tests/1501-2000/1898. maximum-number-of-removable-characters/sol.rs create mode 100644 tests/1501-2000/1898. maximum-number-of-removable-characters/sol.swift create mode 100644 tests/1501-2000/1898. maximum-number-of-removable-characters/sol.ts create mode 100644 tests/1501-2000/1899. merge-triplets-to-form-target-triplet/manifest.yaml create mode 100644 tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.cpp create mode 100644 tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.cs create mode 100644 tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.dart create mode 100644 tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.go create mode 100644 tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.java create mode 100644 tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.kt create mode 100644 tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.py create mode 100644 tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.py2 create mode 100644 tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.rb create mode 100644 tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.rs create mode 100644 tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.swift create mode 100644 tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.ts create mode 100644 tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/manifest.yaml create mode 100644 tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.cpp create mode 100644 tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.cs create mode 100644 tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.dart create mode 100644 tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.go create mode 100644 tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.java create mode 100644 tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.kt create mode 100644 tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.py create mode 100644 tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.py2 create mode 100644 tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.rb create mode 100644 tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.rs create mode 100644 tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.swift create mode 100644 tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.ts create mode 100644 tests/1501-2000/1901. find-a-peak-element-ii/manifest.yaml create mode 100644 tests/1501-2000/1901. find-a-peak-element-ii/sol.cpp create mode 100644 tests/1501-2000/1901. find-a-peak-element-ii/sol.cs create mode 100644 tests/1501-2000/1901. find-a-peak-element-ii/sol.dart create mode 100644 tests/1501-2000/1901. find-a-peak-element-ii/sol.go create mode 100644 tests/1501-2000/1901. find-a-peak-element-ii/sol.java create mode 100644 tests/1501-2000/1901. find-a-peak-element-ii/sol.kt create mode 100644 tests/1501-2000/1901. find-a-peak-element-ii/sol.py create mode 100644 tests/1501-2000/1901. find-a-peak-element-ii/sol.py2 create mode 100644 tests/1501-2000/1901. find-a-peak-element-ii/sol.rb create mode 100644 tests/1501-2000/1901. find-a-peak-element-ii/sol.rs create mode 100644 tests/1501-2000/1901. find-a-peak-element-ii/sol.swift create mode 100644 tests/1501-2000/1901. find-a-peak-element-ii/sol.ts create mode 100644 tests/1501-2000/1903. largest-odd-number-in-string/manifest.yaml create mode 100644 tests/1501-2000/1903. largest-odd-number-in-string/sol.cpp create mode 100644 tests/1501-2000/1903. largest-odd-number-in-string/sol.cs create mode 100644 tests/1501-2000/1903. largest-odd-number-in-string/sol.dart create mode 100644 tests/1501-2000/1903. largest-odd-number-in-string/sol.go create mode 100644 tests/1501-2000/1903. largest-odd-number-in-string/sol.java create mode 100644 tests/1501-2000/1903. largest-odd-number-in-string/sol.kt create mode 100644 tests/1501-2000/1903. largest-odd-number-in-string/sol.py create mode 100644 tests/1501-2000/1903. largest-odd-number-in-string/sol.py2 create mode 100644 tests/1501-2000/1903. largest-odd-number-in-string/sol.rb create mode 100644 tests/1501-2000/1903. largest-odd-number-in-string/sol.rs create mode 100644 tests/1501-2000/1903. largest-odd-number-in-string/sol.swift create mode 100644 tests/1501-2000/1903. largest-odd-number-in-string/sol.ts create mode 100644 tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/manifest.yaml create mode 100644 tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.cpp create mode 100644 tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.cs create mode 100644 tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.dart create mode 100644 tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.go create mode 100644 tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.java create mode 100644 tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.kt create mode 100644 tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.py create mode 100644 tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.py2 create mode 100644 tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.rb create mode 100644 tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.rs create mode 100644 tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.swift create mode 100644 tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.ts create mode 100644 tests/1501-2000/1905. count-sub-islands/manifest.yaml create mode 100644 tests/1501-2000/1905. count-sub-islands/sol.cpp create mode 100644 tests/1501-2000/1905. count-sub-islands/sol.cs create mode 100644 tests/1501-2000/1905. count-sub-islands/sol.dart create mode 100644 tests/1501-2000/1905. count-sub-islands/sol.go create mode 100644 tests/1501-2000/1905. count-sub-islands/sol.java create mode 100644 tests/1501-2000/1905. count-sub-islands/sol.kt create mode 100644 tests/1501-2000/1905. count-sub-islands/sol.py create mode 100644 tests/1501-2000/1905. count-sub-islands/sol.py2 create mode 100644 tests/1501-2000/1905. count-sub-islands/sol.rb create mode 100644 tests/1501-2000/1905. count-sub-islands/sol.rs create mode 100644 tests/1501-2000/1905. count-sub-islands/sol.swift create mode 100644 tests/1501-2000/1905. count-sub-islands/sol.ts create mode 100644 tests/1501-2000/1906. minimum-absolute-difference-queries/manifest.yaml create mode 100644 tests/1501-2000/1906. minimum-absolute-difference-queries/sol.cpp create mode 100644 tests/1501-2000/1906. minimum-absolute-difference-queries/sol.cs create mode 100644 tests/1501-2000/1906. minimum-absolute-difference-queries/sol.dart create mode 100644 tests/1501-2000/1906. minimum-absolute-difference-queries/sol.go create mode 100644 tests/1501-2000/1906. minimum-absolute-difference-queries/sol.java create mode 100644 tests/1501-2000/1906. minimum-absolute-difference-queries/sol.kt create mode 100644 tests/1501-2000/1906. minimum-absolute-difference-queries/sol.py create mode 100644 tests/1501-2000/1906. minimum-absolute-difference-queries/sol.py2 create mode 100644 tests/1501-2000/1906. minimum-absolute-difference-queries/sol.rb create mode 100644 tests/1501-2000/1906. minimum-absolute-difference-queries/sol.rs create mode 100644 tests/1501-2000/1906. minimum-absolute-difference-queries/sol.swift create mode 100644 tests/1501-2000/1906. minimum-absolute-difference-queries/sol.ts create mode 100644 tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/manifest.yaml create mode 100644 tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.cpp create mode 100644 tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.cs create mode 100644 tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.dart create mode 100644 tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.go create mode 100644 tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.java create mode 100644 tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.kt create mode 100644 tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.py create mode 100644 tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.py2 create mode 100644 tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.rb create mode 100644 tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.rs create mode 100644 tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.swift create mode 100644 tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.ts create mode 100644 tests/1501-2000/1910. remove-all-occurrences-of-a-substring/manifest.yaml create mode 100644 tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.cpp create mode 100644 tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.cs create mode 100644 tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.dart create mode 100644 tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.go create mode 100644 tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.java create mode 100644 tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.kt create mode 100644 tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.py create mode 100644 tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.py2 create mode 100644 tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.rb create mode 100644 tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.rs create mode 100644 tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.swift create mode 100644 tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.ts create mode 100644 tests/1501-2000/1911. maximum-alternating-subsequence-sum/manifest.yaml create mode 100644 tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.cpp create mode 100644 tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.cs create mode 100644 tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.dart create mode 100644 tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.go create mode 100644 tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.java create mode 100644 tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.kt create mode 100644 tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.py create mode 100644 tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.py2 create mode 100644 tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.rb create mode 100644 tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.rs create mode 100644 tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.swift create mode 100644 tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.ts create mode 100644 tests/1501-2000/1913. maximum-product-difference-between-two-pairs/manifest.yaml create mode 100644 tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.cpp create mode 100644 tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.cs create mode 100644 tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.dart create mode 100644 tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.go create mode 100644 tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.java create mode 100644 tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.kt create mode 100644 tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.py create mode 100644 tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.py2 create mode 100644 tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.rb create mode 100644 tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.rs create mode 100644 tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.swift create mode 100644 tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.ts create mode 100644 tests/1501-2000/1914. cyclically-rotating-a-grid/manifest.yaml create mode 100644 tests/1501-2000/1914. cyclically-rotating-a-grid/sol.cpp create mode 100644 tests/1501-2000/1914. cyclically-rotating-a-grid/sol.cs create mode 100644 tests/1501-2000/1914. cyclically-rotating-a-grid/sol.dart create mode 100644 tests/1501-2000/1914. cyclically-rotating-a-grid/sol.go create mode 100644 tests/1501-2000/1914. cyclically-rotating-a-grid/sol.java create mode 100644 tests/1501-2000/1914. cyclically-rotating-a-grid/sol.kt create mode 100644 tests/1501-2000/1914. cyclically-rotating-a-grid/sol.py create mode 100644 tests/1501-2000/1914. cyclically-rotating-a-grid/sol.py2 create mode 100644 tests/1501-2000/1914. cyclically-rotating-a-grid/sol.rb create mode 100644 tests/1501-2000/1914. cyclically-rotating-a-grid/sol.rs create mode 100644 tests/1501-2000/1914. cyclically-rotating-a-grid/sol.swift create mode 100644 tests/1501-2000/1914. cyclically-rotating-a-grid/sol.ts create mode 100644 tests/1501-2000/1915. number-of-wonderful-substrings/manifest.yaml create mode 100644 tests/1501-2000/1915. number-of-wonderful-substrings/sol.cpp create mode 100644 tests/1501-2000/1915. number-of-wonderful-substrings/sol.cs create mode 100644 tests/1501-2000/1915. number-of-wonderful-substrings/sol.dart create mode 100644 tests/1501-2000/1915. number-of-wonderful-substrings/sol.go create mode 100644 tests/1501-2000/1915. number-of-wonderful-substrings/sol.java create mode 100644 tests/1501-2000/1915. number-of-wonderful-substrings/sol.kt create mode 100644 tests/1501-2000/1915. number-of-wonderful-substrings/sol.py create mode 100644 tests/1501-2000/1915. number-of-wonderful-substrings/sol.py2 create mode 100644 tests/1501-2000/1915. number-of-wonderful-substrings/sol.rb create mode 100644 tests/1501-2000/1915. number-of-wonderful-substrings/sol.rs create mode 100644 tests/1501-2000/1915. number-of-wonderful-substrings/sol.swift create mode 100644 tests/1501-2000/1915. number-of-wonderful-substrings/sol.ts create mode 100644 tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/manifest.yaml create mode 100644 tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.cpp create mode 100644 tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.cs create mode 100644 tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.dart create mode 100644 tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.go create mode 100644 tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.java create mode 100644 tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.kt create mode 100644 tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.py create mode 100644 tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.py2 create mode 100644 tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.rb create mode 100644 tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.rs create mode 100644 tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.swift create mode 100644 tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.ts create mode 100644 tests/1501-2000/1920. build-array-from-permutation/manifest.yaml create mode 100644 tests/1501-2000/1920. build-array-from-permutation/sol.cpp create mode 100644 tests/1501-2000/1920. build-array-from-permutation/sol.cs create mode 100644 tests/1501-2000/1920. build-array-from-permutation/sol.dart create mode 100644 tests/1501-2000/1920. build-array-from-permutation/sol.go create mode 100644 tests/1501-2000/1920. build-array-from-permutation/sol.java create mode 100644 tests/1501-2000/1920. build-array-from-permutation/sol.kt create mode 100644 tests/1501-2000/1920. build-array-from-permutation/sol.py create mode 100644 tests/1501-2000/1920. build-array-from-permutation/sol.py2 create mode 100644 tests/1501-2000/1920. build-array-from-permutation/sol.rb create mode 100644 tests/1501-2000/1920. build-array-from-permutation/sol.rs create mode 100644 tests/1501-2000/1920. build-array-from-permutation/sol.swift create mode 100644 tests/1501-2000/1920. build-array-from-permutation/sol.ts create mode 100644 tests/1501-2000/1921. eliminate-maximum-number-of-monsters/manifest.yaml create mode 100644 tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.cpp create mode 100644 tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.cs create mode 100644 tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.dart create mode 100644 tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.go create mode 100644 tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.java create mode 100644 tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.kt create mode 100644 tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.py create mode 100644 tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.py2 create mode 100644 tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.rb create mode 100644 tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.rs create mode 100644 tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.swift create mode 100644 tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.ts create mode 100644 tests/1501-2000/1922. count-good-numbers/manifest.yaml create mode 100644 tests/1501-2000/1922. count-good-numbers/sol.cpp create mode 100644 tests/1501-2000/1922. count-good-numbers/sol.cs create mode 100644 tests/1501-2000/1922. count-good-numbers/sol.dart create mode 100644 tests/1501-2000/1922. count-good-numbers/sol.go create mode 100644 tests/1501-2000/1922. count-good-numbers/sol.java create mode 100644 tests/1501-2000/1922. count-good-numbers/sol.kt create mode 100644 tests/1501-2000/1922. count-good-numbers/sol.py create mode 100644 tests/1501-2000/1922. count-good-numbers/sol.py2 create mode 100644 tests/1501-2000/1922. count-good-numbers/sol.rb create mode 100644 tests/1501-2000/1922. count-good-numbers/sol.rs create mode 100644 tests/1501-2000/1922. count-good-numbers/sol.swift create mode 100644 tests/1501-2000/1922. count-good-numbers/sol.ts create mode 100644 tests/1501-2000/1923. longest-common-subpath/manifest.yaml create mode 100644 tests/1501-2000/1923. longest-common-subpath/sol.cpp create mode 100644 tests/1501-2000/1923. longest-common-subpath/sol.cs create mode 100644 tests/1501-2000/1923. longest-common-subpath/sol.dart create mode 100644 tests/1501-2000/1923. longest-common-subpath/sol.go create mode 100644 tests/1501-2000/1923. longest-common-subpath/sol.java create mode 100644 tests/1501-2000/1923. longest-common-subpath/sol.kt create mode 100644 tests/1501-2000/1923. longest-common-subpath/sol.py create mode 100644 tests/1501-2000/1923. longest-common-subpath/sol.py2 create mode 100644 tests/1501-2000/1923. longest-common-subpath/sol.rb create mode 100644 tests/1501-2000/1923. longest-common-subpath/sol.rs create mode 100644 tests/1501-2000/1923. longest-common-subpath/sol.swift create mode 100644 tests/1501-2000/1923. longest-common-subpath/sol.ts create mode 100644 tests/1501-2000/1925. count-square-sum-triples/manifest.yaml create mode 100644 tests/1501-2000/1925. count-square-sum-triples/sol.cpp create mode 100644 tests/1501-2000/1925. count-square-sum-triples/sol.cs create mode 100644 tests/1501-2000/1925. count-square-sum-triples/sol.dart create mode 100644 tests/1501-2000/1925. count-square-sum-triples/sol.go create mode 100644 tests/1501-2000/1925. count-square-sum-triples/sol.java create mode 100644 tests/1501-2000/1925. count-square-sum-triples/sol.kt create mode 100644 tests/1501-2000/1925. count-square-sum-triples/sol.py create mode 100644 tests/1501-2000/1925. count-square-sum-triples/sol.py2 create mode 100644 tests/1501-2000/1925. count-square-sum-triples/sol.rb create mode 100644 tests/1501-2000/1925. count-square-sum-triples/sol.rs create mode 100644 tests/1501-2000/1925. count-square-sum-triples/sol.swift create mode 100644 tests/1501-2000/1925. count-square-sum-triples/sol.ts create mode 100644 tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/manifest.yaml create mode 100644 tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.cpp create mode 100644 tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.cs create mode 100644 tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.dart create mode 100644 tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.go create mode 100644 tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.java create mode 100644 tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.kt create mode 100644 tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.py create mode 100644 tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.py2 create mode 100644 tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.rb create mode 100644 tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.rs create mode 100644 tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.swift create mode 100644 tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.ts create mode 100644 tests/1501-2000/1927. sum-game/manifest.yaml create mode 100644 tests/1501-2000/1927. sum-game/sol.cpp create mode 100644 tests/1501-2000/1927. sum-game/sol.cs create mode 100644 tests/1501-2000/1927. sum-game/sol.dart create mode 100644 tests/1501-2000/1927. sum-game/sol.go create mode 100644 tests/1501-2000/1927. sum-game/sol.java create mode 100644 tests/1501-2000/1927. sum-game/sol.kt create mode 100644 tests/1501-2000/1927. sum-game/sol.py create mode 100644 tests/1501-2000/1927. sum-game/sol.py2 create mode 100644 tests/1501-2000/1927. sum-game/sol.rb create mode 100644 tests/1501-2000/1927. sum-game/sol.rs create mode 100644 tests/1501-2000/1927. sum-game/sol.swift create mode 100644 tests/1501-2000/1927. sum-game/sol.ts create mode 100644 tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/manifest.yaml create mode 100644 tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.cpp create mode 100644 tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.cs create mode 100644 tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.dart create mode 100644 tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.go create mode 100644 tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.java create mode 100644 tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.kt create mode 100644 tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.py create mode 100644 tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.py2 create mode 100644 tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.rb create mode 100644 tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.rs create mode 100644 tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.swift create mode 100644 tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.ts create mode 100644 tests/1501-2000/1929. concatenation-of-array/manifest.yaml create mode 100644 tests/1501-2000/1929. concatenation-of-array/sol.cpp create mode 100644 tests/1501-2000/1929. concatenation-of-array/sol.cs create mode 100644 tests/1501-2000/1929. concatenation-of-array/sol.dart create mode 100644 tests/1501-2000/1929. concatenation-of-array/sol.go create mode 100644 tests/1501-2000/1929. concatenation-of-array/sol.java create mode 100644 tests/1501-2000/1929. concatenation-of-array/sol.kt create mode 100644 tests/1501-2000/1929. concatenation-of-array/sol.py create mode 100644 tests/1501-2000/1929. concatenation-of-array/sol.py2 create mode 100644 tests/1501-2000/1929. concatenation-of-array/sol.rb create mode 100644 tests/1501-2000/1929. concatenation-of-array/sol.rs create mode 100644 tests/1501-2000/1929. concatenation-of-array/sol.swift create mode 100644 tests/1501-2000/1929. concatenation-of-array/sol.ts create mode 100644 tests/1501-2000/1930. unique-length-3-palindromic-subsequences/manifest.yaml create mode 100644 tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.cpp create mode 100644 tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.cs create mode 100644 tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.dart create mode 100644 tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.go create mode 100644 tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.java create mode 100644 tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.kt create mode 100644 tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.py create mode 100644 tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.py2 create mode 100644 tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.rb create mode 100644 tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.rs create mode 100644 tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.swift create mode 100644 tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.ts create mode 100644 tests/1501-2000/1931. painting-a-grid-with-three-different-colors/manifest.yaml create mode 100644 tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.cpp create mode 100644 tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.cs create mode 100644 tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.dart create mode 100644 tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.go create mode 100644 tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.java create mode 100644 tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.kt create mode 100644 tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.py create mode 100644 tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.py2 create mode 100644 tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.rb create mode 100644 tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.rs create mode 100644 tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.swift create mode 100644 tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.ts create mode 100644 tests/1501-2000/1935. maximum-number-of-words-you-can-type/manifest.yaml create mode 100644 tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.cpp create mode 100644 tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.cs create mode 100644 tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.dart create mode 100644 tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.go create mode 100644 tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.java create mode 100644 tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.kt create mode 100644 tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.py create mode 100644 tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.py2 create mode 100644 tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.rb create mode 100644 tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.rs create mode 100644 tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.swift create mode 100644 tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.ts create mode 100644 tests/1501-2000/1936. add-minimum-number-of-rungs/manifest.yaml create mode 100644 tests/1501-2000/1936. add-minimum-number-of-rungs/sol.cpp create mode 100644 tests/1501-2000/1936. add-minimum-number-of-rungs/sol.cs create mode 100644 tests/1501-2000/1936. add-minimum-number-of-rungs/sol.dart create mode 100644 tests/1501-2000/1936. add-minimum-number-of-rungs/sol.go create mode 100644 tests/1501-2000/1936. add-minimum-number-of-rungs/sol.java create mode 100644 tests/1501-2000/1936. add-minimum-number-of-rungs/sol.kt create mode 100644 tests/1501-2000/1936. add-minimum-number-of-rungs/sol.py create mode 100644 tests/1501-2000/1936. add-minimum-number-of-rungs/sol.py2 create mode 100644 tests/1501-2000/1936. add-minimum-number-of-rungs/sol.rb create mode 100644 tests/1501-2000/1936. add-minimum-number-of-rungs/sol.rs create mode 100644 tests/1501-2000/1936. add-minimum-number-of-rungs/sol.swift create mode 100644 tests/1501-2000/1936. add-minimum-number-of-rungs/sol.ts create mode 100644 tests/1501-2000/1937. maximum-number-of-points-with-cost/manifest.yaml create mode 100644 tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.cpp create mode 100644 tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.cs create mode 100644 tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.dart create mode 100644 tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.go create mode 100644 tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.java create mode 100644 tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.kt create mode 100644 tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.py create mode 100644 tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.py2 create mode 100644 tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.rb create mode 100644 tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.rs create mode 100644 tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.swift create mode 100644 tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.ts create mode 100644 tests/1501-2000/1938. maximum-genetic-difference-query/manifest.yaml create mode 100644 tests/1501-2000/1938. maximum-genetic-difference-query/sol.cpp create mode 100644 tests/1501-2000/1938. maximum-genetic-difference-query/sol.cs create mode 100644 tests/1501-2000/1938. maximum-genetic-difference-query/sol.dart create mode 100644 tests/1501-2000/1938. maximum-genetic-difference-query/sol.go create mode 100644 tests/1501-2000/1938. maximum-genetic-difference-query/sol.java create mode 100644 tests/1501-2000/1938. maximum-genetic-difference-query/sol.kt create mode 100644 tests/1501-2000/1938. maximum-genetic-difference-query/sol.py create mode 100644 tests/1501-2000/1938. maximum-genetic-difference-query/sol.py2 create mode 100644 tests/1501-2000/1938. maximum-genetic-difference-query/sol.rb create mode 100644 tests/1501-2000/1938. maximum-genetic-difference-query/sol.rs create mode 100644 tests/1501-2000/1938. maximum-genetic-difference-query/sol.swift create mode 100644 tests/1501-2000/1938. maximum-genetic-difference-query/sol.ts create mode 100644 tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/manifest.yaml create mode 100644 tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.cpp create mode 100644 tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.cs create mode 100644 tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.dart create mode 100644 tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.go create mode 100644 tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.java create mode 100644 tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.kt create mode 100644 tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.py create mode 100644 tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.py2 create mode 100644 tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.rb create mode 100644 tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.rs create mode 100644 tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.swift create mode 100644 tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.ts create mode 100644 tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/manifest.yaml create mode 100644 tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.cpp create mode 100644 tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.cs create mode 100644 tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.dart create mode 100644 tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.go create mode 100644 tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.java create mode 100644 tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.kt create mode 100644 tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.py create mode 100644 tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.py2 create mode 100644 tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.rb create mode 100644 tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.rs create mode 100644 tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.swift create mode 100644 tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.ts create mode 100644 tests/1501-2000/1943. describe-the-painting/manifest.yaml create mode 100644 tests/1501-2000/1943. describe-the-painting/sol.cpp create mode 100644 tests/1501-2000/1943. describe-the-painting/sol.cs create mode 100644 tests/1501-2000/1943. describe-the-painting/sol.dart create mode 100644 tests/1501-2000/1943. describe-the-painting/sol.go create mode 100644 tests/1501-2000/1943. describe-the-painting/sol.java create mode 100644 tests/1501-2000/1943. describe-the-painting/sol.kt create mode 100644 tests/1501-2000/1943. describe-the-painting/sol.py create mode 100644 tests/1501-2000/1943. describe-the-painting/sol.py2 create mode 100644 tests/1501-2000/1943. describe-the-painting/sol.rb create mode 100644 tests/1501-2000/1943. describe-the-painting/sol.rs create mode 100644 tests/1501-2000/1943. describe-the-painting/sol.swift create mode 100644 tests/1501-2000/1943. describe-the-painting/sol.ts create mode 100644 tests/1501-2000/1944. number-of-visible-people-in-a-queue/manifest.yaml create mode 100644 tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.cpp create mode 100644 tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.cs create mode 100644 tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.dart create mode 100644 tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.go create mode 100644 tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.java create mode 100644 tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.kt create mode 100644 tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.py create mode 100644 tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.py2 create mode 100644 tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.rb create mode 100644 tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.rs create mode 100644 tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.swift create mode 100644 tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.ts create mode 100644 tests/1501-2000/1945. sum-of-digits-of-string-after-convert/manifest.yaml create mode 100644 tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.cpp create mode 100644 tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.cs create mode 100644 tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.dart create mode 100644 tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.go create mode 100644 tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.java create mode 100644 tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.kt create mode 100644 tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.py create mode 100644 tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.py2 create mode 100644 tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.rb create mode 100644 tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.rs create mode 100644 tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.swift create mode 100644 tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.ts create mode 100644 tests/1501-2000/1946. largest-number-after-mutating-substring/manifest.yaml create mode 100644 tests/1501-2000/1946. largest-number-after-mutating-substring/sol.cpp create mode 100644 tests/1501-2000/1946. largest-number-after-mutating-substring/sol.cs create mode 100644 tests/1501-2000/1946. largest-number-after-mutating-substring/sol.dart create mode 100644 tests/1501-2000/1946. largest-number-after-mutating-substring/sol.go create mode 100644 tests/1501-2000/1946. largest-number-after-mutating-substring/sol.java create mode 100644 tests/1501-2000/1946. largest-number-after-mutating-substring/sol.kt create mode 100644 tests/1501-2000/1946. largest-number-after-mutating-substring/sol.py create mode 100644 tests/1501-2000/1946. largest-number-after-mutating-substring/sol.py2 create mode 100644 tests/1501-2000/1946. largest-number-after-mutating-substring/sol.rb create mode 100644 tests/1501-2000/1946. largest-number-after-mutating-substring/sol.rs create mode 100644 tests/1501-2000/1946. largest-number-after-mutating-substring/sol.swift create mode 100644 tests/1501-2000/1946. largest-number-after-mutating-substring/sol.ts create mode 100644 tests/1501-2000/1947. maximum-compatibility-score-sum/manifest.yaml create mode 100644 tests/1501-2000/1947. maximum-compatibility-score-sum/sol.cpp create mode 100644 tests/1501-2000/1947. maximum-compatibility-score-sum/sol.cs create mode 100644 tests/1501-2000/1947. maximum-compatibility-score-sum/sol.dart create mode 100644 tests/1501-2000/1947. maximum-compatibility-score-sum/sol.go create mode 100644 tests/1501-2000/1947. maximum-compatibility-score-sum/sol.java create mode 100644 tests/1501-2000/1947. maximum-compatibility-score-sum/sol.kt create mode 100644 tests/1501-2000/1947. maximum-compatibility-score-sum/sol.py create mode 100644 tests/1501-2000/1947. maximum-compatibility-score-sum/sol.py2 create mode 100644 tests/1501-2000/1947. maximum-compatibility-score-sum/sol.rb create mode 100644 tests/1501-2000/1947. maximum-compatibility-score-sum/sol.rs create mode 100644 tests/1501-2000/1947. maximum-compatibility-score-sum/sol.swift create mode 100644 tests/1501-2000/1947. maximum-compatibility-score-sum/sol.ts create mode 100644 tests/1501-2000/1948. delete-duplicate-folders-in-system/manifest.yaml create mode 100644 tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.cpp create mode 100644 tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.cs create mode 100644 tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.dart create mode 100644 tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.go create mode 100644 tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.java create mode 100644 tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.kt create mode 100644 tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.py create mode 100644 tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.py2 create mode 100644 tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.rb create mode 100644 tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.rs create mode 100644 tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.swift create mode 100644 tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.ts create mode 100644 tests/1501-2000/1952. three-divisors/manifest.yaml create mode 100644 tests/1501-2000/1952. three-divisors/sol.cpp create mode 100644 tests/1501-2000/1952. three-divisors/sol.cs create mode 100644 tests/1501-2000/1952. three-divisors/sol.dart create mode 100644 tests/1501-2000/1952. three-divisors/sol.go create mode 100644 tests/1501-2000/1952. three-divisors/sol.java create mode 100644 tests/1501-2000/1952. three-divisors/sol.kt create mode 100644 tests/1501-2000/1952. three-divisors/sol.py create mode 100644 tests/1501-2000/1952. three-divisors/sol.py2 create mode 100644 tests/1501-2000/1952. three-divisors/sol.rb create mode 100644 tests/1501-2000/1952. three-divisors/sol.rs create mode 100644 tests/1501-2000/1952. three-divisors/sol.swift create mode 100644 tests/1501-2000/1952. three-divisors/sol.ts create mode 100644 tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/manifest.yaml create mode 100644 tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.cpp create mode 100644 tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.cs create mode 100644 tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.dart create mode 100644 tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.go create mode 100644 tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.java create mode 100644 tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.kt create mode 100644 tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.py create mode 100644 tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.py2 create mode 100644 tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.rb create mode 100644 tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.rs create mode 100644 tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.swift create mode 100644 tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.ts create mode 100644 tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/manifest.yaml create mode 100644 tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.cpp create mode 100644 tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.cs create mode 100644 tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.dart create mode 100644 tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.go create mode 100644 tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.java create mode 100644 tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.kt create mode 100644 tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.py create mode 100644 tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.py2 create mode 100644 tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.rb create mode 100644 tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.rs create mode 100644 tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.swift create mode 100644 tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.ts create mode 100644 tests/1501-2000/1955. count-number-of-special-subsequences/manifest.yaml create mode 100644 tests/1501-2000/1955. count-number-of-special-subsequences/sol.cpp create mode 100644 tests/1501-2000/1955. count-number-of-special-subsequences/sol.cs create mode 100644 tests/1501-2000/1955. count-number-of-special-subsequences/sol.dart create mode 100644 tests/1501-2000/1955. count-number-of-special-subsequences/sol.go create mode 100644 tests/1501-2000/1955. count-number-of-special-subsequences/sol.java create mode 100644 tests/1501-2000/1955. count-number-of-special-subsequences/sol.kt create mode 100644 tests/1501-2000/1955. count-number-of-special-subsequences/sol.py create mode 100644 tests/1501-2000/1955. count-number-of-special-subsequences/sol.py2 create mode 100644 tests/1501-2000/1955. count-number-of-special-subsequences/sol.rb create mode 100644 tests/1501-2000/1955. count-number-of-special-subsequences/sol.rs create mode 100644 tests/1501-2000/1955. count-number-of-special-subsequences/sol.swift create mode 100644 tests/1501-2000/1955. count-number-of-special-subsequences/sol.ts create mode 100644 tests/1501-2000/1957. delete-characters-to-make-fancy-string/manifest.yaml create mode 100644 tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.cpp create mode 100644 tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.cs create mode 100644 tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.dart create mode 100644 tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.go create mode 100644 tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.java create mode 100644 tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.kt create mode 100644 tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.py create mode 100644 tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.py2 create mode 100644 tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.rb create mode 100644 tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.rs create mode 100644 tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.swift create mode 100644 tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.ts create mode 100644 tests/1501-2000/1958. check-if-move-is-legal/manifest.yaml create mode 100644 tests/1501-2000/1958. check-if-move-is-legal/sol.cpp create mode 100644 tests/1501-2000/1958. check-if-move-is-legal/sol.cs create mode 100644 tests/1501-2000/1958. check-if-move-is-legal/sol.dart create mode 100644 tests/1501-2000/1958. check-if-move-is-legal/sol.go create mode 100644 tests/1501-2000/1958. check-if-move-is-legal/sol.java create mode 100644 tests/1501-2000/1958. check-if-move-is-legal/sol.kt create mode 100644 tests/1501-2000/1958. check-if-move-is-legal/sol.py create mode 100644 tests/1501-2000/1958. check-if-move-is-legal/sol.py2 create mode 100644 tests/1501-2000/1958. check-if-move-is-legal/sol.rb create mode 100644 tests/1501-2000/1958. check-if-move-is-legal/sol.rs create mode 100644 tests/1501-2000/1958. check-if-move-is-legal/sol.swift create mode 100644 tests/1501-2000/1958. check-if-move-is-legal/sol.ts create mode 100644 tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/manifest.yaml create mode 100644 tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.cpp create mode 100644 tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.cs create mode 100644 tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.dart create mode 100644 tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.go create mode 100644 tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.java create mode 100644 tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.kt create mode 100644 tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.py create mode 100644 tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.py2 create mode 100644 tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.rb create mode 100644 tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.rs create mode 100644 tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.swift create mode 100644 tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.ts create mode 100644 tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/manifest.yaml create mode 100644 tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.cpp create mode 100644 tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.cs create mode 100644 tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.dart create mode 100644 tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.go create mode 100644 tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.java create mode 100644 tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.kt create mode 100644 tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.py create mode 100644 tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.py2 create mode 100644 tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.rb create mode 100644 tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.rs create mode 100644 tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.swift create mode 100644 tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.ts create mode 100644 tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/manifest.yaml create mode 100644 tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.cpp create mode 100644 tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.cs create mode 100644 tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.dart create mode 100644 tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.go create mode 100644 tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.java create mode 100644 tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.kt create mode 100644 tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.py create mode 100644 tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.py2 create mode 100644 tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.rb create mode 100644 tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.rs create mode 100644 tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.swift create mode 100644 tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.ts create mode 100644 tests/1501-2000/1962. remove-stones-to-minimize-the-total/manifest.yaml create mode 100644 tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.cpp create mode 100644 tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.cs create mode 100644 tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.dart create mode 100644 tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.go create mode 100644 tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.java create mode 100644 tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.kt create mode 100644 tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.py create mode 100644 tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.py2 create mode 100644 tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.rb create mode 100644 tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.rs create mode 100644 tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.swift create mode 100644 tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.ts create mode 100644 tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/manifest.yaml create mode 100644 tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.cpp create mode 100644 tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.cs create mode 100644 tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.dart create mode 100644 tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.go create mode 100644 tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.java create mode 100644 tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.kt create mode 100644 tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.py create mode 100644 tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.py2 create mode 100644 tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.rb create mode 100644 tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.rs create mode 100644 tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.swift create mode 100644 tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.ts create mode 100644 tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/manifest.yaml create mode 100644 tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.cpp create mode 100644 tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.cs create mode 100644 tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.dart create mode 100644 tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.go create mode 100644 tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.java create mode 100644 tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.kt create mode 100644 tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.py create mode 100644 tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.py2 create mode 100644 tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.rb create mode 100644 tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.rs create mode 100644 tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.swift create mode 100644 tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.ts create mode 100644 tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/manifest.yaml create mode 100644 tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.cpp create mode 100644 tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.cs create mode 100644 tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.dart create mode 100644 tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.go create mode 100644 tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.java create mode 100644 tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.kt create mode 100644 tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.py create mode 100644 tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.py2 create mode 100644 tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.rb create mode 100644 tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.rs create mode 100644 tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.swift create mode 100644 tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.ts create mode 100644 tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/manifest.yaml create mode 100644 tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.cpp create mode 100644 tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.cs create mode 100644 tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.dart create mode 100644 tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.go create mode 100644 tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.java create mode 100644 tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.kt create mode 100644 tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.py create mode 100644 tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.py2 create mode 100644 tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.rb create mode 100644 tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.rs create mode 100644 tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.swift create mode 100644 tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.ts create mode 100644 tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/manifest.yaml create mode 100644 tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.cpp create mode 100644 tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.cs create mode 100644 tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.dart create mode 100644 tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.go create mode 100644 tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.java create mode 100644 tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.kt create mode 100644 tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.py create mode 100644 tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.py2 create mode 100644 tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.rb create mode 100644 tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.rs create mode 100644 tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.swift create mode 100644 tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.ts create mode 100644 tests/1501-2000/1970. last-day-where-you-can-still-cross/manifest.yaml create mode 100644 tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.cpp create mode 100644 tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.cs create mode 100644 tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.dart create mode 100644 tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.go create mode 100644 tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.java create mode 100644 tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.kt create mode 100644 tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.py create mode 100644 tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.py2 create mode 100644 tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.rb create mode 100644 tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.rs create mode 100644 tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.swift create mode 100644 tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.ts create mode 100644 tests/1501-2000/1971. find-if-path-exists-in-graph/manifest.yaml create mode 100644 tests/1501-2000/1971. find-if-path-exists-in-graph/sol.cpp create mode 100644 tests/1501-2000/1971. find-if-path-exists-in-graph/sol.cs create mode 100644 tests/1501-2000/1971. find-if-path-exists-in-graph/sol.dart create mode 100644 tests/1501-2000/1971. find-if-path-exists-in-graph/sol.go create mode 100644 tests/1501-2000/1971. find-if-path-exists-in-graph/sol.java create mode 100644 tests/1501-2000/1971. find-if-path-exists-in-graph/sol.kt create mode 100644 tests/1501-2000/1971. find-if-path-exists-in-graph/sol.py create mode 100644 tests/1501-2000/1971. find-if-path-exists-in-graph/sol.py2 create mode 100644 tests/1501-2000/1971. find-if-path-exists-in-graph/sol.rb create mode 100644 tests/1501-2000/1971. find-if-path-exists-in-graph/sol.rs create mode 100644 tests/1501-2000/1971. find-if-path-exists-in-graph/sol.swift create mode 100644 tests/1501-2000/1971. find-if-path-exists-in-graph/sol.ts create mode 100644 tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/manifest.yaml create mode 100644 tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.cpp create mode 100644 tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.cs create mode 100644 tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.dart create mode 100644 tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.go create mode 100644 tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.java create mode 100644 tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.kt create mode 100644 tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.py create mode 100644 tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.py2 create mode 100644 tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.rb create mode 100644 tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.rs create mode 100644 tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.swift create mode 100644 tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.ts create mode 100644 tests/1501-2000/1975. maximum-matrix-sum/manifest.yaml create mode 100644 tests/1501-2000/1975. maximum-matrix-sum/sol.cpp create mode 100644 tests/1501-2000/1975. maximum-matrix-sum/sol.cs create mode 100644 tests/1501-2000/1975. maximum-matrix-sum/sol.dart create mode 100644 tests/1501-2000/1975. maximum-matrix-sum/sol.go create mode 100644 tests/1501-2000/1975. maximum-matrix-sum/sol.java create mode 100644 tests/1501-2000/1975. maximum-matrix-sum/sol.kt create mode 100644 tests/1501-2000/1975. maximum-matrix-sum/sol.py create mode 100644 tests/1501-2000/1975. maximum-matrix-sum/sol.py2 create mode 100644 tests/1501-2000/1975. maximum-matrix-sum/sol.rb create mode 100644 tests/1501-2000/1975. maximum-matrix-sum/sol.rs create mode 100644 tests/1501-2000/1975. maximum-matrix-sum/sol.swift create mode 100644 tests/1501-2000/1975. maximum-matrix-sum/sol.ts create mode 100644 tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/manifest.yaml create mode 100644 tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.cpp create mode 100644 tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.cs create mode 100644 tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.dart create mode 100644 tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.go create mode 100644 tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.java create mode 100644 tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.kt create mode 100644 tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.py create mode 100644 tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.py2 create mode 100644 tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.rb create mode 100644 tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.rs create mode 100644 tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.swift create mode 100644 tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.ts create mode 100644 tests/1501-2000/1977. number-of-ways-to-separate-numbers/manifest.yaml create mode 100644 tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.cpp create mode 100644 tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.cs create mode 100644 tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.dart create mode 100644 tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.go create mode 100644 tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.java create mode 100644 tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.kt create mode 100644 tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.py create mode 100644 tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.py2 create mode 100644 tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.rb create mode 100644 tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.rs create mode 100644 tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.swift create mode 100644 tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.ts create mode 100644 tests/1501-2000/1979. find-greatest-common-divisor-of-array/manifest.yaml create mode 100644 tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.cpp create mode 100644 tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.cs create mode 100644 tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.dart create mode 100644 tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.go create mode 100644 tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.java create mode 100644 tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.kt create mode 100644 tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.py create mode 100644 tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.py2 create mode 100644 tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.rb create mode 100644 tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.rs create mode 100644 tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.swift create mode 100644 tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.ts create mode 100644 tests/1501-2000/1980. find-unique-binary-string/manifest.yaml create mode 100644 tests/1501-2000/1980. find-unique-binary-string/sol.cpp create mode 100644 tests/1501-2000/1980. find-unique-binary-string/sol.cs create mode 100644 tests/1501-2000/1980. find-unique-binary-string/sol.dart create mode 100644 tests/1501-2000/1980. find-unique-binary-string/sol.go create mode 100644 tests/1501-2000/1980. find-unique-binary-string/sol.java create mode 100644 tests/1501-2000/1980. find-unique-binary-string/sol.kt create mode 100644 tests/1501-2000/1980. find-unique-binary-string/sol.py create mode 100644 tests/1501-2000/1980. find-unique-binary-string/sol.py2 create mode 100644 tests/1501-2000/1980. find-unique-binary-string/sol.rb create mode 100644 tests/1501-2000/1980. find-unique-binary-string/sol.rs create mode 100644 tests/1501-2000/1980. find-unique-binary-string/sol.swift create mode 100644 tests/1501-2000/1980. find-unique-binary-string/sol.ts create mode 100644 tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/manifest.yaml create mode 100644 tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.cpp create mode 100644 tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.cs create mode 100644 tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.dart create mode 100644 tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.go create mode 100644 tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.java create mode 100644 tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.kt create mode 100644 tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.py create mode 100644 tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.py2 create mode 100644 tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.rb create mode 100644 tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.rs create mode 100644 tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.swift create mode 100644 tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.ts create mode 100644 tests/1501-2000/1982. find-array-given-subset-sums/manifest.yaml create mode 100644 tests/1501-2000/1982. find-array-given-subset-sums/sol.cpp create mode 100644 tests/1501-2000/1982. find-array-given-subset-sums/sol.cs create mode 100644 tests/1501-2000/1982. find-array-given-subset-sums/sol.dart create mode 100644 tests/1501-2000/1982. find-array-given-subset-sums/sol.go create mode 100644 tests/1501-2000/1982. find-array-given-subset-sums/sol.java create mode 100644 tests/1501-2000/1982. find-array-given-subset-sums/sol.kt create mode 100644 tests/1501-2000/1982. find-array-given-subset-sums/sol.py create mode 100644 tests/1501-2000/1982. find-array-given-subset-sums/sol.py2 create mode 100644 tests/1501-2000/1982. find-array-given-subset-sums/sol.rb create mode 100644 tests/1501-2000/1982. find-array-given-subset-sums/sol.rs create mode 100644 tests/1501-2000/1982. find-array-given-subset-sums/sol.swift create mode 100644 tests/1501-2000/1982. find-array-given-subset-sums/sol.ts create mode 100644 tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/manifest.yaml create mode 100644 tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.cpp create mode 100644 tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.cs create mode 100644 tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.dart create mode 100644 tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.go create mode 100644 tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.java create mode 100644 tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.kt create mode 100644 tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.py create mode 100644 tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.py2 create mode 100644 tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.rb create mode 100644 tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.rs create mode 100644 tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.swift create mode 100644 tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.ts create mode 100644 tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/manifest.yaml create mode 100644 tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.cpp create mode 100644 tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.cs create mode 100644 tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.dart create mode 100644 tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.go create mode 100644 tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.java create mode 100644 tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.kt create mode 100644 tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.py create mode 100644 tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.py2 create mode 100644 tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.rb create mode 100644 tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.rs create mode 100644 tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.swift create mode 100644 tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.ts create mode 100644 tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/manifest.yaml create mode 100644 tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.cpp create mode 100644 tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.cs create mode 100644 tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.dart create mode 100644 tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.go create mode 100644 tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.java create mode 100644 tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.kt create mode 100644 tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.py create mode 100644 tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.py2 create mode 100644 tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.rb create mode 100644 tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.rs create mode 100644 tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.swift create mode 100644 tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.ts create mode 100644 tests/1501-2000/1987. number-of-unique-good-subsequences/manifest.yaml create mode 100644 tests/1501-2000/1987. number-of-unique-good-subsequences/sol.cpp create mode 100644 tests/1501-2000/1987. number-of-unique-good-subsequences/sol.cs create mode 100644 tests/1501-2000/1987. number-of-unique-good-subsequences/sol.dart create mode 100644 tests/1501-2000/1987. number-of-unique-good-subsequences/sol.go create mode 100644 tests/1501-2000/1987. number-of-unique-good-subsequences/sol.java create mode 100644 tests/1501-2000/1987. number-of-unique-good-subsequences/sol.kt create mode 100644 tests/1501-2000/1987. number-of-unique-good-subsequences/sol.py create mode 100644 tests/1501-2000/1987. number-of-unique-good-subsequences/sol.py2 create mode 100644 tests/1501-2000/1987. number-of-unique-good-subsequences/sol.rb create mode 100644 tests/1501-2000/1987. number-of-unique-good-subsequences/sol.rs create mode 100644 tests/1501-2000/1987. number-of-unique-good-subsequences/sol.swift create mode 100644 tests/1501-2000/1987. number-of-unique-good-subsequences/sol.ts create mode 100644 tests/1501-2000/1991. find-the-middle-index-in-array/manifest.yaml create mode 100644 tests/1501-2000/1991. find-the-middle-index-in-array/sol.cpp create mode 100644 tests/1501-2000/1991. find-the-middle-index-in-array/sol.cs create mode 100644 tests/1501-2000/1991. find-the-middle-index-in-array/sol.dart create mode 100644 tests/1501-2000/1991. find-the-middle-index-in-array/sol.go create mode 100644 tests/1501-2000/1991. find-the-middle-index-in-array/sol.java create mode 100644 tests/1501-2000/1991. find-the-middle-index-in-array/sol.kt create mode 100644 tests/1501-2000/1991. find-the-middle-index-in-array/sol.py create mode 100644 tests/1501-2000/1991. find-the-middle-index-in-array/sol.py2 create mode 100644 tests/1501-2000/1991. find-the-middle-index-in-array/sol.rb create mode 100644 tests/1501-2000/1991. find-the-middle-index-in-array/sol.rs create mode 100644 tests/1501-2000/1991. find-the-middle-index-in-array/sol.swift create mode 100644 tests/1501-2000/1991. find-the-middle-index-in-array/sol.ts create mode 100644 tests/1501-2000/1992. find-all-groups-of-farmland/manifest.yaml create mode 100644 tests/1501-2000/1992. find-all-groups-of-farmland/sol.cpp create mode 100644 tests/1501-2000/1992. find-all-groups-of-farmland/sol.cs create mode 100644 tests/1501-2000/1992. find-all-groups-of-farmland/sol.dart create mode 100644 tests/1501-2000/1992. find-all-groups-of-farmland/sol.go create mode 100644 tests/1501-2000/1992. find-all-groups-of-farmland/sol.java create mode 100644 tests/1501-2000/1992. find-all-groups-of-farmland/sol.kt create mode 100644 tests/1501-2000/1992. find-all-groups-of-farmland/sol.py create mode 100644 tests/1501-2000/1992. find-all-groups-of-farmland/sol.py2 create mode 100644 tests/1501-2000/1992. find-all-groups-of-farmland/sol.rb create mode 100644 tests/1501-2000/1992. find-all-groups-of-farmland/sol.rs create mode 100644 tests/1501-2000/1992. find-all-groups-of-farmland/sol.swift create mode 100644 tests/1501-2000/1992. find-all-groups-of-farmland/sol.ts create mode 100644 tests/1501-2000/1994. the-number-of-good-subsets/manifest.yaml create mode 100644 tests/1501-2000/1994. the-number-of-good-subsets/sol.cpp create mode 100644 tests/1501-2000/1994. the-number-of-good-subsets/sol.cs create mode 100644 tests/1501-2000/1994. the-number-of-good-subsets/sol.dart create mode 100644 tests/1501-2000/1994. the-number-of-good-subsets/sol.go create mode 100644 tests/1501-2000/1994. the-number-of-good-subsets/sol.java create mode 100644 tests/1501-2000/1994. the-number-of-good-subsets/sol.kt create mode 100644 tests/1501-2000/1994. the-number-of-good-subsets/sol.py create mode 100644 tests/1501-2000/1994. the-number-of-good-subsets/sol.py2 create mode 100644 tests/1501-2000/1994. the-number-of-good-subsets/sol.rb create mode 100644 tests/1501-2000/1994. the-number-of-good-subsets/sol.rs create mode 100644 tests/1501-2000/1994. the-number-of-good-subsets/sol.swift create mode 100644 tests/1501-2000/1994. the-number-of-good-subsets/sol.ts create mode 100644 tests/1501-2000/1995. count-special-quadruplets/manifest.yaml create mode 100644 tests/1501-2000/1995. count-special-quadruplets/sol.cpp create mode 100644 tests/1501-2000/1995. count-special-quadruplets/sol.cs create mode 100644 tests/1501-2000/1995. count-special-quadruplets/sol.dart create mode 100644 tests/1501-2000/1995. count-special-quadruplets/sol.go create mode 100644 tests/1501-2000/1995. count-special-quadruplets/sol.java create mode 100644 tests/1501-2000/1995. count-special-quadruplets/sol.kt create mode 100644 tests/1501-2000/1995. count-special-quadruplets/sol.py create mode 100644 tests/1501-2000/1995. count-special-quadruplets/sol.py2 create mode 100644 tests/1501-2000/1995. count-special-quadruplets/sol.rb create mode 100644 tests/1501-2000/1995. count-special-quadruplets/sol.rs create mode 100644 tests/1501-2000/1995. count-special-quadruplets/sol.swift create mode 100644 tests/1501-2000/1995. count-special-quadruplets/sol.ts create mode 100644 tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/manifest.yaml create mode 100644 tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.cpp create mode 100644 tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.cs create mode 100644 tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.dart create mode 100644 tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.go create mode 100644 tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.java create mode 100644 tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.kt create mode 100644 tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.py create mode 100644 tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.py2 create mode 100644 tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.rb create mode 100644 tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.rs create mode 100644 tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.swift create mode 100644 tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.ts create mode 100644 tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/manifest.yaml create mode 100644 tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.cpp create mode 100644 tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.cs create mode 100644 tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.dart create mode 100644 tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.go create mode 100644 tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.java create mode 100644 tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.kt create mode 100644 tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.py create mode 100644 tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.py2 create mode 100644 tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.rb create mode 100644 tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.rs create mode 100644 tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.swift create mode 100644 tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.ts create mode 100644 tests/1501-2000/1998. gcd-sort-of-an-array/manifest.yaml create mode 100644 tests/1501-2000/1998. gcd-sort-of-an-array/sol.cpp create mode 100644 tests/1501-2000/1998. gcd-sort-of-an-array/sol.cs create mode 100644 tests/1501-2000/1998. gcd-sort-of-an-array/sol.dart create mode 100644 tests/1501-2000/1998. gcd-sort-of-an-array/sol.go create mode 100644 tests/1501-2000/1998. gcd-sort-of-an-array/sol.java create mode 100644 tests/1501-2000/1998. gcd-sort-of-an-array/sol.kt create mode 100644 tests/1501-2000/1998. gcd-sort-of-an-array/sol.py create mode 100644 tests/1501-2000/1998. gcd-sort-of-an-array/sol.py2 create mode 100644 tests/1501-2000/1998. gcd-sort-of-an-array/sol.rb create mode 100644 tests/1501-2000/1998. gcd-sort-of-an-array/sol.rs create mode 100644 tests/1501-2000/1998. gcd-sort-of-an-array/sol.swift create mode 100644 tests/1501-2000/1998. gcd-sort-of-an-array/sol.ts create mode 100644 tests/1501-2000/2000. reverse-prefix-of-word/manifest.yaml create mode 100644 tests/1501-2000/2000. reverse-prefix-of-word/sol.cpp create mode 100644 tests/1501-2000/2000. reverse-prefix-of-word/sol.cs create mode 100644 tests/1501-2000/2000. reverse-prefix-of-word/sol.dart create mode 100644 tests/1501-2000/2000. reverse-prefix-of-word/sol.go create mode 100644 tests/1501-2000/2000. reverse-prefix-of-word/sol.java create mode 100644 tests/1501-2000/2000. reverse-prefix-of-word/sol.kt create mode 100644 tests/1501-2000/2000. reverse-prefix-of-word/sol.py create mode 100644 tests/1501-2000/2000. reverse-prefix-of-word/sol.py2 create mode 100644 tests/1501-2000/2000. reverse-prefix-of-word/sol.rb create mode 100644 tests/1501-2000/2000. reverse-prefix-of-word/sol.rs create mode 100644 tests/1501-2000/2000. reverse-prefix-of-word/sol.swift create mode 100644 tests/1501-2000/2000. reverse-prefix-of-word/sol.ts create mode 100644 tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/manifest.yaml create mode 100644 tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.cpp create mode 100644 tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.cs create mode 100644 tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.dart create mode 100644 tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.go create mode 100644 tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.java create mode 100644 tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.kt create mode 100644 tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.py create mode 100644 tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.py2 create mode 100644 tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.rb create mode 100644 tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.rs create mode 100644 tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.swift create mode 100644 tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.ts create mode 100644 tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/manifest.yaml create mode 100644 tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.cpp create mode 100644 tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.cs create mode 100644 tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.dart create mode 100644 tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.go create mode 100644 tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.java create mode 100644 tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.kt create mode 100644 tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.py create mode 100644 tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.py2 create mode 100644 tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.rb create mode 100644 tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.rs create mode 100644 tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.swift create mode 100644 tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.ts create mode 100644 tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/manifest.yaml create mode 100644 tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.cpp create mode 100644 tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.cs create mode 100644 tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.dart create mode 100644 tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.go create mode 100644 tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.java create mode 100644 tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.kt create mode 100644 tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.py create mode 100644 tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.py2 create mode 100644 tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.rb create mode 100644 tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.rs create mode 100644 tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.swift create mode 100644 tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.ts create mode 100644 tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/manifest.yaml create mode 100644 tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.cpp create mode 100644 tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.cs create mode 100644 tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.dart create mode 100644 tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.go create mode 100644 tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.java create mode 100644 tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.kt create mode 100644 tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.py create mode 100644 tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.py2 create mode 100644 tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.rb create mode 100644 tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.rs create mode 100644 tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.swift create mode 100644 tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.ts create mode 100644 tests/2001-2500/2007. find-original-array-from-doubled-array/manifest.yaml create mode 100644 tests/2001-2500/2007. find-original-array-from-doubled-array/sol.cpp create mode 100644 tests/2001-2500/2007. find-original-array-from-doubled-array/sol.cs create mode 100644 tests/2001-2500/2007. find-original-array-from-doubled-array/sol.dart create mode 100644 tests/2001-2500/2007. find-original-array-from-doubled-array/sol.go create mode 100644 tests/2001-2500/2007. find-original-array-from-doubled-array/sol.java create mode 100644 tests/2001-2500/2007. find-original-array-from-doubled-array/sol.kt create mode 100644 tests/2001-2500/2007. find-original-array-from-doubled-array/sol.py create mode 100644 tests/2001-2500/2007. find-original-array-from-doubled-array/sol.py2 create mode 100644 tests/2001-2500/2007. find-original-array-from-doubled-array/sol.rb create mode 100644 tests/2001-2500/2007. find-original-array-from-doubled-array/sol.rs create mode 100644 tests/2001-2500/2007. find-original-array-from-doubled-array/sol.swift create mode 100644 tests/2001-2500/2007. find-original-array-from-doubled-array/sol.ts create mode 100644 tests/2001-2500/2008. maximum-earnings-from-taxi/manifest.yaml create mode 100644 tests/2001-2500/2008. maximum-earnings-from-taxi/sol.cpp create mode 100644 tests/2001-2500/2008. maximum-earnings-from-taxi/sol.cs create mode 100644 tests/2001-2500/2008. maximum-earnings-from-taxi/sol.dart create mode 100644 tests/2001-2500/2008. maximum-earnings-from-taxi/sol.go create mode 100644 tests/2001-2500/2008. maximum-earnings-from-taxi/sol.java create mode 100644 tests/2001-2500/2008. maximum-earnings-from-taxi/sol.kt create mode 100644 tests/2001-2500/2008. maximum-earnings-from-taxi/sol.py create mode 100644 tests/2001-2500/2008. maximum-earnings-from-taxi/sol.py2 create mode 100644 tests/2001-2500/2008. maximum-earnings-from-taxi/sol.rb create mode 100644 tests/2001-2500/2008. maximum-earnings-from-taxi/sol.rs create mode 100644 tests/2001-2500/2008. maximum-earnings-from-taxi/sol.swift create mode 100644 tests/2001-2500/2008. maximum-earnings-from-taxi/sol.ts create mode 100644 tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/manifest.yaml create mode 100644 tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.cpp create mode 100644 tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.cs create mode 100644 tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.dart create mode 100644 tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.go create mode 100644 tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.java create mode 100644 tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.kt create mode 100644 tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.py create mode 100644 tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.py2 create mode 100644 tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.rb create mode 100644 tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.rs create mode 100644 tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.swift create mode 100644 tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.ts create mode 100644 tests/2001-2500/2011. final-value-of-variable-after-performing-operations/manifest.yaml create mode 100644 tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.cpp create mode 100644 tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.cs create mode 100644 tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.dart create mode 100644 tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.go create mode 100644 tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.java create mode 100644 tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.kt create mode 100644 tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.py create mode 100644 tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.py2 create mode 100644 tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.rb create mode 100644 tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.rs create mode 100644 tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.swift create mode 100644 tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.ts create mode 100644 tests/2001-2500/2012. sum-of-beauty-in-the-array/manifest.yaml create mode 100644 tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.cpp create mode 100644 tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.cs create mode 100644 tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.dart create mode 100644 tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.go create mode 100644 tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.java create mode 100644 tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.kt create mode 100644 tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.py create mode 100644 tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.py2 create mode 100644 tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.rb create mode 100644 tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.rs create mode 100644 tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.swift create mode 100644 tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.ts create mode 100644 tests/2001-2500/2014. longest-subsequence-repeated-k-times/manifest.yaml create mode 100644 tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.cpp create mode 100644 tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.cs create mode 100644 tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.dart create mode 100644 tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.go create mode 100644 tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.java create mode 100644 tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.kt create mode 100644 tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.py create mode 100644 tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.py2 create mode 100644 tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.rb create mode 100644 tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.rs create mode 100644 tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.swift create mode 100644 tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.ts create mode 100644 tests/2001-2500/2016. maximum-difference-between-increasing-elements/manifest.yaml create mode 100644 tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.cpp create mode 100644 tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.cs create mode 100644 tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.dart create mode 100644 tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.go create mode 100644 tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.java create mode 100644 tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.kt create mode 100644 tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.py create mode 100644 tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.py2 create mode 100644 tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.rb create mode 100644 tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.rs create mode 100644 tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.swift create mode 100644 tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.ts create mode 100644 tests/2001-2500/2017. grid-game/manifest.yaml create mode 100644 tests/2001-2500/2017. grid-game/sol.cpp create mode 100644 tests/2001-2500/2017. grid-game/sol.cs create mode 100644 tests/2001-2500/2017. grid-game/sol.dart create mode 100644 tests/2001-2500/2017. grid-game/sol.go create mode 100644 tests/2001-2500/2017. grid-game/sol.java create mode 100644 tests/2001-2500/2017. grid-game/sol.kt create mode 100644 tests/2001-2500/2017. grid-game/sol.py create mode 100644 tests/2001-2500/2017. grid-game/sol.py2 create mode 100644 tests/2001-2500/2017. grid-game/sol.rb create mode 100644 tests/2001-2500/2017. grid-game/sol.rs create mode 100644 tests/2001-2500/2017. grid-game/sol.swift create mode 100644 tests/2001-2500/2017. grid-game/sol.ts create mode 100644 tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/manifest.yaml create mode 100644 tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.cpp create mode 100644 tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.cs create mode 100644 tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.dart create mode 100644 tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.go create mode 100644 tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.java create mode 100644 tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.kt create mode 100644 tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.py create mode 100644 tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.py2 create mode 100644 tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.rb create mode 100644 tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.rs create mode 100644 tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.swift create mode 100644 tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.ts create mode 100644 tests/2001-2500/2019. the-score-of-students-solving-math-expression/manifest.yaml create mode 100644 tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.cpp create mode 100644 tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.cs create mode 100644 tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.dart create mode 100644 tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.go create mode 100644 tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.java create mode 100644 tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.kt create mode 100644 tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.py create mode 100644 tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.py2 create mode 100644 tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.rb create mode 100644 tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.rs create mode 100644 tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.swift create mode 100644 tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.ts create mode 100644 tests/2001-2500/2022. convert-1d-array-into-2d-array/manifest.yaml create mode 100644 tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.cpp create mode 100644 tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.cs create mode 100644 tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.dart create mode 100644 tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.go create mode 100644 tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.java create mode 100644 tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.kt create mode 100644 tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.py create mode 100644 tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.py2 create mode 100644 tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.rb create mode 100644 tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.rs create mode 100644 tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.swift create mode 100644 tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.ts create mode 100644 tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/manifest.yaml create mode 100644 tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.cpp create mode 100644 tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.cs create mode 100644 tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.dart create mode 100644 tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.go create mode 100644 tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.java create mode 100644 tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.kt create mode 100644 tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.py create mode 100644 tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.py2 create mode 100644 tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.rb create mode 100644 tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.rs create mode 100644 tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.swift create mode 100644 tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.ts create mode 100644 tests/2001-2500/2024. maximize-the-confusion-of-an-exam/manifest.yaml create mode 100644 tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.cpp create mode 100644 tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.cs create mode 100644 tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.dart create mode 100644 tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.go create mode 100644 tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.java create mode 100644 tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.kt create mode 100644 tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.py create mode 100644 tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.py2 create mode 100644 tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.rb create mode 100644 tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.rs create mode 100644 tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.swift create mode 100644 tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.ts diff --git a/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/manifest.yaml b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/manifest.yaml new file mode 100644 index 00000000..35123b7d --- /dev/null +++ b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/manifest.yaml @@ -0,0 +1,204 @@ +entry: + id: 1520 + title: "maximum-number-of-non-overlapping-substrings" + params: + s: + type: string + call: + cpp: "Solution().maxNumOfSubstrings({s})" + rust: "Solution::max_num_of_substrings({s})" + python3: "Solution().maxNumOfSubstrings({s})" + python2: "Solution().maxNumOfSubstrings({s})" + ruby: "max_num_of_substrings({s})" + java: "new Solution().maxNumOfSubstrings({s})" + csharp: "new Solution().MaxNumOfSubstrings({s})" + kotlin: "Solution().maxNumOfSubstrings({s})" + go: "maxNumOfSubstrings({s})" + dart: "Solution().maxNumOfSubstrings({s})" + swift: "Solution().maxNumOfSubstrings({s})" + typescript: "maxNumOfSubstrings({s})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().maxNumOfSubstrings(s, {result})" + checker: | + class Checker: + def maxNumOfSubstrings(self, s, result): + if not isinstance(result, list) or any(not isinstance(x, str) or not x for x in result): + return False + first = {} + last = {} + for i, ch in enumerate(s): + first.setdefault(ch, i) + last[ch] = i + intervals = [] + for ch in first: + left, right = first[ch], last[ch] + ok = True + while True: + old_left, old_right = left, right + for i in range(left, right + 1): + if first[s[i]] < left: + ok = False + break + right = max(right, last[s[i]]) + if not ok: + break + if left == old_left and right == old_right: + break + if ok: + intervals.append((left, right, s[left:right + 1])) + intervals.sort(key=lambda x: (x[1], x[0])) + expected = [] + end = -1 + for left, right, value in intervals: + if left > end: + expected.append(value) + end = right + return sorted(result) == sorted(expected) + +seed: 15201520 + +tests: + - name: example-one + in: + s: "adefaddaccc" + - name: example-two + in: + s: "abbaccd" + - name: all-unique + in: + s: "abcdefghijklmnopqrstuvwxyz" + - name: one-repeated-character + in: + s: "aaaaaa" + - name: two-blocks + in: + s: "aabbcc" + - name: nested-dependencies + in: + s: "cabcccbaa" + - name: crossing-looking-ranges + in: + s: "abacbadeaf" + - name: single-letter + in: + s: "z" + - name: two-letters + in: + s: "az" + - name: repeated-endpoints + in: + s: "abcaabc" + - name: isolated-middle + in: + s: "xxayybz" + - name: full-closure + in: + s: "abccba" + - name: many-singletons + in: + s: "abcdefghijklmnopqrst" + - name: alternating-two + in: + s: "abababab" + - name: alternating-three + in: + s: "abcabcabc" + - name: long-first-last + in: + s: "abacabadabacaba" + - name: disjoint-runs + in: + s: "aaabbbcccdddeee" + - name: one-wide-and-singletons + in: + s: "abacdefghijak" + - name: reverse-alphabet + in: + s: "zyxwvutsrqponmlkjihgfedcba" + - name: sparse-duplicates + in: + s: "qwertyqwerty" + - name: closure-chain + in: + s: "abcbacdefed" + - name: repeated-prefix + in: + s: "abcabcx" + - name: repeated-suffix + in: + s: "xabcabc" + - name: palindrome + in: + s: "abccbaabccba" + - name: all-equal-long + in: + s: "mmmmmmmmmmmmmmmm" + - name: disjoint-singletons-with-runs + in: + s: "aabbcddceeffg" + - name: large-alphabet-prefix + in: + s: "abcdefghijklmnopqrstuvwxyza" + - name: overlapping-closures + in: + s: "abacbdcedefg" + - name: alternating-four + in: + s: "abcdabcdabcdabcd" + - name: unique-then-repeat + in: + s: "abcdefghijklmnoapq" + - name: repeat-then-unique + in: + s: "aabcdefghijklmno" + - name: nested-three + in: + s: "abacaba" + - name: separate-pairs + in: + s: "aabbccddee" + - name: mixed-lowercase + in: + s: "kllmnomnoppqrrs" + - name: maximum-small-alphabet + in: + s: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" + - name: generated-random-like + in: + s: + gen: "str" + len: 97 + alphabet: "abcdefgh" + - name: generated-medium + in: + s: + gen: "str" + len: 1000 + alphabet: "abcdefghijkl" + - name: generated-large + in: + s: + gen: "str" + len: 10000 + alphabet: "abcdefghijklmnop" + - name: generated-near-limit + in: + s: + gen: "str" + len: 50000 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: generated-maximum + in: + s: + gen: "str" + len: 100000 + alphabet: "abcdefghijklmnopqrstuvwxyz" diff --git a/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.cpp b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.cpp new file mode 100644 index 00000000..d5fc5a62 --- /dev/null +++ b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + vector maxNumOfSubstrings(string s) { + int n = s.length(); + unordered_map counts; + for (char c : s) counts[c]++; + unordered_map first, last; + for (auto& [k, v] : counts) { + first[k] = s.find(k); + last[k] = s.rfind(k); + } + + vector res; + deque> queue; + + for (auto& [k, v] : counts) { + queue.push_front({first[k], last[k], v}); + int left = INT_MAX; + int right = INT_MIN; + int total = 0; + + for (auto& arr : queue) { + total += arr[2]; + left = min(left, arr[0]); + right = max(right, arr[1]); + if (total == right - left + 1) break; + } + + if (total == right - left + 1) { + res.push_back(s.substr(left, right - left + 1)); + queue.clear(); + } + } + + return res; + } +}; diff --git a/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.cs b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.cs new file mode 100644 index 00000000..d0473a4c --- /dev/null +++ b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.cs @@ -0,0 +1,39 @@ +public class Solution { + public IList MaxNumOfSubstrings(string s) { + int n = s.Length; + var counts = new Dictionary(); + foreach (char c in s) { + counts[c] = counts.GetValueOrDefault(c) + 1; + } + var first = new Dictionary(); + var last = new Dictionary(); + foreach (var k in counts.Keys) { + first[k] = s.IndexOf(k); + last[k] = s.LastIndexOf(k); + } + + var res = new List(); + var queue = new LinkedList(); + + foreach (var k in counts.Keys) { + queue.AddFirst(new int[] {first[k], last[k], counts[k]}); + int left = int.MaxValue; + int right = int.MinValue; + int total = 0; + + foreach (var arr in queue) { + total += arr[2]; + left = Math.Min(left, arr[0]); + right = Math.Max(right, arr[1]); + if (total == right - left + 1) break; + } + + if (total == right - left + 1) { + res.Add(s.Substring(left, right - left + 1)); + queue.Clear(); + } + } + + return res; + } +} diff --git a/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.dart b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.dart new file mode 100644 index 00000000..b6431356 --- /dev/null +++ b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.dart @@ -0,0 +1,42 @@ +class Solution { + List maxNumOfSubstrings(String s) { + int n = s.length; + Map counts = {}; + for (int i = 0; i < s.length; i++) { + String c = s[i]; + counts[c] = (counts[c] ?? 0) + 1; + } + Map first = {}; + Map last = {}; + counts.forEach((k, v) { + first[k] = s.indexOf(k); + last[k] = s.lastIndexOf(k); + }); + + List res = []; + List> queue = []; + + counts.forEach((k, v) { + queue.insert(0, [first[k]!, last[k]!, v]); + int left = 1 << 62; + int right = -(1 << 62); + int total = 0; + + for (var arr in queue) { + total += arr[2]; + if (arr[0] < left) left = arr[0]; + if (arr[1] > right) right = arr[1]; + if (total == right - left + 1) { + break; + } + } + + if (total == right - left + 1) { + res.add(s.substring(left, right + 1)); + queue = []; + } + }); + + return res; + } +} diff --git a/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.go b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.go new file mode 100644 index 00000000..f1c0b5c3 --- /dev/null +++ b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.go @@ -0,0 +1,25 @@ +func maxNumOfSubstrings(s string) []string { + first, last := [26]int{}, [26]int{} + for i := range first { first[i] = len(s) } + for i := 0; i < len(s); i++ { + c := s[i] - 'a' + if i < first[c] { first[c] = i } + last[c] = i + } + answer := []string{} + previousEnd := -1 + for start := 0; start < len(s); start++ { + if first[s[start]-'a'] != start { continue } + end, index, valid := last[s[start]-'a'], start, true + for index <= end { + c := s[index] - 'a' + if first[c] < start { valid = false; break } + if last[c] > end { end = last[c] } + index++ + } + if !valid { continue } + if start > previousEnd { answer = append(answer, s[start:end+1]) } else { answer[len(answer)-1] = s[start:end+1] } + previousEnd = end + } + return answer +} diff --git a/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.java b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.java new file mode 100644 index 00000000..988337d0 --- /dev/null +++ b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.java @@ -0,0 +1,41 @@ +class Solution { + public List maxNumOfSubstrings(String s) { + int n = s.length(); + Map counts = new HashMap<>(); + for (char c : s.toCharArray()) { + counts.put(c, counts.getOrDefault(c, 0) + 1); + } + Map first = new HashMap<>(); + Map last = new HashMap<>(); + for (char c : counts.keySet()) { + first.put(c, s.indexOf(c)); + last.put(c, s.lastIndexOf(c)); + } + + List res = new ArrayList<>(); + Deque queue = new ArrayDeque<>(); + + for (char c : counts.keySet()) { + queue.addFirst(new int[]{first.get(c), last.get(c), counts.get(c)}); + int left = Integer.MAX_VALUE; + int right = Integer.MIN_VALUE; + int total = 0; + + for (int[] arr : queue) { + total += arr[2]; + left = Math.min(left, arr[0]); + right = Math.max(right, arr[1]); + if (total == right - left + 1) { + break; + } + } + + if (total == right - left + 1) { + res.add(s.substring(left, right + 1)); + queue.clear(); + } + } + + return res; + } +} diff --git a/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.kt b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.kt new file mode 100644 index 00000000..3d1046fe --- /dev/null +++ b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.kt @@ -0,0 +1,41 @@ +class Solution { + fun maxNumOfSubstrings(s: String): List { + val n = s.length + val counts = mutableMapOf() + for (c in s) { + counts[c] = counts.getOrDefault(c, 0) + 1 + } + val first = mutableMapOf() + val last = mutableMapOf() + for (k in counts.keys) { + first[k] = s.indexOf(k) + last[k] = s.lastIndexOf(k) + } + + val res = mutableListOf() + val queue = ArrayDeque() + + for (k in counts.keys) { + queue.addFirst(intArrayOf(first[k]!!, last[k]!!, counts[k]!!)) + var left = Int.MAX_VALUE + var right = Int.MIN_VALUE + var total = 0 + + for (arr in queue) { + total += arr[2] + left = minOf(left, arr[0]) + right = maxOf(right, arr[1]) + if (total == right - left + 1) { + break + } + } + + if (total == right - left + 1) { + res.add(s.substring(left, right + 1)) + queue.clear() + } + } + + return res + } +} diff --git a/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.py b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.py new file mode 100644 index 00000000..67a1936c --- /dev/null +++ b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.py @@ -0,0 +1,31 @@ +from collections import Counter, deque +from math import inf +from typing import List + + +class Solution: + def maxNumOfSubstrings(self, s: str) -> List[str]: + n = len(s) + counts = Counter(s) + first = {k: s.find(k) for k in counts} + last = {k: s.rfind(k) for k in counts} + + res = [] + queue = deque() + + for k in counts: + queue.appendleft([first[k], last[k], counts[k]]) + left, right, total = inf, -inf, 0 + + for x, y, z in queue: + total += z + left = min(left, x) + right = max(right, y) + if total == right - left + 1: + break + + if total == right - left + 1: + res.append(s[left : right + 1]) + queue = deque() + + return res diff --git a/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.py2 b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.py2 new file mode 100644 index 00000000..83929ae0 --- /dev/null +++ b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.py2 @@ -0,0 +1,34 @@ +class Solution(object): + def maxNumOfSubstrings(self, s): + n = len(s) + first = [n] * 26 + last = [0] * 26 + for index, char in enumerate(s): + letter = ord(char) - ord('a') + first[letter] = min(first[letter], index) + last[letter] = index + + answer = [] + previous_end = -1 + for start in xrange(n): + if first[ord(s[start]) - ord('a')] != start: + continue + end = last[ord(s[start]) - ord('a')] + index = start + valid = True + while index <= end: + letter = ord(s[index]) - ord('a') + if first[letter] < start: + valid = False + break + end = max(end, last[letter]) + index += 1 + if not valid: + continue + value = s[start:end + 1] + if start > previous_end: + answer.append(value) + else: + answer[-1] = value + previous_end = end + return answer diff --git a/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.rb b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.rb new file mode 100644 index 00000000..1e231299 --- /dev/null +++ b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.rb @@ -0,0 +1,39 @@ +# @param {String} s +# @return {String[]} +def max_num_of_substrings(s) + n = s.length + counts = Hash.new(0) + s.each_char { |c| counts[c] += 1 } + first = {} + last = {} + counts.each_key do |k| + first[k] = s.index(k) + last[k] = s.rindex(k) + end + + res = [] + queue = [] + + counts.each_key do |k| + queue.unshift([first[k], last[k], counts[k]]) + left = Float::INFINITY + right = -Float::INFINITY + total = 0 + + queue.each do |x, y, z| + total += z + left = [left, x].min + right = [right, y].max + if total == right - left + 1 + break + end + end + + if total == right - left + 1 + res << s[left..right] + queue = [] + end + end + + res +end diff --git a/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.rs b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.rs new file mode 100644 index 00000000..546e0b07 --- /dev/null +++ b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.rs @@ -0,0 +1,45 @@ +impl Solution { + pub fn max_num_of_substrings(s: String) -> Vec { + let bytes = s.as_bytes(); + let n = bytes.len(); + let mut first = [n; 26]; + let mut last = [0; 26]; + for (index, &ch) in bytes.iter().enumerate() { + let letter = (ch - b'a') as usize; + first[letter] = first[letter].min(index); + last[letter] = index; + } + + let mut answer = Vec::new(); + let mut previous_end: isize = -1; + for start in 0..n { + if first[(bytes[start] - b'a') as usize] != start { + continue; + } + let mut end = last[(bytes[start] - b'a') as usize]; + let mut index = start; + let mut valid = true; + while index <= end { + let letter = (bytes[index] - b'a') as usize; + if first[letter] < start { + valid = false; + break; + } + end = end.max(last[letter]); + index += 1; + } + if !valid { + continue; + } + let value = s[start..end + 1].to_string(); + if start as isize > previous_end { + answer.push(value); + } else { + answer.pop(); + answer.push(value); + } + previous_end = end as isize; + } + answer + } +} diff --git a/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.swift b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.swift new file mode 100644 index 00000000..61652b8a --- /dev/null +++ b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.swift @@ -0,0 +1,32 @@ +class Solution { + func maxNumOfSubstrings(_ s: String) -> [String] { + let bytes = Array(s.utf8) + let n = bytes.count + var first = Array(repeating: n, count: 26) + var last = Array(repeating: 0, count: 26) + for index in 0.. previousEnd { answer.append(value) } else { answer[answer.count - 1] = value } + previousEnd = end + } + return answer + } +} diff --git a/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.ts b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.ts new file mode 100644 index 00000000..d09dd170 --- /dev/null +++ b/tests/1501-2000/1520. maximum-number-of-non-overlapping-substrings/sol.ts @@ -0,0 +1,39 @@ +function maxNumOfSubstrings(s: string): string[] { + const n = s.length; + const counts: Map = new Map(); + for (const c of s) { + counts.set(c, (counts.get(c) || 0) + 1); + } + const first: Map = new Map(); + const last: Map = new Map(); + for (const k of counts.keys()) { + first.set(k, s.indexOf(k)); + last.set(k, s.lastIndexOf(k)); + } + + const res: string[] = []; + let queue: [number, number, number][] = []; + + for (const k of counts.keys()) { + queue.unshift([first.get(k)!, last.get(k)!, counts.get(k)!]); + let left = Infinity; + let right = -Infinity; + let total = 0; + + for (const [x, y, z] of queue) { + total += z; + left = Math.min(left, x); + right = Math.max(right, y); + if (total === right - left + 1) { + break; + } + } + + if (total === right - left + 1) { + res.push(s.substring(left, right + 1)); + queue = []; + } + } + + return res; +} diff --git a/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/manifest.yaml b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/manifest.yaml new file mode 100644 index 00000000..96779481 --- /dev/null +++ b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/manifest.yaml @@ -0,0 +1,303 @@ +entry: + id: 1521 + title: "find-a-value-of-a-mysterious-function-closest-to-target" + params: + arr: + type: array + items: + type: int + target: + type: int + call: + cpp: "Solution().closestToTarget({arr}, {target})" + rust: "Solution::closest_to_target({arr}, {target})" + python3: "Solution().closestToTarget({arr}, {target})" + python2: "Solution().closestToTarget({arr}, {target})" + ruby: "closest_to_target({arr}, {target})" + java: "new Solution().closestToTarget({arr}, {target})" + csharp: "new Solution().ClosestToTarget({arr}, {target})" + kotlin: "Solution().closestToTarget({arr}, {target})" + go: "closestToTarget({arr}, {target})" + dart: "Solution().closestToTarget({arr}, {target})" + swift: "Solution().closestToTarget({arr}, {target})" + typescript: "closestToTarget({arr}, {target})" +judge: + type: "exact" +limits: + time_ms: 3000 + memory_mb: 512 +oracle: + python3: + call: "Checker().closestToTarget(arr, target, {result})" + checker: | + class Checker: + def closestToTarget(self, arr, target, result): + if not isinstance(result, int) or isinstance(result, bool) or result < 0: + return False + best = 10**18 + active = set() + for value in arr: + current = {value} + for old in active: + current.add(old & value) + active = current + for value2 in active: + best = min(best, abs(value2 - target)) + return result == best +seed: 15211521 +tests: + - name: example-one + in: + arr: [9, 12, 3, 7, 15] + target: 5 + out: 2 + - name: example-two + in: + arr: [1000000, 1000000, 1000000] + target: 1 + out: 999999 + - name: example-three + in: + arr: [1, 2, 4, 8, 16] + target: 0 + out: 0 + - name: single-exact + in: + arr: [37] + target: 37 + out: 0 + - name: single-below + in: + arr: [37] + target: 0 + out: 37 + - name: single-above + in: + arr: [37] + target: 100 + out: 63 + - name: all-equal + in: + arr: [255, 255, 255, 255] + target: 200 + out: 55 + - name: decreasing-bits + in: + arr: [31, 15, 7, 3, 1] + target: 6 + out: 1 + - name: increasing-bits + in: + arr: [1, 3, 7, 15, 31] + target: 14 + out: 1 + - name: zero-target + in: + arr: [8, 4, 2, 1] + target: 0 + out: 0 + - name: target-overall-range + in: + arr: [1, 1, 1] + target: 10000000 + out: 9999999 + - name: adjacent-zero-and + in: + arr: [8, 7] + target: 0 + out: 0 + - name: duplicate-values + in: + arr: [42, 42, 40, 42] + target: 41 + out: 1 + - name: high-values + in: + arr: [1048575, 1048574, 1048572] + target: 1048573 + out: 1 + - name: sparse-bits + in: + arr: [65536, 32768, 16384, 8192] + target: 12345 + out: 4039 + - name: alternating + in: + arr: [170, 85, 170, 85, 170] + target: 80 + out: 5 + - name: mixed-small + in: + arr: [13, 6, 11, 9, 4, 15] + target: 10 + out: 1 + - name: powers-and-mask + in: + arr: [64, 96, 112, 120] + target: 100 + out: 4 + - name: one-bit-values + in: + arr: [2, 2, 4, 8, 16] + target: 3 + out: 1 + - name: all-ones + in: + arr: [1, 1, 1, 1, 1] + target: 0 + out: 1 + - name: wide-spread + in: + arr: [1000000, 524288, 262144, 131072, 65536] + target: 500000 + out: 24288 + - name: short-three + in: + arr: [10, 12, 14] + target: 11 + out: 1 + - name: short-four + in: + arr: [7, 11, 13, 15] + target: 9 + out: 0 + - name: repeated-zero-producing + in: + arr: [3, 4, 12, 5] + target: 2 + out: 1 + - name: near-million + in: + arr: [999999, 999998, 999997] + target: 999996 + out: 0 + - name: binary-boundary + in: + arr: [524287, 524288, 524289] + target: 524288 + out: 0 + - name: long-repeated + in: + arr: [1023, 1022, 1021, 1020, 1023, 1022, 1021, 1020] + target: 1020 + out: 0 + - name: target-between + in: + arr: [48, 56, 60, 62] + target: 59 + out: 1 + - name: isolated-low + in: + arr: [100, 200, 400, 800] + target: 3 + out: 3 + - name: mask-collapse + in: + arr: [255, 240, 15, 3] + target: 17 + out: 2 + - name: ten-values + in: + arr: [31, 30, 28, 24, 16, 1, 3, 7, 15, 31] + target: 20 + out: 4 + - name: max-single + in: + arr: [1000000] + target: 10000000 + out: 9000000 + - name: target-one + in: + arr: [2, 6, 14, 30] + target: 1 + out: 1 + - name: target-max + in: + arr: [1000000, 999999] + target: 10000000 + out: 9000000 + - name: varied-nine + in: + arr: [5, 18, 27, 44, 63, 72, 91, 128, 255] + target: 35 + out: 8 + - name: generator-small + in: + arr: + gen: "array" + len: 1 + of: + gen: "int" + min: 1 + max: 1000000 + distinct: false + sorted: false + elemType: "int" + target: + gen: "int" + min: 0 + max: 10000000 + - name: generator-medium + in: + arr: + gen: "array" + len: 37 + of: + gen: "int" + min: 1 + max: 1000000 + distinct: false + sorted: false + elemType: "int" + target: + gen: "int" + min: 0 + max: 10000000 + - name: generator-large + in: + arr: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000000 + distinct: false + sorted: false + elemType: "int" + target: + gen: "int" + min: 0 + max: 10000000 + - name: generator-near-limit + in: + arr: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 1000000 + distinct: false + sorted: false + elemType: "int" + target: + gen: "int" + min: 0 + max: 10000000 + - name: generator-max-limit + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000 + distinct: false + sorted: false + elemType: "int" + target: + gen: "int" + min: 0 + max: 10000000 diff --git a/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.cpp b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.cpp new file mode 100644 index 00000000..1b50af1b --- /dev/null +++ b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int closestToTarget(vector& arr, int target) { + int n = arr.size(); + int LOG = (int)log2(n) + 1; + vector> st(n, vector(LOG, 0)); + for (int i = 0; i < n; i++) st[i][0] = arr[i]; + for (int j = 1; j < LOG; j++) { + for (int i = 0; i + (1 << j) <= n; i++) { + st[i][j] = st[i][j-1] & st[i + (1 << (j-1))][j-1]; + } + } + vector logs(n + 1, 0); + for (int i = 2; i <= n; i++) logs[i] = logs[i / 2] + 1; + + int res = INT_MAX; + for (int l = 0; l < n; l++) { + int left = l, right = n - 1; + while (left <= right) { + int mid = (left + right) / 2; + int k = logs[mid - l + 1]; + int val = st[l][k] & st[mid - (1 << k) + 1][k]; + res = min(res, abs(val - target)); + if (val >= target) left = mid + 1; + else right = mid - 1; + } + } + return res; + } +}; diff --git a/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.cs b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.cs new file mode 100644 index 00000000..ef2c6d05 --- /dev/null +++ b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.cs @@ -0,0 +1,29 @@ +public class Solution { + public int ClosestToTarget(int[] arr, int target) { + int n = arr.Length; + int LOG = (int)Math.Log(n, 2) + 1; + int[,] st = new int[n, LOG]; + for (int i = 0; i < n; i++) st[i, 0] = arr[i]; + for (int j = 1; j < LOG; j++) { + for (int i = 0; i + (1 << j) <= n; i++) { + st[i, j] = st[i, j-1] & st[i + (1 << (j-1)), j-1]; + } + } + int[] logs = new int[n + 1]; + for (int i = 2; i <= n; i++) logs[i] = logs[i / 2] + 1; + + int res = int.MaxValue; + for (int l = 0; l < n; l++) { + int left = l, right = n - 1; + while (left <= right) { + int mid = (left + right) / 2; + int k = logs[mid - l + 1]; + int val = st[l, k] & st[mid - (1 << k) + 1, k]; + res = Math.Min(res, Math.Abs(val - target)); + if (val >= target) left = mid + 1; + else right = mid - 1; + } + } + return res; + } +} diff --git a/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.dart b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.dart new file mode 100644 index 00000000..0f35d0df --- /dev/null +++ b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.dart @@ -0,0 +1,19 @@ +class Solution { + int closestToTarget(List arr, int target) { + var answer = 1 << 60; + var previous = []; + for (final value in arr) { + final current = [value]; + for (final old in previous) { + final candidate = old & value; + if (candidate != current.last) current.add(candidate); + } + for (final candidate in current) { + final difference = (candidate - target).abs(); + if (difference < answer) answer = difference; + } + previous = current; + } + return answer; + } +} diff --git a/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.go b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.go new file mode 100644 index 00000000..b04bf432 --- /dev/null +++ b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.go @@ -0,0 +1,41 @@ +func closestToTarget(arr []int, target int) int { + n := len(arr) + LOG := int(math.Log2(float64(n))) + 1 + st := make([][]int, n) + for i := range st { + st[i] = make([]int, LOG) + st[i][0] = arr[i] + } + for j := 1; j < LOG; j++ { + for i := 0; i + (1 << j) <= n; i++ { + st[i][j] = st[i][j-1] & st[i + (1 << (j-1))][j-1] + } + } + logs := make([]int, n+1) + for i := 2; i <= n; i++ { + logs[i] = logs[i/2] + 1 + } + + res := int(^uint(0) >> 1) // max int + for l := 0; l < n; l++ { + left, right := l, n-1 + for left <= right { + mid := (left + right) / 2 + k := logs[mid-l+1] + val := st[l][k] & st[mid - (1 << k) + 1][k] + diff := val - target + if diff < 0 { + diff = -diff + } + if diff < res { + res = diff + } + if val >= target { + left = mid + 1 + } else { + right = mid - 1 + } + } + } + return res +} diff --git a/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.java b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.java new file mode 100644 index 00000000..b77bf0fa --- /dev/null +++ b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.java @@ -0,0 +1,29 @@ +class Solution { + public int closestToTarget(int[] arr, int target) { + int n = arr.length; + int LOG = (int)(Math.log(n) / Math.log(2)) + 1; + int[][] st = new int[n][LOG]; + for (int i = 0; i < n; i++) st[i][0] = arr[i]; + for (int j = 1; j < LOG; j++) { + for (int i = 0; i + (1 << j) <= n; i++) { + st[i][j] = st[i][j-1] & st[i + (1 << (j-1))][j-1]; + } + } + int[] logs = new int[n + 1]; + for (int i = 2; i <= n; i++) logs[i] = logs[i / 2] + 1; + + int res = Integer.MAX_VALUE; + for (int l = 0; l < n; l++) { + int left = l, right = n - 1; + while (left <= right) { + int mid = (left + right) / 2; + int k = logs[mid - l + 1]; + int val = st[l][k] & st[mid - (1 << k) + 1][k]; + res = Math.min(res, Math.abs(val - target)); + if (val >= target) left = mid + 1; + else right = mid - 1; + } + } + return res; + } +} diff --git a/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.kt b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.kt new file mode 100644 index 00000000..991420e7 --- /dev/null +++ b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.kt @@ -0,0 +1,17 @@ +class Solution { + fun closestToTarget(arr: IntArray, target: Int): Int { + var answer = Int.MAX_VALUE + var previous = IntArray(0) + for (value in arr) { + val current = ArrayList() + current.add(value) + for (old in previous) { + val candidate = old and value + if (current.last() != candidate) current.add(candidate) + } + for (candidate in current) answer = minOf(answer, kotlin.math.abs(candidate - target)) + previous = current.toIntArray() + } + return answer + } +} diff --git a/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.py b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.py new file mode 100644 index 00000000..f9606507 --- /dev/null +++ b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.py @@ -0,0 +1,30 @@ +class Solution: + def closestToTarget(self, arr: List[int], target: int) -> int: + n = len(arr) + LOG = math.floor(math.log2(n)) + 1 + st = [[0] * LOG for _ in range(n)] + for i in range(n): + st[i][0] = arr[i] + for j in range(1, LOG): + for i in range(n - (1 << j) + 1): + st[i][j] = st[i][j - 1] & st[i + (1 << (j - 1))][j - 1] + logs = [0] * (n + 1) + for i in range(2, n + 1): + logs[i] = logs[i // 2] + 1 + + def query(l, r): + k = logs[r - l + 1] + return st[l][k] & st[r - (1 << k) + 1][k] + + res = float("inf") + for l in range(n): + L, R = l, n - 1 + while L <= R: + mid = (L + R) // 2 + val = query(l, mid) + res = min(res, abs(val - target)) + if val >= target: + L = mid + 1 + else: + R = mid - 1 + return res diff --git a/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.py2 b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.py2 new file mode 100644 index 00000000..c6687844 --- /dev/null +++ b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def closestToTarget(self, arr, target): + answer = 1 << 60 + previous = [] + for value in arr: + current = [value] + for old in previous: + candidate = old & value + if candidate != current[-1]: + current.append(candidate) + for candidate in current: + answer = min(answer, abs(candidate - target)) + previous = current + return answer diff --git a/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.rb b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.rb new file mode 100644 index 00000000..1fe8b0f3 --- /dev/null +++ b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.rb @@ -0,0 +1,37 @@ +# @param {Integer[]} arr +# @param {Integer} target +# @return {Integer} +def closest_to_target(arr, target) + n = arr.length + log = Math.log2(n).floor + 1 + st = Array.new(n) { Array.new(log, 0) } + n.times { |i| st[i][0] = arr[i] } + (1...log).each do |j| + (0..n - (1 << j)).each do |i| + st[i][j] = st[i][j-1] & st[i + (1 << (j-1))][j-1] + end + end + logs = Array.new(n + 1, 0) + (2..n).each { |i| logs[i] = logs[i / 2] + 1 } + query = lambda do |l, r| + k = logs[r - l + 1] + st[l][k] & st[r - (1 << k) + 1][k] + end + + res = 2**31 - 1 + (0...n).each do |l| + left = l + right = n - 1 + while left <= right + mid = (left + right) / 2 + val = query.call(l, mid) + res = [res, (val - target).abs].min + if val >= target + left = mid + 1 + else + right = mid - 1 + end + end + end + res +end diff --git a/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.rs b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.rs new file mode 100644 index 00000000..fd32405b --- /dev/null +++ b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn closest_to_target(arr: Vec, target: i32) -> i32 { + let mut answer = i32::MAX; + let mut previous: Vec = Vec::new(); + for value in arr { + let mut current = vec![value]; + for &old in &previous { + let next = old & value; + if current.last() != Some(&next) { + current.push(next); + } + } + for &value in ¤t { + answer = answer.min((value - target).abs()); + } + previous = current; + } + answer + } +} diff --git a/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.swift b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.swift new file mode 100644 index 00000000..523a3907 --- /dev/null +++ b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func closestToTarget(_ arr: [Int], _ target: Int) -> Int { + var answer = Int.max + var previous: [Int] = [] + for value in arr { + var current = [value] + for old in previous { + let candidate = old & value + if current.last != candidate { current.append(candidate) } + } + for candidate in current { answer = min(answer, abs(candidate - target)) } + previous = current + } + return answer + } +} diff --git a/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.ts b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.ts new file mode 100644 index 00000000..63a1c0ab --- /dev/null +++ b/tests/1501-2000/1521. find-a-value-of-a-mysterious-function-closest-to-target/sol.ts @@ -0,0 +1,30 @@ +function closestToTarget(arr: number[], target: number): number { + const n = arr.length; + const LOG = Math.floor(Math.log2(n)) + 1; + const st: number[][] = Array.from({ length: n }, () => + new Array(LOG).fill(0), + ); + for (let i = 0; i < n; i++) st[i][0] = arr[i]; + for (let j = 1; j < LOG; j++) { + for (let i = 0; i + (1 << j) <= n; i++) { + st[i][j] = st[i][j - 1] & st[i + (1 << (j - 1))][j - 1]; + } + } + const logs: number[] = new Array(n + 1).fill(0); + for (let i = 2; i <= n; i++) logs[i] = logs[Math.floor(i / 2)] + 1; + + let res = Number.MAX_SAFE_INTEGER; + for (let l = 0; l < n; l++) { + let left = l, + right = n - 1; + while (left <= right) { + const mid = Math.floor((left + right) / 2); + const k = logs[mid - l + 1]; + const val = st[l][k] & st[mid - (1 << k) + 1][k]; + res = Math.min(res, Math.abs(val - target)); + if (val >= target) left = mid + 1; + else right = mid - 1; + } + } + return res; +} diff --git a/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/manifest.yaml b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/manifest.yaml new file mode 100644 index 00000000..fc8aedfd --- /dev/null +++ b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/manifest.yaml @@ -0,0 +1,263 @@ +entry: + id: 1523 + title: "count-odd-numbers-in-an-interval-range" + params: + low: + type: int + high: + type: int + call: + cpp: "Solution().countOdds({low}, {high})" + rust: "Solution::count_odds({low}, {high})" + python3: "Solution().countOdds({low}, {high})" + python2: "Solution().countOdds({low}, {high})" + ruby: "count_odds({low}, {high})" + java: "new Solution().countOdds({low}, {high})" + csharp: "new Solution().CountOdds({low}, {high})" + kotlin: "Solution().countOdds({low}, {high})" + go: "countOdds({low}, {high})" + dart: "Solution().countOdds({low}, {high})" + swift: "Solution().countOdds({low}, {high})" + typescript: "countOdds({low}, {high})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().countOdds(low, high, {result})" + checker: | + class Checker: + def countOdds(self, low, high, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + expected = (high + 1) // 2 - low // 2 + return result == expected + +seed: 1523 + +tests: + - name: example-one + in: + low: 3 + high: 7 + out: 3 + - name: example-two + in: + low: 8 + high: 10 + out: 1 + - name: zero-to-zero + in: + low: 0 + high: 0 + out: 0 + - name: zero-to-one + in: + low: 0 + high: 1 + out: 1 + - name: zero-to-two + in: + low: 0 + high: 2 + out: 1 + - name: zero-to-three + in: + low: 0 + high: 3 + out: 2 + - name: even-singleton + in: + low: 2 + high: 2 + out: 0 + - name: odd-singleton + in: + low: 9 + high: 9 + out: 1 + - name: adjacent-even-odd + in: + low: 10 + high: 11 + out: 1 + - name: adjacent-odd-even + in: + low: 11 + high: 12 + out: 1 + - name: two-even-values + in: + low: 10 + high: 12 + out: 1 + - name: two-odd-values + in: + low: 11 + high: 13 + out: 2 + - name: short-even-start + in: + low: 20 + high: 25 + out: 3 + - name: short-odd-start + in: + low: 21 + high: 26 + out: 3 + - name: interval-one-digit + in: + low: 1 + high: 9 + out: 5 + - name: interval-two-digits + in: + low: 10 + high: 99 + out: 45 + - name: interval-three-digits + in: + low: 100 + high: 999 + out: 450 + - name: around-power-boundary + in: + low: 999 + high: 1001 + out: 2 + - name: medium-even-even + in: + low: 1234 + high: 5678 + out: 2222 + - name: medium-odd-odd + in: + low: 1235 + high: 5679 + out: 2223 + - name: medium-even-odd + in: + low: 2468 + high: 13579 + out: 5556 + - name: medium-odd-even + in: + low: 2469 + high: 13578 + out: 5555 + - name: narrow-large-even + in: + low: 100000 + high: 100000 + out: 0 + - name: narrow-large-odd + in: + low: 100001 + high: 100001 + out: 1 + - name: large-symmetric + in: + low: 100000 + high: 200000 + out: 50000 + - name: near-limit-even-even + in: + low: 999999996 + high: 1000000000 + out: 2 + - name: near-limit-even-odd + in: + low: 999999996 + high: 999999999 + out: 2 + - name: near-limit-odd-even + in: + low: 999999997 + high: 1000000000 + out: 2 + - name: near-limit-odd-odd + in: + low: 999999997 + high: 999999999 + out: 2 + - name: full-range + in: + low: 0 + high: 1000000000 + out: 500000000 + - name: high-limit-singleton + in: + low: 1000000000 + high: 1000000000 + out: 0 + - name: high-limit-pair + in: + low: 999999999 + high: 1000000000 + out: 1 + - name: sparse-midrange + in: + low: 400000001 + high: 400000010 + out: 5 + - name: odd-length-interval + in: + low: 500000000 + high: 500000005 + out: 3 + - name: even-length-interval + in: + low: 500000001 + high: 500000006 + out: 3 + - name: generated-max-from-zero + in: + low: 0 + high: + gen: "int" + min: 0 + max: 1000000000 + judge: + type: "exact" + - name: generated-max-from-one + in: + low: 1 + high: + gen: "int" + min: 1 + max: 1000000000 + judge: + type: "exact" + - name: generated-high-from-even + in: + low: 24680 + high: + gen: "int" + min: 24680 + max: 1000000000 + judge: + type: "exact" + - name: generated-high-from-large + in: + low: 500000000 + high: + gen: "int" + min: 500000000 + max: 1000000000 + judge: + type: "exact" + - name: generated-high-limit-range + in: + low: 999999000 + high: + gen: "int" + min: 999999000 + max: 1000000000 + judge: + type: "exact" diff --git a/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.cpp b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.cpp new file mode 100644 index 00000000..6682c3c2 --- /dev/null +++ b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + int countOdds(int low, int high) { + return (high + 1) / 2 - low / 2; + } +}; diff --git a/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.cs b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.cs new file mode 100644 index 00000000..1604dc03 --- /dev/null +++ b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.cs @@ -0,0 +1,5 @@ +public class Solution { + public int CountOdds(int low, int high) { + return (high + 1) / 2 - low / 2; + } +} diff --git a/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.dart b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.dart new file mode 100644 index 00000000..67e8b969 --- /dev/null +++ b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.dart @@ -0,0 +1,5 @@ +class Solution { + int countOdds(int low, int high) { + return (high + 1) ~/ 2 - low ~/ 2; + } +} diff --git a/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.go b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.go new file mode 100644 index 00000000..a9b477d8 --- /dev/null +++ b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.go @@ -0,0 +1,3 @@ +func countOdds(low int, high int) int { + return (high + 1) / 2 - low / 2 +} diff --git a/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.java b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.java new file mode 100644 index 00000000..bdeffb37 --- /dev/null +++ b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.java @@ -0,0 +1,5 @@ +class Solution { + public int countOdds(int low, int high) { + return (high + 1) / 2 - low / 2; + } +} diff --git a/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.kt b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.kt new file mode 100644 index 00000000..aa4211e3 --- /dev/null +++ b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.kt @@ -0,0 +1,5 @@ +class Solution { + fun countOdds(low: Int, high: Int): Int { + return (high + 1) / 2 - low / 2 + } +} diff --git a/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.py b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.py new file mode 100644 index 00000000..205a579b --- /dev/null +++ b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.py @@ -0,0 +1,3 @@ +class Solution: + def countOdds(self, low: int, high: int) -> int: + return (high + 1) // 2 - (low // 2) diff --git a/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.py2 b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.py2 new file mode 100644 index 00000000..a006d57c --- /dev/null +++ b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.py2 @@ -0,0 +1,8 @@ +class Solution(object): + def countOdds(self, low, high): + """ + :type low: int + :type high: int + :rtype: int + """ + return (high + 1) // 2 - low // 2 diff --git a/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.rb b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.rb new file mode 100644 index 00000000..12e6702c --- /dev/null +++ b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.rb @@ -0,0 +1,6 @@ +# @param {Integer} low +# @param {Integer} high +# @return {Integer} +def count_odds(low, high) + (high + 1) / 2 - low / 2 +end diff --git a/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.rs b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.rs new file mode 100644 index 00000000..905b7bb4 --- /dev/null +++ b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.rs @@ -0,0 +1,5 @@ +impl Solution { + pub fn count_odds(low: i32, high: i32) -> i32 { + (high + 1) / 2 - low / 2 + } +} diff --git a/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.swift b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.swift new file mode 100644 index 00000000..1753cab4 --- /dev/null +++ b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.swift @@ -0,0 +1,5 @@ +class Solution { + func countOdds(_ low: Int, _ high: Int) -> Int { + return (high + 1) / 2 - low / 2 + } +} diff --git a/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.ts b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.ts new file mode 100644 index 00000000..45ffd56f --- /dev/null +++ b/tests/1501-2000/1523. count-odd-numbers-in-an-interval-range/sol.ts @@ -0,0 +1,3 @@ +function countOdds(low: number, high: number): number { + return Math.floor((high + 1) / 2) - Math.floor(low / 2); +} diff --git a/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/manifest.yaml b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/manifest.yaml new file mode 100644 index 00000000..90f300b1 --- /dev/null +++ b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/manifest.yaml @@ -0,0 +1,363 @@ +entry: + id: 1524 + title: "number-of-sub-arrays-with-odd-sum" + params: + arr: + type: array + items: + type: int + call: + cpp: "Solution().numOfSubarrays({arr})" + rust: "Solution::num_of_subarrays({arr})" + python3: "Solution().numOfSubarrays({arr})" + python2: "Solution().numOfSubarrays({arr})" + ruby: "num_of_subarrays({arr})" + java: "new Solution().numOfSubarrays({arr})" + csharp: "new Solution().NumOfSubarrays({arr})" + kotlin: "Solution().numOfSubarrays({arr})" + go: "numOfSubarrays({arr})" + dart: "Solution().numOfSubarrays({arr})" + swift: "Solution().numOfSubarrays({arr})" + typescript: "numOfSubarrays({arr})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().numOfSubarrays(arr, {result})" + checker: | + class Checker: + def numOfSubarrays(self, arr, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + odd_prefixes = 0 + parity = 0 + for value in arr: + parity ^= value & 1 + if parity: + odd_prefixes += 1 + expected = odd_prefixes * (len(arr) - odd_prefixes + 1) % 1000000007 + return result == expected + +seed: 1524 + +tests: + - name: example-1 + in: + arr: [1, 3, 5] + out: 4 + - name: example-2-all-even + in: + arr: [2, 4, 6] + out: 0 + - name: example-3-mixed + in: + arr: [1, 2, 3, 4, 5, 6, 7] + out: 16 + - name: single-odd + in: + arr: [1] + out: 1 + - name: single-even + in: + arr: [2] + out: 0 + - name: two-odd + in: + arr: [1, 1] + out: 2 + - name: odd-even + in: + arr: [1, 2] + out: 2 + - name: even-odd + in: + arr: [2, 1] + out: 2 + - name: alternating-odds + in: + arr: [1, 2, 1, 2, 1] + out: 9 + - name: all-ones + in: + arr: [1, 1, 1, 1, 1, 1] + out: 12 + - name: all-hundred + in: + arr: [100, 100, 100, 100, 100] + out: 0 + - name: all-ninety-nine + in: + arr: [99, 99, 99, 99] + out: 6 + - name: odd-prefixes + in: + arr: [1, 2, 2, 2] + out: 4 + - name: even-prefixes + in: + arr: [2, 1, 1, 1] + out: 6 + - name: parity-blocks + in: + arr: [2, 2, 1, 2, 2, 1] + out: 12 + - name: alternating-parity-eight + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8] + out: 20 + - name: minimum-values + in: + arr: [1, 1, 2, 2, 1, 2, 1] + out: 15 + - name: maximum-values-mixed + in: + arr: [100, 99, 100, 99, 100, 99] + out: 12 + - name: odd-even-odd + in: + arr: [5, 10, 15] + out: 4 + - name: long-even-prefix + in: + arr: [2, 2, 2, 2, 1] + out: 5 + - name: long-odd-prefix + in: + arr: [1, 2, 2, 2, 2] + out: 5 + - name: varied-small + in: + arr: [3, 8, 7, 4, 9, 2, 6] + out: 15 + - name: varied-medium + in: + arr: [12, 5, 18, 21, 34, 7, 8, 11, 20, 1] + out: 30 + - name: repeated-pattern + in: + arr: [1, 4, 1, 4, 1, 4, 1, 4, 1, 4] + out: 30 + - name: mostly-even + in: + arr: [2, 4, 6, 8, 10, 12, 13, 14] + out: 14 + - name: mostly-odd + in: + arr: [1, 3, 5, 7, 9, 2, 4, 6] + out: 18 + - name: ten-increasing + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + out: 30 + - name: ten-decreasing + in: + arr: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + out: 30 + - name: twenty-all-even + in: + arr: + [ + 2, + 4, + 6, + 8, + 10, + 12, + 14, + 16, + 18, + 20, + 22, + 24, + 26, + 28, + 30, + 32, + 34, + 36, + 38, + 40, + ] + out: 0 + - name: twenty-all-odd + in: + arr: + [ + 1, + 3, + 5, + 7, + 9, + 11, + 13, + 15, + 17, + 19, + 21, + 23, + 25, + 27, + 29, + 31, + 33, + 35, + 37, + 39, + ] + out: 110 + - name: thirty-one-pattern + in: + arr: + [ + 1, + 2, + 2, + 1, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + ] + out: 255 + - name: forty-seven-mixed + in: + arr: + [ + 7, + 14, + 21, + 28, + 35, + 42, + 49, + 56, + 63, + 70, + 77, + 84, + 91, + 98, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + ] + out: 576 + - name: max-length-ones + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1 + distinct: false + sorted: false + elemType: "int" + - name: max-length-even + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: 2 + max: 100 + distinct: false + sorted: false + elemType: "int" + - name: max-length-odd + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: 99 + max: 99 + distinct: false + sorted: false + elemType: "int" + - name: large-alternating + in: + arr: + gen: "array" + len: 99999 + of: + gen: "int" + min: 1 + max: 2 + distinct: false + sorted: false + elemType: "int" + - name: large-high-values + in: + arr: + gen: "array" + len: 75000 + of: + gen: "int" + min: 98 + max: 100 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.cpp b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.cpp new file mode 100644 index 00000000..55656c44 --- /dev/null +++ b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int numOfSubarrays(vector& arr) { + long long oddCount = 0; + long long prefixSum = 0; + const long long mod = 1000000007LL; + for (int a : arr) { + prefixSum += a; + oddCount += prefixSum % 2; + } + oddCount += (arr.size() - oddCount) * oddCount; + return static_cast(oddCount % mod); + } +}; diff --git a/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.cs b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.cs new file mode 100644 index 00000000..4ca61535 --- /dev/null +++ b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public int NumOfSubarrays(int[] arr) { + long oddCount = 0; + long prefixSum = 0; + const long mod = 1000000007L; + foreach (int a in arr) { + prefixSum += a; + oddCount += prefixSum % 2; + } + oddCount += (arr.Length - oddCount) * oddCount; + return (int)(oddCount % mod); + } +} diff --git a/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.dart b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.dart new file mode 100644 index 00000000..177542f5 --- /dev/null +++ b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.dart @@ -0,0 +1,13 @@ +class Solution { + int numOfSubarrays(List arr) { + int oddCount = 0; + int prefixSum = 0; + const int mod = 1000000007; + for (int a in arr) { + prefixSum += a; + oddCount += prefixSum % 2; + } + oddCount += (arr.length - oddCount) * oddCount; + return oddCount % mod; + } +} diff --git a/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.go b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.go new file mode 100644 index 00000000..e9e2f8ba --- /dev/null +++ b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.go @@ -0,0 +1,11 @@ +func numOfSubarrays(arr []int) int { + oddCount := int64(0) + prefixSum := int64(0) + const mod = 1000000007 + for _, a := range arr { + prefixSum += int64(a) + oddCount += prefixSum % 2 + } + oddCount += (int64(len(arr)) - oddCount) * oddCount + return int(oddCount % mod) +} diff --git a/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.java b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.java new file mode 100644 index 00000000..40c0e3c5 --- /dev/null +++ b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int numOfSubarrays(int[] arr) { + long oddCount = 0; + long prefixSum = 0; + int mod = 1_000_000_007; + for (int a : arr) { + prefixSum += a; + oddCount += prefixSum % 2; + } + oddCount += (arr.length - oddCount) * oddCount; + return (int)(oddCount % mod); + } +} diff --git a/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.kt b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.kt new file mode 100644 index 00000000..65cdeb7e --- /dev/null +++ b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun numOfSubarrays(arr: IntArray): Int { + var oddCount = 0L + var prefixSum = 0L + val mod = 1_000_000_007 + for (a in arr) { + prefixSum += a + oddCount += prefixSum % 2 + } + oddCount += (arr.size - oddCount) * oddCount + return (oddCount % mod).toInt() + } +} diff --git a/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.py b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.py new file mode 100644 index 00000000..f744463a --- /dev/null +++ b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.py @@ -0,0 +1,8 @@ +class Solution: + def numOfSubarrays(self, arr: List[int]) -> int: + oddCount, prefixSum, mod = 0, 0, 1_000_000_007 + for a in arr: + prefixSum += a + oddCount += prefixSum % 2 + oddCount += (len(arr) - oddCount) * oddCount + return oddCount % mod diff --git a/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.py2 b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.py2 new file mode 100644 index 00000000..bb0a4274 --- /dev/null +++ b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def numOfSubarrays(self, arr): + """ + :type arr: List[int] + :rtype: int + """ + oddCount = 0 + prefixSum = 0 + mod = 1000000007 + for a in arr: + prefixSum += a + oddCount += prefixSum % 2 + oddCount += (len(arr) - oddCount) * oddCount + return oddCount % mod diff --git a/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.rb b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.rb new file mode 100644 index 00000000..edc1f640 --- /dev/null +++ b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.rb @@ -0,0 +1,13 @@ +# @param {Integer[]} arr +# @return {Integer} +def num_of_subarrays(arr) + odd_count = 0 + prefix_sum = 0 + mod = 1_000_000_007 + arr.each do |a| + prefix_sum += a + odd_count += prefix_sum % 2 + end + odd_count += (arr.length - odd_count) * odd_count + odd_count % mod +end diff --git a/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.rs b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.rs new file mode 100644 index 00000000..25d4a7ee --- /dev/null +++ b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn num_of_subarrays(arr: Vec) -> i32 { + let mut odd_count: i64 = 0; + let mut prefix_sum: i64 = 0; + let mod_val: i64 = 1_000_000_007; + for &a in &arr { + prefix_sum += a as i64; + odd_count += prefix_sum % 2; + } + odd_count += (arr.len() as i64 - odd_count) * odd_count; + (odd_count % mod_val) as i32 + } +} diff --git a/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.swift b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.swift new file mode 100644 index 00000000..11153a34 --- /dev/null +++ b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.swift @@ -0,0 +1,13 @@ +class Solution { + func numOfSubarrays(_ arr: [Int]) -> Int { + var oddCount = 0 + var prefixSum = 0 + let mod = 1_000_000_007 + for a in arr { + prefixSum += a + oddCount += prefixSum % 2 + } + oddCount += (arr.count - oddCount) * oddCount + return oddCount % mod + } +} diff --git a/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.ts b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.ts new file mode 100644 index 00000000..938fb87f --- /dev/null +++ b/tests/1501-2000/1524. number-of-sub-arrays-with-odd-sum/sol.ts @@ -0,0 +1,11 @@ +function numOfSubarrays(arr: number[]): number { + let oddCount = 0; + let prefixSum = 0; + const mod = 1000000007; + for (const a of arr) { + prefixSum += a; + oddCount += prefixSum % 2; + } + oddCount += (arr.length - oddCount) * oddCount; + return oddCount % mod; +} diff --git a/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/manifest.yaml b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/manifest.yaml new file mode 100644 index 00000000..43ba0c00 --- /dev/null +++ b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/manifest.yaml @@ -0,0 +1,225 @@ +entry: + id: 1525 + title: "number-of-good-ways-to-split-a-string" + params: + s: + type: string + call: + cpp: "Solution().numSplits({s})" + rust: "Solution::num_splits({s})" + python3: "Solution().numSplits({s})" + python2: "Solution().numSplits({s})" + ruby: "num_splits({s})" + java: "new Solution().numSplits({s})" + csharp: "new Solution().NumSplits({s})" + kotlin: "Solution().numSplits({s})" + go: "numSplits({s})" + dart: "Solution().numSplits({s})" + swift: "Solution().numSplits({s})" + typescript: "numSplits({s})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().numSplits(s, {result})" + checker: | + class Checker: + def numSplits(self, s, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not isinstance(s, str) or not (1 <= len(s) <= 100000): + return False + if any(c < 'a' or c > 'z' for c in s): + return False + from collections import Counter + left = set() + right = Counter(s) + expected = 0 + for c in s[:-1]: + left.add(c) + right[c] -= 1 + if right[c] == 0: + del right[c] + if len(left) == len(right): + expected += 1 + return result == expected + +seed: 1525 + +tests: + - name: two-equal + in: + s: "aa" + out: 1 + - name: two-different + in: + s: "ab" + out: 1 + - name: three-same + in: + s: "aaa" + out: 2 + - name: repeated-prefix + in: + s: "aab" + out: 1 + - name: alternating-three + in: + s: "aba" + out: 0 + - name: three-distinct + in: + s: "abc" + out: 0 + - name: four-distinct + in: + s: "abcd" + out: 1 + - name: all-same-four + in: + s: "aaaa" + out: 3 + - name: first-repeat + in: + s: "aabc" + out: 0 + - name: two-pairs + in: + s: "aacc" + out: 1 + - name: late-repeat + in: + s: "aaca" + out: 0 + - name: example-one + in: + s: "aacaba" + out: 2 + - name: repeated-alphabet + in: + s: "abcabc" + out: 1 + - name: long-tail-repeat + in: + s: "aaaaab" + out: 1 + - name: alternating-six + in: + s: "ababab" + out: 3 + - name: asymmetric-seven + in: + s: "abacaba" + out: 0 + - name: three-pairs + in: + s: "aabbcc" + out: 1 + - name: all-distinct-five + in: + s: "abcde" + out: 0 + - name: six-distinct-pairs + in: + s: "aabbccddeeff" + out: 1 + - name: all-z-six + in: + s: "zzzzzz" + out: 5 + - name: six-unique-word + in: + s: "qwerty" + out: 1 + - name: alphabet-forward + in: + s: "abcdefghijklmnopqrstuvwxyz" + out: 1 + - name: alphabet-repeated + in: + s: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" + out: 1 + - name: fifty-a-then-b + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + out: 1 + - name: alternating-hundred + in: + s: "abababababababababababababababababababababababababababababababababababababababababababababababababab" + out: 97 + - name: abc-cycle-hundred + in: + s: "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabca" + out: 95 + - name: balanced-pairs + in: + s: "aabbccddeeffgghhiijjkkllmmnn" + out: 1 + - name: five-cycle + in: + s: "abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde" + out: 91 + - name: four-block-hundred + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbcccccccccccccccccccccccccddddddddddddddddddddddddd" + out: 1 + - name: single-character + in: + s: "a" + out: 0 + - name: mirrored-six + in: + s: "aabbaa" + out: 1 + - name: repeated-triple + in: + s: "abcabcabc" + out: 4 + - name: alternating-eight + in: + s: "abababab" + out: 5 + - name: mirrored-three-symbols + in: + s: "abccba" + out: 1 + - name: mixed-six + in: + s: "aabbaba" + out: 3 + - name: generated-short + in: + s: + gen: "str" + len: 1 + alphabet: "abcz" + - name: generated-medium + in: + s: + gen: "str" + len: 257 + alphabet: "abcdef" + - name: generated-large-binary + in: + s: + gen: "str" + len: 100000 + alphabet: "ab" + - name: generated-large-lowercase + in: + s: + gen: "str" + len: 100000 + alphabet: "abcdefghijklm" + - name: generated-large-full-alphabet + in: + s: + gen: "str" + len: 99999 + alphabet: "abcdefghijklmnopqrstuvwxyz" diff --git a/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.cpp b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.cpp new file mode 100644 index 00000000..19cc449f --- /dev/null +++ b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int numSplits(string s) { + int n = s.size(); + int counter = 0; + unordered_map distinct_left, distinct_right; + + for (char c : s) { + distinct_right[c]++; + } + for (int i = 0; i < n - 1; i++) { + char c = s[i]; + distinct_left[c]++; + distinct_right[c]--; + if (distinct_right[c] == 0) { + distinct_right.erase(c); + } + if (distinct_left.size() == distinct_right.size()) { + counter++; + } + } + + return counter; + } +}; diff --git a/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.cs b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.cs new file mode 100644 index 00000000..401a78e3 --- /dev/null +++ b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.cs @@ -0,0 +1,33 @@ +public class Solution { + public int NumSplits(string s) { + int n = s.Length; + int counter = 0; + Dictionary distinct_left = new Dictionary(); + Dictionary distinct_right = new Dictionary(); + + foreach (char c in s) { + if (distinct_right.ContainsKey(c)) { + distinct_right[c]++; + } else { + distinct_right[c] = 1; + } + } + for (int i = 0; i < n - 1; i++) { + char c = s[i]; + if (distinct_left.ContainsKey(c)) { + distinct_left[c]++; + } else { + distinct_left[c] = 1; + } + distinct_right[c]--; + if (distinct_right[c] == 0) { + distinct_right.Remove(c); + } + if (distinct_left.Count == distinct_right.Count) { + counter++; + } + } + + return counter; + } +} diff --git a/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.dart b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.dart new file mode 100644 index 00000000..09f6c824 --- /dev/null +++ b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.dart @@ -0,0 +1,26 @@ +class Solution { + int numSplits(String s) { + int n = s.length; + int counter = 0; + Map distinct_left = {}; + Map distinct_right = {}; + + for (int i = 0; i < n; i++) { + String c = s[i]; + distinct_right[c] = (distinct_right[c] ?? 0) + 1; + } + for (int i = 0; i < n - 1; i++) { + String c = s[i]; + distinct_left[c] = (distinct_left[c] ?? 0) + 1; + distinct_right[c] = (distinct_right[c] ?? 0) - 1; + if (distinct_right[c] == 0) { + distinct_right.remove(c); + } + if (distinct_left.length == distinct_right.length) { + counter++; + } + } + + return counter; + } +} diff --git a/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.go b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.go new file mode 100644 index 00000000..05f53445 --- /dev/null +++ b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.go @@ -0,0 +1,23 @@ +func numSplits(s string) int { + n := len(s) + counter := 0 + distinct_left := make(map[rune]int) + distinct_right := make(map[rune]int) + + for _, c := range s { + distinct_right[c]++ + } + for i := 0; i < n-1; i++ { + c := rune(s[i]) + distinct_left[c]++ + distinct_right[c]-- + if distinct_right[c] == 0 { + delete(distinct_right, c) + } + if len(distinct_left) == len(distinct_right) { + counter++ + } + } + + return counter +} diff --git a/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.java b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.java new file mode 100644 index 00000000..2f9f1ef7 --- /dev/null +++ b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.java @@ -0,0 +1,25 @@ +class Solution { + public int numSplits(String s) { + int n = s.length(); + int counter = 0; + Map distinct_left = new HashMap<>(); + Map distinct_right = new HashMap<>(); + + for (char c : s.toCharArray()) { + distinct_right.put(c, distinct_right.getOrDefault(c, 0) + 1); + } + for (int i = 0; i < n - 1; i++) { + char c = s.charAt(i); + distinct_left.put(c, distinct_left.getOrDefault(c, 0) + 1); + distinct_right.put(c, distinct_right.get(c) - 1); + if (distinct_right.get(c) == 0) { + distinct_right.remove(c); + } + if (distinct_left.size() == distinct_right.size()) { + counter++; + } + } + + return counter; + } +} diff --git a/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.kt b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.kt new file mode 100644 index 00000000..4500216b --- /dev/null +++ b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun numSplits(s: String): Int { + val n = s.length + var counter = 0 + val distinct_left = mutableMapOf() + val distinct_right = mutableMapOf() + + for (c in s) { + distinct_right[c] = (distinct_right[c] ?: 0) + 1 + } + for (i in 0 until n - 1) { + val c = s[i] + distinct_left[c] = (distinct_left[c] ?: 0) + 1 + distinct_right[c] = (distinct_right[c] ?: 0) - 1 + if (distinct_right[c] == 0) { + distinct_right.remove(c) + } + if (distinct_left.size == distinct_right.size) { + counter++ + } + } + + return counter + } +} diff --git a/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.py b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.py new file mode 100644 index 00000000..a2b7ee3b --- /dev/null +++ b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.py @@ -0,0 +1,18 @@ +class Solution: + def numSplits(self, s: str) -> int: + n = len(s) + counter = 0 + distinct_left = defaultdict(int) + distinct_right = defaultdict(int) + + for c in s: + distinct_right[c] += 1 + for i in range(0, n - 1): + distinct_left[s[i]] += 1 + distinct_right[s[i]] -= 1 + if distinct_right[s[i]] == 0: + distinct_right.pop(s[i]) + if len(distinct_left) == len(distinct_right): + counter += 1 + + return counter diff --git a/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.py2 b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.py2 new file mode 100644 index 00000000..d593831d --- /dev/null +++ b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def numSplits(self, s): + """ + :type s: str + :rtype: int + """ + n = len(s) + counter = 0 + distinct_left = {} + distinct_right = {} + + for c in s: + distinct_right[c] = distinct_right.get(c, 0) + 1 + for i in range(0, n - 1): + distinct_left[s[i]] = distinct_left.get(s[i], 0) + 1 + distinct_right[s[i]] -= 1 + if distinct_right[s[i]] == 0: + del distinct_right[s[i]] + if len(distinct_left) == len(distinct_right): + counter += 1 + + return counter diff --git a/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.rb b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.rb new file mode 100644 index 00000000..507af487 --- /dev/null +++ b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.rb @@ -0,0 +1,24 @@ +# @param {String} s +# @return {Integer} +def num_splits(s) + n = s.length + counter = 0 + distinct_left = Hash.new(0) + distinct_right = Hash.new(0) + + s.each_char do |c| + distinct_right[c] += 1 + end + (0...n-1).each do |i| + distinct_left[s[i]] += 1 + distinct_right[s[i]] -= 1 + if distinct_right[s[i]] == 0 + distinct_right.delete(s[i]) + end + if distinct_left.length == distinct_right.length + counter += 1 + end + end + + counter +end diff --git a/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.rs b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.rs new file mode 100644 index 00000000..a08d02cf --- /dev/null +++ b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn num_splits(s: String) -> i32 { + let n = s.len(); + let mut counter = 0; + let mut distinct_left: std::collections::HashMap = std::collections::HashMap::new(); + let mut distinct_right: std::collections::HashMap = std::collections::HashMap::new(); + + for c in s.chars() { + *distinct_right.entry(c).or_insert(0) += 1; + } + for (i, c) in s.chars().enumerate().take(n.saturating_sub(1)) { + *distinct_left.entry(c).or_insert(0) += 1; + *distinct_right.entry(c).or_insert(0) -= 1; + if distinct_right[&c] == 0 { + distinct_right.remove(&c); + } + if distinct_left.len() == distinct_right.len() { + counter += 1; + } + } + + counter + } +} diff --git a/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.swift b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.swift new file mode 100644 index 00000000..64cd9192 --- /dev/null +++ b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func numSplits(_ s: String) -> Int { + let chars = Array(s.utf8) + var left = Array(repeating: 0, count: 26) + var right = Array(repeating: 0, count: 26) + for ch in chars { right[Int(ch - 97)] += 1 } + var leftDistinct = 0 + var rightDistinct = right.filter { $0 > 0 }.count + var answer = 0 + for index in 0..<(chars.count - 1) { + let letter = Int(chars[index] - 97) + if left[letter] == 0 { leftDistinct += 1 } + left[letter] += 1 + right[letter] -= 1 + if right[letter] == 0 { rightDistinct -= 1 } + if leftDistinct == rightDistinct { answer += 1 } + } + return answer + } +} diff --git a/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.ts b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.ts new file mode 100644 index 00000000..e732c7f2 --- /dev/null +++ b/tests/1501-2000/1525. number-of-good-ways-to-split-a-string/sol.ts @@ -0,0 +1,23 @@ +function numSplits(s: string): number { + const n = s.length; + let counter = 0; + const distinct_left: Map = new Map(); + const distinct_right: Map = new Map(); + + for (const c of s) { + distinct_right.set(c, (distinct_right.get(c) ?? 0) + 1); + } + for (let i = 0; i < n - 1; i++) { + const c = s[i]; + distinct_left.set(c, (distinct_left.get(c) ?? 0) + 1); + distinct_right.set(c, (distinct_right.get(c) ?? 0) - 1); + if (distinct_right.get(c) === 0) { + distinct_right.delete(c); + } + if (distinct_left.size === distinct_right.size) { + counter++; + } + } + + return counter; +} diff --git a/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/manifest.yaml b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/manifest.yaml new file mode 100644 index 00000000..363b6234 --- /dev/null +++ b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/manifest.yaml @@ -0,0 +1,273 @@ +entry: + id: 1526 + title: "minimum-number-of-increments-on-subarrays-to-form-a-target-array" + params: + target: + type: array + items: + type: int + call: + cpp: "Solution().minNumberOperations({target})" + rust: "Solution::min_number_operations({target})" + python3: "Solution().minNumberOperations({target})" + python2: "Solution().minNumberOperations({target})" + ruby: "min_number_operations({target})" + java: "new Solution().minNumberOperations({target})" + csharp: "new Solution().MinNumberOperations({target})" + kotlin: "Solution().minNumberOperations({target})" + go: "minNumberOperations({target})" + dart: "Solution().minNumberOperations({target})" + swift: "Solution().minNumberOperations({target})" + typescript: "minNumberOperations({target})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().minNumberOperations(target, {result})" + checker: | + class Checker: + def minNumberOperations(self, target, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + expected = target[0] + for i in range(1, len(target)): + if target[i] > target[i - 1]: + expected += target[i] - target[i - 1] + return result == expected + +seed: 1526 + +tests: + - name: "single-minimum" + in: + target: [1] + out: 1 + - name: "single-maximum" + in: + target: [100000] + out: 100000 + - name: "all-ones" + in: + target: [1, 1, 1, 1, 1] + out: 1 + - name: "flat-large" + in: + target: [100000, 100000, 100000, 100000] + out: 100000 + - name: "strict-increase" + in: + target: [1, 2, 3, 4, 5] + out: 5 + - name: "strict-decrease" + in: + target: [5, 4, 3, 2, 1] + out: 5 + - name: "mountain" + in: + target: [1, 2, 3, 2, 1] + out: 3 + - name: "example-two" + in: + target: [3, 1, 1, 2] + out: 4 + - name: "example-three" + in: + target: [3, 1, 5, 4, 2] + out: 7 + - name: "alternating-low-high" + in: + target: [1, 100, 1, 100, 1] + out: 199 + - name: "alternating-high-low" + in: + target: [100, 1, 100, 1, 100] + out: 298 + - name: "two-peaks" + in: + target: [2, 5, 2, 4, 1] + out: 7 + - name: "plateaus" + in: + target: [4, 4, 2, 2, 7, 7, 3] + out: 9 + - name: "zero-rise-differences" + in: + target: [9, 9, 8, 8, 7, 7] + out: 9 + - name: "sawtooth-small" + in: + target: [1, 3, 2, 4, 3, 5, 4] + out: 7 + - name: "deep-valley" + in: + target: [10, 1, 1, 1, 10] + out: 19 + - name: "one-rise-at-end" + in: + target: [7, 7, 7, 20] + out: 20 + - name: "one-rise-at-start" + in: + target: [20, 7, 7, 7] + out: 20 + - name: "repeated-peaks" + in: + target: [2, 8, 2, 8, 2, 8, 2] + out: 20 + - name: "near-max-rises" + in: + target: [99998, 99999, 100000, 99999, 100000] + out: 100001 + - name: "small-random-one" + in: + target: [6, 2, 9, 4, 8, 1] + out: 17 + - name: "small-random-two" + in: + target: [8, 3, 3, 6, 2, 10] + out: 19 + - name: "small-random-three" + in: + target: [5, 1, 4, 4, 2, 9, 3] + out: 15 + - name: "small-random-four" + in: + target: [2, 7, 1, 6, 5, 9] + out: 16 + - name: "small-random-five" + in: + target: [10, 2, 8, 3, 7, 1, 5] + out: 24 + - name: "two-elements-rise" + in: + target: [4, 9] + out: 9 + - name: "two-elements-fall" + in: + target: [9, 4] + out: 9 + - name: "three-elements-valley" + in: + target: [7, 1, 7] + out: 13 + - name: "three-elements-plateau-rise" + in: + target: [3, 3, 10] + out: 10 + - name: "long-flat-with-spike" + in: + target: [4, 4, 4, 4, 12, 4, 4, 4, 4] + out: 12 + - name: "nested-rises" + in: + target: [1, 5, 2, 6, 3, 7, 4, 8] + out: 17 + - name: "descending-staircase" + in: + target: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + out: 10 + - name: "ascending-staircase" + in: + target: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + out: 10 + - name: "alternating-extremes" + in: + target: [1, 100000, 1, 100000, 1, 100000] + out: 299998 + - name: "max-length-pattern" + in: + target: + [ + 100000, + 99999, + 99998, + 99997, + 99996, + 99995, + 99994, + 99993, + 99992, + 99991, + 99990, + 99989, + 99988, + 99987, + 99986, + 99985, + 99984, + 99983, + 99982, + 99981, + ] + out: 100000 + - name: "generator-uniform-max" + in: + target: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + seed: 152601 + - name: "generator-uniform-small" + in: + target: + gen: "array" + len: 99999 + of: + gen: "int" + min: 1 + max: 10 + distinct: false + sorted: false + elemType: "int" + seed: 152602 + - name: "generator-singleton" + in: + target: + gen: "array" + len: 1 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + seed: 152603 + - name: "generator-short-random" + in: + target: + gen: "array" + len: 257 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + seed: 152604 + - name: "generator-medium-random" + in: + target: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + seed: 152605 diff --git a/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.cpp b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.cpp new file mode 100644 index 00000000..ccbcb7a0 --- /dev/null +++ b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int minNumberOperations(vector& target) { + int total = target[0]; + for (int i = 1; i < target.size(); i++) { + if (target[i] > target[i - 1]) { + total += target[i] - target[i - 1]; + } + } + return total; + } +}; diff --git a/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.cs b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.cs new file mode 100644 index 00000000..77fa2310 --- /dev/null +++ b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.cs @@ -0,0 +1,11 @@ +public class Solution { + public int MinNumberOperations(int[] target) { + int total = target[0]; + for (int i = 1; i < target.Length; i++) { + if (target[i] > target[i - 1]) { + total += target[i] - target[i - 1]; + } + } + return total; + } +} diff --git a/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.dart b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.dart new file mode 100644 index 00000000..563e488c --- /dev/null +++ b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.dart @@ -0,0 +1,11 @@ +class Solution { + int minNumberOperations(List target) { + int total = target[0]; + for (int i = 1; i < target.length; i++) { + if (target[i] > target[i - 1]) { + total += target[i] - target[i - 1]; + } + } + return total; + } +} diff --git a/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.go b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.go new file mode 100644 index 00000000..ee7194ef --- /dev/null +++ b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.go @@ -0,0 +1,9 @@ +func minNumberOperations(target []int) int { + total := target[0] + for i := 1; i < len(target); i++ { + if target[i] > target[i-1] { + total += target[i] - target[i-1] + } + } + return total +} diff --git a/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.java b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.java new file mode 100644 index 00000000..c1774b77 --- /dev/null +++ b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.java @@ -0,0 +1,11 @@ +class Solution { + public int minNumberOperations(int[] target) { + int total = target[0]; + for (int i = 1; i < target.length; i++) { + if (target[i] > target[i - 1]) { + total += target[i] - target[i - 1]; + } + } + return total; + } +} diff --git a/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.kt b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.kt new file mode 100644 index 00000000..a322aab5 --- /dev/null +++ b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.kt @@ -0,0 +1,11 @@ +class Solution { + fun minNumberOperations(target: IntArray): Int { + var total = target[0] + for (i in 1 until target.size) { + if (target[i] > target[i - 1]) { + total += target[i] - target[i - 1] + } + } + return total + } +} diff --git a/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.py b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.py new file mode 100644 index 00000000..6efcd069 --- /dev/null +++ b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.py @@ -0,0 +1,7 @@ +class Solution: + def minNumberOperations(self, target: List[int]) -> int: + sum = target[0] # start with first element + for i in range(1, len(target)): + if target[i] > target[i - 1]: + sum += target[i] - target[i - 1] # add only when value rises + return sum # total operations diff --git a/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.py2 b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.py2 new file mode 100644 index 00000000..24d77e17 --- /dev/null +++ b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def minNumberOperations(self, target): + """ + :type target: List[int] + :rtype: int + """ + total = target[0] + for i in range(1, len(target)): + if target[i] > target[i - 1]: + total += target[i] - target[i - 1] + return total diff --git a/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.rb b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.rb new file mode 100644 index 00000000..86351396 --- /dev/null +++ b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.rb @@ -0,0 +1,11 @@ +# @param {Integer[]} target +# @return {Integer} +def min_number_operations(target) + total = target[0] + (1...target.length).each do |i| + if target[i] > target[i - 1] + total += target[i] - target[i - 1] + end + end + total +end diff --git a/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.rs b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.rs new file mode 100644 index 00000000..3dbdb5ca --- /dev/null +++ b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn min_number_operations(target: Vec) -> i32 { + let mut total = target[0]; + for i in 1..target.len() { + if target[i] > target[i - 1] { + total += target[i] - target[i - 1]; + } + } + total + } +} diff --git a/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.swift b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.swift new file mode 100644 index 00000000..062d4989 --- /dev/null +++ b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.swift @@ -0,0 +1,11 @@ +class Solution { + func minNumberOperations(_ target: [Int]) -> Int { + var total = target[0] + for i in 1.. target[i - 1] { + total += target[i] - target[i - 1] + } + } + return total + } +} diff --git a/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.ts b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.ts new file mode 100644 index 00000000..c5e7b9cc --- /dev/null +++ b/tests/1501-2000/1526. minimum-number-of-increments-on-subarrays-to-form-a-target-array/sol.ts @@ -0,0 +1,9 @@ +function minNumberOperations(target: number[]): number { + let total = target[0]; + for (let i = 1; i < target.length; i++) { + if (target[i] > target[i - 1]) { + total += target[i] - target[i - 1]; + } + } + return total; +} diff --git a/tests/1501-2000/1528. shuffle-string/manifest.yaml b/tests/1501-2000/1528. shuffle-string/manifest.yaml new file mode 100644 index 00000000..d3eff4cf --- /dev/null +++ b/tests/1501-2000/1528. shuffle-string/manifest.yaml @@ -0,0 +1,557 @@ +entry: + id: 1528 + title: "shuffle-string" + params: + s: + type: string + indices: + type: array + items: + type: int + call: + cpp: "Solution().restoreString({s}, {indices})" + rust: "Solution::restore_string({s}, {indices})" + python3: "Solution().restoreString({s}, {indices})" + python2: "Solution().restoreString({s}, {indices})" + ruby: "restore_string({s}, {indices})" + java: "new Solution().restoreString({s}, {indices})" + csharp: "new Solution().RestoreString({s}, {indices})" + kotlin: "Solution().restoreString({s}, {indices})" + go: "restoreString({s}, {indices})" + dart: "Solution().restoreString({s}, {indices})" + swift: "Solution().restoreString({s}, {indices})" + typescript: "restoreString({s}, {indices})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().restoreString(s, indices, {result})" + checker: | + class Checker: + def restoreString(self, s, indices, result): + if not isinstance(result, str): + return False + if len(s) != len(indices) or sorted(indices) != list(range(len(s))): + return False + expected = [''] * len(s) + for ch, pos in zip(s, indices): + expected[pos] = ch + return result == ''.join(expected) + +seed: 1528 + +tests: + - name: example-shuffled + in: + s: "codeleet" + indices: [4, 5, 6, 7, 0, 2, 1, 3] + out: "leetcode" + - name: example-identity + in: + s: "abc" + indices: [0, 1, 2] + out: "abc" + - name: two-characters-swap + in: + s: "ab" + indices: [1, 0] + out: "ba" + - name: one-character + in: + s: "z" + indices: [0] + out: "z" + - name: repeated-letters + in: + s: "aaaaaa" + indices: [5, 4, 3, 2, 1, 0] + out: "aaaaaa" + - name: repeated-pattern + in: + s: "abababab" + indices: [7, 6, 5, 4, 3, 2, 1, 0] + out: "babababa" + - name: reverse-alphabet + in: + s: "zyxwvutsrqponmlkjihgfedcba" + indices: + [ + 25, + 24, + 23, + 22, + 21, + 20, + 19, + 18, + 17, + 16, + 15, + 14, + 13, + 12, + 11, + 10, + 9, + 8, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + 0, + ] + out: "abcdefghijklmnopqrstuvwxyz" + - name: cyclic-left + in: + s: "abcdef" + indices: [5, 0, 1, 2, 3, 4] + out: "bcdefa" + - name: cyclic-right + in: + s: "abcdef" + indices: [1, 2, 3, 4, 5, 0] + out: "fabcde" + - name: even-odd-placement + in: + s: "abcdefgh" + indices: [0, 2, 4, 6, 1, 3, 5, 7] + out: "aebfcgdh" + - name: odd-even-placement + in: + s: "abcdefgh" + indices: [1, 3, 5, 7, 0, 2, 4, 6] + out: "eafbgchd" + - name: pairwise-swaps + in: + s: "abcdefghij" + indices: [1, 0, 3, 2, 5, 4, 7, 6, 9, 8] + out: "badcfehgji" + - name: scattered-ten + in: + s: "helloworld" + indices: [9, 0, 8, 1, 7, 2, 6, 3, 5, 4] + out: "elwrdloolh" + - name: alphabet-mixed + in: + s: "thequickbrownfox" + indices: [9, 0, 10, 5, 2, 14, 8, 3, 12, 1, 15, 7, 4, 11, 6, 13] + out: "hruknqowctefbxio" + - name: palindrome-source + in: + s: "abccba" + indices: [2, 5, 0, 4, 1, 3] + out: "cbaacb" + - name: vowels-consonants + in: + s: "aeiouxyz" + indices: [4, 3, 2, 1, 0, 7, 6, 5] + out: "uoieazyx" + - name: length-eleven + in: + s: "abcdefghijk" + indices: [10, 8, 6, 4, 2, 0, 1, 3, 5, 7, 9] + out: "fgehdicjbka" + - name: length-twelve + in: + s: "abcdefghijkl" + indices: [6, 0, 11, 5, 2, 9, 1, 8, 4, 10, 3, 7] + out: "bgekidalhfjc" + - name: length-thirteen + in: + s: "mnopqrstuvwxy" + indices: [12, 0, 11, 1, 10, 2, 9, 3, 8, 4, 7, 5, 6] + out: "nprtvxywusqom" + - name: length-fourteen + in: + s: "abcdefghijklmn" + indices: [13, 1, 12, 3, 11, 5, 10, 7, 9, 0, 8, 2, 6, 4] + out: "jbldnfmhkigeca" + - name: length-fifteen + in: + s: "abcdefghijklmno" + indices: [7, 14, 0, 6, 13, 1, 5, 12, 2, 4, 11, 3, 10, 9, 8] + out: "cfiljgdaonmkheb" + - name: length-sixteen + in: + s: "abcdefghijklmnop" + indices: [15, 0, 14, 1, 13, 2, 12, 3, 11, 4, 10, 5, 9, 6, 8, 7] + out: "bdfhjlnpomkigeca" + - name: length-seventeen + in: + s: "abcdefghijklmnopq" + indices: [8, 7, 6, 5, 4, 3, 2, 1, 0, 16, 15, 14, 13, 12, 11, 10, 9] + out: "ihgfedcbaqponmlkj" + - name: length-eighteen + in: + s: "abcdefghijklmnopqr" + indices: [2, 5, 8, 11, 14, 17, 1, 4, 7, 10, 13, 16, 0, 3, 6, 9, 12, 15] + out: "mganhboicpjdqkerlf" + - name: length-nineteen + in: + s: "abcdefghijklmnopqrs" + indices: + [18, 0, 17, 1, 16, 2, 15, 3, 14, 4, 13, 5, 12, 6, 11, 7, 10, 8, 9] + out: "bdfhjlnprsqomkigeca" + - name: length-twenty + in: + s: "abcdefghijklmnopqrst" + indices: + [0, 19, 1, 18, 2, 17, 3, 16, 4, 15, 5, 14, 6, 13, 7, 12, 8, 11, 9, 10] + out: "acegikmoqstrpnljhfdb" + - name: duplicate-blocks + in: + s: "zzzaaabbbccc" + indices: [11, 8, 5, 2, 9, 6, 3, 0, 10, 7, 4, 1] + out: "bcabczaczabz" + - name: short-permutation + in: + s: "qwerty" + indices: [4, 2, 5, 1, 3, 0] + out: "yrwtqe" + - name: all-letters-once + in: + s: "abcdefghijklmnopqrstuvwxy" + indices: + [ + 24, + 0, + 23, + 1, + 22, + 2, + 21, + 3, + 20, + 4, + 19, + 5, + 18, + 6, + 17, + 7, + 16, + 8, + 15, + 9, + 14, + 10, + 13, + 11, + 12, + ] + out: "bdfhjlnprtvxywusqomkigeca" + - name: large-identity-100 + in: + s: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv" + indices: + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + 63, + 64, + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + 99, + ] + out: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv" + - name: large-reverse-100 + in: + s: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv" + indices: + [ + 99, + 98, + 97, + 96, + 95, + 94, + 93, + 92, + 91, + 90, + 89, + 88, + 87, + 86, + 85, + 84, + 83, + 82, + 81, + 80, + 79, + 78, + 77, + 76, + 75, + 74, + 73, + 72, + 71, + 70, + 69, + 68, + 67, + 66, + 65, + 64, + 63, + 62, + 61, + 60, + 59, + 58, + 57, + 56, + 55, + 54, + 53, + 52, + 51, + 50, + 49, + 48, + 47, + 46, + 45, + 44, + 43, + 42, + 41, + 40, + 39, + 38, + 37, + 36, + 35, + 34, + 33, + 32, + 31, + 30, + 29, + 28, + 27, + 26, + 25, + 24, + 23, + 22, + 21, + 20, + 19, + 18, + 17, + 16, + 15, + 14, + 13, + 12, + 11, + 10, + 9, + 8, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + 0, + ] + out: "vutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcba" + - name: mixed-case-pattern-lower + in: + s: "mississippi" + indices: [10, 0, 9, 1, 8, 2, 7, 3, 6, 4, 5] + out: "issipipsism" + - name: long-repeated + in: + s: "abcdefghijklmnopqrstuvwxyza" + indices: + [ + 1, + 3, + 5, + 7, + 9, + 11, + 13, + 15, + 17, + 19, + 21, + 23, + 25, + 0, + 2, + 4, + 6, + 8, + 10, + 12, + 14, + 16, + 18, + 20, + 22, + 24, + 26, + ] + out: "naobpcqdresftguhviwjxkylzma" + - name: digits-not-allowed-replaced-by-letters + in: + s: "abcdefghijkl" + indices: [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] + out: "lkjihgfedcba" + - name: three-cycles + in: + s: "abcdefghi" + indices: [3, 4, 5, 0, 1, 2, 8, 6, 7] + out: "defabchig" + - name: sparse-reversal + in: + s: "abcdefghijklmnop" + indices: [4, 5, 6, 7, 0, 1, 2, 3, 12, 13, 14, 15, 8, 9, 10, 11] + out: "efghabcdmnopijkl" + - name: same-letter-permutation + in: + s: "leetcode" + indices: [7, 6, 5, 4, 3, 2, 1, 0] + out: "edocteel" + - name: twenty-six-rotation + in: + s: "abcdefghijklmnopqrstuvwxyz" + indices: + [ + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + ] + out: "nopqrstuvwxyzabcdefghijklm" diff --git a/tests/1501-2000/1528. shuffle-string/sol.cpp b/tests/1501-2000/1528. shuffle-string/sol.cpp new file mode 100644 index 00000000..0063f18a --- /dev/null +++ b/tests/1501-2000/1528. shuffle-string/sol.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + string restoreString(string s, vector& indices) { + string res(indices.size(), ' '); + for (int i = 0; i < indices.size(); i++) { + res[indices[i]] = s[i]; + } + return res; + } +}; diff --git a/tests/1501-2000/1528. shuffle-string/sol.cs b/tests/1501-2000/1528. shuffle-string/sol.cs new file mode 100644 index 00000000..497e4ec0 --- /dev/null +++ b/tests/1501-2000/1528. shuffle-string/sol.cs @@ -0,0 +1,9 @@ +public class Solution { + public string RestoreString(string s, int[] indices) { + char[] res = new char[indices.Length]; + for (int i = 0; i < indices.Length; i++) { + res[indices[i]] = s[i]; + } + return new string(res); + } +} diff --git a/tests/1501-2000/1528. shuffle-string/sol.dart b/tests/1501-2000/1528. shuffle-string/sol.dart new file mode 100644 index 00000000..42b827c5 --- /dev/null +++ b/tests/1501-2000/1528. shuffle-string/sol.dart @@ -0,0 +1,9 @@ +class Solution { + String restoreString(String s, List indices) { + List res = List.filled(indices.length, ''); + for (int i = 0; i < indices.length; i++) { + res[indices[i]] = s[i]; + } + return res.join(); + } +} diff --git a/tests/1501-2000/1528. shuffle-string/sol.go b/tests/1501-2000/1528. shuffle-string/sol.go new file mode 100644 index 00000000..0983e8e9 --- /dev/null +++ b/tests/1501-2000/1528. shuffle-string/sol.go @@ -0,0 +1,7 @@ +func restoreString(s string, indices []int) string { + res := make([]byte, len(indices)) + for i := 0; i < len(indices); i++ { + res[indices[i]] = s[i] + } + return string(res) +} diff --git a/tests/1501-2000/1528. shuffle-string/sol.java b/tests/1501-2000/1528. shuffle-string/sol.java new file mode 100644 index 00000000..595836b3 --- /dev/null +++ b/tests/1501-2000/1528. shuffle-string/sol.java @@ -0,0 +1,9 @@ +class Solution { + public String restoreString(String s, int[] indices) { + char[] res = new char[indices.length]; + for (int i = 0; i < indices.length; i++) { + res[indices[i]] = s.charAt(i); + } + return new String(res); + } +} diff --git a/tests/1501-2000/1528. shuffle-string/sol.kt b/tests/1501-2000/1528. shuffle-string/sol.kt new file mode 100644 index 00000000..79614acc --- /dev/null +++ b/tests/1501-2000/1528. shuffle-string/sol.kt @@ -0,0 +1,9 @@ +class Solution { + fun restoreString(s: String, indices: IntArray): String { + val res = CharArray(indices.size) + for (i in indices.indices) { + res[indices[i]] = s[i] + } + return String(res) + } +} diff --git a/tests/1501-2000/1528. shuffle-string/sol.py b/tests/1501-2000/1528. shuffle-string/sol.py new file mode 100644 index 00000000..4f238a45 --- /dev/null +++ b/tests/1501-2000/1528. shuffle-string/sol.py @@ -0,0 +1,8 @@ +class Solution: + def restoreString(self, s: str, indices: List[int]) -> str: + res = [0] * len(indices) + for i in range(len(indices)): + res[indices[i]] = s[i] + + res = "".join(map(str, res)) + return res diff --git a/tests/1501-2000/1528. shuffle-string/sol.py2 b/tests/1501-2000/1528. shuffle-string/sol.py2 new file mode 100644 index 00000000..c89451cd --- /dev/null +++ b/tests/1501-2000/1528. shuffle-string/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def restoreString(self, s, indices): + """ + :type s: str + :type indices: List[int] + :rtype: str + """ + res = [''] * len(indices) + for i in range(len(indices)): + res[indices[i]] = s[i] + return ''.join(res) diff --git a/tests/1501-2000/1528. shuffle-string/sol.rb b/tests/1501-2000/1528. shuffle-string/sol.rb new file mode 100644 index 00000000..0b1d87e4 --- /dev/null +++ b/tests/1501-2000/1528. shuffle-string/sol.rb @@ -0,0 +1,10 @@ +# @param {String} s +# @param {Integer[]} indices +# @return {String} +def restore_string(s, indices) + res = Array.new(indices.length, '') + indices.each_with_index do |idx, i| + res[idx] = s[i] + end + res.join +end diff --git a/tests/1501-2000/1528. shuffle-string/sol.rs b/tests/1501-2000/1528. shuffle-string/sol.rs new file mode 100644 index 00000000..226e2c72 --- /dev/null +++ b/tests/1501-2000/1528. shuffle-string/sol.rs @@ -0,0 +1,10 @@ +impl Solution { + pub fn restore_string(s: String, indices: Vec) -> String { + let mut res = vec![' '; indices.len()]; + for (i, &idx) in indices.iter().enumerate() { + let c = s.chars().nth(i).unwrap(); + res[idx as usize] = c; + } + res.into_iter().collect() + } +} diff --git a/tests/1501-2000/1528. shuffle-string/sol.swift b/tests/1501-2000/1528. shuffle-string/sol.swift new file mode 100644 index 00000000..13ba7900 --- /dev/null +++ b/tests/1501-2000/1528. shuffle-string/sol.swift @@ -0,0 +1,10 @@ +class Solution { + func restoreString(_ s: String, _ indices: [Int]) -> String { + var res = Array(repeating: Character(" "), count: indices.count) + let chars = Array(s) + for i in 0.. int: + minCount = 0 + flag = 0 + n = len(target) + + for i in range(n): + if target[i] != chr(flag % 2 + ord("0")): + minCount += 1 + flag += 1 + + return minCount diff --git a/tests/1501-2000/1529. minimum-suffix-flips/sol.py2 b/tests/1501-2000/1529. minimum-suffix-flips/sol.py2 new file mode 100644 index 00000000..0821ddc9 --- /dev/null +++ b/tests/1501-2000/1529. minimum-suffix-flips/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def minFlips(self, target): + """ + :type target: str + :rtype: int + """ + minCount = 0 + flag = 0 + n = len(target) + + for i in range(n): + if target[i] != chr(flag % 2 + ord('0')): + minCount += 1 + flag += 1 + + return minCount diff --git a/tests/1501-2000/1529. minimum-suffix-flips/sol.rb b/tests/1501-2000/1529. minimum-suffix-flips/sol.rb new file mode 100644 index 00000000..9d82a36c --- /dev/null +++ b/tests/1501-2000/1529. minimum-suffix-flips/sol.rb @@ -0,0 +1,16 @@ +# @param {String} target +# @return {Integer} +def min_flips(target) + min_count = 0 + flag = 0 + n = target.length + + for i in 0...n + if target[i] != (flag % 2 + 48).chr + min_count += 1 + flag += 1 + end + end + + min_count +end diff --git a/tests/1501-2000/1529. minimum-suffix-flips/sol.rs b/tests/1501-2000/1529. minimum-suffix-flips/sol.rs new file mode 100644 index 00000000..009919be --- /dev/null +++ b/tests/1501-2000/1529. minimum-suffix-flips/sol.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn min_flips(target: String) -> i32 { + let mut min_count = 0; + let mut flag = 0; + let n = target.len(); + let chars: Vec = target.chars().collect(); + + for i in 0..n { + let expected = char::from_u32(48 + (flag % 2) as u32).unwrap(); + if chars[i] != expected { + min_count += 1; + flag += 1; + } + } + + min_count + } +} diff --git a/tests/1501-2000/1529. minimum-suffix-flips/sol.swift b/tests/1501-2000/1529. minimum-suffix-flips/sol.swift new file mode 100644 index 00000000..218bde17 --- /dev/null +++ b/tests/1501-2000/1529. minimum-suffix-flips/sol.swift @@ -0,0 +1,18 @@ +class Solution { + func minFlips(_ target: String) -> Int { + var minCount = 0 + var flag = 0 + let n = target.count + let chars = Array(target) + + for i in 0..> graph; + function dfs = [&](TreeNode* node, TreeNode* parent) { + if (!node) return; + if (parent) { + graph[parent].push_back(node); + graph[node].push_back(parent); + } + dfs(node->left, node); + dfs(node->right, node); + }; + dfs(root, nullptr); + + vector leaves; + for (auto& [node, _] : graph) { + if (!node->left && !node->right) leaves.push_back(node); + } + + int ans = 0; + for (int i = 0; i < leaves.size(); i++) { + TreeNode* leaf = leaves[i]; + queue> q; + unordered_set visited; + q.push({leaf, 0}); + visited.insert(leaf); + + while (!q.empty()) { + auto [node, dist] = q.front(); q.pop(); + if (dist >= distance) continue; + for (auto& nei : graph[node]) { + if (!visited.count(nei)) { + visited.insert(nei); + q.push({nei, dist + 1}); + if (!nei->left && !nei->right) { + auto it = find(leaves.begin(), leaves.end(), nei); + if (it - leaves.begin() > i) ans++; + } + } + } + } + } + return ans; + } +}; diff --git a/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.cs b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.cs new file mode 100644 index 00000000..625c933d --- /dev/null +++ b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.cs @@ -0,0 +1,59 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + public int CountPairs(TreeNode root, int distance) { + var graph = new Dictionary>(); + void Dfs(TreeNode node, TreeNode parent) { + if (node == null) return; + if (parent != null) { + if (!graph.ContainsKey(parent)) graph[parent] = new List(); + if (!graph.ContainsKey(node)) graph[node] = new List(); + graph[parent].Add(node); + graph[node].Add(parent); + } + Dfs(node.left, node); + Dfs(node.right, node); + } + Dfs(root, null); + + var leaves = new List(); + foreach (var node in graph.Keys) { + if (node.left == null && node.right == null) leaves.Add(node); + } + + int ans = 0; + for (int i = 0; i < leaves.Count; i++) { + var leaf = leaves[i]; + var q = new Queue<(TreeNode, int)>(); + var visited = new HashSet(); + q.Enqueue((leaf, 0)); + visited.Add(leaf); + + while (q.Count > 0) { + var (node, dist) = q.Dequeue(); + if (dist >= distance) continue; + foreach (var nei in graph[node]) { + if (!visited.Contains(nei)) { + visited.Add(nei); + q.Enqueue((nei, dist + 1)); + if (nei.left == null && nei.right == null && leaves.IndexOf(nei) > i) { + ans++; + } + } + } + } + } + return ans; + } +} diff --git a/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.dart b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.dart new file mode 100644 index 00000000..e5e11c31 --- /dev/null +++ b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.dart @@ -0,0 +1,53 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * int val; + * TreeNode? left; + * TreeNode? right; + * TreeNode([this.val = 0, this.left, this.right]); + * } + */ +class Solution { + int countPairs(TreeNode? root, int distance) { + Map> graph = {}; + + void dfs(TreeNode? node, TreeNode? parent) { + if (node == null) return; + if (parent != null) { + graph.putIfAbsent(parent, () => []).add(node); + graph.putIfAbsent(node, () => []).add(parent); + } + dfs(node.left, node); + dfs(node.right, node); + } + dfs(root, null); + + List leaves = graph.keys.where((n) => n.left == null && n.right == null).toList(); + int ans = 0; + + for (int i = 0; i < leaves.length; i++) { + TreeNode leaf = leaves[i]; + Queue> q = Queue(); + Set visited = {}; + q.add([leaf, 0]); + visited.add(leaf); + + while (q.isNotEmpty) { + final curr = q.removeFirst(); + final node = curr[0] as TreeNode; + final dist = curr[1] as int; + if (dist >= distance) continue; + for (final nei in (graph[node] ?? [])) { + if (!visited.contains(nei)) { + visited.add(nei); + q.add([nei, dist + 1]); + if (nei.left == null && nei.right == null && leaves.indexOf(nei) > i) { + ans++; + } + } + } + } + } + return ans; + } +} diff --git a/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.go b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.go new file mode 100644 index 00000000..7efe42ca --- /dev/null +++ b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.go @@ -0,0 +1,73 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func countPairs(root *TreeNode, distance int) int { + graph := make(map[*TreeNode][]*TreeNode) + + var dfs func(node, parent *TreeNode) + dfs = func(node, parent *TreeNode) { + if node == nil { + return + } + if parent != nil { + graph[parent] = append(graph[parent], node) + graph[node] = append(graph[node], parent) + } + dfs(node.Left, node) + dfs(node.Right, node) + } + dfs(root, nil) + + var leaves []*TreeNode + for node := range graph { + if node.Left == nil && node.Right == nil { + leaves = append(leaves, node) + } + } + + ans := 0 + for i, leaf := range leaves { + type Pair struct { + node *TreeNode + dist int + } + q := []Pair{{leaf, 0}} + visited := map[*TreeNode]bool{leaf: true} + + for len(q) > 0 { + curr := q[0] + q = q[1:] + node, dist := curr.node, curr.dist + if dist >= distance { + continue + } + for _, nei := range graph[node] { + if !visited[nei] { + visited[nei] = true + q = append(q, Pair{nei, dist + 1}) + // check if nei is leaf and index > i + isLeaf := nei.Left == nil && nei.Right == nil + if isLeaf { + // find index in leaves + idx := -1 + for j, l := range leaves { + if l == nei { + idx = j + break + } + } + if idx > i { + ans++ + } + } + } + } + } + } + return ans +} diff --git a/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.java b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.java new file mode 100644 index 00000000..47e9bbb3 --- /dev/null +++ b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.java @@ -0,0 +1,66 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int countPairs(TreeNode root, int distance) { + Map> graph = new HashMap<>(); + dfs(root, null, graph); + + List leaves = new ArrayList<>(); + for (TreeNode node : graph.keySet()) { + if (node.left == null && node.right == null) { + leaves.add(node); + } + } + + int ans = 0; + for (int i = 0; i < leaves.size(); i++) { + TreeNode leaf = leaves.get(i); + Queue nodeQueue = new LinkedList<>(); + Queue distQueue = new LinkedList<>(); + Set visited = new HashSet<>(); + nodeQueue.offer(leaf); + distQueue.offer(0); + visited.add(leaf); + + while (!nodeQueue.isEmpty()) { + TreeNode node = nodeQueue.poll(); + int dist = distQueue.poll(); + if (dist >= distance) continue; + for (TreeNode nei : graph.getOrDefault(node, new ArrayList<>())) { + if (!visited.contains(nei)) { + visited.add(nei); + nodeQueue.offer(nei); + distQueue.offer(dist + 1); + if (leaves.contains(nei) && leaves.indexOf(nei) > i) { + ans++; + } + } + } + } + } + return ans; + } + + private void dfs(TreeNode node, TreeNode parent, Map> graph) { + if (node == null) return; + if (parent != null) { + graph.computeIfAbsent(parent, k -> new ArrayList<>()).add(node); + graph.computeIfAbsent(node, k -> new ArrayList<>()).add(parent); + } + dfs(node.left, node, graph); + dfs(node.right, node, graph); + } +} diff --git a/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.kt b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.kt new file mode 100644 index 00000000..3620e034 --- /dev/null +++ b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.kt @@ -0,0 +1,51 @@ +/** + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + fun countPairs(root: TreeNode?, distance: Int): Int { + val graph = mutableMapOf>() + fun dfs(node: TreeNode?, parent: TreeNode?) { + if (node == null) return + if (parent != null) { + graph.getOrPut(parent) { mutableListOf() }.add(node) + graph.getOrPut(node) { mutableListOf() }.add(parent) + } + dfs(node.left, node) + dfs(node.right, node) + } + dfs(root, null) + + val leaves = graph.keys.filter { it.left == null && it.right == null } + var ans = 0 + + for (i in leaves.indices) { + val leaf = leaves[i] + val q = ArrayDeque>() + val visited = mutableSetOf() + q.add(leaf to 0) + visited.add(leaf) + + while (q.isNotEmpty()) { + val (node, dist) = q.removeFirst() + if (dist >= distance) continue + for (nei in graph[node] ?: emptyList()) { + if (nei !in visited) { + visited.add(nei) + q.add(nei to dist + 1) + if (nei in leaves && leaves.indexOf(nei) > i) { + ans++ + } + } + } + } + } + return ans + } +} diff --git a/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.py b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.py new file mode 100644 index 00000000..cd7e7958 --- /dev/null +++ b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.py @@ -0,0 +1,47 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def countPairs(self, root: Optional[TreeNode], distance: int) -> int: + + self.ans = 0 + + graph = defaultdict(list) + + def dfs(node, parent): + nonlocal graph + + if not node: + return None + + if parent: + graph[parent].append(node) + graph[node].append(parent) + + dfs(node.left, node) + dfs(node.right, node) + + dfs(root, None) + + leaves = [node for node in graph if not node.left and not node.right] + ans = 0 + + for i, leaf in enumerate(leaves): + q = deque([(leaf, 0)]) + visited = set([leaf]) + + while q: + node, dist = q.popleft() + if dist >= distance: + continue + for nei in graph[node]: + if nei not in visited: + visited.add(nei) + q.append((nei, dist + 1)) + if nei in leaves and leaves.index(nei) > i: + ans += 1 + + return ans diff --git a/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.py2 b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.py2 new file mode 100644 index 00000000..f30035fb --- /dev/null +++ b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.py2 @@ -0,0 +1,46 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution(object): + def countPairs(self, root, distance): + """ + :type root: Optional[TreeNode] + :type distance: int + :rtype: int + """ + self.ans = 0 + + graph = {} + def dfs(node,parent): + if not node: + return None + if parent: + graph.setdefault(parent, []).append(node) + graph.setdefault(node, []).append(parent) + dfs(node.left, node) + dfs(node.right, node) + + dfs(root, None) + + leaves = [node for node in graph if not node.left and not node.right] + ans = 0 + + for i, leaf in enumerate(leaves): + q = [(leaf, 0)] + visited = set([leaf]) + + while q: + node, dist = q.pop(0) + if dist >= distance: + continue + for nei in graph.get(node, []): + if nei not in visited: + visited.add(nei) + q.append((nei, dist + 1)) + if nei in leaves and leaves.index(nei) > i: + ans += 1 + + return ans diff --git a/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.rb b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.rb new file mode 100644 index 00000000..55f7e035 --- /dev/null +++ b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.rb @@ -0,0 +1,53 @@ +# Definition for a binary tree node. +# class TreeNode +# attr_accessor :val, :left, :right +# def initialize(val = 0, left = nil, right = nil) +# @val = val +# @left = left +# @right = right +# end +# end +# @param {TreeNode} root +# @param {Integer} distance +# @return {Integer} +def count_pairs(root, distance) + graph = {} + + dfs = lambda do |node, parent| + return if node.nil? + if parent + graph[parent] ||= [] + graph[node] ||= [] + graph[parent] << node + graph[node] << parent + end + dfs.call(node.left, node) + dfs.call(node.right, node) + end + + dfs.call(root, nil) + + leaves = graph.keys.select { |n| n.left.nil? && n.right.nil? } + ans = 0 + + leaves.each_with_index do |leaf, i| + q = [[leaf, 0]] + visited = [leaf] + + until q.empty? + node, dist = q.shift + next if dist >= distance + (graph[node] || []).each do |nei| + unless visited.include?(nei) + visited << nei + q << [nei, dist + 1] + if leaves.include?(nei) && leaves.index(nei) > i + ans += 1 + end + end + end + end + end + + ans +end diff --git a/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.rs b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.rs new file mode 100644 index 00000000..3e9ba378 --- /dev/null +++ b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.rs @@ -0,0 +1,28 @@ +impl Solution { + pub fn count_pairs(root: Option>>, distance: i32) -> i32 { + fn dfs(node: Option>>, distance: i32, answer: &mut i32) -> Vec { + let Some(node) = node else { return Vec::new() }; + let (left, right) = { + let node = node.borrow(); + (node.left.clone(), node.right.clone()) + }; + if left.is_none() && right.is_none() { return vec![1]; } + let left_distances = dfs(left, distance, answer); + let right_distances = dfs(right, distance, answer); + for &a in &left_distances { + for &b in &right_distances { + if a + b <= distance { *answer += 1; } + } + } + let mut result = Vec::new(); + for value in left_distances.into_iter().chain(right_distances) { + if value < distance { result.push(value + 1); } + } + result + } + + let mut answer = 0; + dfs(root, distance, &mut answer); + answer + } +} diff --git a/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.swift b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.swift new file mode 100644 index 00000000..c027a430 --- /dev/null +++ b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.swift @@ -0,0 +1,17 @@ +class Solution { + func countPairs(_ root: TreeNode?, _ distance: Int) -> Int { + var answer = 0 + func dfs(_ node: TreeNode?) -> [Int] { + guard let node = node else { return [] } + if node.left == nil && node.right == nil { return [1] } + let left = dfs(node.left) + let right = dfs(node.right) + for a in left { + for b in right where a + b <= distance { answer += 1 } + } + return (left + right).compactMap { $0 < distance ? $0 + 1 : nil } + } + _ = dfs(root) + return answer + } +} diff --git a/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.ts b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.ts new file mode 100644 index 00000000..a890d12a --- /dev/null +++ b/tests/1501-2000/1530. number-of-good-leaf-nodes-pairs/sol.ts @@ -0,0 +1,58 @@ +/** + * Definition for a binary tree node. + * 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 countPairs(root: TreeNode | null, distance: number): number { + const graph = new Map(); + + function dfs(node: TreeNode | null, parent: TreeNode | null) { + if (!node) return; + if (parent) { + if (!graph.has(parent)) graph.set(parent, []); + if (!graph.has(node)) graph.set(node, []); + graph.get(parent)!.push(node); + graph.get(node)!.push(parent); + } + dfs(node.left, node); + dfs(node.right, node); + } + dfs(root, null); + + const leaves: TreeNode[] = []; + for (const node of graph.keys()) { + if (!node.left && !node.right) leaves.push(node); + } + + let ans = 0; + for (let i = 0; i < leaves.length; i++) { + const leaf = leaves[i]; + const q: Array<[TreeNode, number]> = [[leaf, 0]]; + const visited = new Set([leaf]); + + while (q.length > 0) { + const [node, dist] = q.shift()!; + if (dist >= distance) continue; + const neighbors = graph.get(node) || []; + for (const nei of neighbors) { + if (!visited.has(nei)) { + visited.add(nei); + q.push([nei, dist + 1]); + if (!nei.left && !nei.right && leaves.indexOf(nei) > i) { + ans++; + } + } + } + } + } + return ans; +} diff --git a/tests/1501-2000/1531. string-compression-ii/manifest.yaml b/tests/1501-2000/1531. string-compression-ii/manifest.yaml new file mode 100644 index 00000000..044a1f24 --- /dev/null +++ b/tests/1501-2000/1531. string-compression-ii/manifest.yaml @@ -0,0 +1,275 @@ +entry: + id: 1531 + title: "string-compression-ii" + params: + s: + type: string + k: + type: int + call: + cpp: "Solution().getLengthOfOptimalCompression({s}, {k})" + rust: "Solution::get_length_of_optimal_compression({s}, {k})" + python3: "Solution().getLengthOfOptimalCompression({s}, {k})" + python2: "Solution().getLengthOfOptimalCompression({s}, {k})" + ruby: "get_length_of_optimal_compression({s}, {k})" + java: "new Solution().getLengthOfOptimalCompression({s}, {k})" + csharp: "new Solution().GetLengthOfOptimalCompression({s}, {k})" + kotlin: "Solution().getLengthOfOptimalCompression({s}, {k})" + go: "getLengthOfOptimalCompression({s}, {k})" + dart: "Solution().getLengthOfOptimalCompression({s}, {k})" + swift: "Solution().getLengthOfOptimalCompression({s}, {k})" + typescript: "getLengthOfOptimalCompression({s}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().getLengthOfOptimalCompression(s, k, {result})" + checker: | + class Checker: + def getLengthOfOptimalCompression(self, s, k, result): + if not isinstance(s, str) or not isinstance(k, int): + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + n = len(s) + if n < 1 or n > 100 or k < 0 or k > n: + return False + if any(ch < 'a' or ch > 'z' for ch in s): + return False + dp = [[10**9] * (k + 1) for _ in range(n + 1)] + dp[0][0] = 0 + for i in range(1, n + 1): + for deleted in range(k + 1): + same = 0 + removed = 0 + for left in range(i, 0, -1): + if s[left - 1] == s[i - 1]: + same += 1 + else: + removed += 1 + if deleted >= removed: + digits = 0 if same == 1 else 1 if same < 10 else 2 if same < 100 else 3 + dp[i][deleted] = min(dp[i][deleted], dp[left - 1][deleted - removed] + 1 + digits) + if deleted: + dp[i][deleted] = min(dp[i][deleted], dp[i - 1][deleted - 1]) + return result == dp[n][k] + +seed: 1531 + +tests: + - name: single-keep + in: + s: "a" + k: 0 + out: 1 + - name: single-delete + in: + s: "a" + k: 1 + out: 0 + - name: pair-same + in: + s: "aa" + k: 0 + out: 2 + - name: pair-delete-one + in: + s: "aa" + k: 1 + out: 1 + - name: pair-different + in: + s: "ab" + k: 0 + out: 2 + - name: pair-different-delete + in: + s: "ab" + k: 1 + out: 1 + - name: triple-no-delete + in: + s: "aaa" + k: 0 + out: 2 + - name: triple-one-delete + in: + s: "aaa" + k: 1 + out: 2 + - name: triple-two-delete + in: + s: "aaa" + k: 2 + out: 1 + - name: official-example-one + in: + s: "aaabcccd" + k: 2 + out: 4 + - name: official-example-two + in: + s: "aabbaa" + k: 2 + out: 2 + - name: official-example-three + in: + s: "aaaaaaaaaaa" + k: 0 + out: 3 + - name: eleven-delete-one + in: + s: "aaaaaaaaaaa" + k: 1 + out: 3 + - name: eleven-delete-ten + in: + s: "aaaaaaaaaaa" + k: 10 + out: 1 + - name: three-pairs + in: + s: "aabbcc" + k: 0 + out: 6 + - name: three-pairs-one + in: + s: "aabbcc" + k: 1 + out: 5 + - name: three-pairs-two + in: + s: "aabbcc" + k: 2 + out: 4 + - name: three-pairs-three + in: + s: "aabbcc" + k: 3 + out: 3 + - name: alternating-no-delete + in: + s: "abababab" + k: 0 + out: 8 + - name: alternating-delete-three + in: + s: "abababab" + k: 3 + out: 3 + - name: alternating-delete-four + in: + s: "abababab" + k: 4 + out: 2 + - name: repeated-cycle + in: + s: "abcabcabc" + k: 2 + out: 7 + - name: repeated-cycle-delete-six + in: + s: "abcabcabc" + k: 6 + out: 2 + - name: bridge-runs-one + in: + s: "aabbbaa" + k: 1 + out: 5 + - name: bridge-runs-two + in: + s: "aabbbaa" + k: 2 + out: 4 + - name: bridge-runs-three + in: + s: "aabbbaa" + k: 3 + out: 2 + - name: two-long-runs + in: + s: "aaaaaaaaaabbbbbbbbbb" + k: 0 + out: 6 + - name: two-long-runs-delete-nine + in: + s: "aaaaaaaaaabbbbbbbbbb" + k: 9 + out: 4 + - name: two-long-runs-delete-ten + in: + s: "aaaaaaaaaabbbbbbbbbb" + k: 10 + out: 3 + - name: two-long-runs-delete-nineteen + in: + s: "aaaaaaaaaabbbbbbbbbb" + k: 19 + out: 1 + - name: delete-all + in: + s: "aaaaaaaaaabbbbbbbbbb" + k: 20 + out: 0 + - name: ninety-nine-and-one + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" + k: 0 + out: 4 + - name: ninety-nine-delete-one + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" + k: 1 + out: 3 + - name: two-fifty-runs-delete-forty-nine + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + k: 49 + out: 4 + - name: two-fifty-runs-delete-fifty + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + k: 50 + out: 3 + - name: generated-random-small + in: + s: + gen: "str" + len: 100 + alphabet: "abc" + k: 0 + - name: generated-random-quarter + in: + s: + gen: "str" + len: 100 + alphabet: "abcd" + k: 25 + - name: generated-random-half + in: + s: + gen: "str" + len: 100 + alphabet: "abcde" + k: 50 + - name: generated-broad-alphabet + in: + s: + gen: "str" + len: 100 + alphabet: "abcdefghij" + k: 75 + - name: generated-max-deletion + in: + s: + gen: "str" + len: 100 + alphabet: "ab" + k: 100 diff --git a/tests/1501-2000/1531. string-compression-ii/sol.cpp b/tests/1501-2000/1531. string-compression-ii/sol.cpp new file mode 100644 index 00000000..82af59dd --- /dev/null +++ b/tests/1501-2000/1531. string-compression-ii/sol.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int getLengthOfOptimalCompression(string s, int k) { + int n = s.size(); + int dp[110][110]; + for (int i = 0; i < 110; i++) { + for (int j = 0; j < 110; j++) { + dp[i][j] = 9999; + } + } + dp[0][0] = 0; + + for (int i = 1; i <= n; i++) { + for (int j = 0; j <= k; j++) { + int cnt = 0, del = 0; + for (int l = i; l >= 1; l--) { + if (s[l-1] == s[i-1]) cnt++; + else del++; + if (j - del >= 0) { + int add = (cnt >= 100) ? 3 : ((cnt >= 10) ? 2 : ((cnt >= 2) ? 1 : 0)); + dp[i][j] = min(dp[i][j], dp[l-1][j-del] + 1 + add); + } + } + if (j > 0) { + dp[i][j] = min(dp[i][j], dp[i-1][j-1]); + } + } + } + return dp[n][k]; + } +}; diff --git a/tests/1501-2000/1531. string-compression-ii/sol.cs b/tests/1501-2000/1531. string-compression-ii/sol.cs new file mode 100644 index 00000000..c123da73 --- /dev/null +++ b/tests/1501-2000/1531. string-compression-ii/sol.cs @@ -0,0 +1,30 @@ +public class Solution { + public int GetLengthOfOptimalCompression(string s, int k) { + int n = s.Length; + int[,] dp = new int[110, 110]; + for (int i = 0; i < 110; i++) { + for (int j = 0; j < 110; j++) { + dp[i, j] = 9999; + } + } + dp[0, 0] = 0; + + for (int i = 1; i <= n; i++) { + for (int j = 0; j <= k; j++) { + int cnt = 0, del = 0; + for (int l = i; l >= 1; l--) { + if (s[l-1] == s[i-1]) cnt++; + else del++; + if (j - del >= 0) { + int add = cnt >= 100 ? 3 : (cnt >= 10 ? 2 : (cnt >= 2 ? 1 : 0)); + dp[i, j] = Math.Min(dp[i, j], dp[l-1, j-del] + 1 + add); + } + } + if (j > 0) { + dp[i, j] = Math.Min(dp[i, j], dp[i-1, j-1]); + } + } + } + return dp[n, k]; + } +} diff --git a/tests/1501-2000/1531. string-compression-ii/sol.dart b/tests/1501-2000/1531. string-compression-ii/sol.dart new file mode 100644 index 00000000..1cb29a10 --- /dev/null +++ b/tests/1501-2000/1531. string-compression-ii/sol.dart @@ -0,0 +1,28 @@ +class Solution { + int getLengthOfOptimalCompression(String s, int k) { + int n = s.length; + List> dp = List.generate(110, (_) => List.filled(110, 9999)); + dp[0][0] = 0; + + for (int i = 1; i <= n; i++) { + for (int j = 0; j <= k; j++) { + int cnt = 0, del = 0; + for (int l = i; l >= 1; l--) { + if (s[l - 1] == s[i - 1]) { + cnt++; + } else { + del++; + } + if (j - del >= 0) { + int add = cnt >= 100 ? 3 : (cnt >= 10 ? 2 : (cnt >= 2 ? 1 : 0)); + dp[i][j] = (dp[i][j] < dp[l - 1][j - del] + 1 + add) ? dp[i][j] : dp[l - 1][j - del] + 1 + add; + } + } + if (j > 0) { + dp[i][j] = (dp[i][j] < dp[i - 1][j - 1]) ? dp[i][j] : dp[i - 1][j - 1]; + } + } + } + return dp[n][k]; + } +} diff --git a/tests/1501-2000/1531. string-compression-ii/sol.go b/tests/1501-2000/1531. string-compression-ii/sol.go new file mode 100644 index 00000000..19d347c5 --- /dev/null +++ b/tests/1501-2000/1531. string-compression-ii/sol.go @@ -0,0 +1,43 @@ +func getLengthOfOptimalCompression(s string, k int) int { + n := len(s) + dp := make([][]int, 110) + for i := range dp { + dp[i] = make([]int, 110) + for j := range dp[i] { + dp[i][j] = 9999 + } + } + dp[0][0] = 0 + + for i := 1; i <= n; i++ { + for j := 0; j <= k; j++ { + cnt, del := 0, 0 + for l := i; l >= 1; l-- { + if s[l-1] == s[i-1] { + cnt++ + } else { + del++ + } + if j-del >= 0 { + add := 0 + if cnt >= 100 { + add = 3 + } else if cnt >= 10 { + add = 2 + } else if cnt >= 2 { + add = 1 + } + if val := dp[l-1][j-del] + 1 + add; val < dp[i][j] { + dp[i][j] = val + } + } + } + if j > 0 { + if dp[i-1][j-1] < dp[i][j] { + dp[i][j] = dp[i-1][j-1] + } + } + } + } + return dp[n][k] +} diff --git a/tests/1501-2000/1531. string-compression-ii/sol.java b/tests/1501-2000/1531. string-compression-ii/sol.java new file mode 100644 index 00000000..2cde410e --- /dev/null +++ b/tests/1501-2000/1531. string-compression-ii/sol.java @@ -0,0 +1,33 @@ +class Solution { + public int getLengthOfOptimalCompression(String s, int k) { + int n = s.length(); + int[][] dp = new int[110][110]; + for (int[] row : dp) { + Arrays.fill(row, 9999); + } + dp[0][0] = 0; + + for (int i = 1; i <= n; i++) { + for (int j = 0; j <= k; j++) { + int cnt = 0, del = 0; + for (int l = i; l >= 1; l--) { + if (s.charAt(l - 1) == s.charAt(i - 1)) { + cnt++; + } else { + del++; + } + + if (j - del >= 0) { + int add = cnt >= 100 ? 3 : (cnt >= 10 ? 2 : (cnt >= 2 ? 1 : 0)); + dp[i][j] = Math.min(dp[i][j], dp[l - 1][j - del] + 1 + add); + } + } + + if (j > 0) { + dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1]); + } + } + } + return dp[n][k]; + } +} diff --git a/tests/1501-2000/1531. string-compression-ii/sol.kt b/tests/1501-2000/1531. string-compression-ii/sol.kt new file mode 100644 index 00000000..3388783d --- /dev/null +++ b/tests/1501-2000/1531. string-compression-ii/sol.kt @@ -0,0 +1,32 @@ +class Solution { + fun getLengthOfOptimalCompression(s: String, k: Int): Int { + val n = s.length + val dp = Array(110) { IntArray(110) { 9999 } } + dp[0][0] = 0 + + for (i in 1..n) { + for (j in 0..k) { + var cnt = 0 + var del = 0 + for (l in i downTo 1) { + if (s[l - 1] == s[i - 1]) cnt++ else del++ + + if (j - del >= 0) { + val add = when { + cnt >= 100 -> 3 + cnt >= 10 -> 2 + cnt >= 2 -> 1 + else -> 0 + } + dp[i][j] = minOf(dp[i][j], dp[l - 1][j - del] + 1 + add) + } + } + + if (j > 0) { + dp[i][j] = minOf(dp[i][j], dp[i - 1][j - 1]) + } + } + } + return dp[n][k] + } +} diff --git a/tests/1501-2000/1531. string-compression-ii/sol.py b/tests/1501-2000/1531. string-compression-ii/sol.py new file mode 100644 index 00000000..253f5fd1 --- /dev/null +++ b/tests/1501-2000/1531. string-compression-ii/sol.py @@ -0,0 +1,35 @@ +class Solution: + def getLengthOfOptimalCompression(self, s: str, k: int) -> int: + n = len(s) + dp = [[9999] * 110 for _ in range(110)] + dp[0][0] = 0 + + for i in range(1, n + 1): + for j in range(0, k + 1): + cnt, del_ = 0, 0 + for l in range(i, 0, -1): + if s[l - 1] == s[i - 1]: + cnt += 1 + else: + del_ += 1 + + if j - del_ >= 0: + dp[i][j] = min( + dp[i][j], + dp[l - 1][j - del_] + + 1 + + ( + 3 + if cnt >= 100 + else 2 + if cnt >= 10 + else 1 + if cnt >= 2 + else 0 + ), + ) + + if j > 0: + dp[i][j] = min(dp[i][j], dp[i - 1][j - 1]) + + return dp[n][k] diff --git a/tests/1501-2000/1531. string-compression-ii/sol.py2 b/tests/1501-2000/1531. string-compression-ii/sol.py2 new file mode 100644 index 00000000..431bd32c --- /dev/null +++ b/tests/1501-2000/1531. string-compression-ii/sol.py2 @@ -0,0 +1,27 @@ +class Solution(object): + def getLengthOfOptimalCompression(self, s, k): + """ + :type s: str + :type k: int + :rtype: int + """ + n = len(s) + dp = [[9999] * 110 for _ in range(110)] + dp[0][0] = 0 + + for i in range(1, n + 1): + for j in range(0, k + 1): + cnt, del_ = 0, 0 + for l in range(i, 0, -1): + if s[l - 1] == s[i - 1]: + cnt += 1 + else: + del_ += 1 + + if j - del_ >= 0: + dp[i][j] = min(dp[i][j], dp[l - 1][j - del_] + 1 + (3 if cnt >= 100 else 2 if cnt >= 10 else 1 if cnt >= 2 else 0)) + + if j > 0: + dp[i][j] = min(dp[i][j], dp[i - 1][j - 1]) + + return dp[n][k] diff --git a/tests/1501-2000/1531. string-compression-ii/sol.rb b/tests/1501-2000/1531. string-compression-ii/sol.rb new file mode 100644 index 00000000..55a433b1 --- /dev/null +++ b/tests/1501-2000/1531. string-compression-ii/sol.rb @@ -0,0 +1,41 @@ +# @param {String} s +# @param {Integer} k +# @return {Integer} +def get_length_of_optimal_compression(s, k) + n = s.length + dp = Array.new(110) { Array.new(110, 9999) } + dp[0][0] = 0 + + (1..n).each do |i| + (0..k).each do |j| + cnt = 0 + del = 0 + i.downto(1) do |l| + if s[l - 1] == s[i - 1] + cnt += 1 + else + del += 1 + end + + if j - del >= 0 + add = if cnt >= 100 + 3 + elsif cnt >= 10 + 2 + elsif cnt >= 2 + 1 + else + 0 + end + dp[i][j] = [dp[i][j], dp[l - 1][j - del] + 1 + add].min + end + end + + if j > 0 + dp[i][j] = [dp[i][j], dp[i - 1][j - 1]].min + end + end + end + + dp[n][k] +end diff --git a/tests/1501-2000/1531. string-compression-ii/sol.rs b/tests/1501-2000/1531. string-compression-ii/sol.rs new file mode 100644 index 00000000..a36e4869 --- /dev/null +++ b/tests/1501-2000/1531. string-compression-ii/sol.rs @@ -0,0 +1,31 @@ +impl Solution { + pub fn get_length_of_optimal_compression(s: String, k: i32) -> i32 { + let n = s.len(); + let s_chars: Vec = s.chars().collect(); + let k = k as usize; + let mut dp = vec![vec![9999; 110]; 110]; + dp[0][0] = 0; + + for i in 1..=n { + for j in 0..=k { + let mut cnt = 0; + let mut del = 0; + for l in (1..=i).rev() { + if s_chars[l - 1] == s_chars[i - 1] { + cnt += 1; + } else { + del += 1; + } + if j >= del { + let add = if cnt >= 100 { 3 } else if cnt >= 10 { 2 } else if cnt >= 2 { 1 } else { 0 }; + dp[i][j] = dp[i][j].min(dp[l - 1][j - del] + 1 + add); + } + } + if j > 0 { + dp[i][j] = dp[i][j].min(dp[i - 1][j - 1]); + } + } + } + dp[n][k] as i32 + } +} diff --git a/tests/1501-2000/1531. string-compression-ii/sol.swift b/tests/1501-2000/1531. string-compression-ii/sol.swift new file mode 100644 index 00000000..88ae1d60 --- /dev/null +++ b/tests/1501-2000/1531. string-compression-ii/sol.swift @@ -0,0 +1,30 @@ +class Solution { + func getLengthOfOptimalCompression(_ s: String, _ k: Int) -> Int { + let n = s.count + let chars = Array(s) + var dp = Array(repeating: Array(repeating: 9999, count: 110), count: 110) + dp[0][0] = 0 + + for i in 1...n { + for j in 0...k { + var cnt = 0 + var del = 0 + for l in stride(from: i, through: 1, by: -1) { + if chars[l-1] == chars[i-1] { + cnt += 1 + } else { + del += 1 + } + if j - del >= 0 { + let add = cnt >= 100 ? 3 : (cnt >= 10 ? 2 : (cnt >= 2 ? 1 : 0)) + dp[i][j] = min(dp[i][j], dp[l-1][j-del] + 1 + add) + } + } + if j > 0 { + dp[i][j] = min(dp[i][j], dp[i-1][j-1]) + } + } + } + return dp[n][k] + } +} diff --git a/tests/1501-2000/1531. string-compression-ii/sol.ts b/tests/1501-2000/1531. string-compression-ii/sol.ts new file mode 100644 index 00000000..2bc43b16 --- /dev/null +++ b/tests/1501-2000/1531. string-compression-ii/sol.ts @@ -0,0 +1,27 @@ +function getLengthOfOptimalCompression(s: string, k: number): number { + const n = s.length; + const dp: number[][] = Array.from({ length: 110 }, () => + Array(110).fill(9999), + ); + dp[0][0] = 0; + + for (let i = 1; i <= n; i++) { + for (let j = 0; j <= k; j++) { + let cnt = 0, + del = 0; + for (let l = i; l >= 1; l--) { + if (s[l - 1] === s[i - 1]) cnt++; + else del++; + + if (j - del >= 0) { + const add = cnt >= 100 ? 3 : cnt >= 10 ? 2 : cnt >= 2 ? 1 : 0; + dp[i][j] = Math.min(dp[i][j], dp[l - 1][j - del] + 1 + add); + } + } + if (j > 0) { + dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1]); + } + } + } + return dp[n][k]; +} diff --git a/tests/1501-2000/1534. count-good-triplets/manifest.yaml b/tests/1501-2000/1534. count-good-triplets/manifest.yaml new file mode 100644 index 00000000..325f1427 --- /dev/null +++ b/tests/1501-2000/1534. count-good-triplets/manifest.yaml @@ -0,0 +1,405 @@ +entry: + id: 1534 + title: "count-good-triplets" + params: + arr: + type: array + items: + type: int + a: + type: int + b: + type: int + c: + type: int + call: + cpp: "Solution().countGoodTriplets({arr}, {a}, {b}, {c})" + rust: "Solution::count_good_triplets({arr}, {a}, {b}, {c})" + python3: "Solution().countGoodTriplets({arr}, {a}, {b}, {c})" + python2: "Solution().countGoodTriplets({arr}, {a}, {b}, {c})" + ruby: "count_good_triplets({arr}, {a}, {b}, {c})" + java: "new Solution().countGoodTriplets({arr}, {a}, {b}, {c})" + csharp: "new Solution().CountGoodTriplets({arr}, {a}, {b}, {c})" + kotlin: "Solution().countGoodTriplets({arr}, {a}, {b}, {c})" + go: "countGoodTriplets({arr}, {a}, {b}, {c})" + dart: "Solution().countGoodTriplets({arr}, {a}, {b}, {c})" + swift: "Solution().countGoodTriplets({arr}, {a}, {b}, {c})" + typescript: "countGoodTriplets({arr}, {a}, {b}, {c})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().countGoodTriplets(arr, a, b, c, {result})" + checker: | + class Checker: + def countGoodTriplets(self, arr, a, b, c, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + expected = 0 + for i in range(len(arr)): + for j in range(i + 1, len(arr)): + for k in range(j + 1, len(arr)): + if (abs(arr[i] - arr[j]) <= a and + abs(arr[j] - arr[k]) <= b and + abs(arr[i] - arr[k]) <= c): + expected += 1 + return result == expected + +seed: 1534 + +tests: + - name: example-one + in: + arr: [3, 0, 1, 1, 9, 7] + a: 7 + b: 2 + c: 3 + out: 4 + - name: example-two + in: + arr: [1, 1, 2, 2, 3] + a: 0 + b: 0 + c: 1 + out: 0 + - name: minimum-length-all-equal + in: + arr: [5, 5, 5] + a: 0 + b: 0 + c: 0 + out: 1 + - name: minimum-length-fails-a + in: + arr: [0, 1, 2] + a: 0 + b: 10 + c: 10 + out: 0 + - name: minimum-length-fails-b + in: + arr: [0, 0, 1] + a: 0 + b: 0 + c: 10 + out: 0 + - name: minimum-length-fails-c + in: + arr: [0, 0, 1] + a: 10 + b: 10 + c: 0 + out: 0 + - name: all-triplets-pass + in: + arr: [0, 1, 2, 3, 4] + a: 1000 + b: 1000 + c: 1000 + out: 10 + - name: all-triplets-fail-zero-threshold + in: + arr: [0, 1, 2, 3, 4] + a: 0 + b: 0 + c: 0 + out: 0 + - name: all-equal-six + in: + arr: [7, 7, 7, 7, 7, 7] + a: 0 + b: 0 + c: 0 + out: 20 + - name: duplicate-pairs + in: + arr: [1, 1, 2, 2] + a: 0 + b: 1 + c: 1 + out: 2 + - name: alternating-values + in: + arr: [0, 10, 0, 10, 0] + a: 0 + b: 10 + c: 0 + out: 1 + - name: only-adjacent-values + in: + arr: [0, 1, 2, 3] + a: 1 + b: 1 + c: 2 + out: 2 + - name: strict-middle-bound + in: + arr: [0, 2, 4, 6] + a: 2 + b: 2 + c: 4 + out: 2 + - name: negative-direction + in: + arr: [9, 6, 3, 0] + a: 3 + b: 3 + c: 6 + out: 2 + - name: one-valid-triplet + in: + arr: [0, 100, 101, 1000] + a: 100 + b: 1 + c: 101 + out: 1 + - name: separated-blocks + in: + arr: [0, 0, 0, 100, 100, 100] + a: 0 + b: 0 + c: 0 + out: 2 + - name: threshold-boundaries + in: + arr: [10, 20, 30, 40] + a: 10 + b: 10 + c: 20 + out: 2 + - name: one-below-boundary + in: + arr: [10, 20, 31, 40] + a: 10 + b: 10 + c: 20 + out: 0 + - name: large-values + in: + arr: [0, 1000, 500, 999, 1] + a: 1000 + b: 499 + c: 1000 + out: 5 + - name: repeated-middle + in: + arr: [4, 8, 8, 8, 12] + a: 4 + b: 0 + c: 8 + out: 4 + - name: increasing-tight + in: + arr: [1, 2, 3, 4, 5, 6] + a: 2 + b: 2 + c: 4 + out: 12 + - name: increasing-loose-middle + in: + arr: [1, 2, 3, 4, 5, 6] + a: 1 + b: 1000 + c: 1000 + out: 10 + - name: decreasing-tight + in: + arr: [6, 5, 4, 3, 2, 1] + a: 1 + b: 1 + c: 2 + out: 4 + - name: alternating-three-values + in: + arr: [0, 5, 10, 0, 5, 10] + a: 5 + b: 5 + c: 10 + out: 12 + - name: all-zero + in: + arr: [0, 0, 0, 0, 0, 0, 0] + a: 0 + b: 0 + c: 0 + out: 35 + - name: only-c-restricts + in: + arr: [0, 2, 4, 6, 8] + a: 1000 + b: 1000 + c: 4 + out: 3 + - name: only-a-restricts + in: + arr: [0, 2, 4, 6, 8] + a: 2 + b: 1000 + c: 1000 + out: 6 + - name: only-b-restricts + in: + arr: [0, 2, 4, 6, 8] + a: 1000 + b: 2 + c: 1000 + out: 6 + - name: scattered-seven + in: + arr: [2, 20, 3, 21, 4, 22, 5] + a: 2 + b: 2 + c: 3 + out: 5 + - name: max-array-small-values + in: + arr: [1, 1, 1, 2, 2, 2, 3, 3] + a: 0 + b: 1 + c: 2 + out: 17 + - name: max-thresholds + in: + arr: [0, 250, 500, 750, 1000] + a: 1000 + b: 1000 + c: 1000 + out: 10 + - name: mixed-boundary + in: + arr: [1000, 999, 0, 1, 500] + a: 1 + b: 1000 + c: 500 + out: 2 + - name: exactly-three-equal-at-end + in: + arr: [10, 20, 30, 30, 30] + a: 0 + b: 0 + c: 0 + out: 1 + - name: eight-with-one-valid-family + in: + arr: [0, 0, 1, 1, 2, 2, 100, 100] + a: 1 + b: 1 + c: 2 + out: 16 + - name: nine-uniform + in: + arr: [11, 11, 11, 11, 11, 11, 11, 11, 11] + a: 0 + b: 0 + c: 0 + out: 84 + - name: ten-ramp + in: + arr: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + a: 3 + b: 3 + c: 6 + out: 54 + - name: generator-random-small + in: + arr: + gen: "array" + len: + gen: "int" + min: 3 + max: 20 + of: + gen: "int" + min: 0 + max: 1000 + elemType: "int" + a: + gen: "int" + min: 0 + max: 1000 + b: + gen: "int" + min: 0 + max: 1000 + c: + gen: "int" + min: 0 + max: 1000 + - name: generator-random-medium + in: + arr: + gen: "array" + len: + gen: "int" + min: 40 + max: 60 + of: + gen: "int" + min: 0 + max: 1000 + elemType: "int" + a: + gen: "int" + min: 0 + max: 1000 + b: + gen: "int" + min: 0 + max: 1000 + c: + gen: "int" + min: 0 + max: 1000 + - name: generator-maximum + in: + arr: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 1000 + elemType: "int" + a: + gen: "int" + min: 0 + max: 1000 + b: + gen: "int" + min: 0 + max: 1000 + c: + gen: "int" + min: 0 + max: 1000 + - name: generator-duplicate-heavy + in: + arr: + gen: "array" + len: + gen: "int" + min: 70 + max: 100 + of: + gen: "int" + min: 0 + max: 5 + elemType: "int" + a: + gen: "int" + min: 0 + max: 5 + b: + gen: "int" + min: 0 + max: 5 + c: + gen: "int" + min: 0 + max: 5 diff --git a/tests/1501-2000/1534. count-good-triplets/sol.cpp b/tests/1501-2000/1534. count-good-triplets/sol.cpp new file mode 100644 index 00000000..78eb10fa --- /dev/null +++ b/tests/1501-2000/1534. count-good-triplets/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int countGoodTriplets(vector& arr, int a, int b, int c) { + int n = arr.size(); + int count = 0; + for (int i = 0; i < n; i++) { + for (int j = i+1; j < n; j++) { + for (int k = j+1; k < n; k++) { + if (abs(arr[i] - arr[j]) <= a && abs(arr[j] - arr[k]) <= b && abs(arr[i] - arr[k]) <= c) { + count++; + } + } + } + } + return count; + } +}; diff --git a/tests/1501-2000/1534. count-good-triplets/sol.cs b/tests/1501-2000/1534. count-good-triplets/sol.cs new file mode 100644 index 00000000..6a4327f2 --- /dev/null +++ b/tests/1501-2000/1534. count-good-triplets/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public int CountGoodTriplets(int[] arr, int a, int b, int c) { + int n = arr.Length; + int count = 0; + for (int i = 0; i < n; i++) { + for (int j = i+1; j < n; j++) { + for (int k = j+1; k < n; k++) { + if (Math.Abs(arr[i] - arr[j]) <= a && Math.Abs(arr[j] - arr[k]) <= b && Math.Abs(arr[i] - arr[k]) <= c) { + count++; + } + } + } + } + return count; + } +} diff --git a/tests/1501-2000/1534. count-good-triplets/sol.dart b/tests/1501-2000/1534. count-good-triplets/sol.dart new file mode 100644 index 00000000..ea72b2f1 --- /dev/null +++ b/tests/1501-2000/1534. count-good-triplets/sol.dart @@ -0,0 +1,14 @@ +class Solution { + int countGoodTriplets(List arr, int a, int b, int c) { + var answer = 0; + for (var i = 0; i < arr.length; i++) { + for (var j = i + 1; j < arr.length; j++) { + if ((arr[i] - arr[j]).abs() > a) continue; + for (var k = j + 1; k < arr.length; k++) { + if ((arr[j] - arr[k]).abs() <= b && (arr[i] - arr[k]).abs() <= c) answer++; + } + } + } + return answer; + } +} diff --git a/tests/1501-2000/1534. count-good-triplets/sol.go b/tests/1501-2000/1534. count-good-triplets/sol.go new file mode 100644 index 00000000..f49bf37f --- /dev/null +++ b/tests/1501-2000/1534. count-good-triplets/sol.go @@ -0,0 +1,21 @@ +func countGoodTriplets(arr []int, a int, b int, c int) int { + n := len(arr) + count := 0 + for i := 0; i < n; i++ { + for j := i+1; j < n; j++ { + for k := j+1; k < n; k++ { + if abs(arr[i] - arr[j]) <= a && abs(arr[j] - arr[k]) <= b && abs(arr[i] - arr[k]) <= c { + count++ + } + } + } + } + return count +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} diff --git a/tests/1501-2000/1534. count-good-triplets/sol.java b/tests/1501-2000/1534. count-good-triplets/sol.java new file mode 100644 index 00000000..73f69c7e --- /dev/null +++ b/tests/1501-2000/1534. count-good-triplets/sol.java @@ -0,0 +1,16 @@ +class Solution { + public int countGoodTriplets(int[] arr, int a, int b, int c) { + int n = arr.length; + int count = 0; + for (int i = 0; i < n; i++) { + for (int j = i+1; j < n; j++) { + for (int k = j+1; k < n; k++) { + if (Math.abs(arr[i] - arr[j]) <= a && Math.abs(arr[j] - arr[k]) <= b && Math.abs(arr[i] - arr[k]) <= c) { + count++; + } + } + } + } + return count; + } +} diff --git a/tests/1501-2000/1534. count-good-triplets/sol.kt b/tests/1501-2000/1534. count-good-triplets/sol.kt new file mode 100644 index 00000000..6ef2946f --- /dev/null +++ b/tests/1501-2000/1534. count-good-triplets/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun countGoodTriplets(arr: IntArray, a: Int, b: Int, c: Int): Int { + val n = arr.size + var count = 0 + for (i in 0 until n) { + for (j in i+1 until n) { + for (k in j+1 until n) { + if (Math.abs(arr[i] - arr[j]) <= a && Math.abs(arr[j] - arr[k]) <= b && Math.abs(arr[i] - arr[k]) <= c) { + count++ + } + } + } + } + return count + } +} diff --git a/tests/1501-2000/1534. count-good-triplets/sol.py b/tests/1501-2000/1534. count-good-triplets/sol.py new file mode 100644 index 00000000..7cfff149 --- /dev/null +++ b/tests/1501-2000/1534. count-good-triplets/sol.py @@ -0,0 +1,14 @@ +class Solution: + def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int: + n = len(arr) + count = 0 + for i in range(n): + for j in range(i + 1, n): + for k in range(j + 1, n): + if ( + abs(arr[i] - arr[j]) <= a + and abs(arr[j] - arr[k]) <= b + and abs(arr[i] - arr[k]) <= c + ): + count += 1 + return count diff --git a/tests/1501-2000/1534. count-good-triplets/sol.py2 b/tests/1501-2000/1534. count-good-triplets/sol.py2 new file mode 100644 index 00000000..b16cd529 --- /dev/null +++ b/tests/1501-2000/1534. count-good-triplets/sol.py2 @@ -0,0 +1,17 @@ +class Solution(object): + def countGoodTriplets(self, arr, a, b, c): + """ + :type arr: List[int] + :type a: int + :type b: int + :type c: int + :rtype: int + """ + n = len(arr) + count = 0 + for i in range(n): + for j in range(i+1, n): + for k in range(j+1, n): + if abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c: + count += 1 + return count diff --git a/tests/1501-2000/1534. count-good-triplets/sol.rb b/tests/1501-2000/1534. count-good-triplets/sol.rb new file mode 100644 index 00000000..a3b987e2 --- /dev/null +++ b/tests/1501-2000/1534. count-good-triplets/sol.rb @@ -0,0 +1,19 @@ +# @param {Integer[]} arr +# @param {Integer} a +# @param {Integer} b +# @param {Integer} c +# @return {Integer} +def count_good_triplets(arr, a, b, c) + n = arr.length + count = 0 + (0...n).each do |i| + ((i+1)...n).each do |j| + ((j+1)...n).each do |k| + if (arr[i] - arr[j]).abs <= a && (arr[j] - arr[k]).abs <= b && (arr[i] - arr[k]).abs <= c + count += 1 + end + end + end + end + count +end diff --git a/tests/1501-2000/1534. count-good-triplets/sol.rs b/tests/1501-2000/1534. count-good-triplets/sol.rs new file mode 100644 index 00000000..664fcbe0 --- /dev/null +++ b/tests/1501-2000/1534. count-good-triplets/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn count_good_triplets(arr: Vec, a: i32, b: i32, c: i32) -> i32 { + let n = arr.len(); + let mut count = 0; + for i in 0..n { + for j in (i+1)..n { + for k in (j+1)..n { + if (arr[i] - arr[j]).abs() <= a && (arr[j] - arr[k]).abs() <= b && (arr[i] - arr[k]).abs() <= c { + count += 1; + } + } + } + } + count + } +} diff --git a/tests/1501-2000/1534. count-good-triplets/sol.swift b/tests/1501-2000/1534. count-good-triplets/sol.swift new file mode 100644 index 00000000..d7964b54 --- /dev/null +++ b/tests/1501-2000/1534. count-good-triplets/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func countGoodTriplets(_ arr: [Int], _ a: Int, _ b: Int, _ c: Int) -> Int { + let n = arr.count + var count = 0 + for i in 0.. value: + streak += 1 + else: + candidate = value + streak = 1 + if streak >= k: + return result == candidate + return result == candidate + +seed: 1535 + +tests: + - name: example-one + in: + arr: [2, 1, 3, 5, 4, 6, 7] + k: 2 + out: 5 + - name: example-two-large-k + in: + arr: [3, 2, 1] + k: 10 + out: 3 + - name: smallest-array-first-wins + in: + arr: [2, 1, 3] + k: 1 + out: 2 + - name: smallest-array-second-wins + in: + arr: [1, 2, 3] + k: 1 + out: 2 + - name: maximum-at-front + in: + arr: [10, 1, 2, 3, 4] + k: 4 + out: 10 + - name: maximum-at-end + in: + arr: [1, 2, 3, 4, 10] + k: 4 + out: 10 + - name: descending-k-one + in: + arr: [9, 8, 7, 6, 5] + k: 1 + out: 9 + - name: ascending-k-one + in: + arr: [1, 2, 3, 4, 5] + k: 1 + out: 2 + - name: ascending-k-two + in: + arr: [1, 2, 3, 4, 5] + k: 2 + out: 5 + - name: ascending-k-four + in: + arr: [1, 2, 3, 4, 5] + k: 4 + out: 5 + - name: descending-k-four + in: + arr: [5, 4, 3, 2, 1] + k: 4 + out: 5 + - name: winner-changes-many-times + in: + arr: [2, 7, 1, 8, 3, 9, 4, 6, 5] + k: 3 + out: 9 + - name: winner-changes-before-streak + in: + arr: [8, 1, 7, 2, 6, 3, 5, 4] + k: 3 + out: 8 + - name: maximum-value-one-million + in: + arr: [999999, 1, 500000, 1000000] + k: 2 + out: 1000000 + - name: minimum-value-one + in: + arr: [1, 100, 2, 99] + k: 2 + out: 100 + - name: six-elements-middle-maximum + in: + arr: [4, 1, 6, 2, 5, 3] + k: 3 + out: 6 + - name: seven-elements-early-maximum + in: + arr: [7, 2, 6, 1, 5, 3, 4] + k: 5 + out: 7 + - name: seven-elements-late-maximum + in: + arr: [2, 6, 1, 5, 3, 4, 7] + k: 5 + out: 7 + - name: k-equals-one + in: + arr: [11, 4, 9, 2, 8] + k: 1 + out: 11 + - name: k-equals-array-minus-one + in: + arr: [4, 9, 1, 7, 3, 8] + k: 5 + out: 9 + - name: duplicate-shaped-values-but-distinct + in: + arr: [100, 1, 99, 2, 98, 3, 97] + k: 4 + out: 100 + - name: alternating-low-high + in: + arr: [1, 10, 2, 9, 3, 8, 4, 7, 5, 6] + k: 2 + out: 10 + - name: alternating-high-low + in: + arr: [10, 1, 9, 2, 8, 3, 7, 4, 6, 5] + k: 6 + out: 10 + - name: powers-of-two + in: + arr: [2, 16, 4, 8, 1, 32] + k: 2 + out: 16 + - name: nonconsecutive-values + in: + arr: [1000, 10, 500, 20, 900, 30] + k: 3 + out: 1000 + - name: two-digit-values + in: + arr: [42, 17, 99, 3, 88, 12] + k: 2 + out: 99 + - name: winner-after-four-comparisons + in: + arr: [6, 1, 5, 2, 4, 3] + k: 4 + out: 6 + - name: new-candidate-resets-streak + in: + arr: [3, 2, 9, 1, 8, 7] + k: 2 + out: 9 + - name: new-candidate-wins-immediately + in: + arr: [1, 100, 2, 3, 4] + k: 1 + out: 100 + - name: large-gap-values + in: + arr: [500000, 2, 999998, 1, 1000000, 3] + k: 3 + out: 1000000 + - name: nine-elements-k-three + in: + arr: [5, 9, 1, 8, 2, 7, 3, 6, 4] + k: 3 + out: 9 + - name: nine-elements-k-seven + in: + arr: [5, 9, 1, 8, 2, 7, 3, 6, 4] + k: 7 + out: 9 + - name: ten-elements-middle + in: + arr: [4, 1, 3, 2, 10, 5, 6, 7, 8, 9] + k: 4 + out: 10 + - name: extreme-two-elements + in: + arr: [1, 1000000] + k: 1000000000 + out: 1000000 + - name: extreme-two-elements-reverse + in: + arr: [1000000, 1] + k: 1000000000 + out: 1000000 + - name: generated-small-distinct + in: + arr: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 1000000 + distinct: true + sorted: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 1000000000 + - name: generated-medium-distinct + in: + arr: + gen: "array" + len: 25 + of: + gen: "int" + min: 1 + max: 1000000 + distinct: true + sorted: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 1000 + - name: generated-large-distinct + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000 + distinct: true + sorted: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 1000000000 + - name: generated-large-small-k + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000 + distinct: true + sorted: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 3 + - name: generated-large-near-limit-k + in: + arr: + gen: "array" + len: 99999 + of: + gen: "int" + min: 1 + max: 1000000 + distinct: true + sorted: false + elemType: "int" + k: + gen: "int" + min: 999990000 + max: 1000000000 diff --git a/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.cpp b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.cpp new file mode 100644 index 00000000..e1eac16a --- /dev/null +++ b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int getWinner(vector& arr, int k) { + int candidate = arr[0]; + int streak = 0; + for (int i = 1; i < arr.size(); ++i) { + if (candidate > arr[i]) { + streak++; + } else { + candidate = arr[i]; + streak = 1; + } + if (streak == k) return candidate; + } + return candidate; + } +}; diff --git a/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.cs b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.cs new file mode 100644 index 00000000..072ceca6 --- /dev/null +++ b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public int GetWinner(int[] arr, int k) { + int candidate = arr[0]; + int streak = 0; + for (int i = 1; i < arr.Length; i++) { + if (candidate > arr[i]) { + streak++; + } else { + candidate = arr[i]; + streak = 1; + } + if (streak == k) return candidate; + } + return candidate; + } +} diff --git a/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.dart b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.dart new file mode 100644 index 00000000..fb6e6d5a --- /dev/null +++ b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.dart @@ -0,0 +1,16 @@ +class Solution { + int getWinner(List arr, int k) { + int candidate = arr[0]; + int streak = 0; + for (int i = 1; i < arr.length; i++) { + if (candidate > arr[i]) { + streak++; + } else { + candidate = arr[i]; + streak = 1; + } + if (streak == k) return candidate; + } + return candidate; + } +} diff --git a/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.go b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.go new file mode 100644 index 00000000..9a4b9d06 --- /dev/null +++ b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.go @@ -0,0 +1,16 @@ +func getWinner(arr []int, k int) int { + candidate := arr[0] + streak := 0 + for i := 1; i < len(arr); i++ { + if candidate > arr[i] { + streak++ + } else { + candidate = arr[i] + streak = 1 + } + if streak == k { + return candidate + } + } + return candidate +} diff --git a/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.java b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.java new file mode 100644 index 00000000..6d906a12 --- /dev/null +++ b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.java @@ -0,0 +1,16 @@ +class Solution { + public int getWinner(int[] arr, int k) { + int candidate = arr[0]; + int streak = 0; + for (int i = 1; i < arr.length; ++i) { + if (candidate > arr[i]) { + streak++; + } else { + candidate = arr[i]; + streak = 1; + } + if (streak == k) return candidate; + } + return candidate; + } +} diff --git a/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.kt b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.kt new file mode 100644 index 00000000..0ba9e520 --- /dev/null +++ b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun getWinner(arr: IntArray, k: Int): Int { + var candidate = arr[0] + var streak = 0 + for (i in 1 until arr.size) { + if (candidate > arr[i]) { + streak++ + } else { + candidate = arr[i] + streak = 1 + } + if (streak == k) return candidate + } + return candidate + } +} diff --git a/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.py b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.py new file mode 100644 index 00000000..4d532f05 --- /dev/null +++ b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.py @@ -0,0 +1,91 @@ +class Solution: + def getWinner(self, arr: List[int], k: int) -> int: + + # ---------------------------------------------- + candidate = arr[0] + streak = 0 + for el in arr[1:]: + if candidate > el: + streak += 1 + else: + candidate = el + streak = 1 + + if streak == k: + return candidate + return candidate # at last + # ---------------------------------------------- + + # same using maxi---------------------------------------------- + maxi = max(arr) + candidate = arr[0] + streak = 0 + for el in arr[1:]: + if candidate > el: + streak += 1 + else: + candidate = el + streak = 1 + + if streak == k or candidate == maxi: # if candidate==maxi till then + return candidate + + # ---------------------------------------------- + + n = len(arr) + + k = min( + k, n - 1 + ) # k can be very large so no use,, ,keep it smakl till max maybe len of array + # Maximum element reaches the front in at most (n-1) rounds. + # After that it wins forever, so cap k to (n-1). + + # -------------------------------------------------------------------------- + # what was i doing in first try was right but gave TLE + """ + count = 0 + candidate = None + + # while count el: + streak += 1 + else: + candidate = el + streak = 1 + if streak == k: + return candidate + return candidate diff --git a/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.rb b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.rb new file mode 100644 index 00000000..9a10f27b --- /dev/null +++ b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.rb @@ -0,0 +1,17 @@ +# @param {Integer[]} arr +# @param {Integer} k +# @return {Integer} +def get_winner(arr, k) + candidate = arr[0] + streak = 0 + (1...arr.length).each do |i| + if candidate > arr[i] + streak += 1 + else + candidate = arr[i] + streak = 1 + end + return candidate if streak == k + end + candidate +end diff --git a/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.rs b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.rs new file mode 100644 index 00000000..b3cf2d34 --- /dev/null +++ b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn get_winner(arr: Vec, k: i32) -> i32 { + let mut candidate = arr[0]; + let mut streak = 0; + for i in 1..arr.len() { + if candidate > arr[i] { + streak += 1; + } else { + candidate = arr[i]; + streak = 1; + } + if streak == k { return candidate; } + } + candidate + } +} diff --git a/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.swift b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.swift new file mode 100644 index 00000000..bcd55104 --- /dev/null +++ b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func getWinner(_ arr: [Int], _ k: Int) -> Int { + var candidate = arr[0] + var streak = 0 + for i in 1.. arr[i] { + streak += 1 + } else { + candidate = arr[i] + streak = 1 + } + if streak == k { return candidate } + } + return candidate + } +} diff --git a/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.ts b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.ts new file mode 100644 index 00000000..a4ec1ded --- /dev/null +++ b/tests/1501-2000/1535. find-the-winner-of-an-array-game/sol.ts @@ -0,0 +1,14 @@ +function getWinner(arr: number[], k: number): number { + let candidate = arr[0]; + let streak = 0; + for (let i = 1; i < arr.length; i++) { + if (candidate > arr[i]) { + streak++; + } else { + candidate = arr[i]; + streak = 1; + } + if (streak === k) return candidate; + } + return candidate; +} diff --git a/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/manifest.yaml b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/manifest.yaml new file mode 100644 index 00000000..dfb7efda --- /dev/null +++ b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/manifest.yaml @@ -0,0 +1,387 @@ +entry: + id: 1536 + title: "minimum-swaps-to-arrange-a-binary-grid" + params: + grid: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().minSwaps({grid})" + rust: "Solution::min_swaps({grid})" + python3: "Solution().minSwaps({grid})" + python2: "Solution().minSwaps({grid})" + ruby: "min_swaps({grid})" + java: "new Solution().minSwaps({grid})" + csharp: "new Solution().MinSwaps({grid})" + kotlin: "Solution().minSwaps({grid})" + go: "minSwaps({grid})" + dart: "Solution().minSwaps({grid})" + swift: "Solution().minSwaps({grid})" + typescript: "minSwaps({grid})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minSwaps(grid, {result})" + checker: | + class Checker: + def minSwaps(self, grid, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + n = len(grid) + zeros = [] + for row in grid: + count = 0 + for value in reversed(row): + if value == 0: + count += 1 + else: + break + zeros.append(count) + swaps = 0 + for i in range(n): + needed = n - i - 1 + j = i + while j < n and zeros[j] < needed: + j += 1 + if j == n: + return result == -1 + swaps += j - i + value = zeros.pop(j) + zeros.insert(i, value) + return result == swaps + +seed: 1536 + +tests: + - name: single-zero + in: + grid: + - [0] + out: 0 + - name: single-one + in: + grid: + - [1] + out: 0 + - name: all-zero-two + in: + grid: + - [0, 0] + - [0, 0] + out: 0 + - name: impossible-all-one-two + in: + grid: + - [1, 1] + - [1, 1] + out: -1 + - name: already-valid-two + in: + grid: + - [1, 0] + - [1, 1] + out: 0 + - name: one-swap-two + in: + grid: + - [0, 1] + - [1, 0] + out: 1 + - name: official-example-one + in: + grid: + - [0, 0, 1] + - [1, 1, 0] + - [1, 0, 0] + out: 3 + - name: official-example-two + in: + grid: + - [0, 1, 1, 0] + - [0, 1, 1, 0] + - [0, 1, 1, 0] + - [0, 1, 1, 0] + out: -1 + - name: official-example-three + in: + grid: + - [1, 0, 0] + - [1, 1, 0] + - [1, 1, 1] + out: 0 + - name: zero-suffix-three + in: + grid: + - [0, 0, 0] + - [0, 1, 0] + - [1, 1, 1] + out: 0 + - name: insufficient-suffix-three + in: + grid: + - [0, 0, 0, 1] + - [0, 0, 1, 1] + - [0, 1, 1, 1] + - [1, 1, 1, 1] + out: -1 + - name: no-required-suffix-four + in: + grid: + - [1, 1, 1, 1] + - [0, 1, 1, 1] + - [0, 0, 1, 1] + - [0, 0, 0, 1] + out: -1 + - name: cyclic-three + in: + grid: + - [0, 1, 0] + - [0, 0, 1] + - [1, 0, 0] + out: 2 + - name: diagonal-ones-three + in: + grid: + - [1, 0, 1] + - [0, 1, 0] + - [0, 0, 1] + out: -1 + - name: already-valid-four + in: + grid: + - [0, 0, 0, 0] + - [1, 0, 0, 0] + - [1, 1, 0, 0] + - [1, 1, 1, 0] + out: 0 + - name: shifted-valid-four + in: + grid: + - [0, 0, 0, 0] + - [0, 0, 0, 1] + - [0, 0, 1, 1] + - [0, 1, 1, 1] + out: -1 + - name: late-zero-four + in: + grid: + - [0, 0, 1, 0] + - [0, 1, 1, 0] + - [1, 1, 1, 0] + - [1, 1, 1, 1] + out: -1 + - name: nontrivial-three + in: + grid: + - [0, 0, 0] + - [1, 0, 1] + - [1, 1, 0] + out: 1 + - name: five-step-order + in: + grid: + - [0, 0, 0, 0, 1] + - [0, 0, 0, 1, 1] + - [0, 0, 1, 1, 1] + - [0, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + out: -1 + - name: five-near-valid + in: + grid: + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 1] + - [0, 0, 0, 1, 1] + - [0, 0, 1, 1, 1] + - [0, 1, 1, 1, 1] + out: -1 + - name: four-rotation + in: + grid: + - [0, 1, 0, 0] + - [0, 0, 1, 0] + - [0, 0, 0, 1] + - [1, 0, 0, 0] + out: 3 + - name: descending-valid-four + in: + grid: + - [1, 0, 0, 0] + - [1, 1, 0, 0] + - [1, 1, 1, 0] + - [1, 1, 1, 1] + out: 0 + - name: six-already-valid + in: + grid: + - [0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 1] + - [0, 0, 0, 0, 1, 1] + - [0, 0, 0, 1, 1, 1] + - [0, 0, 1, 1, 1, 1] + - [0, 1, 1, 1, 1, 1] + out: -1 + - name: six-all-ones-bottom + in: + grid: + - [0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 1] + - [0, 0, 0, 0, 1, 1] + - [0, 0, 0, 1, 1, 1] + - [0, 0, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1] + out: -1 + - name: four-mixed-a + in: + grid: + - [0, 0, 1, 1] + - [0, 1, 0, 1] + - [1, 0, 0, 1] + - [1, 1, 1, 0] + out: -1 + - name: three-mixed-a + in: + grid: + - [0, 0, 0] + - [0, 1, 1] + - [1, 0, 1] + out: -1 + - name: four-mixed-b + in: + grid: + - [0, 0, 0, 0] + - [0, 1, 0, 1] + - [1, 1, 0, 0] + - [1, 0, 1, 0] + out: 2 + - name: five-mixed-a + in: + grid: + - [0, 0, 0, 0, 0] + - [0, 1, 0, 0, 1] + - [1, 0, 1, 0, 0] + - [1, 1, 0, 1, 0] + - [1, 1, 1, 0, 1] + out: -1 + - name: four-mixed-c + in: + grid: + - [0, 0, 0, 0] + - [0, 0, 1, 0] + - [0, 1, 1, 0] + - [1, 1, 1, 0] + out: -1 + - name: four-mixed-d + in: + grid: + - [0, 0, 0, 0] + - [0, 0, 0, 1] + - [0, 0, 1, 0] + - [0, 1, 1, 0] + out: -1 + - name: three-sparse + in: + grid: + - [0, 0, 0] + - [1, 0, 0] + - [0, 1, 0] + out: 0 + - name: five-subdiagonal + in: + grid: + - [0, 0, 0, 0, 0] + - [1, 0, 0, 0, 0] + - [0, 1, 0, 0, 0] + - [0, 0, 1, 0, 0] + - [0, 0, 0, 1, 0] + out: 0 + - name: three-reverse-diagonal + in: + grid: + - [0, 0, 1] + - [0, 1, 0] + - [1, 0, 0] + out: 3 + - name: four-last-row-zeros + in: + grid: + - [1, 1, 0, 0] + - [1, 0, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 1] + out: 1 + - name: generated-two + in: + grid: + gen: "array" + len: 2 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 1 + elemType: "int" + - name: generated-three + in: + grid: + gen: "array" + len: 3 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 0 + max: 1 + elemType: "int" + - name: generated-five + in: + grid: + gen: "array" + len: 5 + of: + gen: "array" + len: 5 + of: + gen: "int" + min: 0 + max: 1 + elemType: "int" + - name: generated-twenty + in: + grid: + gen: "array" + len: 20 + of: + gen: "array" + len: 20 + of: + gen: "int" + min: 0 + max: 1 + elemType: "int" + - name: generated-max-size + in: + grid: + gen: "array" + len: 200 + of: + gen: "array" + len: 200 + of: + gen: "int" + min: 0 + max: 1 + elemType: "int" diff --git a/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.cpp b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.cpp new file mode 100644 index 00000000..6f3d2ce0 --- /dev/null +++ b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int minSwaps(vector>& grid) { + int n = grid.size(); + vector zeros(n); + for (int i = 0; i < n; i++) { + int count = 0; + for (int j = n - 1; j >= 0; j--) { + if (grid[i][j] == 0) { + count++; + } else { + break; + } + } + zeros[i] = count; + } + int swaps = 0; + for (int i = 0; i < n; i++) { + int needed = n - i - 1; + int j = i; + while (j < n && zeros[j] < needed) { + j++; + } + if (j == n) { + return -1; + } + while (j > i) { + swap(zeros[j], zeros[j - 1]); + j--; + swaps++; + } + } + return swaps; + } +}; diff --git a/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.cs b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.cs new file mode 100644 index 00000000..2c6b72ab --- /dev/null +++ b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.cs @@ -0,0 +1,36 @@ +public class Solution { + public int MinSwaps(int[][] grid) { + int n = grid.Length; + int[] zeros = new int[n]; + for (int i = 0; i < n; i++) { + int count = 0; + for (int j = n - 1; j >= 0; j--) { + if (grid[i][j] == 0) { + count++; + } else { + break; + } + } + zeros[i] = count; + } + int swaps = 0; + for (int i = 0; i < n; i++) { + int needed = n - i - 1; + int j = i; + while (j < n && zeros[j] < needed) { + j++; + } + if (j == n) { + return -1; + } + while (j > i) { + int temp = zeros[j]; + zeros[j] = zeros[j - 1]; + zeros[j - 1] = temp; + j--; + swaps++; + } + } + return swaps; + } +} diff --git a/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.dart b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.dart new file mode 100644 index 00000000..1b466205 --- /dev/null +++ b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.dart @@ -0,0 +1,36 @@ +class Solution { + int minSwaps(List> grid) { + int n = grid.length; + List zeros = List.filled(n, 0); + for (int i = 0; i < n; i++) { + int count = 0; + for (int j = n - 1; j >= 0; j--) { + if (grid[i][j] == 0) { + count++; + } else { + break; + } + } + zeros[i] = count; + } + int swaps = 0; + for (int i = 0; i < n; i++) { + int needed = n - i - 1; + int j = i; + while (j < n && zeros[j] < needed) { + j++; + } + if (j == n) { + return -1; + } + while (j > i) { + int temp = zeros[j]; + zeros[j] = zeros[j - 1]; + zeros[j - 1] = temp; + j--; + swaps++; + } + } + return swaps; + } +} diff --git a/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.go b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.go new file mode 100644 index 00000000..4d2a80bb --- /dev/null +++ b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.go @@ -0,0 +1,32 @@ +func minSwaps(grid [][]int) int { + n := len(grid) + zeros := make([]int, n) + for i := 0; i < n; i++ { + count := 0 + for j := n - 1; j >= 0; j-- { + if grid[i][j] == 0 { + count++ + } else { + break + } + } + zeros[i] = count + } + swaps := 0 + for i := 0; i < n; i++ { + needed := n - i - 1 + j := i + for j < n && zeros[j] < needed { + j++ + } + if j == n { + return -1 + } + for j > i { + zeros[j], zeros[j-1] = zeros[j-1], zeros[j] + j-- + swaps++ + } + } + return swaps +} diff --git a/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.java b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.java new file mode 100644 index 00000000..19b1661b --- /dev/null +++ b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.java @@ -0,0 +1,36 @@ +class Solution { + public int minSwaps(int[][] grid) { + int n = grid.length; + int[] zeros = new int[n]; + for (int i = 0; i < n; i++) { + int count = 0; + for (int j = n - 1; j >= 0; j--) { + if (grid[i][j] == 0) { + count++; + } else { + break; + } + } + zeros[i] = count; + } + int swaps = 0; + for (int i = 0; i < n; i++) { + int needed = n - i - 1; + int j = i; + while (j < n && zeros[j] < needed) { + j++; + } + if (j == n) { + return -1; + } + while (j > i) { + int temp = zeros[j]; + zeros[j] = zeros[j - 1]; + zeros[j - 1] = temp; + j--; + swaps++; + } + } + return swaps; + } +} diff --git a/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.kt b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.kt new file mode 100644 index 00000000..e584459c --- /dev/null +++ b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.kt @@ -0,0 +1,36 @@ +class Solution { + fun minSwaps(grid: Array): Int { + val n = grid.size + val zeros = IntArray(n) + for (i in 0 until n) { + var count = 0 + for (j in n - 1 downTo 0) { + if (grid[i][j] == 0) { + count++ + } else { + break + } + } + zeros[i] = count + } + var swaps = 0 + for (i in 0 until n) { + val needed = n - i - 1 + var j = i + while (j < n && zeros[j] < needed) { + j++ + } + if (j == n) { + return -1 + } + while (j > i) { + val temp = zeros[j] + zeros[j] = zeros[j - 1] + zeros[j - 1] = temp + j-- + swaps++ + } + } + return swaps + } +} diff --git a/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.py b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.py new file mode 100644 index 00000000..ff23a39f --- /dev/null +++ b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.py @@ -0,0 +1,29 @@ +class Solution: + def minSwaps(self, grid): + n = len(grid) + zeros = [] + + for row in grid: + count = 0 + for j in range(n - 1, -1, -1): + if row[j] == 0: + count += 1 + else: + break + zeros.append(count) + + swaps = 0 + + for i in range(n): + needed = n - i - 1 + j = i + while j < n and zeros[j] < needed: + j += 1 + if j == n: + return -1 + while j > i: + zeros[j], zeros[j - 1] = zeros[j - 1], zeros[j] + j -= 1 + swaps += 1 + + return swaps diff --git a/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.py2 b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.py2 new file mode 100644 index 00000000..0850b477 --- /dev/null +++ b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.py2 @@ -0,0 +1,29 @@ +class Solution(object): + def minSwaps(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + n = len(grid) + zeros = [] + for row in grid: + count = 0 + for j in range(n - 1, -1, -1): + if row[j] == 0: + count += 1 + else: + break + zeros.append(count) + swaps = 0 + for i in range(n): + needed = n - i - 1 + j = i + while j < n and zeros[j] < needed: + j += 1 + if j == n: + return -1 + while j > i: + zeros[j], zeros[j - 1] = zeros[j - 1], zeros[j] + j -= 1 + swaps += 1 + return swaps diff --git a/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.rb b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.rb new file mode 100644 index 00000000..22a4d3ec --- /dev/null +++ b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.rb @@ -0,0 +1,32 @@ +# @param {Integer[][]} grid +# @return {Integer} +def min_swaps(grid) + n = grid.size + zeros = [] + grid.each do |row| + count = 0 + (n-1).downto(0) do |j| + if row[j] == 0 + count += 1 + else + break + end + end + zeros << count + end + swaps = 0 + (0...n).each do |i| + needed = n - i - 1 + j = i + while j < n && zeros[j] < needed + j += 1 + end + return -1 if j == n + while j > i + zeros[j], zeros[j-1] = zeros[j-1], zeros[j] + j -= 1 + swaps += 1 + end + end + swaps +end diff --git a/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.rs b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.rs new file mode 100644 index 00000000..aeeaa6b5 --- /dev/null +++ b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.rs @@ -0,0 +1,34 @@ +impl Solution { + pub fn min_swaps(grid: Vec>) -> i32 { + let n = grid.len(); + let mut zeros = vec![0; n]; + for i in 0..n { + let mut count = 0; + for j in (0..n).rev() { + if grid[i][j] == 0 { + count += 1; + } else { + break; + } + } + zeros[i] = count; + } + let mut swaps = 0; + for i in 0..n { + let needed = n - i - 1; + let mut j = i; + while j < n && zeros[j] < needed { + j += 1; + } + if j == n { + return -1; + } + while j > i { + zeros.swap(j, j - 1); + j -= 1; + swaps += 1; + } + } + swaps + } +} diff --git a/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.swift b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.swift new file mode 100644 index 00000000..60696214 --- /dev/null +++ b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.swift @@ -0,0 +1,34 @@ +class Solution { + func minSwaps(_ grid: [[Int]]) -> Int { + let n = grid.count + var zeros = [Int](repeating: 0, count: n) + for i in 0.. i { + zeros.swapAt(j, j - 1) + j -= 1 + swaps += 1 + } + } + return swaps + } +} diff --git a/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.ts b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.ts new file mode 100644 index 00000000..027e09dd --- /dev/null +++ b/tests/1501-2000/1536. minimum-swaps-to-arrange-a-binary-grid/sol.ts @@ -0,0 +1,32 @@ +function minSwaps(grid: number[][]): number { + const n = grid.length; + const zeros: number[] = []; + for (let i = 0; i < n; i++) { + let count = 0; + for (let j = n - 1; j >= 0; j--) { + if (grid[i][j] === 0) { + count++; + } else { + break; + } + } + zeros.push(count); + } + let swaps = 0; + for (let i = 0; i < n; i++) { + const needed = n - i - 1; + let j = i; + while (j < n && zeros[j] < needed) { + j++; + } + if (j === n) { + return -1; + } + while (j > i) { + [zeros[j], zeros[j - 1]] = [zeros[j - 1], zeros[j]]; + j--; + swaps++; + } + } + return swaps; +} diff --git a/tests/1501-2000/1537. get-the-maximum-score/manifest.yaml b/tests/1501-2000/1537. get-the-maximum-score/manifest.yaml new file mode 100644 index 00000000..dcd9221c --- /dev/null +++ b/tests/1501-2000/1537. get-the-maximum-score/manifest.yaml @@ -0,0 +1,348 @@ +entry: + id: 1537 + title: "get-the-maximum-score" + params: + nums1: + type: array + items: + type: int + nums2: + type: array + items: + type: int + call: + cpp: "Solution().maxSum({nums1}, {nums2})" + rust: "Solution::max_sum({nums1}, {nums2})" + python3: "Solution().maxSum({nums1}, {nums2})" + python2: "Solution().maxSum({nums1}, {nums2})" + ruby: "max_sum({nums1}, {nums2})" + java: "new Solution().maxSum({nums1}, {nums2})" + csharp: "new Solution().MaxSum({nums1}, {nums2})" + kotlin: "Solution().maxSum({nums1}, {nums2})" + go: "maxSum({nums1}, {nums2})" + dart: "Solution().maxSum({nums1}, {nums2})" + swift: "Solution().maxSum({nums1}, {nums2})" + typescript: "maxSum({nums1}, {nums2})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxSum(nums1, nums2, {result})" + checker: | + class Checker: + def maxSum(self, nums1, nums2, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + i = j = 0 + left = right = answer = 0 + while i < len(nums1) and j < len(nums2): + if nums1[i] == nums2[j]: + answer += max(left, right) + nums1[i] + left = right = 0 + i += 1 + j += 1 + elif nums1[i] < nums2[j]: + left += nums1[i] + i += 1 + else: + right += nums2[j] + j += 1 + left += sum(nums1[i:]) + right += sum(nums2[j:]) + expected = (answer + max(left, right)) % 1000000007 + return result == expected + +seed: 1537 + +tests: + - name: example-one + in: + nums1: [2, 4, 5, 8, 10] + nums2: [4, 6, 8, 9] + out: 30 + - name: example-two + in: + nums1: [1, 3, 5, 7, 9] + nums2: [3, 5, 100] + out: 109 + - name: example-three + in: + nums1: [1, 2, 3, 4, 5] + nums2: [6, 7, 8, 9, 10] + out: 40 + - name: one-common-value + in: + nums1: [1] + nums2: [1] + out: 1 + - name: one-disjoint-value + in: + nums1: [1] + nums2: [2] + out: 2 + - name: maximum-singleton + in: + nums1: [10000000] + nums2: [10000000] + out: 10000000 + - name: identical-three + in: + nums1: [1, 2, 3] + nums2: [1, 2, 3] + out: 6 + - name: fully-disjoint + in: + nums1: [1, 3, 5] + nums2: [2, 4, 6] + out: 12 + - name: two-crossings + in: + nums1: [1, 2, 10] + nums2: [2, 3, 10] + out: 16 + - name: one-crossing-middle + in: + nums1: [1, 5, 10] + nums2: [2, 5, 9] + out: 17 + - name: prefer-first-prefix + in: + nums1: [1, 100] + nums2: [1, 2, 3] + out: 101 + - name: prefer-second-suffix + in: + nums1: [1, 2, 3] + nums2: [3, 100] + out: 106 + - name: disjoint-even-odd + in: + nums1: [2, 4, 6, 8] + nums2: [1, 3, 5, 7] + out: 20 + - name: identical-four + in: + nums1: [1, 4, 7, 10] + nums2: [1, 4, 7, 10] + out: 22 + - name: alternating-crossings + in: + nums1: [1, 2, 4, 8, 16] + nums2: [2, 3, 5, 8, 13, 21] + out: 53 + - name: disjoint-medium + in: + nums1: [10, 20, 30] + nums2: [5, 15, 25, 35] + out: 80 + - name: repeated-choice-segments + in: + nums1: [1, 100, 200] + nums2: [50, 100, 150, 200] + out: 500 + - name: crossing-at-two-points + in: + nums1: [1, 2, 100, 101] + nums2: [2, 3, 4, 101] + out: 204 + - name: high-values-common + in: + nums1: [9999990, 10000000] + nums2: [1, 9999990, 10000000] + out: 19999991 + - name: high-values-disjoint + in: + nums1: [1, 9999999] + nums2: [2, 9999998] + out: 10000000 + - name: four-way-segments + in: + nums1: [1, 50, 100, 150] + nums2: [25, 50, 75, 150] + out: 325 + - name: sparse-common-values + in: + nums1: [3, 6, 9, 12] + nums2: [1, 3, 5, 9, 13] + out: 32 + - name: common-large-tail + in: + nums1: [1, 2, 3, 10000000] + nums2: [2, 3, 4, 10000000] + out: 10000010 + - name: disjoint-three-hundreds + in: + nums1: [100, 200, 300] + nums2: [50, 150, 250] + out: 600 + - name: common-first-and-last + in: + nums1: [1, 10, 20, 30] + nums2: [5, 10, 15, 30] + out: 65 + - name: single-common-middle + in: + nums1: [7, 8, 9] + nums2: [1, 8, 10] + out: 25 + - name: powers-with-crossings + in: + nums1: [1, 4, 9, 16] + nums2: [2, 4, 8, 16] + out: 31 + - name: short-chain + in: + nums1: [1, 2, 3, 4, 5, 6] + nums2: [3, 6, 9] + out: 30 + - name: large-common-tail + in: + nums1: [2, 100, 200, 300] + nums2: [1, 50, 100, 250, 300] + out: 701 + - name: large-gap-choice + in: + nums1: [1, 1000, 10000] + nums2: [2, 1000, 20000] + out: 21002 + - name: multiple-small-crossings + in: + nums1: [1, 2, 5, 6, 10] + nums2: [2, 4, 6, 8, 10] + out: 32 + - name: all-second-better + in: + nums1: [5, 10, 15] + nums2: [1, 2, 3] + out: 30 + - name: common-extremes + in: + nums1: [1, 100, 1000] + nums2: [1, 50, 100, 500, 1000] + out: 1651 + - name: alternating-odd-common + in: + nums1: [2, 3, 7, 11] + nums2: [1, 3, 5, 7, 9, 11] + out: 37 + - name: maximum-common-tail + in: + nums1: [9999999, 10000000] + nums2: [9999998, 10000000] + out: 19999999 + - name: generated-balanced-medium + in: + nums1: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 10000000 + distinct: true + sorted: true + elemType: "int" + nums2: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 10000000 + distinct: true + sorted: true + elemType: "int" + - name: generated-large-first + in: + nums1: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 10000000 + distinct: true + sorted: true + elemType: "int" + nums2: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 10000000 + distinct: true + sorted: true + elemType: "int" + - name: generated-large-second + in: + nums1: + gen: "array" + len: 99999 + of: + gen: "int" + min: 1 + max: 10000000 + distinct: true + sorted: true + elemType: "int" + nums2: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 10000000 + distinct: true + sorted: true + elemType: "int" + - name: generated-short-dense + in: + nums1: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 2000 + distinct: true + sorted: true + elemType: "int" + nums2: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 2000 + distinct: true + sorted: true + elemType: "int" + - name: generated-large-sparse + in: + nums1: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 10000000 + distinct: true + sorted: true + elemType: "int" + nums2: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 10000000 + distinct: true + sorted: true + elemType: "int" diff --git a/tests/1501-2000/1537. get-the-maximum-score/sol.cpp b/tests/1501-2000/1537. get-the-maximum-score/sol.cpp new file mode 100644 index 00000000..6660f9c5 --- /dev/null +++ b/tests/1501-2000/1537. get-the-maximum-score/sol.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int maxSum(vector& nums1, vector& nums2) { + int p1 = 0, p2 = 0; + long long sum1 = 0, sum2 = 0, result = 0; + while (p1 < nums1.size() && p2 < nums2.size()) { + if (nums1[p1] == nums2[p2]) { + result += max(sum1, sum2) + nums1[p1]; + sum1 = 0; sum2 = 0; + p1++; p2++; + } else if (nums1[p1] < nums2[p2]) { + sum1 += nums1[p1]; + p1++; + } else { + sum2 += nums2[p2]; + p2++; + } + } + while (p1 < nums1.size()) { + sum1 += nums1[p1]; + p1++; + } + while (p2 < nums2.size()) { + sum2 += nums2[p2]; + p2++; + } + return (int)((result + max(sum1, sum2)) % 1000000007); + } +}; diff --git a/tests/1501-2000/1537. get-the-maximum-score/sol.cs b/tests/1501-2000/1537. get-the-maximum-score/sol.cs new file mode 100644 index 00000000..033103af --- /dev/null +++ b/tests/1501-2000/1537. get-the-maximum-score/sol.cs @@ -0,0 +1,28 @@ +public class Solution { + public int MaxSum(int[] nums1, int[] nums2) { + int p1 = 0, p2 = 0; + long sum1 = 0, sum2 = 0, result = 0; + while (p1 < nums1.Length && p2 < nums2.Length) { + if (nums1[p1] == nums2[p2]) { + result += Math.Max(sum1, sum2) + nums1[p1]; + sum1 = 0; sum2 = 0; + p1++; p2++; + } else if (nums1[p1] < nums2[p2]) { + sum1 += nums1[p1]; + p1++; + } else { + sum2 += nums2[p2]; + p2++; + } + } + while (p1 < nums1.Length) { + sum1 += nums1[p1]; + p1++; + } + while (p2 < nums2.Length) { + sum2 += nums2[p2]; + p2++; + } + return (int)((result + Math.Max(sum1, sum2)) % 1000000007); + } +} diff --git a/tests/1501-2000/1537. get-the-maximum-score/sol.dart b/tests/1501-2000/1537. get-the-maximum-score/sol.dart new file mode 100644 index 00000000..7ff13911 --- /dev/null +++ b/tests/1501-2000/1537. get-the-maximum-score/sol.dart @@ -0,0 +1,28 @@ +class Solution { + int maxSum(List nums1, List nums2) { + int p1 = 0, p2 = 0; + int sum1 = 0, sum2 = 0, result = 0; + while (p1 < nums1.length && p2 < nums2.length) { + if (nums1[p1] == nums2[p2]) { + result += (sum1 > sum2 ? sum1 : sum2) + nums1[p1]; + sum1 = 0; sum2 = 0; + p1++; p2++; + } else if (nums1[p1] < nums2[p2]) { + sum1 += nums1[p1]; + p1++; + } else { + sum2 += nums2[p2]; + p2++; + } + } + while (p1 < nums1.length) { + sum1 += nums1[p1]; + p1++; + } + while (p2 < nums2.length) { + sum2 += nums2[p2]; + p2++; + } + return (result + (sum1 > sum2 ? sum1 : sum2)) % 1000000007; + } +} diff --git a/tests/1501-2000/1537. get-the-maximum-score/sol.go b/tests/1501-2000/1537. get-the-maximum-score/sol.go new file mode 100644 index 00000000..6c2df8f6 --- /dev/null +++ b/tests/1501-2000/1537. get-the-maximum-score/sol.go @@ -0,0 +1,37 @@ +func maxSum(nums1 []int, nums2 []int) int { + p1, p2 := 0, 0 + sum1, sum2, result := int64(0), int64(0), int64(0) + for p1 < len(nums1) && p2 < len(nums2) { + if nums1[p1] == nums2[p2] { + if sum1 > sum2 { + result += sum1 + } else { + result += sum2 + } + result += int64(nums1[p1]) + sum1, sum2 = 0, 0 + p1++ + p2++ + } else if nums1[p1] < nums2[p2] { + sum1 += int64(nums1[p1]) + p1++ + } else { + sum2 += int64(nums2[p2]) + p2++ + } + } + for p1 < len(nums1) { + sum1 += int64(nums1[p1]) + p1++ + } + for p2 < len(nums2) { + sum2 += int64(nums2[p2]) + p2++ + } + if sum1 > sum2 { + result += sum1 + } else { + result += sum2 + } + return int(result % 1000000007) +} diff --git a/tests/1501-2000/1537. get-the-maximum-score/sol.java b/tests/1501-2000/1537. get-the-maximum-score/sol.java new file mode 100644 index 00000000..6605a36a --- /dev/null +++ b/tests/1501-2000/1537. get-the-maximum-score/sol.java @@ -0,0 +1,28 @@ +class Solution { + public int maxSum(int[] nums1, int[] nums2) { + int p1 = 0, p2 = 0; + long sum1 = 0, sum2 = 0, result = 0; + while (p1 < nums1.length && p2 < nums2.length) { + if (nums1[p1] == nums2[p2]) { + result += Math.max(sum1, sum2) + nums1[p1]; + sum1 = 0; sum2 = 0; + p1++; p2++; + } else if (nums1[p1] < nums2[p2]) { + sum1 += nums1[p1]; + p1++; + } else { + sum2 += nums2[p2]; + p2++; + } + } + while (p1 < nums1.length) { + sum1 += nums1[p1]; + p1++; + } + while (p2 < nums2.length) { + sum2 += nums2[p2]; + p2++; + } + return (int)((result + Math.max(sum1, sum2)) % 1000000007); + } +} diff --git a/tests/1501-2000/1537. get-the-maximum-score/sol.kt b/tests/1501-2000/1537. get-the-maximum-score/sol.kt new file mode 100644 index 00000000..8139c71d --- /dev/null +++ b/tests/1501-2000/1537. get-the-maximum-score/sol.kt @@ -0,0 +1,33 @@ +class Solution { + fun maxSum(nums1: IntArray, nums2: IntArray): Int { + var p1 = 0 + var p2 = 0 + var sum1 = 0L + var sum2 = 0L + var result = 0L + while (p1 < nums1.size && p2 < nums2.size) { + if (nums1[p1] == nums2[p2]) { + result += maxOf(sum1, sum2) + nums1[p1] + sum1 = 0 + sum2 = 0 + p1++ + p2++ + } else if (nums1[p1] < nums2[p2]) { + sum1 += nums1[p1] + p1++ + } else { + sum2 += nums2[p2] + p2++ + } + } + while (p1 < nums1.size) { + sum1 += nums1[p1] + p1++ + } + while (p2 < nums2.size) { + sum2 += nums2[p2] + p2++ + } + return ((result + maxOf(sum1, sum2)) % 1000000007L).toInt() + } +} diff --git a/tests/1501-2000/1537. get-the-maximum-score/sol.py b/tests/1501-2000/1537. get-the-maximum-score/sol.py new file mode 100644 index 00000000..f790426e --- /dev/null +++ b/tests/1501-2000/1537. get-the-maximum-score/sol.py @@ -0,0 +1,31 @@ +class Solution: + def maxSum(self, nums1: List[int], nums2: List[int]) -> int: + ## RC ## + ## APPROACH : GREEDY ## + ## LOGIC ## + ## 1. similar to merging 2 sorted arrays + ## 2. Maintain sum for each array + ## 3. when you find the same element in both arrays, only take maximum of sum1, sum2 and reset them + + p1, p2, sum1, sum2, result = 0, 0, 0, 0, 0 + while p1 < len(nums1) and p2 < len(nums2): + if nums1[p1] == nums2[p2]: + result += max(sum1, sum2) + nums1[p1] + sum1, sum2 = 0, 0 + p1, p2 = p1 + 1, p2 + 1 + elif nums1[p1] < nums2[p2]: + sum1 += nums1[p1] + p1 += 1 + else: + sum2 += nums2[p2] + p2 += 1 + + while p1 < len(nums1): + sum1 += nums1[p1] + p1 += 1 + + while p2 < len(nums2): + sum2 += nums2[p2] + p2 += 1 + + return (result + max(sum1, sum2)) % (10**9 + 7) diff --git a/tests/1501-2000/1537. get-the-maximum-score/sol.py2 b/tests/1501-2000/1537. get-the-maximum-score/sol.py2 new file mode 100644 index 00000000..99f5ae9f --- /dev/null +++ b/tests/1501-2000/1537. get-the-maximum-score/sol.py2 @@ -0,0 +1,27 @@ +class Solution(object): + def maxSum(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: int + """ + p1, p2, sum1, sum2, result = 0, 0, 0, 0, 0 + while p1 < len(nums1) and p2 < len(nums2): + if nums1[p1] == nums2[p2]: + result += max(sum1, sum2) + nums1[p1] + sum1, sum2 = 0, 0 + p1 += 1 + p2 += 1 + elif nums1[p1] < nums2[p2]: + sum1 += nums1[p1] + p1 += 1 + else: + sum2 += nums2[p2] + p2 += 1 + while p1 < len(nums1): + sum1 += nums1[p1] + p1 += 1 + while p2 < len(nums2): + sum2 += nums2[p2] + p2 += 1 + return (result + max(sum1, sum2)) % (10**9 + 7) diff --git a/tests/1501-2000/1537. get-the-maximum-score/sol.rb b/tests/1501-2000/1537. get-the-maximum-score/sol.rb new file mode 100644 index 00000000..38a8d9ad --- /dev/null +++ b/tests/1501-2000/1537. get-the-maximum-score/sol.rb @@ -0,0 +1,29 @@ +# @param {Integer[]} nums1 +# @param {Integer[]} nums2 +# @return {Integer} +def max_sum(nums1, nums2) + p1, p2, sum1, sum2, result = 0, 0, 0, 0, 0 + while p1 < nums1.length && p2 < nums2.length + if nums1[p1] == nums2[p2] + result += [sum1, sum2].max + nums1[p1] + sum1, sum2 = 0, 0 + p1 += 1 + p2 += 1 + elsif nums1[p1] < nums2[p2] + sum1 += nums1[p1] + p1 += 1 + else + sum2 += nums2[p2] + p2 += 1 + end + end + while p1 < nums1.length + sum1 += nums1[p1] + p1 += 1 + end + while p2 < nums2.length + sum2 += nums2[p2] + p2 += 1 + end + (result + [sum1, sum2].max) % (10**9 + 7) +end diff --git a/tests/1501-2000/1537. get-the-maximum-score/sol.rs b/tests/1501-2000/1537. get-the-maximum-score/sol.rs new file mode 100644 index 00000000..2ad7affd --- /dev/null +++ b/tests/1501-2000/1537. get-the-maximum-score/sol.rs @@ -0,0 +1,30 @@ +impl Solution { + pub fn max_sum(nums1: Vec, nums2: Vec) -> i32 { + let (mut p1, mut p2) = (0, 0); + let (mut sum1, mut sum2, mut result) = (0i64, 0i64, 0i64); + while p1 < nums1.len() && p2 < nums2.len() { + if nums1[p1] == nums2[p2] { + result += sum1.max(sum2) + nums1[p1] as i64; + sum1 = 0; + sum2 = 0; + p1 += 1; + p2 += 1; + } else if nums1[p1] < nums2[p2] { + sum1 += nums1[p1] as i64; + p1 += 1; + } else { + sum2 += nums2[p2] as i64; + p2 += 1; + } + } + while p1 < nums1.len() { + sum1 += nums1[p1] as i64; + p1 += 1; + } + while p2 < nums2.len() { + sum2 += nums2[p2] as i64; + p2 += 1; + } + ((result + sum1.max(sum2)) % 1_000_000_007) as i32 + } +} diff --git a/tests/1501-2000/1537. get-the-maximum-score/sol.swift b/tests/1501-2000/1537. get-the-maximum-score/sol.swift new file mode 100644 index 00000000..290e2712 --- /dev/null +++ b/tests/1501-2000/1537. get-the-maximum-score/sol.swift @@ -0,0 +1,28 @@ +class Solution { + func maxSum(_ nums1: [Int], _ nums2: [Int]) -> Int { + var p1 = 0, p2 = 0 + var sum1 = 0, sum2 = 0, result = 0 + while p1 < nums1.count && p2 < nums2.count { + if nums1[p1] == nums2[p2] { + result += max(sum1, sum2) + nums1[p1] + sum1 = 0; sum2 = 0 + p1 += 1; p2 += 1 + } else if nums1[p1] < nums2[p2] { + sum1 += nums1[p1] + p1 += 1 + } else { + sum2 += nums2[p2] + p2 += 1 + } + } + while p1 < nums1.count { + sum1 += nums1[p1] + p1 += 1 + } + while p2 < nums2.count { + sum2 += nums2[p2] + p2 += 1 + } + return (result + max(sum1, sum2)) % 1000000007 + } +} diff --git a/tests/1501-2000/1537. get-the-maximum-score/sol.ts b/tests/1501-2000/1537. get-the-maximum-score/sol.ts new file mode 100644 index 00000000..d648a938 --- /dev/null +++ b/tests/1501-2000/1537. get-the-maximum-score/sol.ts @@ -0,0 +1,31 @@ +function maxSum(nums1: number[], nums2: number[]): number { + let p1 = 0, + p2 = 0; + let sum1 = 0, + sum2 = 0, + result = 0; + while (p1 < nums1.length && p2 < nums2.length) { + if (nums1[p1] === nums2[p2]) { + result += Math.max(sum1, sum2) + nums1[p1]; + sum1 = 0; + sum2 = 0; + p1++; + p2++; + } else if (nums1[p1] < nums2[p2]) { + sum1 += nums1[p1]; + p1++; + } else { + sum2 += nums2[p2]; + p2++; + } + } + while (p1 < nums1.length) { + sum1 += nums1[p1]; + p1++; + } + while (p2 < nums2.length) { + sum2 += nums2[p2]; + p2++; + } + return (result + Math.max(sum1, sum2)) % 1000000007; +} diff --git a/tests/1501-2000/1539. kth-missing-positive-number/manifest.yaml b/tests/1501-2000/1539. kth-missing-positive-number/manifest.yaml new file mode 100644 index 00000000..1c461e8b --- /dev/null +++ b/tests/1501-2000/1539. kth-missing-positive-number/manifest.yaml @@ -0,0 +1,315 @@ +entry: + id: 1539 + title: "kth-missing-positive-number" + params: + arr: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().findKthPositive({arr}, {k})" + rust: "Solution::find_kth_positive({arr}, {k})" + python3: "Solution().findKthPositive({arr}, {k})" + python2: "Solution().findKthPositive({arr}, {k})" + ruby: "find_kth_positive({arr}, {k})" + java: "new Solution().findKthPositive({arr}, {k})" + csharp: "new Solution().FindKthPositive({arr}, {k})" + kotlin: "Solution().findKthPositive({arr}, {k})" + go: "findKthPositive({arr}, {k})" + dart: "Solution().findKthPositive({arr}, {k})" + swift: "Solution().findKthPositive({arr}, {k})" + typescript: "findKthPositive({arr}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().findKthPositive(arr, k, {result})" + checker: | + class Checker: + def findKthPositive(self, arr, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + present = set(arr) + missing = 0 + value = 1 + while missing < k: + if value not in present: + missing += 1 + value += 1 + return result == value - 1 + +seed: 1539001 + +tests: + - name: "example_one" + in: + arr: [2, 3, 4, 7, 11] + k: 5 + out: 9 + - name: "example_two" + in: + arr: [1, 2, 3, 4] + k: 2 + out: 6 + - name: "missing_one_before_first" + in: + arr: [2] + k: 1 + out: 1 + - name: "single_present_one" + in: + arr: [1] + k: 1 + out: 2 + - name: "single_present_max" + in: + arr: [1000] + k: 1000 + out: 1001 + - name: "all_initial_numbers" + in: + arr: [1, 2, 3, 4, 5] + k: 1 + out: 6 + - name: "gap_at_start" + in: + arr: [3, 4, 5] + k: 2 + out: 2 + - name: "gap_between_values" + in: + arr: [1, 3, 5, 7] + k: 3 + out: 6 + - name: "gap_after_array" + in: + arr: [2, 4, 6] + k: 5 + out: 8 + - name: "consecutive_prefix_then_gap" + in: + arr: [1, 2, 3, 10] + k: 4 + out: 7 + - name: "alternating_gaps" + in: + arr: [2, 4, 6, 8, 10] + k: 6 + out: 11 + - name: "large_gap_first" + in: + arr: [50, 51, 52] + k: 10 + out: 10 + - name: "large_gap_after_prefix" + in: + arr: [1, 2, 3, 100] + k: 10 + out: 13 + - name: "answer_at_array_boundary" + in: + arr: [2, 3, 4, 5] + k: 1 + out: 1 + - name: "answer_just_after_boundary" + in: + arr: [2, 3, 4, 5] + k: 2 + out: 6 + - name: "dense_low_values" + in: + arr: [1, 2, 4, 5, 6, 8] + k: 3 + out: 9 + - name: "sparse_low_values" + in: + arr: [10, 20, 30, 40] + k: 7 + out: 7 + - name: "negative_not_allowed_boundary_values" + in: + arr: [1, 1000] + k: 999 + out: 1001 + - name: "near_max_array_values" + in: + arr: [996, 997, 998, 999, 1000] + k: 5 + out: 5 + - name: "large_k_small_array" + in: + arr: [1, 2] + k: 1000 + out: 1002 + - name: "large_k_dense_array" + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + k: 1000 + out: 1010 + - name: "odd_numbers" + in: + arr: [1, 3, 5, 7, 9] + k: 5 + out: 10 + - name: "even_numbers" + in: + arr: [2, 4, 6, 8, 10] + k: 5 + out: 9 + - name: "one_missing_each_block" + in: + arr: [1, 2, 4, 5, 7, 8, 10, 11] + k: 4 + out: 12 + - name: "long_prefix" + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + k: 3 + out: 18 + - name: "long_prefix_with_early_gap" + in: + arr: [1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + k: 4 + out: 18 + - name: "mixed_small_gaps" + in: + arr: [2, 5, 6, 9, 12, 13] + k: 8 + out: 14 + - name: "first_missing_is_last_query" + in: + arr: [2, 3, 4, 5, 6] + k: 1 + out: 1 + - name: "many_missing_before_first" + in: + arr: [20, 21, 22] + k: 19 + out: 19 + - name: "one_element_gap_exact" + in: + arr: [1, 2, 4] + k: 1 + out: 3 + - name: "one_element_gap_after" + in: + arr: [1, 2, 4] + k: 2 + out: 5 + - name: "full_small_range_except_middle" + in: + arr: [1, 2, 3, 5, 6, 7, 8, 9, 10] + k: 1 + out: 4 + - name: "full_small_range_except_start" + in: + arr: [2, 3, 4, 5, 6, 7, 8, 9, 10] + k: 1 + out: 1 + - name: "full_small_range_except_end" + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8, 9] + k: 1 + out: 10 + - name: "generator_small" + seed: 153901 + in: + arr: + gen: "array" + len: + gen: "int" + min: 1 + max: 25 + of: + gen: "int" + min: 1 + max: 1000 + distinct: true + sorted: true + elemType: "int" + k: + gen: "int" + min: 1 + max: 25 + - name: "generator_medium" + seed: 153902 + in: + arr: + gen: "array" + len: + gen: "int" + min: 100 + max: 250 + of: + gen: "int" + min: 1 + max: 1000 + distinct: true + sorted: true + elemType: "int" + k: + gen: "int" + min: 1 + max: 1000 + - name: "generator_large_sparse" + seed: 153903 + in: + arr: + gen: "array" + len: + gen: "int" + min: 500 + max: 1000 + of: + gen: "int" + min: 1 + max: 1000 + distinct: true + sorted: true + elemType: "int" + k: + gen: "int" + min: 1 + max: 1000 + - name: "generator_dense_prefix" + seed: 153904 + in: + arr: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000 + distinct: true + sorted: true + elemType: "int" + k: + gen: "int" + min: 1 + max: 1000 + - name: "generator_singleton" + seed: 153905 + in: + arr: + gen: "array" + len: 1 + of: + gen: "int" + min: 1 + max: 1000 + distinct: true + sorted: true + elemType: "int" + k: + gen: "int" + min: 1 + max: 1000 diff --git a/tests/1501-2000/1539. kth-missing-positive-number/sol.cpp b/tests/1501-2000/1539. kth-missing-positive-number/sol.cpp new file mode 100644 index 00000000..88c7a71a --- /dev/null +++ b/tests/1501-2000/1539. kth-missing-positive-number/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int findKthPositive(vector& arr, int k) { + int low = 0, high = arr.size() - 1; + while (low <= high) { + int mid = (low + high) / 2; + int missing = arr[mid] - (mid + 1); + if (missing < k) { + low = mid + 1; + } else { + high = mid - 1; + } + } + return high + 1 + k; + } +}; diff --git a/tests/1501-2000/1539. kth-missing-positive-number/sol.cs b/tests/1501-2000/1539. kth-missing-positive-number/sol.cs new file mode 100644 index 00000000..37695980 --- /dev/null +++ b/tests/1501-2000/1539. kth-missing-positive-number/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int FindKthPositive(int[] arr, int k) { + int low = 0, high = arr.Length - 1; + while (low <= high) { + int mid = (low + high) / 2; + int missing = arr[mid] - (mid + 1); + if (missing < k) { + low = mid + 1; + } else { + high = mid - 1; + } + } + return high + 1 + k; + } +} diff --git a/tests/1501-2000/1539. kth-missing-positive-number/sol.dart b/tests/1501-2000/1539. kth-missing-positive-number/sol.dart new file mode 100644 index 00000000..f04f973f --- /dev/null +++ b/tests/1501-2000/1539. kth-missing-positive-number/sol.dart @@ -0,0 +1,15 @@ +class Solution { + int findKthPositive(List arr, int k) { + int low = 0, high = arr.length - 1; + while (low <= high) { + int mid = (low + high) ~/ 2; + int missing = arr[mid] - (mid + 1); + if (missing < k) { + low = mid + 1; + } else { + high = mid - 1; + } + } + return high + 1 + k; + } +} diff --git a/tests/1501-2000/1539. kth-missing-positive-number/sol.go b/tests/1501-2000/1539. kth-missing-positive-number/sol.go new file mode 100644 index 00000000..1b918625 --- /dev/null +++ b/tests/1501-2000/1539. kth-missing-positive-number/sol.go @@ -0,0 +1,13 @@ +func findKthPositive(arr []int, k int) int { + low, high := 0, len(arr)-1 + for low <= high { + mid := (low + high) / 2 + missing := arr[mid] - (mid + 1) + if missing < k { + low = mid + 1 + } else { + high = mid - 1 + } + } + return high + 1 + k +} diff --git a/tests/1501-2000/1539. kth-missing-positive-number/sol.java b/tests/1501-2000/1539. kth-missing-positive-number/sol.java new file mode 100644 index 00000000..684d7f9c --- /dev/null +++ b/tests/1501-2000/1539. kth-missing-positive-number/sol.java @@ -0,0 +1,15 @@ +class Solution { + public int findKthPositive(int[] arr, int k) { + int low = 0, high = arr.length - 1; + while (low <= high) { + int mid = (low + high) / 2; + int missing = arr[mid] - (mid + 1); + if (missing < k) { + low = mid + 1; + } else { + high = mid - 1; + } + } + return high + 1 + k; + } +} diff --git a/tests/1501-2000/1539. kth-missing-positive-number/sol.kt b/tests/1501-2000/1539. kth-missing-positive-number/sol.kt new file mode 100644 index 00000000..9d19ca69 --- /dev/null +++ b/tests/1501-2000/1539. kth-missing-positive-number/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun findKthPositive(arr: IntArray, k: Int): Int { + var low = 0 + var high = arr.size - 1 + while (low <= high) { + val mid = (low + high) / 2 + val missing = arr[mid] - (mid + 1) + if (missing < k) { + low = mid + 1 + } else { + high = mid - 1 + } + } + return high + 1 + k + } +} diff --git a/tests/1501-2000/1539. kth-missing-positive-number/sol.py b/tests/1501-2000/1539. kth-missing-positive-number/sol.py new file mode 100644 index 00000000..f1b50ec6 --- /dev/null +++ b/tests/1501-2000/1539. kth-missing-positive-number/sol.py @@ -0,0 +1,14 @@ +class Solution: + def findKthPositive(self, arr: List[int], k: int) -> int: + low, high = 0, len(arr) - 1 + + while low <= high: + mid = (low + high) // 2 + missing = arr[mid] - (mid + 1) + + if missing < k: + low = mid + 1 + else: + high = mid - 1 + + return high + 1 + k diff --git a/tests/1501-2000/1539. kth-missing-positive-number/sol.py2 b/tests/1501-2000/1539. kth-missing-positive-number/sol.py2 new file mode 100644 index 00000000..4aaf46cf --- /dev/null +++ b/tests/1501-2000/1539. kth-missing-positive-number/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def findKthPositive(self, arr, k): + """ + :type arr: List[int] + :type k: int + :rtype: int + """ + low, high = 0, len(arr) - 1 + while low <= high: + mid = (low + high) // 2 + missing = arr[mid] - (mid + 1) + if missing < k: + low = mid + 1 + else: + high = mid - 1 + return high + 1 + k diff --git a/tests/1501-2000/1539. kth-missing-positive-number/sol.rb b/tests/1501-2000/1539. kth-missing-positive-number/sol.rb new file mode 100644 index 00000000..34fb2f46 --- /dev/null +++ b/tests/1501-2000/1539. kth-missing-positive-number/sol.rb @@ -0,0 +1,13 @@ +def find_kth_positive(arr, k) + low, high = 0, arr.length - 1 + while low <= high + mid = (low + high) / 2 + missing = arr[mid] - (mid + 1) + if missing < k + low = mid + 1 + else + high = mid - 1 + end + end + return high + 1 + k +end diff --git a/tests/1501-2000/1539. kth-missing-positive-number/sol.rs b/tests/1501-2000/1539. kth-missing-positive-number/sol.rs new file mode 100644 index 00000000..9af735e6 --- /dev/null +++ b/tests/1501-2000/1539. kth-missing-positive-number/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn find_kth_positive(arr: Vec, k: i32) -> i32 { + let mut low = 0; + let mut high = arr.len() as i32 - 1; + while low <= high { + let mid = (low + high) / 2; + let missing = arr[mid as usize] - (mid + 1); + if missing < k { + low = mid + 1; + } else { + high = mid - 1; + } + } + return high + 1 + k; + } +} diff --git a/tests/1501-2000/1539. kth-missing-positive-number/sol.swift b/tests/1501-2000/1539. kth-missing-positive-number/sol.swift new file mode 100644 index 00000000..03e5bb0a --- /dev/null +++ b/tests/1501-2000/1539. kth-missing-positive-number/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func findKthPositive(_ arr: [Int], _ k: Int) -> Int { + var low = 0, high = arr.count - 1 + while low <= high { + let mid = (low + high) / 2 + let missing = arr[mid] - (mid + 1) + if missing < k { + low = mid + 1 + } else { + high = mid - 1 + } + } + return high + 1 + k + } +} diff --git a/tests/1501-2000/1539. kth-missing-positive-number/sol.ts b/tests/1501-2000/1539. kth-missing-positive-number/sol.ts new file mode 100644 index 00000000..d8c6aa2e --- /dev/null +++ b/tests/1501-2000/1539. kth-missing-positive-number/sol.ts @@ -0,0 +1,14 @@ +function findKthPositive(arr: number[], k: number): number { + let low = 0, + high = arr.length - 1; + while (low <= high) { + const mid = Math.floor((low + high) / 2); + const missing = arr[mid] - (mid + 1); + if (missing < k) { + low = mid + 1; + } else { + high = mid - 1; + } + } + return high + 1 + k; +} diff --git a/tests/1501-2000/1540. can-convert-string-in-k-moves/manifest.yaml b/tests/1501-2000/1540. can-convert-string-in-k-moves/manifest.yaml new file mode 100644 index 00000000..bf1622cd --- /dev/null +++ b/tests/1501-2000/1540. can-convert-string-in-k-moves/manifest.yaml @@ -0,0 +1,346 @@ +entry: + id: 1540 + title: "can-convert-string-in-k-moves" + params: + s: + type: string + t: + type: string + k: + type: int + call: + cpp: "Solution().canConvertString({s}, {t}, {k})" + rust: "Solution::can_convert_string({s}, {t}, {k})" + python3: "Solution().canConvertString({s}, {t}, {k})" + python2: "Solution().canConvertString({s}, {t}, {k})" + ruby: "can_convert_string({s}, {t}, {k})" + java: "new Solution().canConvertString({s}, {t}, {k})" + csharp: "new Solution().CanConvertString({s}, {t}, {k})" + kotlin: "Solution().canConvertString({s}, {t}, {k})" + go: "canConvertString({s}, {t}, {k})" + dart: "Solution().canConvertString({s}, {t}, {k})" + swift: "Solution().canConvertString({s}, {t}, {k})" + typescript: "canConvertString({s}, {t}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().canConvertString(s, t, k, {result})" + checker: | + class Checker: + def canConvertString(self, s, t, k, result): + if not isinstance(result, bool): + return False + if len(s) != len(t): + return result is False + used = {} + for a, b in zip(s, t): + diff = (ord(b) - ord(a)) % 26 + if diff == 0: + continue + used[diff] = used.get(diff, 0) + 1 + if diff + 26 * (used[diff] - 1) > k: + return result is False + return result is True + +seed: 1540 + +tests: + - name: example-one + in: + s: "input" + t: "ouput" + k: 9 + out: true + - name: example-two + in: + s: "abc" + t: "bcd" + k: 10 + out: false + - name: example-three + in: + s: "aab" + t: "bbb" + k: 27 + out: true + - name: identical-zero + in: + s: "abc" + t: "abc" + k: 0 + out: true + - name: one-shift-one-move + in: + s: "a" + t: "b" + k: 1 + out: true + - name: one-shift-no-move + in: + s: "a" + t: "b" + k: 0 + out: false + - name: wraparound + in: + s: "z" + t: "a" + k: 1 + out: true + - name: shift-twenty-six + in: + s: "a" + t: "a" + k: 26 + out: true + - name: repeated-shift-needs-twenty-seven + in: + s: "aa" + t: "bb" + k: 27 + out: true + - name: repeated-shift-too-small + in: + s: "aa" + t: "bb" + k: 26 + out: false + - name: distinct-shifts + in: + s: "abc" + t: "bdf" + k: 5 + out: true + - name: distinct-shifts-last-too-large + in: + s: "abc" + t: "bdf" + k: 2 + out: false + - name: same-diff-three-too-small + in: + s: "aaa" + t: "bbb" + k: 52 + out: false + - name: same-diff-three-boundary + in: + s: "aaa" + t: "bbb" + k: 53 + out: true + - name: same-diff-three-at-fifty-five + in: + s: "aaa" + t: "bbb" + k: 55 + out: true + - name: mismatch-length-shorter + in: + s: "ab" + t: "abc" + k: 100 + out: false + - name: mismatch-length-longer + in: + s: "abcd" + t: "abc" + k: 100 + out: false + - name: all-z-to-a + in: + s: "zzzz" + t: "aaaa" + k: 80 + out: true + - name: all-z-to-b + in: + s: "zzzz" + t: "bbbb" + k: 1 + out: false + - name: zero-shifts-only + in: + s: "aaaa" + t: "aaaa" + k: 0 + out: true + - name: mixed-zero-and-one + in: + s: "aaaa" + t: "abab" + k: 27 + out: true + - name: mixed-zero-and-one-too-small + in: + s: "aaaa" + t: "abab" + k: 1 + out: false + - name: repeated-diff-two + in: + s: "aaaa" + t: "cccc" + k: 80 + out: true + - name: repeated-diff-two-too-small + in: + s: "aaaa" + t: "cccc" + k: 79 + out: false + - name: wrap-diff-twenty-five + in: + s: "bbbb" + t: "aaaa" + k: 103 + out: true + - name: wrap-diff-twenty-five-repeat + in: + s: "bbbb" + t: "aaaa" + k: 76 + out: false + - name: high-k-repeated + in: + s: "aaaaa" + t: "bbbbb" + k: 1000000000 + out: true + - name: high-k-zero-shift-boundary + in: + s: "zzzzz" + t: "zzzzz" + k: 0 + out: true + - name: alternating-large-shifts + in: + s: "azaz" + t: "zaza" + k: 51 + out: true + - name: alternating-large-shifts-low + in: + s: "azaz" + t: "zaza" + k: 50 + out: false + - name: all-different-letters + in: + s: "abcdef" + t: "bcdefg" + k: 131 + out: true + - name: all-different-letters-low + in: + s: "abcdef" + t: "bcdefg" + k: 130 + out: false + - name: long-equal + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + t: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + k: 0 + out: true + - name: long-single-shift + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + t: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + k: 1000000000 + out: true + - name: long-repeated-shift-boundary + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + t: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + k: 26 + out: false + - name: mixed-repeated-shifts + in: + s: "aaaaaaaaaa" + t: "bbbbbbbbbb" + k: 235 + out: true + - name: mixed-repeated-shifts-low + in: + s: "aaaaaaaaaa" + t: "bbbbbbbbbb" + k: 234 + out: false + - name: generated-random-short + in: + s: + gen: "str" + len: 100 + alphabet: "abcxyz" + t: + gen: "str" + len: 100 + alphabet: "abcxyz" + k: + gen: "int" + min: 0 + max: 1000000000 + - name: generated-random-medium + in: + s: + gen: "str" + len: 1000 + alphabet: "abcmnz" + t: + gen: "str" + len: 1000 + alphabet: "abcmnz" + k: + gen: "int" + min: 0 + max: 1000000000 + - name: generated-random-large + in: + s: + gen: "str" + len: 50000 + alphabet: "abmz" + t: + gen: "str" + len: 50000 + alphabet: "abmz" + k: + gen: "int" + min: 0 + max: 1000000000 + - name: generated-random-max + in: + s: + gen: "str" + len: 100000 + alphabet: "az" + t: + gen: "str" + len: 100000 + alphabet: "az" + k: + gen: "int" + min: 0 + max: 1000000000 + - name: generated-random-max-wide-alphabet + in: + s: + gen: "str" + len: 100000 + alphabet: "afkpuz" + t: + gen: "str" + len: 100000 + alphabet: "afkpuz" + k: + gen: "int" + min: 0 + max: 1000000000 diff --git a/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.cpp b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.cpp new file mode 100644 index 00000000..087bac45 --- /dev/null +++ b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + bool canConvertString(string s, string t, int k) { + if (s.length() != t.length()) return false; + int shift_count[26] = {0}; + for (int i = 0; i < s.length(); ++i) { + if (s[i] == t[i]) continue; + int diff = (t[i] - s[i] + 26) % 26; + shift_count[diff]++; + if (diff + 26 * (shift_count[diff] - 1) > k) return false; + } + return true; + } +}; diff --git a/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.cs b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.cs new file mode 100644 index 00000000..2520f46f --- /dev/null +++ b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public bool CanConvertString(string s, string t, int k) { + if (s.Length != t.Length) return false; + int[] shiftCount = new int[26]; + for (int i = 0; i < s.Length; i++) { + if (s[i] == t[i]) continue; + int diff = (t[i] - s[i] + 26) % 26; + shiftCount[diff]++; + if (diff + 26 * (shiftCount[diff] - 1) > k) return false; + } + return true; + } +} diff --git a/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.dart b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.dart new file mode 100644 index 00000000..9beb7692 --- /dev/null +++ b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.dart @@ -0,0 +1,13 @@ +class Solution { + bool canConvertString(String s, String t, int k) { + if (s.length != t.length) return false; + List shiftCount = List.filled(26, 0); + for (int i = 0; i < s.length; i++) { + if (s.codeUnitAt(i) == t.codeUnitAt(i)) continue; + int diff = (t.codeUnitAt(i) - s.codeUnitAt(i) + 26) % 26; + shiftCount[diff]++; + if (diff + 26 * (shiftCount[diff] - 1) > k) return false; + } + return true; + } +} diff --git a/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.go b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.go new file mode 100644 index 00000000..5384c3c7 --- /dev/null +++ b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.go @@ -0,0 +1,17 @@ +func canConvertString(s string, t string, k int) bool { + if len(s) != len(t) { + return false + } + shiftCount := make([]int, 26) + for i := 0; i < len(s); i++ { + if s[i] == t[i] { + continue + } + diff := int(t[i]-s[i]+26) % 26 + shiftCount[diff]++ + if diff+26*(shiftCount[diff]-1) > k { + return false + } + } + return true +} diff --git a/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.java b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.java new file mode 100644 index 00000000..6af2e88f --- /dev/null +++ b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.java @@ -0,0 +1,13 @@ +class Solution { + public boolean canConvertString(String s, String t, int k) { + if (s.length() != t.length()) return false; + int[] shiftCount = new int[26]; + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == t.charAt(i)) continue; + int diff = (t.charAt(i) - s.charAt(i) + 26) % 26; + shiftCount[diff]++; + if (diff + 26 * (shiftCount[diff] - 1) > k) return false; + } + return true; + } +} diff --git a/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.kt b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.kt new file mode 100644 index 00000000..ad184a3e --- /dev/null +++ b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun canConvertString(s: String, t: String, k: Int): Boolean { + if (s.length != t.length) return false + val shiftCount = IntArray(26) + for (i in s.indices) { + if (s[i] == t[i]) continue + val diff = (t[i] - s[i] + 26) % 26 + shiftCount[diff]++ + if (diff + 26 * (shiftCount[diff] - 1) > k) return false + } + return true + } +} diff --git a/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.py b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.py new file mode 100644 index 00000000..4d525350 --- /dev/null +++ b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.py @@ -0,0 +1,25 @@ +from collections import defaultdict + + +class Solution(object): + def canConvertString(self, s, t, k): + """ + :type s: str + :type t: str + :type k: int + :rtype: bool + """ + if len(s) != len(t): + return False + + shift_count = defaultdict(int) + + for i in range(len(s)): + if s[i] == t[i]: + continue + diff = (ord(t[i]) - ord(s[i])) % 26 + shift_count[diff] += 1 + if diff + 26 * (shift_count[diff] - 1) > k: + return False + + return True diff --git a/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.py2 b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.py2 new file mode 100644 index 00000000..37923245 --- /dev/null +++ b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.py2 @@ -0,0 +1,19 @@ +class Solution(object): + def canConvertString(self, s, t, k): + """ + :type s: str + :type t: str + :type k: int + :rtype: bool + """ + if len(s) != len(t): + return False + shift_count = [0] * 26 + for i in range(len(s)): + if s[i] == t[i]: + continue + diff = (ord(t[i]) - ord(s[i])) % 26 + shift_count[diff] += 1 + if diff + 26 * (shift_count[diff] - 1) > k: + return False + return True diff --git a/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.rb b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.rb new file mode 100644 index 00000000..c3194791 --- /dev/null +++ b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.rb @@ -0,0 +1,11 @@ +def can_convert_string(s, t, k) + return false if s.length != t.length + shift_count = Array.new(26, 0) + (0...s.length).each do |i| + next if s[i] == t[i] + diff = (t[i].ord - s[i].ord) % 26 + shift_count[diff] += 1 + return false if diff + 26 * (shift_count[diff] - 1) > k + end + true +end diff --git a/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.rs b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.rs new file mode 100644 index 00000000..75b5523a --- /dev/null +++ b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn can_convert_string(s: String, t: String, k: i32) -> bool { + if s.len() != t.len() { return false; } + let s_bytes = s.as_bytes(); + let t_bytes = t.as_bytes(); + let mut shift_count = vec![0i32; 26]; + for i in 0..s_bytes.len() { + if s_bytes[i] == t_bytes[i] { continue; } + let diff = ((t_bytes[i] as i32 - s_bytes[i] as i32) % 26 + 26) % 26; + shift_count[diff as usize] += 1; + if diff + 26 * (shift_count[diff as usize] - 1) > k { return false; } + } + true + } +} diff --git a/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.swift b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.swift new file mode 100644 index 00000000..c2b65abb --- /dev/null +++ b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func canConvertString(_ s: String, _ t: String, _ k: Int) -> Bool { + if s.count != t.count { return false } + let sArr = Array(s.utf8) + let tArr = Array(t.utf8) + var shiftCount = [Int](repeating: 0, count: 26) + for i in 0.. k { return false } + } + return true + } +} diff --git a/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.ts b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.ts new file mode 100644 index 00000000..80359340 --- /dev/null +++ b/tests/1501-2000/1540. can-convert-string-in-k-moves/sol.ts @@ -0,0 +1,11 @@ +function canConvertString(s: string, t: string, k: number): boolean { + if (s.length !== t.length) return false; + const shiftCount: number[] = new Array(26).fill(0); + for (let i = 0; i < s.length; i++) { + if (s[i] === t[i]) continue; + const diff = (t.charCodeAt(i) - s.charCodeAt(i) + 26) % 26; + shiftCount[diff]++; + if (diff + 26 * (shiftCount[diff] - 1) > k) return false; + } + return true; +} diff --git a/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/manifest.yaml b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/manifest.yaml new file mode 100644 index 00000000..18820374 --- /dev/null +++ b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/manifest.yaml @@ -0,0 +1,215 @@ +entry: + id: 1541 + title: "minimum-insertions-to-balance-a-parentheses-string" + params: + s: + type: string + call: + cpp: "Solution().minInsertions({s})" + rust: "Solution::min_insertions({s})" + python3: "Solution().minInsertions({s})" + python2: "Solution().minInsertions({s})" + ruby: "min_insertions({s})" + java: "new Solution().minInsertions({s})" + csharp: "new Solution().MinInsertions({s})" + kotlin: "Solution().minInsertions({s})" + go: "minInsertions({s})" + dart: "Solution().minInsertions({s})" + swift: "Solution().minInsertions({s})" + typescript: "minInsertions({s})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minInsertions(s, {result})" + checker: | + class Checker: + def minInsertions(self, s, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + balance = 0 + expected = 0 + i = 0 + while i < len(s): + if s[i] == '(': + balance += 1 + i += 1 + elif i + 1 < len(s) and s[i + 1] == ')': + if balance: + balance -= 1 + else: + expected += 1 + i += 2 + else: + expected += 1 + if balance: + balance -= 1 + else: + expected += 1 + i += 1 + expected += 2 * balance + return result == expected + +seed: 1541 + +tests: + - name: example-one + in: + s: "(()))" + out: 1 + - name: example-two + in: + s: "())" + out: 0 + - name: example-three + in: + s: "))())(" + out: 3 + - name: single-open + in: + s: "(" + out: 2 + - name: single-close + in: + s: ")" + out: 2 + - name: double-close + in: + s: "))" + out: 1 + - name: single-pair + in: + s: "())" + out: 0 + - name: open-and-single-close + in: + s: "()" + out: 1 + - name: two-pairs + in: + s: "())())" + out: 0 + - name: nested-pairs + in: + s: "((()))" + out: 3 + - name: nested-balanced + in: + s: "(())())" + out: 2 + - name: leading-single-close + in: + s: ")())" + out: 2 + - name: leading-pair-close + in: + s: "))())" + out: 1 + - name: alternating + in: + s: "()()()" + out: 3 + - name: alternating-complete + in: + s: "())())())" + out: 0 + - name: unmatched-open-middle + in: + s: "())(()" + out: 3 + - name: unmatched-close-middle + in: + s: "(())))" + out: 0 + - name: all-opens-three + in: + s: "(((" + out: 6 + - name: all-closes-three + in: + s: ")))" + out: 3 + - name: all-opens-six + in: + s: "((((((" + out: 12 + - name: all-closes-five + in: + s: ")))))" + out: 4 + - name: open-close-close-open + in: + s: "())(" + out: 2 + - name: close-open-close-close + in: + s: ")())" + out: 2 + - name: two-open-single-close + in: + s: "(()" + out: 3 + - name: two-open-four-close + in: + s: "(())))" + out: 0 + - name: repeated-complete + in: + s: "())())())())" + out: 0 + - name: repeated-open + in: + s: "((())" + out: 4 + - name: close-run-after-open + in: + s: "()))))" + out: 3 + - name: mixed-short-one + in: + s: "())(()))" + out: 1 + - name: mixed-short-two + in: + s: ")(()())" + out: 5 + - name: mixed-short-three + in: + s: "((()))(" + out: 5 + - name: generated-short + in: + s: + gen: "str" + len: 37 + alphabet: "()" + - name: generated-medium + in: + s: + gen: "str" + len: 1000 + alphabet: "()" + - name: generated-large-a + in: + s: + gen: "str" + len: 50000 + alphabet: "()" + - name: generated-large-b + in: + s: + gen: "str" + len: 99999 + alphabet: "()" + - name: generated-limit + in: + s: + gen: "str" + len: 100000 + alphabet: "()" diff --git a/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.cpp b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.cpp new file mode 100644 index 00000000..8347bd16 --- /dev/null +++ b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int minInsertions(string s) { + vector stack; + int count = 0; + int i = 0; + + while (i < s.length()) { + if (s[i] == '(') { + stack.push_back('('); + } else { + if (stack.empty()) { + if (i != s.length() - 1 && s[i + 1] == ')') { + count += 1; + i++; + } else { + count += 2; + } + } else { + if (i != s.length() - 1 && s[i + 1] == ')') { + stack.pop_back(); + i++; + } else { + count += 1; + stack.pop_back(); + } + } + } + i++; + } + + return count + stack.size() * 2; + } +}; diff --git a/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.cs b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.cs new file mode 100644 index 00000000..0de83fe9 --- /dev/null +++ b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.cs @@ -0,0 +1,33 @@ +public class Solution { + public int MinInsertions(string s) { + var stack = new System.Collections.Generic.Stack(); + int count = 0; + int i = 0; + + while (i < s.Length) { + if (s[i] == '(') { + stack.Push('('); + } else { + if (stack.Count == 0) { + if (i != s.Length - 1 && s[i + 1] == ')') { + count += 1; + i++; + } else { + count += 2; + } + } else { + if (i != s.Length - 1 && s[i + 1] == ')') { + stack.Pop(); + i++; + } else { + count += 1; + stack.Pop(); + } + } + } + i++; + } + + return count + stack.Count * 2; + } +} diff --git a/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.dart b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.dart new file mode 100644 index 00000000..2a5f3afc --- /dev/null +++ b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.dart @@ -0,0 +1,33 @@ +class Solution { + int minInsertions(String s) { + List stack = []; + int count = 0; + int i = 0; + + while (i < s.length) { + if (s[i] == '(') { + stack.add('('); + } else { + if (stack.isEmpty) { + if (i != s.length - 1 && s[i + 1] == ')') { + count += 1; + i++; + } else { + count += 2; + } + } else { + if (i != s.length - 1 && s[i + 1] == ')') { + stack.removeLast(); + i++; + } else { + count += 1; + stack.removeLast(); + } + } + } + i++; + } + + return count + stack.length * 2; + } +} diff --git a/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.go b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.go new file mode 100644 index 00000000..53fe85bb --- /dev/null +++ b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.go @@ -0,0 +1,31 @@ +func minInsertions(s string) int { + stack := make([]byte, 0) + count := 0 + i := 0 + + for i < len(s) { + if s[i] == '(' { + stack = append(stack, '(') + } else { + if len(stack) == 0 { + if i != len(s)-1 && s[i+1] == ')' { + count += 1 + i++ + } else { + count += 2 + } + } else { + if i != len(s)-1 && s[i+1] == ')' { + stack = stack[:len(stack)-1] + i++ + } else { + count += 1 + stack = stack[:len(stack)-1] + } + } + } + i++ + } + + return count + len(stack)*2 +} diff --git a/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.java b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.java new file mode 100644 index 00000000..9b28ee25 --- /dev/null +++ b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.java @@ -0,0 +1,33 @@ +class Solution { + public int minInsertions(String s) { + java.util.Stack stack = new java.util.Stack<>(); + int count = 0; + int i = 0; + + while (i < s.length()) { + if (s.charAt(i) == '(') { + stack.push('('); + } else { + if (stack.isEmpty()) { + if (i != s.length() - 1 && s.charAt(i + 1) == ')') { + count += 1; + i++; + } else { + count += 2; + } + } else { + if (i != s.length() - 1 && s.charAt(i + 1) == ')') { + stack.pop(); + i++; + } else { + count += 1; + stack.pop(); + } + } + } + i++; + } + + return count + stack.size() * 2; + } +} diff --git a/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.kt b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.kt new file mode 100644 index 00000000..ce026121 --- /dev/null +++ b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.kt @@ -0,0 +1,33 @@ +class Solution { + fun minInsertions(s: String): Int { + val stack = java.util.ArrayDeque() + var count = 0 + var i = 0 + + while (i < s.length) { + if (s[i] == '(') { + stack.push('(') + } else { + if (stack.isEmpty()) { + if (i != s.length - 1 && s[i + 1] == ')') { + count += 1 + i++ + } else { + count += 2 + } + } else { + if (i != s.length - 1 && s[i + 1] == ')') { + stack.pop() + i++ + } else { + count += 1 + stack.pop() + } + } + } + i++ + } + + return count + stack.size * 2 + } +} diff --git a/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.py b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.py new file mode 100644 index 00000000..81785415 --- /dev/null +++ b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.py @@ -0,0 +1,26 @@ +class Solution: + def minInsertions(self, s: str) -> int: + stack = [] + count = 0 + i = 0 + + while i < len(s): + if s[i] == "(": + stack.append("(") + else: + if not stack: + if i != len(s) - 1 and s[i + 1] == ")": + count += 1 + i += 1 # Skip next ')' + else: + count += 2 + else: + if i != len(s) - 1 and s[i + 1] == ")": + stack.pop() + i += 1 + else: + count += 1 + stack.pop() + i += 1 + + return count + len(stack) * 2 # Each unmatched '(' needs two ')' diff --git a/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.py2 b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.py2 new file mode 100644 index 00000000..f47f4992 --- /dev/null +++ b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.py2 @@ -0,0 +1,30 @@ +class Solution(object): + def minInsertions(self, s): + """ + :type s: str + :rtype: int + """ + stack = [] + count = 0 + i = 0 + + while i < len(s): + if s[i] == '(': + stack.append('(') + else: + if not stack: + if i != len(s) - 1 and s[i + 1] == ')': + count += 1 + i += 1 + else: + count += 2 + else: + if i != len(s) - 1 and s[i + 1] == ')': + stack.pop() + i += 1 + else: + count += 1 + stack.pop() + i += 1 + + return count + len(stack) * 2 diff --git a/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.rb b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.rb new file mode 100644 index 00000000..ccc76ed9 --- /dev/null +++ b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.rb @@ -0,0 +1,33 @@ +# @param {String} s +# @return {Integer} +def min_insertions(s) + stack = [] + count = 0 + i = 0 + + while i < s.length + if s[i] == '(' + stack << '(' + else + if stack.empty? + if i != s.length - 1 && s[i + 1] == ')' + count += 1 + i += 1 + else + count += 2 + end + else + if i != s.length - 1 && s[i + 1] == ')' + stack.pop + i += 1 + else + count += 1 + stack.pop + end + end + end + i += 1 + end + + count + stack.length * 2 +end diff --git a/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.rs b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.rs new file mode 100644 index 00000000..ef54fb1e --- /dev/null +++ b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.rs @@ -0,0 +1,34 @@ +impl Solution { + pub fn min_insertions(s: String) -> i32 { + let mut stack: Vec = Vec::new(); + let mut count = 0; + let chars: Vec = s.chars().collect(); + let mut i = 0; + + while i < chars.len() { + if chars[i] == '(' { + stack.push('('); + } else { + if stack.is_empty() { + if i != chars.len() - 1 && chars[i + 1] == ')' { + count += 1; + i += 1; + } else { + count += 2; + } + } else { + if i != chars.len() - 1 && chars[i + 1] == ')' { + stack.pop(); + i += 1; + } else { + count += 1; + stack.pop(); + } + } + } + i += 1; + } + + count + stack.len() as i32 * 2 + } +} diff --git a/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.swift b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.swift new file mode 100644 index 00000000..2832165e --- /dev/null +++ b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.swift @@ -0,0 +1,34 @@ +class Solution { + func minInsertions(_ s: String) -> Int { + var stack: [Character] = [] + var count = 0 + var i = 0 + let chars = Array(s) + + while i < chars.count { + if chars[i] == "(" { + stack.append("(") + } else { + if stack.isEmpty { + if i != chars.count - 1 && chars[i + 1] == ")" { + count += 1 + i += 1 + } else { + count += 2 + } + } else { + if i != chars.count - 1 && chars[i + 1] == ")" { + stack.removeLast() + i += 1 + } else { + count += 1 + stack.removeLast() + } + } + } + i += 1 + } + + return count + stack.count * 2 + } +} diff --git a/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.ts b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.ts new file mode 100644 index 00000000..993a8c5e --- /dev/null +++ b/tests/1501-2000/1541. minimum-insertions-to-balance-a-parentheses-string/sol.ts @@ -0,0 +1,31 @@ +function minInsertions(s: string): number { + const stack: string[] = []; + let count = 0; + let i = 0; + + while (i < s.length) { + if (s[i] === "(") { + stack.push("("); + } else { + if (stack.length === 0) { + if (i !== s.length - 1 && s[i + 1] === ")") { + count += 1; + i++; + } else { + count += 2; + } + } else { + if (i !== s.length - 1 && s[i + 1] === ")") { + stack.pop(); + i++; + } else { + count += 1; + stack.pop(); + } + } + } + i++; + } + + return count + stack.length * 2; +} diff --git a/tests/1501-2000/1542. find-longest-awesome-substring/manifest.yaml b/tests/1501-2000/1542. find-longest-awesome-substring/manifest.yaml new file mode 100644 index 00000000..23066dec --- /dev/null +++ b/tests/1501-2000/1542. find-longest-awesome-substring/manifest.yaml @@ -0,0 +1,220 @@ +entry: + id: 1542 + title: "find-longest-awesome-substring" + params: + s: + type: string + call: + cpp: "Solution().longestAwesome({s})" + rust: "Solution::longest_awesome({s})" + python3: "Solution().longestAwesome({s})" + python2: "Solution().longestAwesome({s})" + ruby: "longest_awesome({s})" + java: "new Solution().longestAwesome({s})" + csharp: "new Solution().LongestAwesome({s})" + kotlin: "Solution().longestAwesome({s})" + go: "longestAwesome({s})" + dart: "Solution().longestAwesome({s})" + swift: "Solution().longestAwesome({s})" + typescript: "longestAwesome({s})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().longestAwesome(s, {result})" + checker: | + class Checker: + def longestAwesome(self, s, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + first = {0: -1} + mask = 0 + best = 0 + for i, ch in enumerate(s): + mask ^= 1 << (ord(ch) - 48) + if mask in first: + best = max(best, i - first[mask]) + for bit in range(10): + other = mask ^ (1 << bit) + if other in first: + best = max(best, i - first[other]) + if mask not in first: + first[mask] = i + return result == best + +seed: 1542 + +tests: + - name: example-3242415 + in: + s: "3242415" + out: 5 + - name: example-distinct-eight + in: + s: "12345678" + out: 1 + - name: example-full-six + in: + s: "213123" + out: 6 + - name: single-zero + in: + s: "0" + out: 1 + - name: single-nine + in: + s: "9" + out: 1 + - name: two-equal + in: + s: "00" + out: 2 + - name: two-different + in: + s: "01" + out: 1 + - name: all-zeroes + in: + s: "0000000000" + out: 10 + - name: all-distinct-digits + in: + s: "0123456789" + out: 1 + - name: ten-pair-palindrome + in: + s: "01234567899876543210" + out: 20 + - name: repeated-two-digits + in: + s: "1212121212" + out: 9 + - name: one-odd-count + in: + s: "1122334455667788999" + out: 19 + - name: odd-digit-at-front + in: + s: "0123456789" + out: 1 + - name: odd-digit-at-end + in: + s: "01234567890" + out: 1 + - name: alternating-zero-one + in: + s: "0101010101010101" + out: 16 + - name: separated-pair + in: + s: "0123401234" + out: 10 + - name: nested-awesome + in: + s: "111222333444555" + out: 7 + - name: one-extra-middle + in: + s: "0010200" + out: 3 + - name: many-odd-prefix + in: + s: "01234567890123456789" + out: 20 + - name: only-one-longest + in: + s: "01234567890123456788" + out: 19 + - name: long-symmetric-block + in: + s: "98765432100123456789" + out: 20 + - name: runs-with-tail + in: + s: "00000111112222233333" + out: 13 + - name: ten-digit-blocks + in: + s: "012345678901234567890123456789" + out: 21 + - name: disturbed-block + in: + s: "012345678901234567890123456788" + out: 23 + - name: all-nine + in: + s: "99999999999999999999" + out: 20 + - name: sparse-nine + in: + s: "90909090909090909090" + out: 20 + - name: prefix-single-best + in: + s: "123456789000000" + out: 7 + - name: suffix-single-best + in: + s: "000000123456789" + out: 7 + - name: two-odd-digits + in: + s: "123456789012345678" + out: 1 + - name: mixed-nine-block + in: + s: "314159265358979323846" + out: 3 + - name: long-repeated-cycle + in: + s: "0123012301230123012301230123" + out: 25 + - name: near-limit-small + in: + s: "0000000000111111111122222222223333333333" + out: 40 + - name: near-limit-distinct-pattern + in: + s: "01234567890123456789012345678901234567890123456789" + out: 41 + - name: generated-uniform + in: + s: + gen: "str" + len: 100000 + alphabet: "0123456789" + seed: 154201 + - name: generated-binary + in: + s: + gen: "str" + len: 99999 + alphabet: "01" + seed: 154202 + - name: generated-heavy-zero + in: + s: + gen: "str" + len: 100000 + alphabet: "0123" + seed: 154203 + - name: generated-cyclic + in: + s: + gen: "str" + len: 100000 + alphabet: "0123456789" + seed: 154204 + - name: generated-short-random + in: + s: + gen: "str" + len: 1000 + alphabet: "0123456789" + seed: 154205 diff --git a/tests/1501-2000/1542. find-longest-awesome-substring/sol.cpp b/tests/1501-2000/1542. find-longest-awesome-substring/sol.cpp new file mode 100644 index 00000000..d6dc1732 --- /dev/null +++ b/tests/1501-2000/1542. find-longest-awesome-substring/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int longestAwesome(string s) { + int n = s.size(); + unordered_map mask; + int curMask = 0; + mask[curMask] = -1; + int ans = 1; + for (int i = 0; i < n; i++) { + int num = s[i] - '0'; + curMask ^= (1 << num); + int needMask = curMask; + if (mask.count(needMask)) { + ans = max(ans, i - mask[needMask]); + } + for (int bit = 0; bit < 10; bit++) { + int nNeedMax = needMask ^ (1 << bit); + if (mask.count(nNeedMax)) { + ans = max(ans, i - mask[nNeedMax]); + } + } + if (!mask.count(curMask)) { + mask[curMask] = i; + } + } + return ans; + } +}; diff --git a/tests/1501-2000/1542. find-longest-awesome-substring/sol.cs b/tests/1501-2000/1542. find-longest-awesome-substring/sol.cs new file mode 100644 index 00000000..6e8af232 --- /dev/null +++ b/tests/1501-2000/1542. find-longest-awesome-substring/sol.cs @@ -0,0 +1,27 @@ +public class Solution { + public int LongestAwesome(string s) { + int n = s.Length; + var mask = new Dictionary(); + int curMask = 0; + mask[curMask] = -1; + int ans = 1; + for (int i = 0; i < n; i++) { + int num = s[i] - '0'; + curMask ^= (1 << num); + int needMask = curMask; + if (mask.ContainsKey(needMask)) { + ans = Math.Max(ans, i - mask[needMask]); + } + for (int bit = 0; bit < 10; bit++) { + int nNeedMax = needMask ^ (1 << bit); + if (mask.ContainsKey(nNeedMax)) { + ans = Math.Max(ans, i - mask[nNeedMax]); + } + } + if (!mask.ContainsKey(curMask)) { + mask[curMask] = i; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1542. find-longest-awesome-substring/sol.dart b/tests/1501-2000/1542. find-longest-awesome-substring/sol.dart new file mode 100644 index 00000000..da88b9d3 --- /dev/null +++ b/tests/1501-2000/1542. find-longest-awesome-substring/sol.dart @@ -0,0 +1,27 @@ +class Solution { + int longestAwesome(String s) { + int n = s.length; + Map mask = {}; + int curMask = 0; + mask[curMask] = -1; + int ans = 1; + for (int i = 0; i < n; i++) { + int num = s.codeUnitAt(i) - 48; + curMask ^= (1 << num); + int needMask = curMask; + if (mask.containsKey(needMask)) { + final length = i - mask[needMask]!; + if (length > ans) ans = length; + } + for (int bit = 0; bit < 10; bit++) { + int nNeedMax = needMask ^ (1 << bit); + if (mask.containsKey(nNeedMax)) { + final length = i - mask[nNeedMax]!; + if (length > ans) ans = length; + } + } + mask.putIfAbsent(curMask, () => i); + } + return ans; + } +} diff --git a/tests/1501-2000/1542. find-longest-awesome-substring/sol.go b/tests/1501-2000/1542. find-longest-awesome-substring/sol.go new file mode 100644 index 00000000..35796a58 --- /dev/null +++ b/tests/1501-2000/1542. find-longest-awesome-substring/sol.go @@ -0,0 +1,29 @@ +func longestAwesome(s string) int { + n := len(s) + mask := make(map[int]int) + curMask := 0 + mask[curMask] = -1 + ans := 1 + for i := 0; i < n; i++ { + num := int(s[i] - '0') + curMask ^= 1 << num + needMask := curMask + if val, ok := mask[needMask]; ok { + if i - val > ans { + ans = i - val + } + } + for bit := 0; bit < 10; bit++ { + nNeedMax := needMask ^ (1 << bit) + if val, ok := mask[nNeedMax]; ok { + if i - val > ans { + ans = i - val + } + } + } + if _, ok := mask[curMask]; !ok { + mask[curMask] = i + } + } + return ans +} diff --git a/tests/1501-2000/1542. find-longest-awesome-substring/sol.java b/tests/1501-2000/1542. find-longest-awesome-substring/sol.java new file mode 100644 index 00000000..98ca44fe --- /dev/null +++ b/tests/1501-2000/1542. find-longest-awesome-substring/sol.java @@ -0,0 +1,27 @@ +class Solution { + public int longestAwesome(String s) { + int n = s.length(); + HashMap mask = new HashMap<>(); + int curMask = 0; + mask.put(curMask, -1); + int ans = 1; + for (int i = 0; i < n; i++) { + int num = s.charAt(i) - '0'; + curMask ^= (1 << num); + int needMask = curMask; + if (mask.containsKey(needMask)) { + ans = Math.max(ans, i - mask.get(needMask)); + } + for (int bit = 0; bit < 10; bit++) { + int nNeedMax = needMask ^ (1 << bit); + if (mask.containsKey(nNeedMax)) { + ans = Math.max(ans, i - mask.get(nNeedMax)); + } + } + if (!mask.containsKey(curMask)) { + mask.put(curMask, i); + } + } + return ans; + } +} diff --git a/tests/1501-2000/1542. find-longest-awesome-substring/sol.kt b/tests/1501-2000/1542. find-longest-awesome-substring/sol.kt new file mode 100644 index 00000000..375d5893 --- /dev/null +++ b/tests/1501-2000/1542. find-longest-awesome-substring/sol.kt @@ -0,0 +1,21 @@ +class Solution { + fun longestAwesome(s: String): Int { + val n = s.length + val mask = HashMap() + var curMask = 0 + mask[curMask] = -1 + var ans = 1 + for (i in 0 until n) { + val num = s[i] - '0' + curMask = curMask xor (1 shl num) + val needMask = curMask + mask[needMask]?.let { ans = maxOf(ans, i - it) } + for (bit in 0..9) { + val nNeedMax = needMask xor (1 shl bit) + mask[nNeedMax]?.let { ans = maxOf(ans, i - it) } + } + mask.putIfAbsent(curMask, i) + } + return ans + } +} diff --git a/tests/1501-2000/1542. find-longest-awesome-substring/sol.py b/tests/1501-2000/1542. find-longest-awesome-substring/sol.py new file mode 100644 index 00000000..63daa088 --- /dev/null +++ b/tests/1501-2000/1542. find-longest-awesome-substring/sol.py @@ -0,0 +1,25 @@ +class Solution: + def longestAwesome(self, s: str) -> int: + n = len(s) + mask = {} + cur_mask = 0b0000000000 + perfect_is_naaaaaa = 0b0000000000 + mask[cur_mask] = -1 + ans = 1 + for i in range(n): + num = int(s[i]) + cur_mask ^= 1 << num + need_mask = perfect_is_naaaaaa ^ cur_mask + # all + if need_mask in mask: + ans = max(ans, i - mask[need_mask]) + # drop 1 + for bit in range(10): + n_need_max = need_mask ^ (1 << bit) + if n_need_max in mask: + ans = max(ans, i - mask[n_need_max]) + + if cur_mask not in mask: + mask[cur_mask] = i + + return ans diff --git a/tests/1501-2000/1542. find-longest-awesome-substring/sol.py2 b/tests/1501-2000/1542. find-longest-awesome-substring/sol.py2 new file mode 100644 index 00000000..06515d89 --- /dev/null +++ b/tests/1501-2000/1542. find-longest-awesome-substring/sol.py2 @@ -0,0 +1,24 @@ +class Solution(object): + def longestAwesome(self, s): + """ + :type s: str + :rtype: int + """ + n = len(s) + mask = {} + cur_mask = 0 + mask[cur_mask] = -1 + ans = 1 + for i in range(n): + num = int(s[i]) + cur_mask ^= 1 << num + need_mask = cur_mask + if need_mask in mask: + ans = max(ans, i - mask[need_mask]) + for bit in range(10): + n_need_max = need_mask ^ (1 << bit) + if n_need_max in mask: + ans = max(ans, i - mask[n_need_max]) + if cur_mask not in mask: + mask[cur_mask] = i + return ans diff --git a/tests/1501-2000/1542. find-longest-awesome-substring/sol.rb b/tests/1501-2000/1542. find-longest-awesome-substring/sol.rb new file mode 100644 index 00000000..a397e001 --- /dev/null +++ b/tests/1501-2000/1542. find-longest-awesome-substring/sol.rb @@ -0,0 +1,25 @@ +# @param {String} s +# @return {Integer} +def longest_awesome(s) + n = s.length + mask = {} + cur_mask = 0 + mask[cur_mask] = -1 + ans = 1 + (0...n).each do |i| + num = s[i].to_i + cur_mask ^= 1 << num + need_mask = cur_mask + if mask.key?(need_mask) + ans = [ans, i - mask[need_mask]].max + end + (0...10).each do |bit| + n_need_max = need_mask ^ (1 << bit) + if mask.key?(n_need_max) + ans = [ans, i - mask[n_need_max]].max + end + end + mask[cur_mask] = i unless mask.key?(cur_mask) + end + ans +end diff --git a/tests/1501-2000/1542. find-longest-awesome-substring/sol.rs b/tests/1501-2000/1542. find-longest-awesome-substring/sol.rs new file mode 100644 index 00000000..9b83ee88 --- /dev/null +++ b/tests/1501-2000/1542. find-longest-awesome-substring/sol.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn longest_awesome(s: String) -> i32 { + let n = s.len(); + let mut mask = std::collections::HashMap::new(); + let mut cur_mask: u32 = 0; + mask.insert(cur_mask, -1i32); + let mut ans = 1i32; + let bytes = s.as_bytes(); + for i in 0..n { + let num = bytes[i] - b'0'; + cur_mask ^= 1 << num; + let need_mask = cur_mask; + if let Some(&val) = mask.get(&need_mask) { + ans = ans.max(i as i32 - val); + } + for bit in 0..10 { + let n_need_max = need_mask ^ (1 << bit); + if let Some(&val) = mask.get(&n_need_max) { + ans = ans.max(i as i32 - val); + } + } + mask.entry(cur_mask).or_insert(i as i32); + } + ans + } +} diff --git a/tests/1501-2000/1542. find-longest-awesome-substring/sol.swift b/tests/1501-2000/1542. find-longest-awesome-substring/sol.swift new file mode 100644 index 00000000..0de22034 --- /dev/null +++ b/tests/1501-2000/1542. find-longest-awesome-substring/sol.swift @@ -0,0 +1,28 @@ +class Solution { + func longestAwesome(_ s: String) -> Int { + let n = s.count + var mask = [Int: Int]() + var curMask = 0 + mask[curMask] = -1 + var ans = 1 + let chars = Array(s) + for i in 0..(); + let curMask = 0; + mask.set(curMask, -1); + let ans = 1; + for (let i = 0; i < n; i++) { + const num = parseInt(s[i]); + curMask ^= 1 << num; + const needMask = curMask; + if (mask.has(needMask)) { + ans = Math.max(ans, i - mask.get(needMask)!); + } + for (let bit = 0; bit < 10; bit++) { + const nNeedMax = needMask ^ (1 << bit); + if (mask.has(nNeedMax)) { + ans = Math.max(ans, i - mask.get(nNeedMax)!); + } + } + if (!mask.has(curMask)) { + mask.set(curMask, i); + } + } + return ans; +} diff --git a/tests/1501-2000/1544. make-the-string-great/manifest.yaml b/tests/1501-2000/1544. make-the-string-great/manifest.yaml new file mode 100644 index 00000000..ea74750f --- /dev/null +++ b/tests/1501-2000/1544. make-the-string-great/manifest.yaml @@ -0,0 +1,216 @@ +entry: + id: 1544 + title: "make-the-string-great" + params: + s: + type: string + call: + cpp: "Solution().makeGood({s})" + rust: "Solution::make_good({s})" + python3: "Solution().makeGood({s})" + python2: "Solution().makeGood({s})" + ruby: "make_good({s})" + java: "new Solution().makeGood({s})" + csharp: "new Solution().MakeGood({s})" + kotlin: "Solution().makeGood({s})" + go: "makeGood({s})" + dart: "Solution().makeGood({s})" + swift: "Solution().makeGood({s})" + typescript: "makeGood({s})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().makeGood(s, {result})" + checker: | + class Checker: + def makeGood(self, s, result): + if not isinstance(result, str): + return False + stack = [] + for ch in s: + if stack and ch.lower() == stack[-1].lower() and ch != stack[-1]: + stack.pop() + else: + stack.append(ch) + return result == "".join(stack) + +seed: 1544 + +tests: + - name: example-one + in: + s: "leEeetcode" + out: "leetcode" + - name: example-two + in: + s: "abBAcC" + out: "" + - name: example-three + in: + s: "s" + out: "s" + - name: single-uppercase + in: + s: "Z" + out: "Z" + - name: matching-pair-lower-upper + in: + s: "aA" + out: "" + - name: matching-pair-upper-lower + in: + s: "Aa" + out: "" + - name: nonmatching-pair + in: + s: "ab" + out: "ab" + - name: same-case-pair + in: + s: "AA" + out: "AA" + - name: alternating-cancellation + in: + s: "aAaA" + out: "" + - name: cancellation-reveals-pair + in: + s: "aBbA" + out: "" + - name: nested-cancellation + in: + s: "mMnNnMmM" + out: "nM" + - name: mixed-survivors + in: + s: "abBAcdDCe" + out: "e" + - name: lowercase-word + in: + s: "algorithm" + out: "algorithm" + - name: uppercase-word + in: + s: "ALGORITHM" + out: "ALGORITHM" + - name: case-insensitive-neighbors + in: + s: "aBcC" + out: "aB" + - name: pair-at-front + in: + s: "aAbc" + out: "bc" + - name: pair-at-end + in: + s: "abBc" + out: "ac" + - name: pair-in-middle + in: + s: "abBcde" + out: "acde" + - name: two-independent-pairs + in: + s: "aAbBcC" + out: "" + - name: repeated-letter-chain + in: + s: "aAaAaAa" + out: "a" + - name: no-cancellation-after-removal + in: + s: "xYyX" + out: "" + - name: digits-not-allowed-but-letters + in: + s: "qQwWeErR" + out: "" + - name: all-lowercase-boundary + in: + s: "abcdefghijklmnopqrstuvwxyz" + out: "abcdefghijklmnopqrstuvwxyz" + - name: all-uppercase-boundary + in: + s: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + out: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + - name: all-pairs + in: + s: "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ" + out: "" + - name: repeated-same-case + in: + s: "aabbccAABBCC" + out: "aabbccAABBCC" + - name: long-cascade + in: + s: "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZzYxXwWvVuUtTsSrRqQpPoOnNmMlLkKjJiIhHgGfFeEdDcCbBaA" + out: "zY" + - name: long-no-pairs + in: + s: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + out: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + - name: opposite-case-runs + in: + s: "AAAaaaBBBbbbCCCccc" + out: "" + - name: separated-pairs + in: + s: "aXxAbYyBcZzC" + out: "" + - name: chain-with-middle + in: + s: "pPqRrQ" + out: "" + - name: repeated-canceling-block + in: + s: "aAbBaAbB" + out: "" + - name: near-limit-no-cancel + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + - name: near-limit-full-cancel + in: + s: "aAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaA" + out: "" + - name: near-limit-cascade + in: + s: "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYaAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyY" + out: "" + - name: generated-valid-letters-1 + in: + s: + gen: "str" + len: 100 + alphabet: "aAbBcCxX" + - name: generated-valid-letters-2 + in: + s: + gen: "str" + len: 100 + alphabet: "dDeEfFyY" + - name: generated-valid-letters-3 + in: + s: + gen: "str" + len: 99 + alphabet: "gGhHiIzZ" + - name: generated-valid-letters-4 + in: + s: + gen: "str" + len: 100 + alphabet: "jJkKlLmM" + - name: generated-valid-letters-5 + in: + s: + gen: "str" + len: 100 + alphabet: "nNoOpPqQ" diff --git a/tests/1501-2000/1544. make-the-string-great/sol.cpp b/tests/1501-2000/1544. make-the-string-great/sol.cpp new file mode 100644 index 00000000..6bf623d6 --- /dev/null +++ b/tests/1501-2000/1544. make-the-string-great/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + string makeGood(string s) { + vector stack; + for (char ch : s) { + if (!stack.empty() && tolower(ch) == tolower(stack.back()) && ch != stack.back()) { + stack.pop_back(); + } else { + stack.push_back(ch); + } + } + return string(stack.begin(), stack.end()); + } +}; diff --git a/tests/1501-2000/1544. make-the-string-great/sol.cs b/tests/1501-2000/1544. make-the-string-great/sol.cs new file mode 100644 index 00000000..f028a4e1 --- /dev/null +++ b/tests/1501-2000/1544. make-the-string-great/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public string MakeGood(string s) { + var stack = new StringBuilder(); + foreach (char ch in s) { + if (stack.Length > 0 && char.ToLower(ch) == char.ToLower(stack[stack.Length - 1]) && ch != stack[stack.Length - 1]) { + stack.Length--; + } else { + stack.Append(ch); + } + } + return stack.ToString(); + } +} diff --git a/tests/1501-2000/1544. make-the-string-great/sol.dart b/tests/1501-2000/1544. make-the-string-great/sol.dart new file mode 100644 index 00000000..67e5d799 --- /dev/null +++ b/tests/1501-2000/1544. make-the-string-great/sol.dart @@ -0,0 +1,14 @@ +class Solution { + String makeGood(String s) { + List stack = []; + for (int i = 0; i < s.length; i++) { + String ch = s[i]; + if (stack.isNotEmpty && ch.toLowerCase() == stack.last.toLowerCase() && ch != stack.last) { + stack.removeLast(); + } else { + stack.add(ch); + } + } + return stack.join(); + } +} diff --git a/tests/1501-2000/1544. make-the-string-great/sol.go b/tests/1501-2000/1544. make-the-string-great/sol.go new file mode 100644 index 00000000..f8cc8cdf --- /dev/null +++ b/tests/1501-2000/1544. make-the-string-great/sol.go @@ -0,0 +1,11 @@ +func makeGood(s string) string { + stack := []rune{} + for _, ch := range s { + if len(stack) > 0 && unicode.ToLower(ch) == unicode.ToLower(stack[len(stack)-1]) && ch != stack[len(stack)-1] { + stack = stack[:len(stack)-1] + } else { + stack = append(stack, ch) + } + } + return string(stack) +} diff --git a/tests/1501-2000/1544. make-the-string-great/sol.java b/tests/1501-2000/1544. make-the-string-great/sol.java new file mode 100644 index 00000000..ecc51204 --- /dev/null +++ b/tests/1501-2000/1544. make-the-string-great/sol.java @@ -0,0 +1,13 @@ +class Solution { + public String makeGood(String s) { + StringBuilder stack = new StringBuilder(); + for (char ch : s.toCharArray()) { + if (stack.length() > 0 && Character.toLowerCase(ch) == Character.toLowerCase(stack.charAt(stack.length() - 1)) && ch != stack.charAt(stack.length() - 1)) { + stack.deleteCharAt(stack.length() - 1); + } else { + stack.append(ch); + } + } + return stack.toString(); + } +} diff --git a/tests/1501-2000/1544. make-the-string-great/sol.kt b/tests/1501-2000/1544. make-the-string-great/sol.kt new file mode 100644 index 00000000..fb8f5024 --- /dev/null +++ b/tests/1501-2000/1544. make-the-string-great/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun makeGood(s: String): String { + val stack = StringBuilder() + for (ch in s) { + if (stack.isNotEmpty() && kotlin.math.abs(ch.code - stack.last().code) == 32) { + stack.deleteCharAt(stack.length - 1) + } else { + stack.append(ch) + } + } + return stack.toString() + } +} diff --git a/tests/1501-2000/1544. make-the-string-great/sol.py b/tests/1501-2000/1544. make-the-string-great/sol.py new file mode 100644 index 00000000..a164fc09 --- /dev/null +++ b/tests/1501-2000/1544. make-the-string-great/sol.py @@ -0,0 +1,11 @@ +class Solution: + def makeGood(self, s: str) -> str: + stack = [] + + for ch in s: + if stack and ch.lower() == stack[-1].lower() and ch != stack[-1]: + stack.pop() + else: + stack.append(ch) + + return "".join(stack) diff --git a/tests/1501-2000/1544. make-the-string-great/sol.py2 b/tests/1501-2000/1544. make-the-string-great/sol.py2 new file mode 100644 index 00000000..60e79284 --- /dev/null +++ b/tests/1501-2000/1544. make-the-string-great/sol.py2 @@ -0,0 +1,13 @@ +class Solution(object): + def makeGood(self, s): + """ + :type s: str + :rtype: str + """ + stack = [] + for ch in s: + if stack and ch.lower() == stack[-1].lower() and ch != stack[-1]: + stack.pop() + else: + stack.append(ch) + return "".join(stack) diff --git a/tests/1501-2000/1544. make-the-string-great/sol.rb b/tests/1501-2000/1544. make-the-string-great/sol.rb new file mode 100644 index 00000000..01fb2d5f --- /dev/null +++ b/tests/1501-2000/1544. make-the-string-great/sol.rb @@ -0,0 +1,13 @@ +# @param {String} s +# @return {String} +def make_good(s) + stack = [] + s.each_char do |ch| + if !stack.empty? && ch.downcase == stack[-1].downcase && ch != stack[-1] + stack.pop() + else + stack.push(ch) + end + end + stack.join() +end diff --git a/tests/1501-2000/1544. make-the-string-great/sol.rs b/tests/1501-2000/1544. make-the-string-great/sol.rs new file mode 100644 index 00000000..5b314a86 --- /dev/null +++ b/tests/1501-2000/1544. make-the-string-great/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn make_good(s: String) -> String { + let mut stack: Vec = Vec::new(); + for ch in s.chars() { + if let Some(&last) = stack.last() { + if ch.to_ascii_lowercase() == last.to_ascii_lowercase() && ch != last { + stack.pop(); + continue; + } + } + stack.push(ch); + } + stack.into_iter().collect() + } +} diff --git a/tests/1501-2000/1544. make-the-string-great/sol.swift b/tests/1501-2000/1544. make-the-string-great/sol.swift new file mode 100644 index 00000000..3f7dc68b --- /dev/null +++ b/tests/1501-2000/1544. make-the-string-great/sol.swift @@ -0,0 +1,13 @@ +class Solution { + func makeGood(_ s: String) -> String { + var stack: [Character] = [] + for ch in s { + if let last = stack.last, ch.lowercased() == last.lowercased() && ch != last { + stack.removeLast() + } else { + stack.append(ch) + } + } + return String(stack) + } +} diff --git a/tests/1501-2000/1544. make-the-string-great/sol.ts b/tests/1501-2000/1544. make-the-string-great/sol.ts new file mode 100644 index 00000000..0cc11d72 --- /dev/null +++ b/tests/1501-2000/1544. make-the-string-great/sol.ts @@ -0,0 +1,15 @@ +function makeGood(s: string): string { + const stack: string[] = []; + for (const ch of s) { + if ( + stack.length > 0 && + ch.toLowerCase() === stack[stack.length - 1].toLowerCase() && + ch !== stack[stack.length - 1] + ) { + stack.pop(); + } else { + stack.push(ch); + } + } + return stack.join(""); +} diff --git a/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/manifest.yaml b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/manifest.yaml new file mode 100644 index 00000000..b0f5a27e --- /dev/null +++ b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/manifest.yaml @@ -0,0 +1,202 @@ +entry: + id: 1545 + title: "find-kth-bit-in-nth-binary-string" + params: + n: + type: int + k: + type: int + call: + cpp: "Solution().findKthBit({n}, {k})" + rust: "Solution::find_kth_bit({n}, {k})" + python3: "Solution().findKthBit({n}, {k})" + python2: "Solution().findKthBit({n}, {k})" + ruby: "find_kth_bit({n}, {k})" + java: "new Solution().findKthBit({n}, {k})" + csharp: "new Solution().FindKthBit({n}, {k})" + kotlin: "Solution().findKthBit({n}, {k})" + go: "findKthBit({n}, {k})" + dart: "Solution().findKthBit({n}, {k})" + swift: "Solution().findKthBit({n}, {k})" + typescript: "findKthBit({n}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().findKthBit(n, k, {result})" + checker: | + class Checker: + def findKthBit(self, n, k, result): + def solve(level, pos): + if level == 1: + return "0" + middle = 1 << (level - 1) + if pos == middle: + return "1" + if pos < middle: + return solve(level - 1, pos) + value = solve(level - 1, (1 << level) - pos) + return "1" if value == "0" else "0" + return result == solve(n, k) + +seed: 1545 + +tests: + - name: n1-only-position + in: + n: 1 + k: 1 + - name: n2-first + in: + n: 2 + k: 1 + - name: n2-middle + in: + n: 2 + k: 2 + - name: n2-last + in: + n: 2 + k: 3 + - name: example-one + in: + n: 3 + k: 1 + - name: n3-second + in: + n: 3 + k: 2 + - name: n3-middle + in: + n: 3 + k: 4 + - name: n3-sixth + in: + n: 3 + k: 6 + - name: n3-last + in: + n: 3 + k: 7 + - name: example-two + in: + n: 4 + k: 11 + - name: n4-first + in: + n: 4 + k: 1 + - name: n4-third + in: + n: 4 + k: 3 + - name: n4-middle + in: + n: 4 + k: 8 + - name: n4-last + in: + n: 4 + k: 15 + - name: n5-first + in: + n: 5 + k: 1 + - name: n5-near-middle-left + in: + n: 5 + k: 14 + - name: n5-middle + in: + n: 5 + k: 16 + - name: n5-near-middle-right + in: + n: 5 + k: 18 + - name: n5-last + in: + n: 5 + k: 31 + - name: n6-position-five + in: + n: 6 + k: 5 + - name: n6-position-ten + in: + n: 6 + k: 10 + - name: n6-middle + in: + n: 6 + k: 32 + - name: n6-position-forty + in: + n: 6 + k: 40 + - name: n6-last + in: + n: 6 + k: 63 + - name: n7-position-seven + in: + n: 7 + k: 7 + - name: n7-position-twenty-one + in: + n: 7 + k: 21 + - name: n7-middle + in: + n: 7 + k: 64 + - name: n7-position-one-hundred + in: + n: 7 + k: 100 + - name: n7-last + in: + n: 7 + k: 127 + - name: n10-near-start + in: + n: 10 + k: 2 + - name: n10-quarter + in: + n: 10 + k: 256 + - name: n10-middle + in: + n: 10 + k: 512 + - name: n10-near-end + in: + n: 10 + k: 1022 + - name: n15-middle + in: + n: 15 + k: 16384 + - name: n15-near-end + in: + n: 15 + k: 32766 + - name: n20-first + in: + n: 20 + k: 1 + - name: n20-middle + in: + n: 20 + k: 524288 + - name: n20-last + in: + n: 20 + k: 1048575 diff --git a/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.cpp b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.cpp new file mode 100644 index 00000000..576c9c82 --- /dev/null +++ b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + char findKthBit(int n, int k) { + if (n == 1) { + return '0'; + } + + int length = (1 << n) - 1; + int mid = (length + 1) / 2; + + if (k == mid) { + return '1'; + } + if (k < mid) { + return findKthBit(n - 1, k); + } + + char c = findKthBit(n - 1, length - k + 1); + return c == '0' ? '1' : '0'; + } +}; diff --git a/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.cs b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.cs new file mode 100644 index 00000000..c47ffb07 --- /dev/null +++ b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public char FindKthBit(int n, int k) { + if (n == 1) { + return '0'; + } + + int length = (1 << n) - 1; + int mid = (length + 1) / 2; + + if (k == mid) { + return '1'; + } + if (k < mid) { + return FindKthBit(n - 1, k); + } + + char c = FindKthBit(n - 1, length - k + 1); + return c == '0' ? '1' : '0'; + } +} diff --git a/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.dart b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.dart new file mode 100644 index 00000000..41250623 --- /dev/null +++ b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.dart @@ -0,0 +1,20 @@ +class Solution { + String findKthBit(int n, int k) { + if (n == 1) { + return '0'; + } + + int length = (1 << n) - 1; + int mid = (length + 1) ~/ 2; + + if (k == mid) { + return '1'; + } + if (k < mid) { + return findKthBit(n - 1, k); + } + + String c = findKthBit(n - 1, length - k + 1); + return c == '0' ? '1' : '0'; + } +} diff --git a/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.go b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.go new file mode 100644 index 00000000..7487140c --- /dev/null +++ b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.go @@ -0,0 +1,21 @@ +func findKthBit(n int, k int) byte { + if n == 1 { + return '0' + } + + length := (1 << n) - 1 + mid := (length + 1) / 2 + + if k == mid { + return '1' + } + if k < mid { + return findKthBit(n-1, k) + } + + c := findKthBit(n-1, length-k+1) + if c == '0' { + return '1' + } + return '0' +} diff --git a/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.java b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.java new file mode 100644 index 00000000..58081a91 --- /dev/null +++ b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.java @@ -0,0 +1,20 @@ +class Solution { + public char findKthBit(int n, int k) { + if (n == 1) { + return '0'; + } + + int length = (1 << n) - 1; + int mid = (length + 1) / 2; + + if (k == mid) { + return '1'; + } + if (k < mid) { + return findKthBit(n - 1, k); + } + + char c = findKthBit(n - 1, length - k + 1); + return c == '0' ? '1' : '0'; + } +} diff --git a/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.kt b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.kt new file mode 100644 index 00000000..c6e1e3bc --- /dev/null +++ b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun findKthBit(n: Int, k: Int): Char { + if (n == 1) { + return '0' + } + + val length = (1 shl n) - 1 + val mid = (length + 1) / 2 + + if (k == mid) { + return '1' + } + if (k < mid) { + return findKthBit(n - 1, k) + } + + val c = findKthBit(n - 1, length - k + 1) + return if (c == '0') '1' else '0' + } +} diff --git a/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.py b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.py new file mode 100644 index 00000000..ef30d648 --- /dev/null +++ b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.py @@ -0,0 +1,15 @@ +class Solution: + def findKthBit(self, n: int, k: int) -> str: + if n == 1: + return "0" + + length = (1 << n) - 1 + mid = (length + 1) // 2 + + if k == mid: + return "1" + if k < mid: + return self.findKthBit(n - 1, k) + + c = self.findKthBit(n - 1, length - k + 1) + return "1" if c == "0" else "0" diff --git a/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.py2 b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.py2 new file mode 100644 index 00000000..64e3cbe5 --- /dev/null +++ b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def findKthBit(self, n, k): + """ + :type n: int + :type k: int + :rtype: str + """ + if n == 1: + return '0' + + length = (1 << n) - 1 + mid = (length + 1) // 2 + + if k == mid: + return '1' + if k < mid: + return self.findKthBit(n - 1, k) + + c = self.findKthBit(n - 1, length - k + 1) + return '1' if c == '0' else '0' diff --git a/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.rb b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.rb new file mode 100644 index 00000000..ef51e203 --- /dev/null +++ b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.rb @@ -0,0 +1,21 @@ +# @param {Integer} n +# @param {Integer} k +# @return {Character} +def find_kth_bit(n, k) + if n == 1 + return '0' + end + + length = (1 << n) - 1 + mid = (length + 1) / 2 + + if k == mid + return '1' + end + if k < mid + return find_kth_bit(n - 1, k) + end + + c = find_kth_bit(n - 1, length - k + 1) + return c == '0' ? '1' : '0' +end diff --git a/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.rs b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.rs new file mode 100644 index 00000000..ffcd9d21 --- /dev/null +++ b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn find_kth_bit(n: i32, k: i32) -> char { + if n == 1 { + return '0'; + } + + let length = (1 << n) - 1; + let mid = (length + 1) / 2; + + if k == mid { + return '1'; + } + if k < mid { + return Self::find_kth_bit(n - 1, k); + } + + let c = Self::find_kth_bit(n - 1, length - k + 1); + if c == '0' { '1' } else { '0' } + } +} diff --git a/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.swift b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.swift new file mode 100644 index 00000000..771dee09 --- /dev/null +++ b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func findKthBit(_ n: Int, _ k: Int) -> Character { + if n == 1 { + return "0" + } + + let length = (1 << n) - 1 + let mid = (length + 1) / 2 + + if k == mid { + return "1" + } + if k < mid { + return findKthBit(n - 1, k) + } + + let c = findKthBit(n - 1, length - k + 1) + return c == "0" ? "1" : "0" + } +} diff --git a/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.ts b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.ts new file mode 100644 index 00000000..7841399d --- /dev/null +++ b/tests/1501-2000/1545. find-kth-bit-in-nth-binary-string/sol.ts @@ -0,0 +1,18 @@ +function findKthBit(n: number, k: number): string { + if (n === 1) { + return "0"; + } + + const length = (1 << n) - 1; + const mid = (length + 1) / 2; + + if (k === mid) { + return "1"; + } + if (k < mid) { + return findKthBit(n - 1, k); + } + + const c = findKthBit(n - 1, length - k + 1); + return c === "0" ? "1" : "0"; +} diff --git a/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/manifest.yaml b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/manifest.yaml new file mode 100644 index 00000000..2cdab25d --- /dev/null +++ b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/manifest.yaml @@ -0,0 +1,299 @@ +entry: + id: 1546 + title: "maximum-number-of-non-overlapping-subarrays-with-sum-equals-target" + params: + nums: + type: array + items: + type: int + target: + type: int + call: + cpp: "Solution().maxNonOverlapping({nums}, {target})" + rust: "Solution::max_non_overlapping({nums}, {target})" + python3: "Solution().maxNonOverlapping({nums}, {target})" + python2: "Solution().maxNonOverlapping({nums}, {target})" + ruby: "max_non_overlapping({nums}, {target})" + java: "new Solution().maxNonOverlapping({nums}, {target})" + csharp: "new Solution().MaxNonOverlapping({nums}, {target})" + kotlin: "Solution().maxNonOverlapping({nums}, {target})" + go: "maxNonOverlapping({nums}, {target})" + dart: "Solution().maxNonOverlapping({nums}, {target})" + swift: "Solution().maxNonOverlapping({nums}, {target})" + typescript: "maxNonOverlapping({nums}, {target})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().maxNonOverlapping(nums, target, {result})" + checker: | + class Checker: + def maxNonOverlapping(self, nums, target, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + best_by_prefix = {0: 0} + prefix = 0 + best = 0 + for value in nums: + prefix += value + candidate = best_by_prefix.get(prefix - target) + if candidate is not None: + best = max(best, candidate + 1) + best_by_prefix[prefix] = max(best_by_prefix.get(prefix, 0), best) + return result == best + +seed: 1546 + +tests: + - name: example-repeated-ones + in: + nums: [1, 1, 1, 1, 1] + target: 2 + out: 2 + - name: example-negative-and-positive + in: + nums: [-1, 3, 5, 1, 4, 2, -9] + target: 6 + out: 2 + - name: all-zeroes + in: + nums: [0, 0, 0] + target: 0 + out: 3 + - name: single-hit + in: + nums: [1] + target: 1 + out: 1 + - name: single-miss + in: + nums: [1] + target: 0 + out: 0 + - name: negative-single + in: + nums: [-1] + target: 0 + out: 0 + - name: adjacent-singletons + in: + nums: [2, 2, 2, 2] + target: 2 + out: 4 + - name: alternating-zero-sums + in: + nums: [1, -1, 1, -1, 1, -1] + target: 0 + out: 3 + - name: repeated-canceling-pairs + in: + nums: [3, -3, 3, -3] + target: 0 + out: 2 + - name: overlapping-choice + in: + nums: [5, -2, -3, 5, -5, 5] + target: 5 + out: 3 + - name: prefix-sum-target + in: + nums: [1, 2, 3] + target: 3 + out: 2 + - name: whole-array-target + in: + nums: [1, 2, 3] + target: 6 + out: 1 + - name: impossible-positive + in: + nums: [1, 2, 3] + target: 7 + out: 0 + - name: mixed-zero-target + in: + nums: [-2, -2, 4, -4, 4] + target: 0 + out: 2 + - name: zero-gaps + in: + nums: [0, 1, 0, 1, 0, 1] + target: 1 + out: 3 + - name: competing-negative-ranges + in: + nums: [2, -1, -1, 2, -2, 2] + target: 0 + out: 2 + - name: large-positive-and-negative + in: + nums: [10000, -10000, 10000] + target: 10000 + out: 2 + - name: negative-positive-pairs + in: + nums: [-5, 5, -5, 5] + target: 0 + out: 2 + - name: repeated-four-ranges + in: + nums: [4, 1, -1, 4, 1, -1] + target: 4 + out: 2 + - name: many-zero-sum-options + in: + nums: [1, 1, -2, 2, -2, 2] + target: 0 + out: 2 + - name: max-value-boundary + in: + nums: [10000, -10000, 10000] + target: 10000 + out: 2 + - name: min-value-boundary + in: + nums: [-10000, 10000, -10000, 10000] + target: 0 + out: 2 + - name: alternating-target + in: + nums: [2, -2, 2, -2, 2] + target: 2 + out: 3 + - name: nested-five-sums + in: + nums: [5, 5, -5, 5, -5, 5] + target: 5 + out: 4 + - name: zero-length-segments-forbidden + in: + nums: [1, -2, 3, -2, 1, 2, -1] + target: 2 + out: 2 + - name: separated-seven-sums + in: + nums: [7, -3, -4, 7, -7, 7] + target: 7 + out: 3 + - name: zeros-around-cancel + in: + nums: [0, 0, 1, -1, 0, 0] + target: 0 + out: 5 + - name: negative-target + in: + nums: [-1, -1, -1, 3, 0, 0] + target: -3 + out: 1 + - name: repeated-six-sums + in: + nums: [6, -1, -5, 6, -6, 6] + target: 6 + out: 3 + - name: three-sum-blocks + in: + nums: [2, 2, -1, -1, 2, 2] + target: 3 + out: 2 + - name: zero-sum-separators + in: + nums: [9, -4, -5, 9, -9] + target: 0 + out: 2 + - name: cancellation-with-tail + in: + nums: [-3, 1, 2, -3, 3, -3] + target: 0 + out: 2 + - name: interleaved-unit-ranges + in: + nums: [1, -1, 0, 1, -1, 0, 1] + target: 1 + out: 3 + - name: repeated-zero-ranges + in: + nums: [4, -2, -2, 4, -4, 4, -4] + target: 0 + out: 3 + - name: repeated-eight-ranges + in: + nums: [8, -3, -5, 8, -8, 8] + target: 8 + out: 3 + - name: generated-small-values + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: -10000 + max: 10000 + distinct: false + sorted: false + elemType: "int" + target: + gen: "int" + min: 0 + max: 1000000 + - name: generated-zero-target + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: -1 + max: 1 + distinct: false + sorted: false + elemType: "int" + target: 0 + - name: generated-large-positive-target + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: -10000 + max: 10000 + distinct: false + sorted: false + elemType: "int" + target: 1000000 + - name: generated-large-balanced-values + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: -10000 + max: 10000 + distinct: false + sorted: false + elemType: "int" + target: + gen: "int" + min: 0 + max: 1000000 + - name: generated-medium-boundary-values + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: -10000 + max: 10000 + distinct: false + sorted: false + elemType: "int" + target: 0 diff --git a/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.cpp b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.cpp new file mode 100644 index 00000000..1eea14d4 --- /dev/null +++ b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int maxNonOverlapping(vector& nums, int target) { + int num_of_subarrays = 0; + int temp = 0; + unordered_set visited = {0}; + for (int num : nums) { + temp += num; + int prev = temp - target; + if (visited.count(prev)) { + visited.clear(); + num_of_subarrays++; + } + visited.insert(temp); + } + return num_of_subarrays; + } +}; diff --git a/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.cs b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.cs new file mode 100644 index 00000000..8671313f --- /dev/null +++ b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.cs @@ -0,0 +1,17 @@ +public class Solution { + public int MaxNonOverlapping(int[] nums, int target) { + int numOfSubarrays = 0; + int temp = 0; + HashSet visited = new HashSet { 0 }; + foreach (int num in nums) { + temp += num; + int prev = temp - target; + if (visited.Contains(prev)) { + visited = new HashSet(); + numOfSubarrays++; + } + visited.Add(temp); + } + return numOfSubarrays; + } +} diff --git a/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.dart b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.dart new file mode 100644 index 00000000..580aba4f --- /dev/null +++ b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.dart @@ -0,0 +1,17 @@ +class Solution { + int maxNonOverlapping(List nums, int target) { + int numOfSubarrays = 0; + int temp = 0; + Set visited = {0}; + for (int num in nums) { + temp += num; + int prev = temp - target; + if (visited.contains(prev)) { + visited = {}; + numOfSubarrays++; + } + visited.add(temp); + } + return numOfSubarrays; + } +} diff --git a/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.go b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.go new file mode 100644 index 00000000..30906416 --- /dev/null +++ b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.go @@ -0,0 +1,15 @@ +func maxNonOverlapping(nums []int, target int) int { + numOfSubarrays := 0 + temp := 0 + visited := map[int]bool{0: true} + for _, num := range nums { + temp += num + prev := temp - target + if visited[prev] { + visited = map[int]bool{} + numOfSubarrays++ + } + visited[temp] = true + } + return numOfSubarrays +} diff --git a/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.java b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.java new file mode 100644 index 00000000..8ae9dd7d --- /dev/null +++ b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.java @@ -0,0 +1,18 @@ +class Solution { + public int maxNonOverlapping(int[] nums, int target) { + int num_of_subarrays = 0; + int temp = 0; + Set visited = new HashSet<>(); + visited.add(0); + for (int num : nums) { + temp += num; + int prev = temp - target; + if (visited.contains(prev)) { + visited = new HashSet<>(); + num_of_subarrays++; + } + visited.add(temp); + } + return num_of_subarrays; + } +} diff --git a/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.kt b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.kt new file mode 100644 index 00000000..e58209de --- /dev/null +++ b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.kt @@ -0,0 +1,17 @@ +class Solution { + fun maxNonOverlapping(nums: IntArray, target: Int): Int { + var numOfSubarrays = 0 + var temp = 0 + var visited = mutableSetOf(0) + for (num in nums) { + temp += num + val prev = temp - target + if (prev in visited) { + visited = mutableSetOf() + numOfSubarrays++ + } + visited.add(temp) + } + return numOfSubarrays + } +} diff --git a/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.py b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.py new file mode 100644 index 00000000..d5fb41a6 --- /dev/null +++ b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.py @@ -0,0 +1,11 @@ +class Solution: + def maxNonOverlapping(self, nums, target): + num_of_subarrays, temp, visited = 0, 0, {0} + for i, num in enumerate(nums): + temp += num + prev = temp - target + if prev in visited: + visited = set() + num_of_subarrays += 1 + visited.add(temp) + return num_of_subarrays diff --git a/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.py2 b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.py2 new file mode 100644 index 00000000..3459d746 --- /dev/null +++ b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def maxNonOverlapping(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: int + """ + num_of_subarrays, temp, visited = 0, 0, {0} + for i, num in enumerate(nums): + temp += num + prev = temp - target + if prev in visited: + visited = set() + num_of_subarrays += 1 + visited.add(temp) + return num_of_subarrays diff --git a/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.rb b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.rb new file mode 100644 index 00000000..3ced9a75 --- /dev/null +++ b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.rb @@ -0,0 +1,16 @@ +# @param {Integer[]} nums +# @param {Integer} target +# @return {Integer} +def max_non_overlapping(nums, target) + num_of_subarrays, temp, visited = 0, 0, {0 => true} + nums.each do |num| + temp += num + prev = temp - target + if visited.include?(prev) + visited = {} + num_of_subarrays += 1 + end + visited[temp] = true + end + num_of_subarrays +end diff --git a/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.rs b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.rs new file mode 100644 index 00000000..79ffb78d --- /dev/null +++ b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn max_non_overlapping(nums: Vec, target: i32) -> i32 { + let mut num_of_subarrays = 0; + let mut temp = 0; + let mut visited = std::collections::HashSet::new(); + visited.insert(0); + for num in nums { + temp += num; + let prev = temp - target; + if visited.contains(&prev) { + visited.clear(); + num_of_subarrays += 1; + } + visited.insert(temp); + } + num_of_subarrays + } +} diff --git a/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.swift b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.swift new file mode 100644 index 00000000..f0e73f67 --- /dev/null +++ b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.swift @@ -0,0 +1,17 @@ +class Solution { + func maxNonOverlapping(_ nums: [Int], _ target: Int) -> Int { + var numOfSubarrays = 0 + var temp = 0 + var visited = Set([0]) + for num in nums { + temp += num + let prev = temp - target + if visited.contains(prev) { + visited = Set() + numOfSubarrays += 1 + } + visited.insert(temp) + } + return numOfSubarrays + } +} diff --git a/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.ts b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.ts new file mode 100644 index 00000000..ab12b0db --- /dev/null +++ b/tests/1501-2000/1546. maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/sol.ts @@ -0,0 +1,15 @@ +function maxNonOverlapping(nums: number[], target: number): number { + let numOfSubarrays = 0; + let temp = 0; + let visited = new Set([0]); + for (const num of nums) { + temp += num; + const prev = temp - target; + if (visited.has(prev)) { + visited = new Set(); + numOfSubarrays++; + } + visited.add(temp); + } + return numOfSubarrays; +} diff --git a/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/manifest.yaml b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/manifest.yaml new file mode 100644 index 00000000..bd050930 --- /dev/null +++ b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/manifest.yaml @@ -0,0 +1,288 @@ +entry: + id: 1547 + title: "minimum-cost-to-cut-a-stick" + params: + n: + type: int + cuts: + type: array + items: + type: int + call: + cpp: "Solution().minCost({n}, {cuts})" + rust: "Solution::min_cost({n}, {cuts})" + python3: "Solution().minCost({n}, {cuts})" + python2: "Solution().minCost({n}, {cuts})" + ruby: "min_cost({n}, {cuts})" + java: "new Solution().minCost({n}, {cuts})" + csharp: "new Solution().MinCost({n}, {cuts})" + kotlin: "Solution().minCost({n}, {cuts})" + go: "minCost({n}, {cuts})" + dart: "Solution().minCost({n}, {cuts})" + swift: "Solution().minCost({n}, {cuts})" + typescript: "minCost({n}, {cuts})" +judge: + type: "exact" +limits: + time_ms: 3000 + memory_mb: 512 +oracle: + python3: + call: "Checker().minCost(n, cuts, {result})" + checker: | + class Checker: + def minCost(self, n, cuts, result): + points = sorted([0, n] + list(cuts)) + size = len(points) + dp = [[0] * size for _ in range(size)] + for gap in range(2, size): + for left in range(size - gap): + right = left + gap + dp[left][right] = min( + dp[left][mid] + dp[mid][right] + for mid in range(left + 1, right) + ) + points[right] - points[left] + return result == dp[0][size - 1] +seed: 1547 +tests: + - name: one-cut-small + in: + n: 3 + cuts: [1] + out: 3 + - name: one-cut-left + in: + n: 4 + cuts: [1] + out: 4 + - name: one-cut-middle + in: + n: 4 + cuts: [2] + out: 4 + - name: adjacent-left-cuts + in: + n: 5 + cuts: [1, 2] + out: 7 + - name: asymmetric-two-cuts + in: + n: 5 + cuts: [1, 3] + out: 8 + - name: mirrored-two-cuts + in: + n: 5 + cuts: [2, 4] + out: 8 + - name: one-cut-six + in: + n: 6 + cuts: [1] + out: 6 + - name: separated-two-cuts + in: + n: 6 + cuts: [2, 4] + out: 10 + - name: three-evenly-spaced + in: + n: 6 + cuts: [1, 3, 5] + out: 12 + - name: official-example-one + in: + n: 7 + cuts: [1, 3, 4, 5] + out: 16 + - name: two-cuts-seven + in: + n: 7 + cuts: [2, 5] + out: 12 + - name: three-left-heavy + in: + n: 8 + cuts: [1, 2, 3] + out: 13 + - name: three-symmetric + in: + n: 8 + cuts: [2, 4, 6] + out: 16 + - name: four-almost-even + in: + n: 8 + cuts: [1, 3, 5, 7] + out: 19 + - name: official-example-two + in: + n: 9 + cuts: [5, 6, 1, 4, 2] + out: 22 + - name: five-dense-left + in: + n: 10 + cuts: [1, 2, 3, 4, 5] + out: 22 + - name: three-balanced + in: + n: 10 + cuts: [2, 5, 8] + out: 20 + - name: four-right-heavy + in: + n: 10 + cuts: [1, 4, 7, 9] + out: 23 + - name: two-cuts-eleven + in: + n: 11 + cuts: [3, 6] + out: 17 + - name: three-asymmetric-eleven + in: + n: 11 + cuts: [1, 5, 10] + out: 22 + - name: five-evenly-spaced + in: + n: 12 + cuts: [2, 4, 6, 8, 10] + out: 32 + - name: six-odd-cuts + in: + n: 12 + cuts: [1, 3, 5, 7, 9, 11] + out: 34 + - name: four-thirteen + in: + n: 13 + cuts: [2, 6, 9, 12] + out: 30 + - name: one-cut-large + in: + n: 20 + cuts: [1] + out: 20 + - name: three-cuts-twenty + in: + n: 20 + cuts: [5, 10, 15] + out: 40 + - name: nine-dense-cuts + in: + n: 20 + cuts: [2, 4, 6, 8, 10, 12, 14, 16, 18] + out: 68 + - name: five-irregular-twenty-five + in: + n: 25 + cuts: [1, 7, 13, 19, 24] + out: 63 + - name: five-irregular-thirty + in: + n: 30 + cuts: [3, 8, 14, 21, 27] + out: 77 + - name: nine-cuts-fifty + in: + n: 50 + cuts: [5, 10, 15, 20, 25, 30, 35, 40, 45] + out: 170 + - name: five-cuts-hundred + in: + n: 100 + cuts: [1, 25, 50, 75, 99] + out: 250 + - name: nine-cuts-hundred + in: + n: 100 + cuts: [10, 20, 30, 40, 50, 60, 70, 80, 90] + out: 340 + - name: six-cuts-thousand + in: + n: 1000 + cuts: [1, 100, 250, 500, 750, 999] + out: 2600 + - name: max-n-one-left + in: + n: 999999 + cuts: [1] + out: 999999 + - name: max-n-two-extremes + in: + n: 1000000 + cuts: [1, 999999] + out: 1999999 + - name: max-n-nine-cuts + in: + n: 1000000 + cuts: + [100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000] + out: 3400000 + - name: generated-single-cut + in: + n: 1000000 + cuts: + gen: "array" + len: 1 + of: + gen: "int" + min: 1 + max: 999999 + distinct: true + sorted: false + elemType: "int" + - name: generated-small-cut-set + in: + n: 1000000 + cuts: + gen: "array" + len: 10 + of: + gen: "int" + min: 1 + max: 999999 + distinct: true + sorted: false + elemType: "int" + - name: generated-medium-cut-set + in: + n: 1000000 + cuts: + gen: "array" + len: 50 + of: + gen: "int" + min: 1 + max: 999999 + distinct: true + sorted: false + elemType: "int" + - name: generated-near-limit-cut-set + in: + n: 1000000 + cuts: + gen: "array" + len: 99 + of: + gen: "int" + min: 1 + max: 999999 + distinct: true + sorted: false + elemType: "int" + - name: generated-maximum-cut-set + in: + n: 1000000 + cuts: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 999999 + distinct: true + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.cpp b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.cpp new file mode 100644 index 00000000..c3589f5e --- /dev/null +++ b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int minCost(int n, vector& cuts) { + vector c = cuts; + c.push_back(0); + c.push_back(n); + sort(c.begin(), c.end()); + int m = c.size(); + vector> memo(m, vector(m, -1)); + return optimize(0, m-1, c, memo); + } + + int optimize(int i, int j, vector& c, vector>& memo) { + if (j - i <= 1) return 0; + if (memo[i][j] != -1) return memo[i][j]; + int res = INT_MAX; + for (int k = i+1; k < j; k++) { + int val = optimize(i, k, c, memo) + optimize(k, j, c, memo); + res = min(res, val); + } + memo[i][j] = res + (c[j] - c[i]); + return memo[i][j]; + } +}; diff --git a/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.cs b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.cs new file mode 100644 index 00000000..3687c7e8 --- /dev/null +++ b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.cs @@ -0,0 +1,26 @@ +public class Solution { + public int MinCost(int n, int[] cuts) { + var c = cuts.ToList(); + c.Add(0); + c.Add(n); + c.Sort(); + int m = c.Count; + var memo = new int[m, m]; + for (int i = 0; i < m; i++) + for (int j = 0; j < m; j++) + memo[i, j] = -1; + return Optimize(0, m-1, c, memo); + } + + private int Optimize(int i, int j, List c, int[,] memo) { + if (j - i <= 1) return 0; + if (memo[i, j] != -1) return memo[i, j]; + int res = int.MaxValue; + for (int k = i+1; k < j; k++) { + int val = Optimize(i, k, c, memo) + Optimize(k, j, c, memo); + if (val < res) res = val; + } + memo[i, j] = res + (c[j] - c[i]); + return memo[i, j]; + } +} diff --git a/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.dart b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.dart new file mode 100644 index 00000000..1c6418eb --- /dev/null +++ b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.dart @@ -0,0 +1,20 @@ +class Solution { + int minCost(int n, List cuts) { + List c = [...cuts, 0, n]..sort(); + int m = c.length; + List> memo = List.generate(m, (_) => List.filled(m, -1)); + return optimize(0, m-1, c, memo); + } + + int optimize(int i, int j, List c, List> memo) { + if (j - i <= 1) return 0; + if (memo[i][j] != -1) return memo[i][j]; + int res = 1 << 31 - 1; // max int + for (int k = i+1; k < j; k++) { + int val = optimize(i, k, c, memo) + optimize(k, j, c, memo); + if (val < res) res = val; + } + memo[i][j] = res + (c[j] - c[i]); + return memo[i][j]; + } +} diff --git a/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.go b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.go new file mode 100644 index 00000000..b446e45d --- /dev/null +++ b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.go @@ -0,0 +1,31 @@ +func minCost(n int, cuts []int) int { + c := append(append([]int{}, cuts...), 0, n) + sort.Ints(c) + m := len(c) + memo := make([][]int, m) + for i := range memo { + memo[i] = make([]int, m) + for j := range memo[i] { + memo[i][j] = -1 + } + } + return optimize(0, m-1, c, memo) +} + +func optimize(i, j int, c []int, memo [][]int) int { + if j-i <= 1 { + return 0 + } + if memo[i][j] != -1 { + return memo[i][j] + } + res := int(^uint(0) >> 1) // max int + for k := i+1; k < j; k++ { + val := optimize(i, k, c, memo) + optimize(k, j, c, memo) + if val < res { + res = val + } + } + memo[i][j] = res + (c[j] - c[i]) + return memo[i][j] +} diff --git a/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.java b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.java new file mode 100644 index 00000000..3bce667f --- /dev/null +++ b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.java @@ -0,0 +1,27 @@ +import java.util.*; + +class Solution { + public int minCost(int n, int[] cuts) { + int[] c = new int[cuts.length + 2]; + System.arraycopy(cuts, 0, c, 0, cuts.length); + c[cuts.length] = 0; + c[cuts.length + 1] = n; + Arrays.sort(c); + int m = c.length; + int[][] memo = new int[m][m]; + for (int[] row : memo) Arrays.fill(row, -1); + return optimize(0, m-1, c, memo); + } + + private int optimize(int i, int j, int[] c, int[][] memo) { + if (j - i <= 1) return 0; + if (memo[i][j] != -1) return memo[i][j]; + int res = Integer.MAX_VALUE; + for (int k = i+1; k < j; k++) { + int val = optimize(i, k, c, memo) + optimize(k, j, c, memo); + res = Math.min(res, val); + } + memo[i][j] = res + (c[j] - c[i]); + return memo[i][j]; + } +} diff --git a/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.kt b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.kt new file mode 100644 index 00000000..0eebbe4c --- /dev/null +++ b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.kt @@ -0,0 +1,21 @@ +class Solution { + fun minCost(n: Int, cuts: IntArray): Int { + val c = (cuts + intArrayOf(0, n)).sortedArray() + val m = c.size + val memo = Array(m) { IntArray(m) { -1 } } + return optimize(0, m-1, c, memo) + } + + private fun optimize(i: Int, j: Int, c: IntArray, memo: Array): Int { + if (j - i <= 1) return 0 + if (memo[i][j] != -1) return memo[i][j] + var res = Int.MAX_VALUE + for (k in i+1 until j) { + val val1 = optimize(i, k, c, memo) + val val2 = optimize(k, j, c, memo) + res = minOf(res, val1 + val2) + } + memo[i][j] = res + (c[j] - c[i]) + return memo[i][j] + } +} diff --git a/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.py b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.py new file mode 100644 index 00000000..02d55cf3 --- /dev/null +++ b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.py @@ -0,0 +1,29 @@ +import numpy as np +from functools import lru_cache + + +class Solution: + def minCost(self, n: int, cuts: List[int]) -> int: + # 1. Coordinate Mapping + # We add the boundaries (0, n) to define the full manifold + c = sorted(cuts + [0, n]) + m = len(c) + + # 2. Interval Optimization Table + # We optimize for the minimum cost to process the interval between c[i] and c[j] + @lru_cache(None) + def optimize_manifold(i, j): + # Base Case: No cuts possible between these two coordinates + if j - i <= 1: + return 0 + + # The "Golden" Search: Find the cut 'k' that minimizes the combined cost + # We treat the cost as the current stick length: c[j] - c[i] + res = min( + optimize_manifold(i, k) + optimize_manifold(k, j) + for k in range(i + 1, j) + ) + + return res + (c[j] - c[i]) + + return optimize_manifold(0, m - 1) diff --git a/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.py2 b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.py2 new file mode 100644 index 00000000..26ec7aa0 --- /dev/null +++ b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def minCost(self, n, cuts): + """ + :type n: int + :type cuts: List[int] + :rtype: int + """ + c = sorted(cuts + [0, n]) + m = len(c) + def optimize_manifold(i, j): + key = (i, j) + if key in memo: + return memo[key] + if j - i <= 1: + return 0 + res = min(optimize_manifold(i, k) + optimize_manifold(k, j) + for k in range(i + 1, j)) + memo[key] = res + (c[j] - c[i]) + return memo[key] + + memo = {} + return optimize_manifold(0, m - 1) diff --git a/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.rb b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.rb new file mode 100644 index 00000000..6def08fb --- /dev/null +++ b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.rb @@ -0,0 +1,23 @@ +# @param {Integer} n +# @param {Integer[]} cuts +# @return {Integer} +def min_cost(n, cuts) + c = (cuts + [0, n]).sort + m = c.length + memo = {} + + optimize = lambda do |i, j| + key = [i, j] + return memo[key] if memo.key?(key) + return 0 if j - i <= 1 + + res = Float::INFINITY + (i+1...j).each do |k| + val = optimize.call(i, k) + optimize.call(k, j) + res = val if val < res + end + memo[key] = res + (c[j] - c[i]) + end + + optimize.call(0, m - 1) +end diff --git a/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.rs b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.rs new file mode 100644 index 00000000..a251d961 --- /dev/null +++ b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.rs @@ -0,0 +1,23 @@ +impl Solution { + pub fn min_cost(n: i32, cuts: Vec) -> i32 { + let mut c = cuts.clone(); + c.push(0); + c.push(n); + c.sort(); + let m = c.len(); + let mut memo = vec![vec![-1; m]; m]; + Self::optimize(0, m-1, &c, &mut memo) + } + + fn optimize(i: usize, j: usize, c: &Vec, memo: &mut Vec>) -> i32 { + if j - i <= 1 { return 0; } + if memo[i][j] != -1 { return memo[i][j]; } + let mut res = i32::MAX; + for k in (i+1)..j { + let val = Self::optimize(i, k, c, memo) + Self::optimize(k, j, c, memo); + res = res.min(val); + } + memo[i][j] = res + (c[j] - c[i]); + memo[i][j] + } +} diff --git a/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.swift b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.swift new file mode 100644 index 00000000..984dc2c4 --- /dev/null +++ b/tests/1501-2000/1547. minimum-cost-to-cut-a-stick/sol.swift @@ -0,0 +1,21 @@ +class Solution { + func minCost(_ n: Int, _ cuts: [Int]) -> Int { + var c = cuts + [0, n] + c.sort() + let m = c.count + var memo = Array(repeating: Array(repeating: -1, count: m), count: m) + return optimize(0, m-1, c, &memo) + } + + func optimize(_ i: Int, _ j: Int, _ c: [Int], _ memo: inout [[Int]]) -> Int { + if j - i <= 1 { return 0 } + if memo[i][j] != -1 { return memo[i][j] } + var res = Int.max + for k in (i+1).. a - b); + const m = c.length; + const memo: number[][] = Array.from({ length: m }, () => Array(m).fill(-1)); + return optimize(0, m - 1, c, memo); +} + +function optimize(i: number, j: number, c: number[], memo: number[][]): number { + if (j - i <= 1) return 0; + if (memo[i][j] !== -1) return memo[i][j]; + let res = Number.MAX_SAFE_INTEGER; + for (let k = i + 1; k < j; k++) { + const val = optimize(i, k, c, memo) + optimize(k, j, c, memo); + if (val < res) res = val; + } + memo[i][j] = res + (c[j] - c[i]); + return memo[i][j]; +} diff --git a/tests/1501-2000/1550. three-consecutive-odds/manifest.yaml b/tests/1501-2000/1550. three-consecutive-odds/manifest.yaml new file mode 100644 index 00000000..10dba359 --- /dev/null +++ b/tests/1501-2000/1550. three-consecutive-odds/manifest.yaml @@ -0,0 +1,276 @@ +entry: + id: 1550 + title: "three-consecutive-odds" + params: + arr: + type: array + items: + type: int + call: + cpp: "Solution().threeConsecutiveOdds({arr})" + rust: "Solution::three_consecutive_odds({arr})" + python3: "Solution().threeConsecutiveOdds({arr})" + python2: "Solution().threeConsecutiveOdds({arr})" + ruby: "three_consecutive_odds({arr})" + java: "new Solution().threeConsecutiveOdds({arr})" + csharp: "new Solution().ThreeConsecutiveOdds({arr})" + kotlin: "Solution().threeConsecutiveOdds({arr})" + go: "threeConsecutiveOdds({arr})" + dart: "Solution().threeConsecutiveOdds({arr})" + swift: "Solution().threeConsecutiveOdds({arr})" + typescript: "threeConsecutiveOdds({arr})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().threeConsecutiveOdds(arr, {result})" + checker: | + class Checker: + def threeConsecutiveOdds(self, arr, result): + expected = any(arr[i] % 2 == 1 and arr[i + 1] % 2 == 1 and arr[i + 2] % 2 == 1 + for i in range(len(arr) - 2)) + return result is expected + +seed: 1550 + +tests: + - name: example-no-triple + in: + arr: [2, 6, 4, 1] + out: false + - name: example-triple-late + in: + arr: [1, 2, 34, 3, 4, 5, 7, 23, 12] + out: true + - name: one-even + in: + arr: [2] + out: false + - name: one-odd + in: + arr: [1] + out: false + - name: two-odds + in: + arr: [1, 3] + out: false + - name: three-odds + in: + arr: [1, 3, 5] + out: true + - name: three-evens + in: + arr: [2, 4, 6] + out: false + - name: triple-at-start + in: + arr: [1, 3, 5, 2, 4] + out: true + - name: triple-at-end + in: + arr: [2, 4, 1, 3, 5] + out: true + - name: triple-in-middle + in: + arr: [2, 1, 3, 5, 4] + out: true + - name: separated-by-even + in: + arr: [1, 3, 2, 5, 7, 9] + out: true + - name: exactly-two-runs + in: + arr: [1, 3, 2, 5, 7] + out: false + - name: four-odds + in: + arr: [1, 3, 5, 7] + out: true + - name: five-odds + in: + arr: [9, 7, 5, 3, 1] + out: true + - name: alternating-start-even + in: + arr: [2, 1, 2, 1, 2, 1, 2] + out: false + - name: alternating-start-odd + in: + arr: [1, 2, 1, 2, 1, 2, 1] + out: false + - name: triple-with-boundary-evens + in: + arr: [2, 1, 3, 5, 2] + out: true + - name: odd-run-length-two + in: + arr: [2, 1, 3, 2, 1, 3, 4] + out: false + - name: odd-run-length-three + in: + arr: [2, 1, 3, 5, 2, 1, 3] + out: true + - name: max-values-even + in: + arr: [1000, 998, 996, 994] + out: false + - name: max-values-odd + in: + arr: [999, 997, 995, 993] + out: true + - name: min-and-max + in: + arr: [1, 1000, 999, 997, 995] + out: true + - name: large-gap-before-triple + in: + arr: [2, 4, 6, 8, 10, 1, 3, 5] + out: true + - name: large-gap-after-triple + in: + arr: [1, 3, 5, 8, 10, 12, 14] + out: true + - name: odd-singletons + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8, 9] + out: false + - name: two-runs-no-triple + in: + arr: [1, 3, 2, 5, 7, 2, 9, 1] + out: false + - name: two-triples + in: + arr: [1, 3, 5, 2, 7, 9, 11] + out: true + - name: triple-overlap + in: + arr: [1, 3, 5, 7, 2] + out: true + - name: odd-run-four-with-even + in: + arr: [2, 1, 3, 5, 7, 4] + out: true + - name: all-even-long + in: + arr: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] + out: false + - name: all-odd-long + in: + arr: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] + out: true + - name: triple-using-high-odds + in: + arr: [1000, 999, 1000, 997, 995, 2] + out: false + - name: first-three-then-noise + in: + arr: [999, 1, 3, 2, 1000, 4, 6, 8] + out: true + - name: last-three-after-noise + in: + arr: [1000, 2, 4, 6, 7, 9, 11] + out: true + - name: length-thirty-two-triple-end + in: + arr: + [ + 2, + 4, + 6, + 8, + 10, + 12, + 14, + 16, + 18, + 20, + 22, + 24, + 26, + 28, + 30, + 32, + 34, + 36, + 38, + 40, + 42, + 44, + 46, + 48, + 50, + 52, + 54, + 56, + 1, + 3, + 5, + 2, + ] + out: true + - name: generator-small + in: + arr: + gen: "array" + len: 1 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: "int" + - name: generator-medium + in: + arr: + gen: "array" + len: 17 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: "int" + - name: generator-large + in: + arr: + gen: "array" + len: 250 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: "int" + - name: generator-near-limit + in: + arr: + gen: "array" + len: 999 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: "int" + - name: generator-at-limit + in: + arr: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1550. three-consecutive-odds/sol.cpp b/tests/1501-2000/1550. three-consecutive-odds/sol.cpp new file mode 100644 index 00000000..200543ae --- /dev/null +++ b/tests/1501-2000/1550. three-consecutive-odds/sol.cpp @@ -0,0 +1,8 @@ +class Solution { +public: + bool threeConsecutiveOdds(vector& arr) { + string s = ""; + for (int x : arr) s += to_string(x & 1); + return s.find("111") != string::npos; + } +}; diff --git a/tests/1501-2000/1550. three-consecutive-odds/sol.cs b/tests/1501-2000/1550. three-consecutive-odds/sol.cs new file mode 100644 index 00000000..7eb64454 --- /dev/null +++ b/tests/1501-2000/1550. three-consecutive-odds/sol.cs @@ -0,0 +1,6 @@ +public class Solution { + public bool ThreeConsecutiveOdds(int[] arr) { + string s = string.Concat(arr.Select(x => (x & 1).ToString())); + return s.Contains("111"); + } +} diff --git a/tests/1501-2000/1550. three-consecutive-odds/sol.dart b/tests/1501-2000/1550. three-consecutive-odds/sol.dart new file mode 100644 index 00000000..b778999e --- /dev/null +++ b/tests/1501-2000/1550. three-consecutive-odds/sol.dart @@ -0,0 +1,6 @@ +class Solution { + bool threeConsecutiveOdds(List arr) { + String s = arr.map((x) => (x & 1).toString()).join(); + return s.contains('111'); + } +} diff --git a/tests/1501-2000/1550. three-consecutive-odds/sol.go b/tests/1501-2000/1550. three-consecutive-odds/sol.go new file mode 100644 index 00000000..c9af5123 --- /dev/null +++ b/tests/1501-2000/1550. three-consecutive-odds/sol.go @@ -0,0 +1,7 @@ +func threeConsecutiveOdds(arr []int) bool { + s := "" + for _, x := range arr { + s += fmt.Sprintf("%d", x & 1) + } + return strings.Contains(s, "111") +} diff --git a/tests/1501-2000/1550. three-consecutive-odds/sol.java b/tests/1501-2000/1550. three-consecutive-odds/sol.java new file mode 100644 index 00000000..8a95c48b --- /dev/null +++ b/tests/1501-2000/1550. three-consecutive-odds/sol.java @@ -0,0 +1,7 @@ +class Solution { + public boolean threeConsecutiveOdds(int[] arr) { + StringBuilder sb = new StringBuilder(); + for (int x : arr) sb.append(x & 1); + return sb.toString().contains("111"); + } +} diff --git a/tests/1501-2000/1550. three-consecutive-odds/sol.kt b/tests/1501-2000/1550. three-consecutive-odds/sol.kt new file mode 100644 index 00000000..e39ea3d6 --- /dev/null +++ b/tests/1501-2000/1550. three-consecutive-odds/sol.kt @@ -0,0 +1,5 @@ +class Solution { + fun threeConsecutiveOdds(arr: IntArray): Boolean { + return arr.joinToString("") { (it and 1).toString() }.contains("111") + } +} diff --git a/tests/1501-2000/1550. three-consecutive-odds/sol.py b/tests/1501-2000/1550. three-consecutive-odds/sol.py new file mode 100644 index 00000000..237fcf68 --- /dev/null +++ b/tests/1501-2000/1550. three-consecutive-odds/sol.py @@ -0,0 +1,3 @@ +class Solution(object): + def threeConsecutiveOdds(self, arr): + return "111" in "".join(str(x & 1) for x in arr) diff --git a/tests/1501-2000/1550. three-consecutive-odds/sol.py2 b/tests/1501-2000/1550. three-consecutive-odds/sol.py2 new file mode 100644 index 00000000..df9d2108 --- /dev/null +++ b/tests/1501-2000/1550. three-consecutive-odds/sol.py2 @@ -0,0 +1,7 @@ +class Solution(object): + def threeConsecutiveOdds(self, arr): + """ + :type arr: List[int] + :rtype: bool + """ + return '111' in ''.join(str(x & 1) for x in arr) diff --git a/tests/1501-2000/1550. three-consecutive-odds/sol.rb b/tests/1501-2000/1550. three-consecutive-odds/sol.rb new file mode 100644 index 00000000..b28ddfb4 --- /dev/null +++ b/tests/1501-2000/1550. three-consecutive-odds/sol.rb @@ -0,0 +1,5 @@ +# @param {Integer[]} arr +# @return {Boolean} +def three_consecutive_odds(arr) + arr.map { |x| x & 1 }.join.include?('111') +end diff --git a/tests/1501-2000/1550. three-consecutive-odds/sol.rs b/tests/1501-2000/1550. three-consecutive-odds/sol.rs new file mode 100644 index 00000000..4c875b1f --- /dev/null +++ b/tests/1501-2000/1550. three-consecutive-odds/sol.rs @@ -0,0 +1,5 @@ +impl Solution { + pub fn three_consecutive_odds(arr: Vec) -> bool { + arr.iter().map(|&x| (x & 1).to_string()).collect::().contains("111") + } +} diff --git a/tests/1501-2000/1550. three-consecutive-odds/sol.swift b/tests/1501-2000/1550. three-consecutive-odds/sol.swift new file mode 100644 index 00000000..b33ab87f --- /dev/null +++ b/tests/1501-2000/1550. three-consecutive-odds/sol.swift @@ -0,0 +1,5 @@ +class Solution { + func threeConsecutiveOdds(_ arr: [Int]) -> Bool { + return arr.map { String($0 & 1) }.joined().contains("111") + } +} diff --git a/tests/1501-2000/1550. three-consecutive-odds/sol.ts b/tests/1501-2000/1550. three-consecutive-odds/sol.ts new file mode 100644 index 00000000..cef52af6 --- /dev/null +++ b/tests/1501-2000/1550. three-consecutive-odds/sol.ts @@ -0,0 +1,6 @@ +function threeConsecutiveOdds(arr: number[]): boolean { + return arr + .map((x) => (x & 1).toString()) + .join("") + .includes("111"); +} diff --git a/tests/1501-2000/1551. minimum-operations-to-make-array-equal/manifest.yaml b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/manifest.yaml new file mode 100644 index 00000000..9a6ece8d --- /dev/null +++ b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/manifest.yaml @@ -0,0 +1,208 @@ +entry: + id: 1551 + title: "minimum-operations-to-make-array-equal" + params: + n: + type: int + call: + cpp: "Solution().minOperations({n})" + rust: "Solution::min_operations({n})" + python3: "Solution().minOperations({n})" + python2: "Solution().minOperations({n})" + ruby: "min_operations({n})" + java: "new Solution().minOperations({n})" + csharp: "new Solution().MinOperations({n})" + kotlin: "Solution().minOperations({n})" + go: "minOperations({n})" + dart: "Solution().minOperations({n})" + swift: "Solution().minOperations({n})" + typescript: "minOperations({n})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minOperations(n, {result})" + checker: | + class Checker: + def minOperations(self, n, result): + return isinstance(result, int) and not isinstance(result, bool) and result == (n * n) // 4 + +seed: 1551 + +tests: + - name: n-one + in: + n: 1 + out: 0 + - name: n-two + in: + n: 2 + out: 1 + - name: example-three + in: + n: 3 + out: 2 + - name: n-four + in: + n: 4 + out: 4 + - name: n-five + in: + n: 5 + out: 6 + - name: example-six + in: + n: 6 + out: 9 + - name: n-seven + in: + n: 7 + out: 12 + - name: n-eight + in: + n: 8 + out: 16 + - name: n-nine + in: + n: 9 + out: 20 + - name: n-ten + in: + n: 10 + out: 25 + - name: n-eleven + in: + n: 11 + out: 30 + - name: n-twelve + in: + n: 12 + out: 36 + - name: n-thirteen + in: + n: 13 + out: 42 + - name: n-fourteen + in: + n: 14 + out: 49 + - name: n-fifteen + in: + n: 15 + out: 56 + - name: n-sixteen + in: + n: 16 + out: 64 + - name: n-seventeen + in: + n: 17 + out: 72 + - name: n-eighteen + in: + n: 18 + out: 81 + - name: n-nineteen + in: + n: 19 + out: 90 + - name: n-twenty + in: + n: 20 + out: 100 + - name: n-twenty-one + in: + n: 21 + out: 110 + - name: n-twenty-two + in: + n: 22 + out: 121 + - name: n-twenty-three + in: + n: 23 + out: 132 + - name: n-twenty-four + in: + n: 24 + out: 144 + - name: n-twenty-five + in: + n: 25 + out: 156 + - name: n-fifty + in: + n: 50 + out: 625 + - name: n-ninety-nine + in: + n: 99 + out: 2450 + - name: n-one-hundred + in: + n: 100 + out: 2500 + - name: n-one-hundred-one + in: + n: 101 + out: 2550 + - name: n-nine-ninety-nine + in: + n: 999 + out: 249500 + - name: n-one-thousand + in: + n: 1000 + out: 250000 + - name: n-five-thousand + in: + n: 5000 + out: 6250000 + - name: n-seven-thousand-five-hundred + in: + n: 7500 + out: 14062500 + - name: n-nine-thousand-nine-hundred-ninety-nine + in: + n: 9999 + out: 24995000 + - name: n-maximum + in: + n: 10000 + out: 25000000 + - name: generated-small + in: + n: + gen: "int" + min: 1 + max: 20 + - name: generated-medium + in: + n: + gen: "int" + min: 21 + max: 1000 + - name: generated-large + in: + n: + gen: "int" + min: 1001 + max: 5000 + - name: generated-near-limit + in: + n: + gen: "int" + min: 5001 + max: 9999 + - name: generated-maximum-range + in: + n: + gen: "int" + min: 1 + max: 10000 diff --git a/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.cpp b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.cpp new file mode 100644 index 00000000..e733953b --- /dev/null +++ b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + int minOperations(int n) { + return (n * n) / 4; + } +}; diff --git a/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.cs b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.cs new file mode 100644 index 00000000..3b6950d7 --- /dev/null +++ b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.cs @@ -0,0 +1,5 @@ +public class Solution { + public int MinOperations(int n) { + return (n * n) / 4; + } +} diff --git a/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.dart b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.dart new file mode 100644 index 00000000..477483d0 --- /dev/null +++ b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.dart @@ -0,0 +1,5 @@ +class Solution { + int minOperations(int n) { + return (n * n) ~/ 4; + } +} diff --git a/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.go b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.go new file mode 100644 index 00000000..00d7321c --- /dev/null +++ b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.go @@ -0,0 +1,3 @@ +func minOperations(n int) int { + return (n * n) / 4 +} diff --git a/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.java b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.java new file mode 100644 index 00000000..134c4e61 --- /dev/null +++ b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.java @@ -0,0 +1,5 @@ +class Solution { + public int minOperations(int n) { + return (n * n) / 4; + } +} diff --git a/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.kt b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.kt new file mode 100644 index 00000000..bbeaaf45 --- /dev/null +++ b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.kt @@ -0,0 +1,5 @@ +class Solution { + fun minOperations(n: Int): Int { + return (n * n) / 4 + } +} diff --git a/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.py b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.py new file mode 100644 index 00000000..d120d62f --- /dev/null +++ b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.py @@ -0,0 +1,11 @@ +class Solution: + def minOperations(self, n: int) -> int: + return (n * n) // 4 + + """count=0 + for i in range(n): + if n>=(2 * i) + 1: + count+=n-((2 * i) + 1) + else: + break + return count""" diff --git a/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.py2 b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.py2 new file mode 100644 index 00000000..14669c76 --- /dev/null +++ b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.py2 @@ -0,0 +1,7 @@ +class Solution(object): + def minOperations(self, n): + """ + :type n: int + :rtype: int + """ + return (n * n) // 4 diff --git a/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.rb b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.rb new file mode 100644 index 00000000..e175d8eb --- /dev/null +++ b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.rb @@ -0,0 +1,5 @@ +# @param {Integer} n +# @return {Integer} +def min_operations(n) + (n * n) / 4 +end diff --git a/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.rs b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.rs new file mode 100644 index 00000000..c3a3e4fd --- /dev/null +++ b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.rs @@ -0,0 +1,5 @@ +impl Solution { + pub fn min_operations(n: i32) -> i32 { + (n * n) / 4 + } +} diff --git a/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.swift b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.swift new file mode 100644 index 00000000..dfc7c33e --- /dev/null +++ b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.swift @@ -0,0 +1,5 @@ +class Solution { + func minOperations(_ n: Int) -> Int { + return (n * n) / 4 + } +} diff --git a/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.ts b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.ts new file mode 100644 index 00000000..c56b8755 --- /dev/null +++ b/tests/1501-2000/1551. minimum-operations-to-make-array-equal/sol.ts @@ -0,0 +1,3 @@ +function minOperations(n: number): number { + return Math.floor((n * n) / 4); +} diff --git a/tests/1501-2000/1552. magnetic-force-between-two-balls/manifest.yaml b/tests/1501-2000/1552. magnetic-force-between-two-balls/manifest.yaml new file mode 100644 index 00000000..1b583b7b --- /dev/null +++ b/tests/1501-2000/1552. magnetic-force-between-two-balls/manifest.yaml @@ -0,0 +1,323 @@ +entry: + id: 1552 + title: "magnetic-force-between-two-balls" + params: + position: + type: array + items: + type: int + m: + type: int + call: + cpp: "Solution().maxDistance({position}, {m})" + rust: "Solution::max_distance({position}, {m})" + python3: "Solution().maxDistance({position}, {m})" + python2: "Solution().maxDistance({position}, {m})" + ruby: "max_distance({position}, {m})" + java: "new Solution().maxDistance({position}, {m})" + csharp: "new Solution().MaxDistance({position}, {m})" + kotlin: "Solution().maxDistance({position}, {m})" + go: "maxDistance({position}, {m})" + dart: "Solution().maxDistance({position}, {m})" + swift: "Solution().maxDistance({position}, {m})" + typescript: "maxDistance({position}, {m})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().maxDistance(position, m, {result})" + checker: | + class Checker: + def maxDistance(self, position, m, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + a = sorted(position) + lo, hi = 1, a[-1] - a[0] + best = 0 + while lo <= hi: + mid = (lo + hi) // 2 + count = 1 + last = a[0] + for value in a[1:]: + if value - last >= mid: + count += 1 + last = value + if count >= m: + best = mid + lo = mid + 1 + else: + hi = mid - 1 + return result == best + +seed: 1552 + +tests: + - name: "example_one" + in: + position: [1, 2, 3, 4, 7] + m: 3 + out: 3 + - name: "example_two_unsorted_large" + in: + position: [5, 4, 3, 2, 1, 1000000000] + m: 2 + out: 999999999 + - name: "three_spread_points" + in: + position: [1, 2, 8, 12, 17] + m: 3 + out: 7 + - name: "two_minimum_baskets" + in: + position: [1, 10] + m: 2 + out: 9 + - name: "three_consecutive_choose_two" + in: + position: [1, 2, 3] + m: 2 + out: 2 + - name: "all_consecutive" + in: + position: [1, 2, 3] + m: 3 + out: 1 + - name: "unit_interval_extremes" + in: + position: [1, 100] + m: 2 + out: 99 + - name: "use_every_evenly_spaced" + in: + position: [10, 20, 30, 40, 50] + m: 5 + out: 10 + - name: "six_points_three_balls" + in: + position: [1, 5, 9, 13, 17, 21] + m: 3 + out: 8 + - name: "six_points_four_balls" + in: + position: [1, 4, 7, 10, 13, 16] + m: 4 + out: 3 + - name: "prime_gaps" + in: + position: [2, 3, 5, 7, 11, 13, 17] + m: 4 + out: 4 + - name: "wide_range_three" + in: + position: [1, 100, 200, 300, 400] + m: 3 + out: 199 + - name: "clustered_endpoints" + in: + position: [1, 2, 100, 101, 102] + m: 3 + out: 2 + - name: "two_clusters_four" + in: + position: [10, 11, 12, 100, 101, 102] + m: 4 + out: 2 + - name: "symmetric_five" + in: + position: [1, 50, 51, 52, 100] + m: 3 + out: 49 + - name: "irregular_four" + in: + position: [3, 8, 14, 20, 29, 35] + m: 4 + out: 6 + - name: "five_from_irregular" + in: + position: [1, 9, 10, 18, 27, 40] + m: 5 + out: 8 + - name: "arithmetic_step_ten" + in: + position: [2, 12, 22, 32, 42, 52, 62] + m: 4 + out: 20 + - name: "eight_points_six" + in: + position: [1, 6, 11, 16, 21, 26, 31, 36] + m: 6 + out: 5 + - name: "two_endpoints_large" + in: + position: [100, 200, 300, 400, 500, 600] + m: 2 + out: 500 + - name: "thousand_gaps" + in: + position: [1, 1000, 2000, 3000, 4000] + m: 4 + out: 1000 + - name: "powers_of_two" + in: + position: [7, 14, 28, 56, 112] + m: 3 + out: 49 + - name: "alternating_large_gaps" + in: + position: [1, 3, 100, 103, 200, 205] + m: 3 + out: 102 + - name: "mixed_small_gaps" + in: + position: [4, 8, 15, 16, 23, 42] + m: 3 + out: 19 + - name: "binary_positions" + in: + position: [1, 2, 4, 8, 16, 32, 64] + m: 5 + out: 7 + - name: "eight_step_pattern" + in: + position: [11, 22, 33, 44, 55, 66, 77, 88] + m: 7 + out: 11 + - name: "quarters" + in: + position: [1, 25, 50, 75, 100] + m: 4 + out: 25 + - name: "increasing_gaps" + in: + position: [2, 5, 9, 14, 20, 27] + m: 4 + out: 7 + - name: "paired_clusters" + in: + position: [1, 17, 18, 35, 36, 53] + m: 3 + out: 18 + - name: "seven_step_five" + in: + position: [6, 12, 18, 24, 30, 36, 42] + m: 5 + out: 6 + - name: "large_coordinates" + in: + position: [1, 100000000, 200000000, 300000000, 400000000] + m: 3 + out: 199999999 + - name: "near_upper_pair" + in: + position: [999999990, 999999995, 1000000000] + m: 2 + out: 10 + - name: "large_endpoint_pair" + in: + position: [1, 2, 1000000000] + m: 2 + out: 999999999 + - name: "four_quarters_billion" + in: + position: [1, 250000000, 500000000, 750000000, 1000000000] + m: 4 + out: 250000000 + - name: "seven_step_six" + in: + position: [13, 26, 39, 52, 65, 78, 91] + m: 6 + out: 13 + - name: "generated_small_distinct" + seed: 155201 + in: + position: + gen: "array" + len: 30 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: true + sorted: true + elemType: "int" + m: + gen: "int" + min: 2 + max: 30 + - name: "generated_medium_distinct" + seed: 155202 + in: + position: + gen: "array" + len: 500 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: true + sorted: true + elemType: "int" + m: + gen: "int" + min: 2 + max: 500 + - name: "generated_large_one" + seed: 155203 + in: + position: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: true + sorted: true + elemType: "int" + m: + gen: "int" + min: 2 + max: 100000 + - name: "generated_large_two" + seed: 155204 + in: + position: + gen: "array" + len: 99999 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: true + sorted: true + elemType: "int" + m: + gen: "int" + min: 2 + max: 99999 + - name: "generated_wide_range" + seed: 155205 + in: + position: + gen: "array" + len: + gen: "int" + min: 1000 + max: 5000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: true + sorted: true + elemType: "int" + m: + gen: "int" + min: 2 + max: 5000 diff --git a/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.cpp b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.cpp new file mode 100644 index 00000000..ffc711bc --- /dev/null +++ b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int maxDistance(vector& position, int m) { + sort(position.begin(), position.end()); + int right = position[position.size() - 1] - position[0]; + int left = 1; + + while (left <= right) { + int mid = (left + right) / 2; + int my_balls = 1; + int previous = position[0]; + + for (int i = 1; i < position.size(); i++) { + if (position[i] - previous >= mid) { + my_balls++; + previous = position[i]; + } + } + + if (my_balls >= m) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return right; + } +}; diff --git a/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.cs b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.cs new file mode 100644 index 00000000..0d284a4f --- /dev/null +++ b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.cs @@ -0,0 +1,28 @@ +public class Solution { + public int MaxDistance(int[] position, int m) { + Array.Sort(position); + int right = position[position.Length - 1] - position[0]; + int left = 1; + + while (left <= right) { + int mid = (left + right) / 2; + int myBalls = 1; + int previous = position[0]; + + for (int i = 1; i < position.Length; i++) { + if (position[i] - previous >= mid) { + myBalls++; + previous = position[i]; + } + } + + if (myBalls >= m) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return right; + } +} diff --git a/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.dart b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.dart new file mode 100644 index 00000000..ea669e09 --- /dev/null +++ b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.dart @@ -0,0 +1,28 @@ +class Solution { + int maxDistance(List position, int m) { + position.sort(); + int right = position[position.length - 1] - position[0]; + int left = 1; + + while (left <= right) { + int mid = (left + right) ~/ 2; + int myBalls = 1; + int previous = position[0]; + + for (int i = 1; i < position.length; i++) { + if (position[i] - previous >= mid) { + myBalls++; + previous = position[i]; + } + } + + if (myBalls >= m) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return right; + } +} diff --git a/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.go b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.go new file mode 100644 index 00000000..c4d35cb7 --- /dev/null +++ b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.go @@ -0,0 +1,26 @@ +func maxDistance(position []int, m int) int { + sort.Ints(position) + right := position[len(position)-1] - position[0] + left := 1 + + for left <= right { + mid := (left + right) / 2 + myBalls := 1 + previous := position[0] + + for _, places := range position[1:] { + if places - previous >= mid { + myBalls++ + previous = places + } + } + + if myBalls >= m { + left = mid + 1 + } else { + right = mid - 1 + } + } + + return right +} diff --git a/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.java b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.java new file mode 100644 index 00000000..995171d2 --- /dev/null +++ b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.java @@ -0,0 +1,28 @@ +class Solution { + public int maxDistance(int[] position, int m) { + Arrays.sort(position); + int right = position[position.length - 1] - position[0]; + int left = 1; + + while (left <= right) { + int mid = (left + right) / 2; + int myBalls = 1; + int previous = position[0]; + + for (int i = 1; i < position.length; i++) { + if (position[i] - previous >= mid) { + myBalls++; + previous = position[i]; + } + } + + if (myBalls >= m) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return right; + } +} diff --git a/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.kt b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.kt new file mode 100644 index 00000000..0ec6c10a --- /dev/null +++ b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.kt @@ -0,0 +1,28 @@ +class Solution { + fun maxDistance(position: IntArray, m: Int): Int { + position.sort() + var right = position[position.size - 1] - position[0] + var left = 1 + + while (left <= right) { + val mid = (left + right) / 2 + var myBalls = 1 + var previous = position[0] + + for (i in 1 until position.size) { + if (position[i] - previous >= mid) { + myBalls++ + previous = position[i] + } + } + + if (myBalls >= m) { + left = mid + 1 + } else { + right = mid - 1 + } + } + + return right + } +} diff --git a/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.py b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.py new file mode 100644 index 00000000..fa477daf --- /dev/null +++ b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.py @@ -0,0 +1,22 @@ +class Solution: + def maxDistance(self, position: List[int], m: int) -> int: + position.sort() + right = position[len(position) - 1] - position[0] + left = 1 + + while left <= right: + mid = (left + right) // 2 + my_balls = 1 # Although i have 2 + previous = position[0] + + for places in position[1:]: + if places - previous >= mid: + my_balls += 1 + previous = places + + if my_balls >= m: + left = mid + 1 + else: + right = mid - 1 + + return right diff --git a/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.py2 b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.py2 new file mode 100644 index 00000000..800eee6d --- /dev/null +++ b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.py2 @@ -0,0 +1,27 @@ +class Solution(object): + def maxDistance(self, position, m): + """ + :type position: List[int] + :type m: int + :rtype: int + """ + position.sort() + right = position[-1] - position[0] + left = 1 + + while left <= right: + mid = (left + right) // 2 + my_balls = 1 + previous = position[0] + + for places in position[1:]: + if places - previous >= mid: + my_balls += 1 + previous = places + + if my_balls >= m: + left = mid + 1 + else: + right = mid - 1 + + return right diff --git a/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.rb b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.rb new file mode 100644 index 00000000..94edd090 --- /dev/null +++ b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.rb @@ -0,0 +1,29 @@ +# @param {Integer[]} position +# @param {Integer} m +# @return {Integer} +def max_distance(position, m) + position.sort! + right = position[-1] - position[0] + left = 1 + + while left <= right + mid = (left + right) / 2 + my_balls = 1 + previous = position[0] + + position[1..-1].each do |places| + if places - previous >= mid + my_balls += 1 + previous = places + end + end + + if my_balls >= m + left = mid + 1 + else + right = mid - 1 + end + end + + right +end diff --git a/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.rs b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.rs new file mode 100644 index 00000000..c62df454 --- /dev/null +++ b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.rs @@ -0,0 +1,29 @@ +impl Solution { + pub fn max_distance(position: Vec, m: i32) -> i32 { + let mut sorted = position; + sorted.sort(); + let mut right = sorted[sorted.len() - 1] - sorted[0]; + let mut left = 1; + + while left <= right { + let mid = (left + right) / 2; + let mut my_balls = 1; + let mut previous = sorted[0]; + + for &places in &sorted[1..] { + if places - previous >= mid { + my_balls += 1; + previous = places; + } + } + + if my_balls >= m { + left = mid + 1; + } else { + right = mid - 1; + } + } + + right + } +} diff --git a/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.swift b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.swift new file mode 100644 index 00000000..d0cb1248 --- /dev/null +++ b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.swift @@ -0,0 +1,28 @@ +class Solution { + func maxDistance(_ position: [Int], _ m: Int) -> Int { + var sorted = position.sorted() + var right = sorted[sorted.count - 1] - sorted[0] + var left = 1 + + while left <= right { + let mid = (left + right) / 2 + var myBalls = 1 + var previous = sorted[0] + + for i in 1..= mid { + myBalls += 1 + previous = sorted[i] + } + } + + if myBalls >= m { + left = mid + 1 + } else { + right = mid - 1 + } + } + + return right + } +} diff --git a/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.ts b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.ts new file mode 100644 index 00000000..bbf8314c --- /dev/null +++ b/tests/1501-2000/1552. magnetic-force-between-two-balls/sol.ts @@ -0,0 +1,26 @@ +function maxDistance(position: number[], m: number): number { + position.sort((a, b) => a - b); + let right = position[position.length - 1] - position[0]; + let left = 1; + + while (left <= right) { + const mid = Math.floor((left + right) / 2); + let myBalls = 1; + let previous = position[0]; + + for (let i = 1; i < position.length; i++) { + if (position[i] - previous >= mid) { + myBalls++; + previous = position[i]; + } + } + + if (myBalls >= m) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return right; +} diff --git a/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/manifest.yaml b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/manifest.yaml new file mode 100644 index 00000000..917d2297 --- /dev/null +++ b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/manifest.yaml @@ -0,0 +1,229 @@ +entry: + id: 1553 + title: "minimum-number-of-days-to-eat-n-oranges" + params: + n: + type: int + call: + cpp: "Solution().minDays({n})" + rust: "Solution::min_days({n})" + python3: "Solution().minDays({n})" + python2: "Solution().minDays({n})" + ruby: "min_days({n})" + java: "new Solution().minDays({n})" + csharp: "new Solution().MinDays({n})" + kotlin: "Solution().minDays({n})" + go: "minDays({n})" + dart: "Solution().minDays({n})" + swift: "Solution().minDays({n})" + typescript: "minDays({n})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minDays(n, {result})" + checker: | + from functools import lru_cache + + class Checker: + def minDays(self, n, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + + @lru_cache(None) + def best(x): + if x <= 1: + return x + return 1 + min(x % 2 + best(x // 2), x % 3 + best(x // 3)) + + return result == best(n) + +seed: 1553 + +tests: + - name: minimum-one + in: + n: 1 + out: 1 + - name: two-oranges + in: + n: 2 + out: 2 + - name: three-oranges + in: + n: 3 + out: 2 + - name: four-oranges + in: + n: 4 + out: 3 + - name: five-oranges + in: + n: 5 + out: 4 + - name: example-two + in: + n: 6 + out: 3 + - name: example-one + in: + n: 10 + out: 4 + - name: twelve-oranges + in: + n: 12 + out: 4 + - name: twenty-oranges + in: + n: 20 + out: 5 + - name: thirty-oranges + in: + n: 30 + out: 5 + - name: forty-two-oranges + in: + n: 42 + out: 6 + - name: fifty-oranges + in: + n: 50 + out: 7 + - name: seventy-three-oranges + in: + n: 73 + out: 7 + - name: eighty-one-oranges + in: + n: 81 + out: 5 + - name: ninety-nine-oranges + in: + n: 99 + out: 7 + - name: one-hundred-oranges + in: + n: 100 + out: 8 + - name: one-hundred-one-oranges + in: + n: 101 + out: 9 + - name: power-two-boundary + in: + n: 127 + out: 8 + - name: power-two + in: + n: 128 + out: 8 + - name: before-two-hundred-fifty-six + in: + n: 255 + out: 8 + - name: power-two-two + in: + n: 256 + out: 9 + - name: near-one-thousand + in: + n: 999 + out: 9 + - name: one-thousand + in: + n: 1000 + out: 10 + - name: one-thousand-one + in: + n: 1001 + out: 11 + - name: power-two-large + in: + n: 4096 + out: 13 + - name: near-ten-thousand + in: + n: 9999 + out: 14 + - name: five-digit-value + in: + n: 12345 + out: 15 + - name: near-one-hundred-thousand + in: + n: 99999 + out: 19 + - name: one-hundred-thousand + in: + n: 100000 + out: 19 + - name: near-one-million + in: + n: 999999 + out: 20 + - name: one-million + in: + n: 1000000 + out: 20 + - name: ten-million + in: + n: 10000000 + out: 23 + - name: nine-digit-value + in: + n: 123456789 + out: 28 + - name: near-maximum + in: + n: 1999999999 + out: 32 + - name: maximum-constraint + in: + n: 2000000000 + out: 32 + - name: generated-small + in: + n: + gen: "int" + min: 1 + max: 1000 + judge: + type: "exact" + - name: generated-medium + in: + n: + gen: "int" + min: 1001 + max: 1000000 + judge: + type: "exact" + - name: generated-large + in: + n: + gen: "int" + min: 1000001 + max: 100000000 + judge: + type: "exact" + - name: generated-near-maximum + in: + n: + gen: "int" + min: 1900000000 + max: 2000000000 + judge: + type: "exact" + - name: generated-full-range + in: + n: + gen: "int" + min: 1 + max: 2000000000 + judge: + type: "exact" diff --git a/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.cpp b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.cpp new file mode 100644 index 00000000..abbc6cfa --- /dev/null +++ b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int minDays(int n) { + int ans = 0; + queue q; + q.push(n); + unordered_set seen; + while (!q.empty()) { + int size = q.size(); + for (int i = 0; i < size; ++i) { + int x = q.front(); q.pop(); + if (x == 0) return ans; + seen.insert(x); + if (seen.find(x-1) == seen.end()) q.push(x-1); + if (x % 2 == 0 && seen.find(x/2) == seen.end()) q.push(x/2); + if (x % 3 == 0 && seen.find(x/3) == seen.end()) q.push(x/3); + } + ans++; + } + return ans; + } +}; diff --git a/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.cs b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.cs new file mode 100644 index 00000000..a8b8b74f --- /dev/null +++ b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.cs @@ -0,0 +1,21 @@ +public class Solution { + public int MinDays(int n) { + int ans = 0; + var queue = new Queue(); + queue.Enqueue(n); + var seen = new HashSet(); + while (queue.Count > 0) { + int size = queue.Count; + for (int i = 0; i < size; ++i) { + int x = queue.Dequeue(); + if (x == 0) return ans; + seen.Add(x); + if (!seen.Contains(x-1)) queue.Enqueue(x-1); + if (x % 2 == 0 && !seen.Contains(x/2)) queue.Enqueue(x/2); + if (x % 3 == 0 && !seen.Contains(x/3)) queue.Enqueue(x/3); + } + ans++; + } + return ans; + } +} diff --git a/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.dart b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.dart new file mode 100644 index 00000000..fe5f8d5a --- /dev/null +++ b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.dart @@ -0,0 +1,20 @@ +class Solution { + int minDays(int n) { + int ans = 0; + List queue = [n]; + Set seen = {}; + while (queue.isNotEmpty) { + List newq = []; + for (int x in queue) { + if (x == 0) return ans; + seen.add(x); + if (!seen.contains(x-1)) newq.add(x-1); + if (x % 2 == 0 && !seen.contains(x/2)) newq.add(x~/2); + if (x % 3 == 0 && !seen.contains(x/3)) newq.add(x~/3); + } + ans++; + queue = newq; + } + return ans; + } +} diff --git a/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.go b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.go new file mode 100644 index 00000000..94b9722a --- /dev/null +++ b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.go @@ -0,0 +1,26 @@ +func minDays(n int) int { + ans := 0 + queue := []int{n} + seen := make(map[int]bool) + for len(queue) > 0 { + var newq []int + for _, x := range queue { + if x == 0 { + return ans + } + seen[x] = true + if !seen[x-1] { + newq = append(newq, x-1) + } + if x%2 == 0 && !seen[x/2] { + newq = append(newq, x/2) + } + if x%3 == 0 && !seen[x/3] { + newq = append(newq, x/3) + } + } + ans++ + queue = newq + } + return ans +} diff --git a/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.java b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.java new file mode 100644 index 00000000..20c0f83b --- /dev/null +++ b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.java @@ -0,0 +1,21 @@ +class Solution { + public int minDays(int n) { + int ans = 0; + java.util.Queue queue = new java.util.LinkedList<>(); + queue.offer(n); + java.util.Set seen = new java.util.HashSet<>(); + while (!queue.isEmpty()) { + int size = queue.size(); + for (int i = 0; i < size; i++) { + int x = queue.poll(); + if (x == 0) return ans; + seen.add(x); + if (!seen.contains(x-1)) queue.offer(x-1); + if (x % 2 == 0 && !seen.contains(x/2)) queue.offer(x/2); + if (x % 3 == 0 && !seen.contains(x/3)) queue.offer(x/3); + } + ans++; + } + return ans; + } +} diff --git a/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.kt b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.kt new file mode 100644 index 00000000..b281affc --- /dev/null +++ b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun minDays(n: Int): Int { + var ans = 0 + var queue = mutableListOf(n) + val seen = mutableSetOf() + while (queue.isNotEmpty()) { + val newq = mutableListOf() + for (x in queue) { + if (x == 0) return ans + seen.add(x) + if (x-1 !in seen) newq.add(x-1) + if (x % 2 == 0 && x/2 !in seen) newq.add(x/2) + if (x % 3 == 0 && x/3 !in seen) newq.add(x/3) + } + ans++ + queue = newq + } + return ans + } +} diff --git a/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.py b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.py new file mode 100644 index 00000000..dbae6ab7 --- /dev/null +++ b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.py @@ -0,0 +1,19 @@ +class Solution: + def minDays(self, n: int) -> int: + ans = 0 + queue = [n] + seen = set() + while queue: # bfs + newq = [] + for x in queue: + if x == 0: + return ans + seen.add(x) + if x - 1 not in seen: + newq.append(x - 1) + if x % 2 == 0 and x // 2 not in seen: + newq.append(x // 2) + if x % 3 == 0 and x // 3 not in seen: + newq.append(x // 3) + ans += 1 + queue = newq diff --git a/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.py2 b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.py2 new file mode 100644 index 00000000..b796568b --- /dev/null +++ b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.py2 @@ -0,0 +1,24 @@ +class Solution(object): + def minDays(self, n): + """ + :type n: int + :rtype: int + """ + ans = 0 + queue = [n] + seen = set() + while queue: + newq = [] + for x in queue: + if x == 0: + return ans + seen.add(x) + if x-1 not in seen: + newq.append(x-1) + if x % 2 == 0 and x//2 not in seen: + newq.append(x//2) + if x % 3 == 0 and x//3 not in seen: + newq.append(x//3) + ans += 1 + queue = newq + return ans diff --git a/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.rb b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.rb new file mode 100644 index 00000000..9eeff7e5 --- /dev/null +++ b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.rb @@ -0,0 +1,20 @@ +# @param {Integer} n +# @return {Integer} +def min_days(n) + ans = 0 + queue = [n] + seen = Set.new + while !queue.empty? + newq = [] + queue.each do |x| + return ans if x == 0 + seen.add(x) + newq << (x-1) unless seen.include?(x-1) + newq << (x/2) if x % 2 == 0 && !seen.include?(x/2) + newq << (x/3) if x % 3 == 0 && !seen.include?(x/3) + end + ans += 1 + queue = newq + end + ans +end diff --git a/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.rs b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.rs new file mode 100644 index 00000000..3c9911e0 --- /dev/null +++ b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn min_days(n: i32) -> i32 { + let mut ans = 0; + let mut queue = vec![n]; + let mut seen = std::collections::HashSet::new(); + while !queue.is_empty() { + let mut newq = Vec::new(); + for &x in &queue { + if x == 0 { return ans; } + seen.insert(x); + if !seen.contains(&(x-1)) { newq.push(x-1); } + if x % 2 == 0 && !seen.contains(&(x/2)) { newq.push(x/2); } + if x % 3 == 0 && !seen.contains(&(x/3)) { newq.push(x/3); } + } + ans += 1; + queue = newq; + } + ans + } +} diff --git a/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.swift b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.swift new file mode 100644 index 00000000..e068954a --- /dev/null +++ b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func minDays(_ n: Int) -> Int { + var ans = 0 + var queue = [n] + var seen = Set() + while !queue.isEmpty { + var newq = [Int]() + for x in queue { + if x == 0 { return ans } + seen.insert(x) + if !seen.contains(x-1) { newq.append(x-1) } + if x % 2 == 0 && !seen.contains(x/2) { newq.append(x/2) } + if x % 3 == 0 && !seen.contains(x/3) { newq.append(x/3) } + } + ans += 1 + queue = newq + } + return ans + } +} diff --git a/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.ts b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.ts new file mode 100644 index 00000000..f3051c63 --- /dev/null +++ b/tests/1501-2000/1553. minimum-number-of-days-to-eat-n-oranges/sol.ts @@ -0,0 +1,18 @@ +function minDays(n: number): number { + let ans = 0; + let queue: number[] = [n]; + let seen = new Set(); + while (queue.length > 0) { + let newq: number[] = []; + for (let x of queue) { + if (x === 0) return ans; + seen.add(x); + if (!seen.has(x - 1)) newq.push(x - 1); + if (x % 2 === 0 && !seen.has(x / 2)) newq.push(x / 2); + if (x % 3 === 0 && !seen.has(x / 3)) newq.push(x / 3); + } + ans++; + queue = newq; + } + return ans; +} diff --git a/tests/1501-2000/1556. thousand-separator/manifest.yaml b/tests/1501-2000/1556. thousand-separator/manifest.yaml new file mode 100644 index 00000000..d23b4816 --- /dev/null +++ b/tests/1501-2000/1556. thousand-separator/manifest.yaml @@ -0,0 +1,215 @@ +entry: + id: 1556 + title: "thousand-separator" + params: + n: + type: int + call: + cpp: "Solution().thousandSeparator({n})" + rust: "Solution::thousand_separator({n})" + python3: "Solution().thousandSeparator({n})" + python2: "Solution().thousandSeparator({n})" + ruby: "thousand_separator({n})" + java: "new Solution().thousandSeparator({n})" + csharp: "new Solution().ThousandSeparator({n})" + kotlin: "Solution().thousandSeparator({n})" + go: "thousandSeparator({n})" + dart: "Solution().thousandSeparator({n})" + swift: "Solution().thousandSeparator({n})" + typescript: "thousandSeparator({n})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().thousandSeparator(n, {result})" + checker: | + class Checker: + def thousandSeparator(self, n, result): + if not isinstance(result, str): + return False + return result == format(n, ',').replace(',', '.') + +seed: 1556001 + +tests: + - name: "example_below_thousand" + in: + n: 987 + out: '"987"' + - name: "example_one_separator" + in: + n: 1234 + out: '"1.234"' + - name: "zero" + in: + n: 0 + out: '"0"' + - name: "one" + in: + n: 1 + out: '"1"' + - name: "nine_hundred_ninety_nine" + in: + n: 999 + out: '"999"' + - name: "one_thousand" + in: + n: 1000 + out: '"1.000"' + - name: "one_thousand_one" + in: + n: 1001 + out: '"1.001"' + - name: "ten_thousand" + in: + n: 10000 + out: '"10.000"' + - name: "ten_thousand_one" + in: + n: 10001 + out: '"10.001"' + - name: "ninety_nine_thousand_nine_ninety_nine" + in: + n: 99999 + out: '"99.999"' + - name: "one_hundred_thousand" + in: + n: 100000 + out: '"100.000"' + - name: "one_hundred_thousand_one" + in: + n: 100001 + out: '"100.001"' + - name: "one_million" + in: + n: 1000000 + out: '"1.000.000"' + - name: "one_million_one" + in: + n: 1000001 + out: '"1.000.001"' + - name: "ten_million" + in: + n: 10000000 + out: '"10.000.000"' + - name: "ten_million_one" + in: + n: 10000001 + out: '"10.000.001"' + - name: "ninety_nine_million" + in: + n: 99000000 + out: '"99.000.000"' + - name: "ninety_nine_million_nine" + in: + n: 99000009 + out: '"99.000.009"' + - name: "one_hundred_million" + in: + n: 100000000 + out: '"100.000.000"' + - name: "one_hundred_million_one" + in: + n: 100000001 + out: '"100.000.001"' + - name: "one_billion" + in: + n: 1000000000 + out: '"1.000.000.000"' + - name: "one_billion_one" + in: + n: 1000000001 + out: '"1.000.000.001"' + - name: "two_billion" + in: + n: 2000000000 + out: '"2.000.000.000"' + - name: "max_int" + in: + n: 2147483647 + out: '"2.147.483.647"' + - name: "all_nines_six_digits" + in: + n: 999999 + out: '"999.999"' + - name: "all_nines_seven_digits" + in: + n: 9999999 + out: '"9.999.999"' + - name: "all_nines_eight_digits" + in: + n: 99999999 + out: '"99.999.999"' + - name: "all_nines_nine_digits" + in: + n: 999999999 + out: '"999.999.999"' + - name: "sparse_middle_zero" + in: + n: 1000005 + out: '"1.000.005"' + - name: "sparse_two_groups" + in: + n: 1000000005 + out: '"1.000.000.005"' + - name: "alternating_digits" + in: + n: 101010101 + out: '"101.010.101"' + - name: "ascending_digits" + in: + n: 123456789 + out: '"123.456.789"' + - name: "descending_digits" + in: + n: 987654321 + out: '"987.654.321"' + - name: "mixed_groups" + in: + n: 1203040506 + out: '"1.203.040.506"' + - name: "near_max" + in: + n: 2147483000 + out: '"2.147.483.000"' + - name: "generated_small" + seed: 155601 + in: + n: + gen: "int" + min: 0 + max: 999 + - name: "generated_boundary" + seed: 155602 + in: + n: + gen: "int" + min: 1000 + max: 999999 + - name: "generated_large" + seed: 155603 + in: + n: + gen: "int" + min: 1000000 + max: 999999999 + - name: "generated_near_max" + seed: 155604 + in: + n: + gen: "int" + min: 2000000000 + max: 2147483647 + - name: "generated_full_range" + seed: 155605 + in: + n: + gen: "int" + min: 0 + max: 2147483647 diff --git a/tests/1501-2000/1556. thousand-separator/sol.cpp b/tests/1501-2000/1556. thousand-separator/sol.cpp new file mode 100644 index 00000000..c9f7b703 --- /dev/null +++ b/tests/1501-2000/1556. thousand-separator/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + string thousandSeparator(int n) { + string s = to_string(n); + if (s.length() <= 3) return s; + string result = ""; + int count = 0; + for (int i = s.length() - 1; i >= 0; i--) { + result += s[i]; + count++; + if (count % 3 == 0 && i > 0) { + result += '.'; + } + } + reverse(result.begin(), result.end()); + return result; + } +}; diff --git a/tests/1501-2000/1556. thousand-separator/sol.cs b/tests/1501-2000/1556. thousand-separator/sol.cs new file mode 100644 index 00000000..df9487b0 --- /dev/null +++ b/tests/1501-2000/1556. thousand-separator/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public string ThousandSeparator(int n) { + string s = n.ToString(); + if (s.Length <= 3) return s; + var sb = new System.Text.StringBuilder(); + int count = 0; + for (int i = s.Length - 1; i >= 0; i--) { + sb.Append(s[i]); + count++; + if (count % 3 == 0 && i > 0) { + sb.Append('.'); + } + } + char[] arr = sb.ToString().ToCharArray(); + Array.Reverse(arr); + return new string(arr); + } +} diff --git a/tests/1501-2000/1556. thousand-separator/sol.dart b/tests/1501-2000/1556. thousand-separator/sol.dart new file mode 100644 index 00000000..f5e49cb8 --- /dev/null +++ b/tests/1501-2000/1556. thousand-separator/sol.dart @@ -0,0 +1,16 @@ +class Solution { + String thousandSeparator(int n) { + String s = n.toString(); + if (s.length <= 3) return s; + StringBuffer sb = StringBuffer(); + int count = 0; + for (int i = s.length - 1; i >= 0; i--) { + sb.write(s[i]); + count++; + if (count % 3 == 0 && i > 0) { + sb.write('.'); + } + } + return sb.toString().split('').reversed.join(); + } +} diff --git a/tests/1501-2000/1556. thousand-separator/sol.go b/tests/1501-2000/1556. thousand-separator/sol.go new file mode 100644 index 00000000..be398f98 --- /dev/null +++ b/tests/1501-2000/1556. thousand-separator/sol.go @@ -0,0 +1,20 @@ +func thousandSeparator(n int) string { + s := fmt.Sprintf("%d", n) + if len(s) <= 3 { + return s + } + result := make([]byte, 0) + count := 0 + for i := len(s) - 1; i >= 0; i-- { + result = append(result, s[i]) + count++ + if count%3 == 0 && i > 0 { + result = append(result, '.') + } + } + // reverse result + for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 { + result[i], result[j] = result[j], result[i] + } + return string(result) +} diff --git a/tests/1501-2000/1556. thousand-separator/sol.java b/tests/1501-2000/1556. thousand-separator/sol.java new file mode 100644 index 00000000..e9b99355 --- /dev/null +++ b/tests/1501-2000/1556. thousand-separator/sol.java @@ -0,0 +1,16 @@ +class Solution { + public String thousandSeparator(int n) { + String s = String.valueOf(n); + if (s.length() <= 3) return s; + StringBuilder sb = new StringBuilder(); + int count = 0; + for (int i = s.length() - 1; i >= 0; i--) { + sb.append(s.charAt(i)); + count++; + if (count % 3 == 0 && i > 0) { + sb.append('.'); + } + } + return sb.reverse().toString(); + } +} diff --git a/tests/1501-2000/1556. thousand-separator/sol.kt b/tests/1501-2000/1556. thousand-separator/sol.kt new file mode 100644 index 00000000..47710aec --- /dev/null +++ b/tests/1501-2000/1556. thousand-separator/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun thousandSeparator(n: Int): String { + val s = n.toString() + if (s.length <= 3) return s + val sb = StringBuilder() + var count = 0 + for (i in s.length - 1 downTo 0) { + sb.append(s[i]) + count++ + if (count % 3 == 0 && i > 0) { + sb.append('.') + } + } + return sb.reverse().toString() + } +} diff --git a/tests/1501-2000/1556. thousand-separator/sol.py b/tests/1501-2000/1556. thousand-separator/sol.py new file mode 100644 index 00000000..37c66196 --- /dev/null +++ b/tests/1501-2000/1556. thousand-separator/sol.py @@ -0,0 +1,6 @@ +class Solution: + def thousandSeparator(self, n: int) -> str: + if n < 1000: + return str(n) + + return f"{n:,}".replace(",", ".") diff --git a/tests/1501-2000/1556. thousand-separator/sol.py2 b/tests/1501-2000/1556. thousand-separator/sol.py2 new file mode 100644 index 00000000..8485fed2 --- /dev/null +++ b/tests/1501-2000/1556. thousand-separator/sol.py2 @@ -0,0 +1,17 @@ +class Solution(object): + def thousandSeparator(self, n): + """ + :type n: int + :rtype: str + """ + s = str(n) + if len(s) <= 3: + return s + result = [] + count = 0 + for ch in reversed(s): + result.append(ch) + count += 1 + if count % 3 == 0 and count < len(s): + result.append('.') + return ''.join(reversed(result)) diff --git a/tests/1501-2000/1556. thousand-separator/sol.rb b/tests/1501-2000/1556. thousand-separator/sol.rb new file mode 100644 index 00000000..c674650c --- /dev/null +++ b/tests/1501-2000/1556. thousand-separator/sol.rb @@ -0,0 +1,16 @@ +# @param {Integer} n +# @return {String} +def thousand_separator(n) + s = n.to_s + return s if s.length <= 3 + result = [] + count = 0 + s.reverse.each_char do |ch| + result << ch + count += 1 + if count % 3 == 0 && count < s.length + result << '.' + end + end + result.reverse.join +end diff --git a/tests/1501-2000/1556. thousand-separator/sol.rs b/tests/1501-2000/1556. thousand-separator/sol.rs new file mode 100644 index 00000000..00f3f94c --- /dev/null +++ b/tests/1501-2000/1556. thousand-separator/sol.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn thousand_separator(n: i32) -> String { + let s = n.to_string(); + if s.len() <= 3 { + return s; + } + let mut result = String::new(); + let mut count = 0; + for ch in s.chars().rev() { + result.push(ch); + count += 1; + if count % 3 == 0 && count < s.len() { + result.push('.'); + } + } + result.chars().rev().collect() + } +} diff --git a/tests/1501-2000/1556. thousand-separator/sol.swift b/tests/1501-2000/1556. thousand-separator/sol.swift new file mode 100644 index 00000000..0637b66c --- /dev/null +++ b/tests/1501-2000/1556. thousand-separator/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func thousandSeparator(_ n: Int) -> String { + let s = String(n) + if s.count <= 3 { return s } + var result = "" + var count = 0 + for ch in s.reversed() { + result.append(ch) + count += 1 + if count % 3 == 0 && count < s.count { + result.append(".") + } + } + return String(result.reversed()) + } +} diff --git a/tests/1501-2000/1556. thousand-separator/sol.ts b/tests/1501-2000/1556. thousand-separator/sol.ts new file mode 100644 index 00000000..896bfa19 --- /dev/null +++ b/tests/1501-2000/1556. thousand-separator/sol.ts @@ -0,0 +1,14 @@ +function thousandSeparator(n: number): string { + const s = n.toString(); + if (s.length <= 3) return s; + let result = ""; + let count = 0; + for (let i = s.length - 1; i >= 0; i--) { + result += s[i]; + count++; + if (count % 3 === 0 && i > 0) { + result += "."; + } + } + return result.split("").reverse().join(""); +} diff --git a/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/manifest.yaml b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/manifest.yaml new file mode 100644 index 00000000..5a9bac01 --- /dev/null +++ b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/manifest.yaml @@ -0,0 +1,611 @@ +entry: + id: 1557 + title: minimum-number-of-vertices-to-reach-all-nodes + params: + n: + type: int + edges: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().findSmallestSetOfVertices({n}, {edges})" + rust: "Solution::find_smallest_set_of_vertices({n}, {edges})" + python3: "Solution().findSmallestSetOfVertices({n}, {edges})" + python2: "Solution().findSmallestSetOfVertices({n}, {edges})" + ruby: "find_smallest_set_of_vertices({n}, {edges})" + java: "new Solution().findSmallestSetOfVertices({n}, java.util.Arrays.stream({edges}).map(a -> java.util.Arrays.stream(a).boxed().collect(java.util.stream.Collectors.toList())).collect(java.util.stream.Collectors.toList()))" + csharp: "new Solution().FindSmallestSetOfVertices({n}, {edges})" + kotlin: "Solution().findSmallestSetOfVertices({n}, {edges}.map { it.toList() })" + go: "findSmallestSetOfVertices({n}, {edges})" + dart: "Solution().findSmallestSetOfVertices({n}, {edges})" + swift: "Solution().findSmallestSetOfVertices({n}, {edges})" + typescript: "findSmallestSetOfVertices({n}, {edges})" + +judge: + type: exact + +limits: + time_ms: 2000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().check(n, edges, {result})" + checker: | + class Checker: + def check(self, n, edges, result): + if not isinstance(result, list): + return False + expected = set(range(n)) + incoming = set() + outgoing = [[] for _ in range(n)] + for edge in edges: + if not isinstance(edge, list) or len(edge) != 2: + return False + u, v = edge + if not isinstance(u, int) or not isinstance(v, int) or not (0 <= u < n and 0 <= v < n): + return False + incoming.add(v) + outgoing[u].append(v) + expected -= incoming + if any(not isinstance(node, int) or isinstance(node, bool) or not (0 <= node < n) for node in result): + return False + if len(result) != len(set(result)) or set(result) != expected: + return False + reached = set(result) + stack = list(result) + while stack: + u = stack.pop() + for v in outgoing[u]: + if v not in reached: + reached.add(v) + stack.append(v) + return reached == set(range(n)) + +seed: 1557 + +tests: + - name: example-one + in: + n: 6 + edges: + - [0, 1] + - [0, 2] + - [2, 5] + - [3, 4] + - [4, 2] + out: [0, 3] + - name: example-two + in: + n: 5 + edges: + - [0, 1] + - [2, 1] + - [3, 1] + - [1, 4] + - [2, 4] + out: [0, 2, 3] + - name: three-chain + in: + n: 3 + edges: + - [0, 1] + - [1, 2] + out: [0] + - name: four-chain + in: + n: 4 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + out: [0] + - name: all-sources + in: + n: 5 + edges: + - [0, 1] + - [2, 1] + - [3, 4] + out: [0, 2, 3] + - name: star-from-zero + in: + n: 7 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + out: [0] + - name: star-to-six + in: + n: 7 + edges: + - [0, 6] + - [1, 6] + - [2, 6] + - [3, 6] + - [4, 6] + - [5, 6] + out: [0, 1, 2, 3, 4, 5] + - name: two-disjoint-chains + in: + n: 8 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [4, 5] + - [5, 6] + - [6, 7] + out: [0, 4] + - name: diamond + in: + n: 5 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [2, 3] + - [3, 4] + out: [0] + - name: three-diamonds + in: + n: 8 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [2, 3] + - [3, 4] + - [3, 5] + - [4, 6] + - [5, 7] + out: [0] + - name: isolated-last + in: + n: 6 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + out: [0, 5] + - name: isolated-middle + in: + n: 6 + edges: + - [0, 1] + - [1, 2] + - [3, 4] + out: [0, 3, 5] + - name: many-merges + in: + n: 9 + edges: + - [0, 4] + - [1, 4] + - [2, 5] + - [3, 5] + - [4, 6] + - [5, 6] + - [6, 7] + - [7, 8] + out: [0, 1, 2, 3] + - name: long-branch-and-short + in: + n: 9 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [6, 7] + - [7, 5] + - [5, 8] + out: [0, 6] + - name: complete-forward-six + in: + n: 6 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [2, 3] + - [2, 4] + - [2, 5] + - [3, 4] + - [3, 5] + - [4, 5] + out: [0] + - name: alternating-sources + in: + n: 10 + edges: + - [0, 5] + - [1, 5] + - [2, 6] + - [3, 6] + - [4, 7] + - [5, 8] + - [6, 8] + - [7, 9] + out: [0, 1, 2, 3, 4] + - name: four-components + in: + n: 12 + edges: + - [0, 1] + - [1, 2] + - [3, 4] + - [4, 5] + - [6, 7] + - [7, 8] + - [9, 10] + - [10, 11] + out: [0, 3, 6, 9] + - name: source-with-multiple-levels + in: + n: 10 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [2, 4] + - [3, 5] + - [4, 5] + - [5, 6] + - [5, 7] + - [6, 8] + - [7, 9] + out: [0] + - name: sources-feed-one + in: + n: 8 + edges: + - [0, 7] + - [1, 7] + - [2, 7] + - [3, 7] + - [4, 7] + - [5, 7] + - [6, 7] + out: [0, 1, 2, 3, 4, 5, 6] + - name: sparse-with-tail + in: + n: 11 + edges: + - [0, 2] + - [2, 4] + - [4, 6] + - [1, 3] + - [3, 5] + - [5, 7] + - [8, 9] + - [9, 10] + out: [0, 1, 8] + - name: nested-merges + in: + n: 10 + edges: + - [0, 3] + - [1, 3] + - [2, 4] + - [3, 5] + - [4, 5] + - [5, 6] + - [5, 7] + - [6, 8] + - [7, 9] + out: [0, 1, 2] + - name: twelve-single-source + in: + n: 12 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [2, 4] + - [3, 5] + - [4, 6] + - [5, 7] + - [6, 8] + - [7, 9] + - [8, 10] + - [9, 11] + out: [0] + - name: twelve-independent-sources + in: + n: 12 + edges: + - [0, 11] + - [1, 11] + - [2, 11] + - [3, 11] + - [4, 11] + - [5, 11] + - [6, 11] + - [7, 11] + - [8, 11] + - [9, 11] + - [10, 11] + out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - name: mixed-branches + in: + n: 14 + edges: + - [0, 2] + - [0, 3] + - [2, 5] + - [3, 5] + - [1, 4] + - [4, 6] + - [5, 7] + - [6, 7] + - [7, 8] + - [8, 9] + - [10, 11] + - [11, 12] + - [12, 13] + out: [0, 1, 10] + - name: six-components + in: + n: 18 + edges: + - [0, 1] + - [1, 2] + - [3, 4] + - [4, 5] + - [6, 7] + - [7, 8] + - [9, 10] + - [10, 11] + - [12, 13] + - [13, 14] + - [15, 16] + - [16, 17] + out: [0, 3, 6, 9, 12, 15] + - name: broad-dag + in: + n: 15 + edges: + - [0, 3] + - [0, 4] + - [1, 4] + - [1, 5] + - [2, 5] + - [2, 6] + - [3, 7] + - [4, 7] + - [4, 8] + - [5, 8] + - [6, 9] + - [7, 10] + - [8, 10] + - [9, 11] + - [10, 12] + - [11, 13] + - [12, 14] + out: [0, 1, 2] + - name: sixteen-chain + in: + n: 16 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [11, 12] + - [12, 13] + - [13, 14] + - [14, 15] + out: [0] + - name: sixteen-sources + in: + n: 16 + edges: + - [0, 15] + - [1, 15] + - [2, 15] + - [3, 15] + - [4, 15] + - [5, 15] + - [6, 15] + - [7, 15] + - [8, 15] + - [9, 15] + - [10, 15] + - [11, 15] + - [12, 15] + - [13, 15] + - [14, 15] + out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] + - name: sparse-large-labels + in: + n: 20 + edges: + - [0, 19] + - [1, 18] + - [2, 17] + - [3, 16] + - [4, 15] + - [5, 14] + - [6, 13] + - [7, 12] + - [8, 11] + - [9, 10] + out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + - name: four-source-dag + in: + n: 20 + edges: + - [0, 4] + - [1, 5] + - [2, 6] + - [3, 7] + - [4, 8] + - [5, 8] + - [6, 9] + - [7, 9] + - [8, 10] + - [9, 10] + - [10, 11] + - [11, 12] + - [12, 13] + - [13, 14] + - [14, 15] + - [15, 16] + - [16, 17] + - [17, 18] + - [18, 19] + out: [0, 1, 2, 3] + - name: twenty-chain + in: + n: 20 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [11, 12] + - [12, 13] + - [13, 14] + - [14, 15] + - [15, 16] + - [16, 17] + - [17, 18] + - [18, 19] + out: [0] + - name: twenty-five-components + in: + n: 25 + edges: + - [0, 1] + - [2, 3] + - [4, 5] + - [6, 7] + - [8, 9] + - [10, 11] + - [12, 13] + - [14, 15] + - [16, 17] + - [18, 19] + - [20, 21] + - [22, 23] + out: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24] + - name: thirty-layered + in: + n: 30 + edges: + - [0, 10] + - [1, 11] + - [2, 12] + - [3, 13] + - [4, 14] + - [5, 15] + - [6, 16] + - [7, 17] + - [8, 18] + - [9, 19] + - [10, 20] + - [11, 21] + - [12, 22] + - [13, 23] + - [14, 24] + - [15, 25] + - [16, 26] + - [17, 27] + - [18, 28] + - [19, 29] + out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + - name: wide-two-level + in: + n: 32 + edges: + - [0, 16] + - [1, 17] + - [2, 18] + - [3, 19] + - [4, 20] + - [5, 21] + - [6, 22] + - [7, 23] + - [8, 24] + - [9, 25] + - [10, 26] + - [11, 27] + - [12, 28] + - [13, 29] + - [14, 30] + - [15, 31] + out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + - name: forty-chain + in: + n: 40 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [11, 12] + - [12, 13] + - [13, 14] + - [14, 15] + - [15, 16] + - [16, 17] + - [17, 18] + - [18, 19] + - [19, 20] + - [20, 21] + - [21, 22] + - [22, 23] + - [23, 24] + - [24, 25] + - [25, 26] + - [26, 27] + - [27, 28] + - [28, 29] + - [29, 30] + - [30, 31] + - [31, 32] + - [32, 33] + - [33, 34] + - [34, 35] + - [35, 36] + - [36, 37] + - [37, 38] + - [38, 39] + out: [0] diff --git a/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.cpp b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.cpp new file mode 100644 index 00000000..878e0079 --- /dev/null +++ b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector findSmallestSetOfVertices(int n, vector>& edges) { + vector hasIncoming(n, false); + for (const auto& edge : edges) { + hasIncoming[edge[1]] = true; + } + vector result; + for (int i = 0; i < n; i++) { + if (!hasIncoming[i]) { + result.push_back(i); + } + } + return result; + } +}; diff --git a/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.cs b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.cs new file mode 100644 index 00000000..9aff66e8 --- /dev/null +++ b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public IList FindSmallestSetOfVertices(int n, IList> edges) { + bool[] hasIncoming = new bool[n]; + foreach (var edge in edges) { + hasIncoming[edge[1]] = true; + } + var result = new List(); + for (int i = 0; i < n; i++) { + if (!hasIncoming[i]) { + result.Add(i); + } + } + return result; + } +} diff --git a/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.dart b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.dart new file mode 100644 index 00000000..8cc8c33e --- /dev/null +++ b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.dart @@ -0,0 +1,15 @@ +class Solution { + List findSmallestSetOfVertices(int n, List> edges) { + List hasIncoming = List.filled(n, false); + for (var edge in edges) { + hasIncoming[edge[1]] = true; + } + List result = []; + for (int i = 0; i < n; i++) { + if (!hasIncoming[i]) { + result.add(i); + } + } + return result; + } +} diff --git a/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.go b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.go new file mode 100644 index 00000000..1e944e93 --- /dev/null +++ b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.go @@ -0,0 +1,13 @@ +func findSmallestSetOfVertices(n int, edges [][]int) []int { + hasIncoming := make([]bool, n) + for _, edge := range edges { + hasIncoming[edge[1]] = true + } + var result []int + for i := 0; i < n; i++ { + if !hasIncoming[i] { + result = append(result, i) + } + } + return result +} diff --git a/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.java b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.java new file mode 100644 index 00000000..499e439a --- /dev/null +++ b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.java @@ -0,0 +1,15 @@ +class Solution { + public List findSmallestSetOfVertices(int n, List> edges) { + boolean[] hasIncoming = new boolean[n]; + for (List edge : edges) { + hasIncoming[edge.get(1)] = true; + } + List result = new ArrayList<>(); + for (int i = 0; i < n; i++) { + if (!hasIncoming[i]) { + result.add(i); + } + } + return result; + } +} diff --git a/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.kt b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.kt new file mode 100644 index 00000000..ef14a8ed --- /dev/null +++ b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.kt @@ -0,0 +1,9 @@ +class Solution { + fun findSmallestSetOfVertices(n: Int, edges: List>): List { + val hasIncoming = BooleanArray(n) + for (edge in edges) { + hasIncoming[edge[1]] = true + } + return (0 until n).filter { !hasIncoming[it] } + } +} diff --git a/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.py b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.py new file mode 100644 index 00000000..73285cae --- /dev/null +++ b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.py @@ -0,0 +1,6 @@ +class Solution: + def findSmallestSetOfVertices(self, n, edges): + has_incoming = [False] * n + for _, destination in edges: + has_incoming[destination] = True + return [i for i in range(n) if not has_incoming[i]] diff --git a/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.py2 b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.py2 new file mode 100644 index 00000000..09e2cd6f --- /dev/null +++ b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def findSmallestSetOfVertices(self, n, edges): + """ + :type n: int + :type edges: List[List[int]] + :rtype: List[int] + """ + has_incoming = set() + for _, to in edges: + has_incoming.add(to) + return [i for i in range(n) if i not in has_incoming] diff --git a/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.rb b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.rb new file mode 100644 index 00000000..a1a8a23e --- /dev/null +++ b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.rb @@ -0,0 +1,10 @@ +# @param {Integer} n +# @param {Integer[][]} edges +# @return {Integer[]} +def find_smallest_set_of_vertices(n, edges) + has_incoming = {} + edges.each do |edge| + has_incoming[edge[1]] = true + end + (0...n).select { |i| !has_incoming[i] } +end diff --git a/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.rs b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.rs new file mode 100644 index 00000000..6851af55 --- /dev/null +++ b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.rs @@ -0,0 +1,9 @@ +impl Solution { + pub fn find_smallest_set_of_vertices(n: i32, edges: Vec>) -> Vec { + let mut has_incoming = vec![false; n as usize]; + for edge in &edges { + has_incoming[edge[1] as usize] = true; + } + (0..n).filter(|&i| !has_incoming[i as usize]).collect() + } +} diff --git a/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.swift b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.swift new file mode 100644 index 00000000..89c47f1c --- /dev/null +++ b/tests/1501-2000/1557. minimum-number-of-vertices-to-reach-all-nodes/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func findSmallestSetOfVertices(_ n: Int, _ edges: [[Int]]) -> [Int] { + var hasIncoming = [Bool](repeating: false, count: n) + for edge in edges { + hasIncoming[edge[1]] = true + } + var result: [Int] = [] + for i in 0..& nums) { + int sum_bits = 0; + int max_num = 0; + for (int num : nums) { + sum_bits += __builtin_popcount(num); + if (num > max_num) { + max_num = num; + } + } + int doubling = max_num > 0 ? 32 - __builtin_clz(max_num) - 1 : 0; + return sum_bits + doubling; + } +}; diff --git a/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.cs b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.cs new file mode 100644 index 00000000..16aa1d31 --- /dev/null +++ b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.cs @@ -0,0 +1,14 @@ +public class Solution { + public int MinOperations(int[] nums) { + int sumBits = 0; + int maxNum = 0; + foreach (int num in nums) { + sumBits += Convert.ToString(num, 2).Replace("0", "").Length; + if (num > maxNum) { + maxNum = num; + } + } + int doubling = maxNum > 0 ? Convert.ToString(maxNum, 2).Length - 1 : 0; + return sumBits + doubling; + } +} diff --git a/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.dart b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.dart new file mode 100644 index 00000000..aa7ef01f --- /dev/null +++ b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.dart @@ -0,0 +1,14 @@ +class Solution { + int minOperations(List nums) { + int sumBits = 0; + int maxNum = 0; + for (int num in nums) { + sumBits += num.toRadixString(2).replaceAll('0', '').length; + if (num > maxNum) { + maxNum = num; + } + } + int doubling = maxNum > 0 ? maxNum.toRadixString(2).length - 1 : 0; + return sumBits + doubling; + } +} diff --git a/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.go b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.go new file mode 100644 index 00000000..0007d649 --- /dev/null +++ b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.go @@ -0,0 +1,15 @@ +func minOperations(nums []int) int { + sumBits := 0 + maxNum := 0 + for _, num := range nums { + sumBits += bits.OnesCount(uint(num)) + if num > maxNum { + maxNum = num + } + } + doubling := 0 + if maxNum > 0 { + doubling = bits.Len(uint(maxNum)) - 1 + } + return sumBits + doubling +} diff --git a/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.java b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.java new file mode 100644 index 00000000..86ad82db --- /dev/null +++ b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.java @@ -0,0 +1,14 @@ +class Solution { + public int minOperations(int[] nums) { + int sumBits = 0; + int maxNum = 0; + for (int num : nums) { + sumBits += Integer.bitCount(num); + if (num > maxNum) { + maxNum = num; + } + } + int doubling = maxNum > 0 ? Integer.toBinaryString(maxNum).length() - 1 : 0; + return sumBits + doubling; + } +} diff --git a/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.kt b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.kt new file mode 100644 index 00000000..58e2b4d9 --- /dev/null +++ b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun minOperations(nums: IntArray): Int { + var sumBits = 0 + var maxNum = 0 + for (num in nums) { + sumBits += Integer.bitCount(num) + if (num > maxNum) { + maxNum = num + } + } + val doubling = if (maxNum > 0) Integer.toBinaryString(maxNum).length - 1 else 0 + return sumBits + doubling + } +} diff --git a/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.py b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.py new file mode 100644 index 00000000..eee61fc7 --- /dev/null +++ b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.py @@ -0,0 +1,14 @@ +class Solution(object): + def minOperations(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + sum_bits = 0 + max_num = 0 + for num in nums: + sum_bits += bin(num).count("1") + if num > max_num: + max_num = num + doubling = max_num.bit_length() - 1 if max_num > 0 else 0 + return sum_bits + doubling diff --git a/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.py2 b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.py2 new file mode 100644 index 00000000..1d1d49f9 --- /dev/null +++ b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def minOperations(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + sum_bits = 0 + max_num = 0 + for num in nums: + sum_bits += bin(num).count('1') + if num > max_num: + max_num = num + doubling = max_num.bit_length() - 1 if max_num > 0 else 0 + return sum_bits + doubling diff --git a/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.rb b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.rb new file mode 100644 index 00000000..382c55e6 --- /dev/null +++ b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[]} nums +# @return {Integer} +def min_operations(nums) + sum_bits = 0 + max_num = 0 + nums.each do |num| + sum_bits += num.to_s(2).count('1') + if num > max_num + max_num = num + end + end + doubling = max_num > 0 ? max_num.bit_length - 1 : 0 + sum_bits + doubling +end diff --git a/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.rs b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.rs new file mode 100644 index 00000000..351e0efd --- /dev/null +++ b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn min_operations(nums: Vec) -> i32 { + let mut sum_bits = 0; + let mut max_num = 0; + for &num in &nums { + sum_bits += num.count_ones() as i32; + if num > max_num { + max_num = num; + } + } + let doubling: i32 = if max_num > 0 { + ((32 - max_num.leading_zeros()) - 1) as i32 + } else { 0 }; + sum_bits + doubling + } +} diff --git a/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.swift b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.swift new file mode 100644 index 00000000..40c6a09e --- /dev/null +++ b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.swift @@ -0,0 +1,14 @@ +class Solution { + func minOperations(_ nums: [Int]) -> Int { + var sumBits = 0 + var maxNum = 0 + for num in nums { + sumBits += num.nonzeroBitCount + if num > maxNum { + maxNum = num + } + } + let doubling = maxNum > 0 ? String(maxNum, radix: 2).count - 1 : 0 + return sumBits + doubling + } +} diff --git a/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.ts b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.ts new file mode 100644 index 00000000..51ac0493 --- /dev/null +++ b/tests/1501-2000/1558. minimum-numbers-of-function-calls-to-make-target-array/sol.ts @@ -0,0 +1,12 @@ +function minOperations(nums: number[]): number { + let sumBits = 0; + let maxNum = 0; + for (const num of nums) { + sumBits += num.toString(2).split("1").length - 1; + if (num > maxNum) { + maxNum = num; + } + } + const doubling = maxNum > 0 ? maxNum.toString(2).length - 1 : 0; + return sumBits + doubling; +} diff --git a/tests/1501-2000/1559. detect-cycles-in-2d-grid/manifest.yaml b/tests/1501-2000/1559. detect-cycles-in-2d-grid/manifest.yaml new file mode 100644 index 00000000..56d30dee --- /dev/null +++ b/tests/1501-2000/1559. detect-cycles-in-2d-grid/manifest.yaml @@ -0,0 +1,373 @@ +entry: + id: 1559 + title: "detect-cycles-in-2d-grid" + params: + grid: + type: array + items: + type: array + items: + type: char + call: + cpp: "Solution().containsCycle({grid})" + rust: "Solution::contains_cycle({grid})" + python3: "Solution().containsCycle({grid})" + python2: "Solution().containsCycle({grid})" + ruby: "contains_cycle({grid})" + java: "new Solution().containsCycle({grid})" + csharp: "new Solution().ContainsCycle({grid})" + kotlin: "Solution().containsCycle({grid})" + go: "containsCycle({grid})" + dart: "Solution().containsCycle({grid})" + swift: "Solution().containsCycle({grid})" + typescript: "containsCycle({grid})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().containsCycle(grid, {result})" + checker: | + from collections import deque + class Checker: + def containsCycle(self, grid, result): + if not isinstance(result, bool): + return False + rows = len(grid) + cols = len(grid[0]) if rows else 0 + seen = [[False] * cols for _ in range(rows)] + for sr in range(rows): + for sc in range(cols): + if seen[sr][sc]: + continue + seen[sr][sc] = True + queue = deque([(sr, sc, -1, -1)]) + while queue: + r, c, pr, pc = queue.popleft() + for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): + nr, nc = r + dr, c + dc + if nr < 0 or nr >= rows or nc < 0 or nc >= cols: + continue + if grid[nr][nc] != grid[r][c] or (nr == pr and nc == pc): + continue + if seen[nr][nc]: + return result is True + seen[nr][nc] = True + queue.append((nr, nc, r, c)) + return result is False + +seed: 15591559 + +tests: + - name: example-one + in: + grid: + - ["a", "a", "a", "a"] + - ["a", "b", "b", "a"] + - ["a", "b", "b", "a"] + - ["a", "a", "a", "a"] + out: true + - name: example-two + in: + grid: + - ["c", "c", "c", "a"] + - ["c", "d", "c", "c"] + - ["c", "c", "e", "c"] + - ["f", "c", "c", "c"] + out: true + - name: example-three + in: + grid: + - ["a", "b", "b"] + - ["b", "z", "b"] + - ["b", "b", "a"] + out: false + - name: one-cell + in: + grid: + - ["a"] + out: false + - name: one-row-two + in: + grid: + - ["a", "a"] + out: false + - name: one-row-four + in: + grid: + - ["a", "a", "a", "a"] + out: false + - name: one-column-four + in: + grid: + - ["b"] + - ["b"] + - ["b"] + - ["b"] + out: false + - name: two-by-two-cycle + in: + grid: + - ["a", "a"] + - ["a", "a"] + out: true + - name: two-by-three-cycle + in: + grid: + - ["a", "a", "a"] + - ["a", "a", "a"] + out: true + - name: checkerboard + in: + grid: + - ["a", "b", "a", "b"] + - ["b", "a", "b", "a"] + - ["a", "b", "a", "b"] + out: false + - name: isolated-center + in: + grid: + - ["a", "b", "a"] + - ["b", "a", "b"] + - ["a", "b", "a"] + out: false + - name: ring-around-center + in: + grid: + - ["a", "a", "a"] + - ["a", "b", "a"] + - ["a", "a", "a"] + out: true + - name: hollow-two-by-four + in: + grid: + - ["a", "a", "a", "a"] + - ["a", "b", "b", "a"] + out: false + - name: separated-pairs + in: + grid: + - ["a", "a", "b", "b"] + - ["c", "c", "d", "d"] + - ["e", "e", "f", "f"] + out: false + - name: horizontal-loop + in: + grid: + - ["x", "x", "x"] + - ["x", "y", "x"] + - ["x", "x", "x"] + out: true + - name: narrow-corner + in: + grid: + - ["a", "a", "b"] + - ["a", "b", "b"] + - ["c", "c", "b"] + out: false + - name: five-by-five-border + in: + grid: + - ["a", "a", "a", "a", "a"] + - ["a", "b", "b", "b", "a"] + - ["a", "b", "c", "b", "a"] + - ["a", "b", "b", "b", "a"] + - ["a", "a", "a", "a", "a"] + out: true + - name: five-by-five-diagonal + in: + grid: + - ["a", "b", "c", "d", "e"] + - ["b", "c", "d", "e", "a"] + - ["c", "d", "e", "a", "b"] + - ["d", "e", "a", "b", "c"] + - ["e", "a", "b", "c", "d"] + out: false + - name: large-uniform-three + in: + grid: + - ["z", "z", "z"] + - ["z", "z", "z"] + - ["z", "z", "z"] + out: true + - name: mixed-four-by-four + in: + grid: + - ["a", "b", "c", "d"] + - ["a", "b", "c", "d"] + - ["e", "f", "g", "h"] + - ["e", "f", "g", "h"] + out: false + - name: cycle-in-left-block + in: + grid: + - ["a", "a", "b", "c"] + - ["a", "a", "d", "e"] + - ["f", "g", "h", "i"] + - ["j", "k", "l", "m"] + out: true + - name: cycle-in-right-block + in: + grid: + - ["a", "b", "c", "c"] + - ["d", "e", "c", "c"] + - ["f", "g", "h", "i"] + out: true + - name: no-cycle-two-by-five + in: + grid: + - ["a", "b", "c", "d", "e"] + - ["f", "g", "h", "i", "j"] + out: false + - name: all-b-three-by-four + in: + grid: + - ["b", "b", "b", "b"] + - ["b", "b", "b", "b"] + - ["b", "b", "b", "b"] + out: true + - name: serpentine-no-cycle + in: + grid: + - ["a", "a", "b", "b"] + - ["c", "c", "d", "d"] + - ["e", "e", "f", "f"] + - ["g", "g", "h", "h"] + out: false + - name: two-colour-stripes + in: + grid: + - ["a", "a", "a", "a", "a"] + - ["b", "b", "b", "b", "b"] + - ["a", "a", "a", "a", "a"] + - ["b", "b", "b", "b", "b"] + out: false + - name: single-cycle-island + in: + grid: + - ["a", "b", "c", "d", "e"] + - ["f", "g", "g", "h", "i"] + - ["j", "g", "g", "k", "l"] + - ["m", "n", "o", "p", "q"] + out: true + - name: touching-different-regions + in: + grid: + - ["a", "a", "b", "b"] + - ["a", "c", "c", "b"] + - ["d", "c", "c", "e"] + - ["d", "d", "e", "e"] + out: true + - name: no-cycle-lowercase + in: + grid: + - ["a", "b", "c", "d", "e", "f"] + - ["g", "h", "i", "j", "k", "l"] + - ["m", "n", "o", "p", "q", "r"] + out: false + - name: repeated-l-shaped + in: + grid: + - ["a", "a", "b", "b"] + - ["a", "c", "c", "b"] + - ["a", "c", "c", "b"] + - ["d", "d", "e", "e"] + out: true + - name: full-six-by-two + in: + grid: + - ["q", "q"] + - ["q", "q"] + - ["q", "q"] + - ["q", "q"] + - ["q", "q"] + - ["q", "q"] + out: true + - name: alternating-rows + in: + grid: + - ["a", "b", "a", "b", "a"] + - ["b", "a", "b", "a", "b"] + - ["a", "b", "a", "b", "a"] + - ["b", "a", "b", "a", "b"] + out: false + - name: cycle-at-edge + in: + grid: + - ["r", "r", "r", "s"] + - ["r", "t", "r", "s"] + - ["r", "r", "r", "s"] + - ["u", "v", "w", "x"] + out: true + - name: isolated-duplicates + in: + grid: + - ["a", "b", "a", "b"] + - ["c", "d", "c", "d"] + - ["a", "b", "a", "b"] + out: false + - name: generated-small + in: + grid: + gen: "array" + len: 2 + of: + gen: "array" + len: 2 + of: + gen: "char" + variety: ["a", "b", "c"] + elemType: "string" + - name: generated-medium + in: + grid: + gen: "array" + len: 5 + of: + gen: "array" + len: 7 + of: + gen: "char" + variety: ["a", "b", "c", "d"] + elemType: "string" + - name: generated-wide + in: + grid: + gen: "array" + len: 3 + of: + gen: "array" + len: 40 + of: + gen: "char" + variety: ["a", "b"] + elemType: "string" + - name: generated-large + in: + grid: + gen: "array" + len: 40 + of: + gen: "array" + len: 40 + of: + gen: "char" + variety: ["a", "b", "c", "d", "e"] + elemType: "string" + - name: generated-stress + in: + grid: + gen: "array" + len: 200 + of: + gen: "array" + len: 200 + of: + gen: "char" + variety: ["a", "b", "c", "d", "e", "f"] + elemType: "string" diff --git a/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.cpp b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.cpp new file mode 100644 index 00000000..6a7b6510 --- /dev/null +++ b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + bool containsCycle(vector>& grid) { + int n = grid.size(); + int m = grid[0].size(); + vector> visited(n, vector(m, false)); + vector> directions = {{-1,0}, {1,0}, {0,-1}, {0,1}}; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (!visited[i][j]) { + if (bfs(i, j, grid, visited, directions)) return true; + } + } + } + return false; + } + +private: + bool bfs(int startI, int startJ, vector>& grid, vector>& visited, vector>& directions) { + int n = grid.size(); + int m = grid[0].size(); + queue> q; + q.push({startI, startJ, -1, -1}); + visited[startI][startJ] = true; + + while (!q.empty()) { + auto [x, y, px, py] = q.front(); + q.pop(); + + for (auto& dir : directions) { + int nx = x + dir.first; + int ny = y + dir.second; + if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue; + if (grid[nx][ny] != grid[x][y]) continue; + if (nx == px && ny == py) continue; + if (visited[nx][ny]) return true; + visited[nx][ny] = true; + q.push({nx, ny, x, y}); + } + } + return false; + } +}; diff --git a/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.cs b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.cs new file mode 100644 index 00000000..7190d045 --- /dev/null +++ b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.cs @@ -0,0 +1,39 @@ +public class Solution { + public bool ContainsCycle(char[][] grid) { + int n = grid.Length; + int m = grid[0].Length; + bool[][] visited = new bool[n][]; + for (int i = 0; i < n; i++) visited[i] = new bool[m]; + int[][] directions = new int[][] { new int[] {-1,0}, new int[] {1,0}, new int[] {0,-1}, new int[] {0,1} }; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (!visited[i][j]) { + if (Bfs(i, j, grid, visited, directions, n, m)) return true; + } + } + } + return false; + } + + private bool Bfs(int startI, int startJ, char[][] grid, bool[][] visited, int[][] directions, int n, int m) { + Queue<(int, int, int, int)> queue = new Queue<(int, int, int, int)>(); + queue.Enqueue((startI, startJ, -1, -1)); + visited[startI][startJ] = true; + + while (queue.Count > 0) { + var (x, y, px, py) = queue.Dequeue(); + foreach (var dir in directions) { + int nx = x + dir[0]; + int ny = y + dir[1]; + if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue; + if (grid[nx][ny] != grid[x][y]) continue; + if (nx == px && ny == py) continue; + if (visited[nx][ny]) return true; + visited[nx][ny] = true; + queue.Enqueue((nx, ny, x, y)); + } + } + return false; + } +} diff --git a/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.dart b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.dart new file mode 100644 index 00000000..86f80eda --- /dev/null +++ b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.dart @@ -0,0 +1,44 @@ +class Solution { + bool containsCycle(List> grid) { + final n = grid.length; + final m = grid[0].length; + final visited = List.generate(n, (_) => List.filled(m, false)); + final directions = [ + [-1, 0], [1, 0], [0, -1], [0, 1] + ]; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (!visited[i][j]) { + if (_bfs(i, j, grid, visited, directions)) return true; + } + } + } + return false; + } + + bool _bfs(int startI, int startJ, List> grid, List> visited, List> directions) { + final n = grid.length; + final m = grid[0].length; + final queue = >[]; + queue.add([startI, startJ, -1, -1]); + visited[startI][startJ] = true; + int head = 0; + + while (head < queue.length) { + final cur = queue[head++]; + final x = cur[0], y = cur[1], px = cur[2], py = cur[3]; + + for (final d in directions) { + final nx = x + d[0], ny = y + d[1]; + if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue; + if (grid[nx][ny] != grid[x][y]) continue; + if (nx == px && ny == py) continue; + if (visited[nx][ny]) return true; + visited[nx][ny] = true; + queue.add([nx, ny, x, y]); + } + } + return false; + } +} diff --git a/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.go b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.go new file mode 100644 index 00000000..b90e3bc5 --- /dev/null +++ b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.go @@ -0,0 +1,37 @@ +func containsCycle(grid [][]byte) bool { + n := len(grid) + m := len(grid[0]) + visited := make([][]bool, n) + for i := range visited { + visited[i] = make([]bool, m) + } + + directions := [][]int{{-1,0}, {1,0}, {0,-1}, {0,1}} + + type cell struct { x, y, px, py int } + + for i := 0; i < n; i++ { + for j := 0; j < m; j++ { + if !visited[i][j] { + queue := []cell{{i, j, -1, -1}} + visited[i][j] = true + head := 0 + for head < len(queue) { + cur := queue[head] + head++ + x, y, px, py := cur.x, cur.y, cur.px, cur.py + for _, d := range directions { + nx, ny := x + d[0], y + d[1] + if nx < 0 || ny < 0 || nx >= n || ny >= m { continue } + if grid[nx][ny] != grid[x][y] { continue } + if nx == px && ny == py { continue } + if visited[nx][ny] { return true } + visited[nx][ny] = true + queue = append(queue, cell{nx, ny, x, y}) + } + } + } + } + } + return false +} diff --git a/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.java b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.java new file mode 100644 index 00000000..61794640 --- /dev/null +++ b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.java @@ -0,0 +1,42 @@ +class Solution { + public boolean containsCycle(char[][] grid) { + int n = grid.length; + int m = grid[0].length; + boolean[][] visited = new boolean[n][m]; + int[][] directions = {{-1,0}, {1,0}, {0,-1}, {0,1}}; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (!visited[i][j]) { + if (bfs(i, j, grid, visited, directions)) return true; + } + } + } + return false; + } + + private boolean bfs(int startI, int startJ, char[][] grid, boolean[][] visited, int[][] directions) { + int n = grid.length; + int m = grid[0].length; + int[][] queue = new int[n * m][4]; + int head = 0, tail = 0; + queue[tail++] = new int[]{startI, startJ, -1, -1}; + visited[startI][startJ] = true; + + while (head < tail) { + int[] cur = queue[head++]; + int x = cur[0], y = cur[1], px = cur[2], py = cur[3]; + + for (int[] dir : directions) { + int nx = x + dir[0], ny = y + dir[1]; + if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue; + if (grid[nx][ny] != grid[x][y]) continue; + if (nx == px && ny == py) continue; + if (visited[nx][ny]) return true; + visited[nx][ny] = true; + queue[tail++] = new int[]{nx, ny, x, y}; + } + } + return false; + } +} diff --git a/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.kt b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.kt new file mode 100644 index 00000000..e4f85921 --- /dev/null +++ b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.kt @@ -0,0 +1,45 @@ +class Solution { + fun containsCycle(grid: Array): Boolean { + val n = grid.size + val m = grid[0].size + val visited = Array(n) { BooleanArray(m) } + val directions = arrayOf(intArrayOf(-1,0), intArrayOf(1,0), intArrayOf(0,-1), intArrayOf(0,1)) + + for (i in 0 until n) { + for (j in 0 until m) { + if (!visited[i][j]) { + if (bfs(i, j, grid, visited, directions)) return true + } + } + } + return false + } + + private fun bfs(startI: Int, startJ: Int, grid: Array, visited: Array, directions: Array): Boolean { + val n = grid.size + val m = grid[0].size + val queue = ArrayDeque() + queue.add(intArrayOf(startI, startJ, -1, -1)) + visited[startI][startJ] = true + + while (queue.isNotEmpty()) { + val cur = queue.removeFirst() + val x = cur[0] + val y = cur[1] + val px = cur[2] + val py = cur[3] + + for (dir in directions) { + val nx = x + dir[0] + val ny = y + dir[1] + if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue + if (grid[nx][ny] != grid[x][y]) continue + if (nx == px && ny == py) continue + if (visited[nx][ny]) return true + visited[nx][ny] = true + queue.add(intArrayOf(nx, ny, x, y)) + } + } + return false + } +} diff --git a/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.py b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.py new file mode 100644 index 00000000..356a6f40 --- /dev/null +++ b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.py @@ -0,0 +1,51 @@ +from collections import deque + + +class Solution: + def containsCycle(self, grid): + n = len(grid) + m = len(grid[0]) + + visited = [[False] * m for _ in range(n)] + + def bfs(i, j): + queue = deque() + queue.append((i, j, -1, -1)) # (x, y, parent_x, parent_y) + visited[i][j] = True + + directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] + + while queue: + x, y, px, py = queue.popleft() + + for dx, dy in directions: + nx, ny = x + dx, y + dy + + # boundary check + if nx < 0 or ny < 0 or nx >= n or ny >= m: + continue + + # same character condition + if grid[nx][ny] != grid[x][y]: + continue + + # skip parent + if nx == px and ny == py: + continue + + # cycle detected + if visited[nx][ny]: + return True + + visited[nx][ny] = True + queue.append((nx, ny, x, y)) + + return False + + for i in range(n): + for j in range(m): + if not visited[i][j]: + if bfs(i, j): + return True + + return False diff --git a/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.py2 b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.py2 new file mode 100644 index 00000000..56c18575 --- /dev/null +++ b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.py2 @@ -0,0 +1,40 @@ +class Solution(object): + def containsCycle(self, grid): + """ + :type grid: List[List[str]] + :rtype: bool + """ + n = len(grid) + m = len(grid[0]) + visited = [[False] * m for _ in range(n)] + + def bfs(i, j): + queue = [(i, j, -1, -1)] + visited[i][j] = True + head = 0 + directions = [(-1,0), (1,0), (0,-1), (0,1)] + + while head < len(queue): + x, y, px, py = queue[head] + head += 1 + + for dx, dy in directions: + nx, ny = x + dx, y + dy + if nx < 0 or ny < 0 or nx >= n or ny >= m: + continue + if grid[nx][ny] != grid[x][y]: + continue + if nx == px and ny == py: + continue + if visited[nx][ny]: + return True + visited[nx][ny] = True + queue.append((nx, ny, x, y)) + return False + + for i in range(n): + for j in range(m): + if not visited[i][j]: + if bfs(i, j): + return True + return False diff --git a/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.rb b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.rb new file mode 100644 index 00000000..127ee890 --- /dev/null +++ b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.rb @@ -0,0 +1,38 @@ +# @param {Character[][]} grid +# @return {Boolean} +def contains_cycle(grid) + n = grid.length + m = grid[0].length + visited = Array.new(n) { Array.new(m, false) } + + directions = [[-1,0], [1,0], [0,-1], [0,1]] + + bfs = lambda do |i, j| + queue = [[i, j, -1, -1]] + visited[i][j] = true + head = 0 + + while head < queue.length + x, y, px, py = queue[head] + head += 1 + + directions.each do |dx, dy| + nx, ny = x + dx, y + dy + next if nx < 0 || ny < 0 || nx >= n || ny >= m + next if grid[nx][ny] != grid[x][y] + next if nx == px && ny == py + return true if visited[nx][ny] + visited[nx][ny] = true + queue.push([nx, ny, x, y]) + end + end + false + end + + (0...n).each do |i| + (0...m).each do |j| + return true if !visited[i][j] && bfs.call(i, j) + end + end + false +end diff --git a/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.rs b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.rs new file mode 100644 index 00000000..32ae624a --- /dev/null +++ b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.rs @@ -0,0 +1,46 @@ +impl Solution { + pub fn contains_cycle(grid: Vec>) -> bool { + let n = grid.len(); + let m = grid[0].len(); + let mut visited = vec![vec![false; m]; n]; + let directions = [(-1,0), (1,0), (0,-1), (0,1)]; + + for i in 0..n { + for j in 0..m { + if !visited[i][j] { + if Self::bfs(i, j, &grid, &mut visited, &directions) { + return true; + } + } + } + } + false + } + + fn bfs(start_i: usize, start_j: usize, grid: &Vec>, visited: &mut Vec>, directions: &[(i32, i32)]) -> bool { + let n = grid.len(); + let m = grid[0].len(); + let mut queue = vec![(start_i as i32, start_j as i32, -1i32, -1i32)]; + visited[start_i][start_j] = true; + let mut head = 0; + + while head < queue.len() { + let (x, y, px, py) = queue[head]; + head += 1; + + for &(dx, dy) in directions.iter() { + let nx = x + dx; + let ny = y + dy; + if nx < 0 || ny < 0 || nx >= n as i32 || ny >= m as i32 { continue; } + let nxu = nx as usize; + let nyu = ny as usize; + if grid[nxu][nyu] != grid[x as usize][y as usize] { continue; } + if nx == px && ny == py { continue; } + if visited[nxu][nyu] { return true; } + visited[nxu][nyu] = true; + queue.push((nx, ny, x, y)); + } + } + false + } +} diff --git a/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.swift b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.swift new file mode 100644 index 00000000..18931c9d --- /dev/null +++ b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.swift @@ -0,0 +1,41 @@ +class Solution { + func containsCycle(_ grid: [[Character]]) -> Bool { + let n = grid.count + let m = grid[0].count + var visited = Array(repeating: Array(repeating: false, count: m), count: n) + let directions = [(-1,0), (1,0), (0,-1), (0,1)] + + for i in 0.. Bool { + let n = grid.count + let m = grid[0].count + var queue = [(startI, startJ, -1, -1)] + visited[startI][startJ] = true + var head = 0 + + while head < queue.count { + let (x, y, px, py) = queue[head] + head += 1 + + for (dx, dy) in directions { + let nx = x + dx, ny = y + dy + if nx < 0 || ny < 0 || nx >= n || ny >= m { continue } + if grid[nx][ny] != grid[x][y] { continue } + if nx == px && ny == py { continue } + if visited[nx][ny] { return true } + visited[nx][ny] = true + queue.append((nx, ny, x, y)) + } + } + return false + } +} diff --git a/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.ts b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.ts new file mode 100644 index 00000000..50123a6a --- /dev/null +++ b/tests/1501-2000/1559. detect-cycles-in-2d-grid/sol.ts @@ -0,0 +1,51 @@ +function containsCycle(grid: string[][]): boolean { + const n = grid.length; + const m = grid[0].length; + const visited: boolean[][] = Array.from({ length: n }, () => + Array(m).fill(false), + ); + const directions = [ + [-1, 0], + [1, 0], + [0, -1], + [0, 1], + ]; + + for (let i = 0; i < n; i++) { + for (let j = 0; j < m; j++) { + if (!visited[i][j]) { + if (bfs(i, j, grid, visited, directions)) return true; + } + } + } + return false; + + function bfs( + startI: number, + startJ: number, + grid: string[][], + visited: boolean[][], + directions: number[][], + ): boolean { + const n = grid.length; + const m = grid[0].length; + const queue: number[][] = [[startI, startJ, -1, -1]]; + visited[startI][startJ] = true; + let head = 0; + + while (head < queue.length) { + const [x, y, px, py] = queue[head++]; + for (const [dx, dy] of directions) { + const nx = x + dx, + ny = y + dy; + if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue; + if (grid[nx][ny] !== grid[x][y]) continue; + if (nx === px && ny === py) continue; + if (visited[nx][ny]) return true; + visited[nx][ny] = true; + queue.push([nx, ny, x, y]); + } + } + return false; + } +} diff --git a/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/manifest.yaml b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/manifest.yaml new file mode 100644 index 00000000..c9fd5d74 --- /dev/null +++ b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/manifest.yaml @@ -0,0 +1,538 @@ +entry: + id: 1560 + title: "most-visited-sector-in-a-circular-track" + params: + n: + type: int + rounds: + type: array + items: + type: int + call: + cpp: "Solution().mostVisited({n}, {rounds})" + rust: "Solution::most_visited({n}, {rounds})" + python3: "Solution().mostVisited({n}, {rounds})" + python2: "Solution().mostVisited({n}, {rounds})" + ruby: "most_visited({n}, {rounds})" + java: "new Solution().mostVisited({n}, {rounds})" + csharp: "new Solution().MostVisited({n}, {rounds})" + kotlin: "Solution().mostVisited({n}, {rounds})" + go: "mostVisited({n}, {rounds})" + dart: "Solution().mostVisited({n}, {rounds})" + swift: "Solution().mostVisited({n}, {rounds})" + typescript: "mostVisited({n}, {rounds})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().mostVisited(n, rounds, {result})" + checker: | + class Checker: + def mostVisited(self, n, rounds, result): + start = rounds[0] + end = rounds[-1] + expected = list(range(start, end + 1)) if start <= end else list(range(1, end + 1)) + list(range(start, n + 1)) + return result == expected + +seed: 1560 + +tests: + - name: example-1 + in: + n: 4 + rounds: [1, 3, 1, 2] + out: [1, 2] + - name: example-2 + in: + n: 2 + rounds: [2, 1, 2, 1, 2, 1, 2, 1, 2] + out: [2] + - name: example-3 + in: + n: 7 + rounds: [1, 3, 5, 7] + out: [1, 2, 3, 4, 5, 6, 7] + - name: single-round-forward + in: + n: 5 + rounds: [2, 4] + out: [2, 3, 4] + - name: single-round-wrap + in: + n: 5 + rounds: [4, 2] + out: [1, 2, 4, 5] + - name: adjacent-forward + in: + n: 6 + rounds: [1, 2] + out: [1, 2] + - name: adjacent-wrap + in: + n: 6 + rounds: [6, 1] + out: [1, 6] + - name: full-track-from-one + in: + n: 8 + rounds: [1, 8] + out: [1, 2, 3, 4, 5, 6, 7, 8] + - name: full-track-from-last + in: + n: 8 + rounds: [8, 7] + out: [1, 2, 3, 4, 5, 6, 7, 8] + - name: minimum-n-forward + in: + n: 3 + rounds: [1, 2, 1, 2] + out: [1, 2] + - name: minimum-n-wrap + in: + n: 3 + rounds: [3, 2, 3, 2] + out: [1, 2, 3] + - name: repeated-forward + in: + n: 10 + rounds: [2, 5, 2, 5] + out: [2, 3, 4, 5] + - name: repeated-wrap + in: + n: 10 + rounds: [8, 3, 8, 3] + out: [1, 2, 3, 8, 9, 10] + - name: forward-then-wrap + in: + n: 9 + rounds: [2, 6, 4, 8] + out: [2, 3, 4, 5, 6, 7, 8] + - name: wrap-then-forward + in: + n: 9 + rounds: [8, 3, 6, 2] + out: [1, 2, 8, 9] + - name: endpoint-one + in: + n: 10 + rounds: [1, 10, 1] + out: [1] + - name: endpoint-n + in: + n: 10 + rounds: [10, 1, 10] + out: [10] + - name: long-forward + in: + n: 12 + rounds: [3, 4, 7, 8, 11, 12] + out: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + - name: long-wrap + in: + n: 12 + rounds: [10, 11, 2, 3, 1] + out: [1, 10, 11, 12] + - name: alternating-small + in: + n: 5 + rounds: [1, 5, 2, 4, 3, 2] + out: [1, 2] + - name: middle-forward + in: + n: 15 + rounds: [5, 9, 6, 12] + out: [5, 6, 7, 8, 9, 10, 11, 12] + - name: middle-wrap + in: + n: 15 + rounds: [12, 5, 11, 3] + out: [1, 2, 3, 12, 13, 14, 15] + - name: many-forward + in: + n: 20 + rounds: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] + out: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] + - name: many-wrap + in: + n: 20 + rounds: [19, 2, 18, 3, 17, 4] + out: [1, 2, 3, 4, 19, 20] + - name: singleton-maximum + in: + n: 100 + rounds: [50, 51] + out: [50, 51] + - name: maximum-wrap + in: + n: 100 + rounds: [51, 50] + out: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + 63, + 64, + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + 99, + 100, + ] + - name: max-forward + in: + n: 100 + rounds: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - name: max-wrap-short + in: + n: 100 + rounds: [90, 95, 5, 10] + out: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + 99, + 100, + ] + - name: max-long-forward + in: + n: 100 + rounds: [10, 30, 20, 40, 60, 80, 100] + out: + [ + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + 63, + 64, + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + 99, + 100, + ] + - name: max-long-wrap + in: + n: 100 + rounds: [90, 10, 80, 20, 70, 30, 60, 40] + out: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + 99, + 100, + ] + - name: two-sector-cycle + in: + n: 4 + rounds: [2, 3, 2, 3, 2] + out: [2] + - name: three-sector-cycle + in: + n: 6 + rounds: [4, 5, 6, 1, 2] + out: [1, 2, 4, 5, 6] + - name: repeated-same-start-end + in: + n: 7 + rounds: [3, 5, 3, 5, 3, 5] + out: [3, 4, 5] + - name: lower-half-wrap + in: + n: 11 + rounds: [7, 2, 6, 1] + out: [1, 7, 8, 9, 10, 11] + - name: upper-half-forward + in: + n: 11 + rounds: [4, 9, 5, 10] + out: [4, 5, 6, 7, 8, 9, 10] + - name: dense-short + in: + n: 25 + rounds: [20, 21, 22, 23, 24, 25, 1] + out: [1, 20, 21, 22, 23, 24, 25] + - name: dense-wrap + in: + n: 25 + rounds: [24, 1, 23, 2, 22, 3] + out: [1, 2, 3, 24, 25] + - name: exact-all-sectors + in: + n: 30 + rounds: [1, 10, 20, 30] + out: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + ] diff --git a/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.cpp b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.cpp new file mode 100644 index 00000000..ad761543 --- /dev/null +++ b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + vector mostVisited(int n, vector& rounds) { + int s = rounds[0], e = rounds.back(); + vector ans; + if (s <= e) { + for (int i = s; i <= e; ++i) ans.push_back(i); + } else { + for (int i = 1; i <= e; ++i) ans.push_back(i); + for (int i = s; i <= n; ++i) ans.push_back(i); + } + return ans; + } +}; diff --git a/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.cs b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.cs new file mode 100644 index 00000000..77bcd315 --- /dev/null +++ b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.cs @@ -0,0 +1,14 @@ +public class Solution { + public IList MostVisited(int n, int[] rounds) { + int s = rounds[0]; + int e = rounds[rounds.Length - 1]; + var ans = new List(); + if (s <= e) { + for (int i = s; i <= e; i++) ans.Add(i); + } else { + for (int i = 1; i <= e; i++) ans.Add(i); + for (int i = s; i <= n; i++) ans.Add(i); + } + return ans; + } +} diff --git a/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.dart b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.dart new file mode 100644 index 00000000..6d2183f3 --- /dev/null +++ b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.dart @@ -0,0 +1,11 @@ +class Solution { + List mostVisited(int n, List rounds) { + int s = rounds[0]; + int e = rounds[rounds.length - 1]; + if (s <= e) { + return List.generate(e - s + 1, (i) => s + i); + } else { + return List.generate(e, (i) => i + 1) + List.generate(n - s + 1, (i) => s + i); + } + } +} diff --git a/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.go b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.go new file mode 100644 index 00000000..6792c0ca --- /dev/null +++ b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.go @@ -0,0 +1,17 @@ +func mostVisited(n int, rounds []int) []int { + s, e := rounds[0], rounds[len(rounds)-1] + ans := []int{} + if s <= e { + for i := s; i <= e; i++ { + ans = append(ans, i) + } + } else { + for i := 1; i <= e; i++ { + ans = append(ans, i) + } + for i := s; i <= n; i++ { + ans = append(ans, i) + } + } + return ans +} diff --git a/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.java b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.java new file mode 100644 index 00000000..4bba71fb --- /dev/null +++ b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.java @@ -0,0 +1,13 @@ +class Solution { + public List mostVisited(int n, int[] rounds) { + int s = rounds[0], e = rounds[rounds.length - 1]; + List ans = new ArrayList<>(); + if (s <= e) { + for (int i = s; i <= e; i++) ans.add(i); + } else { + for (int i = 1; i <= e; i++) ans.add(i); + for (int i = s; i <= n; i++) ans.add(i); + } + return ans; + } +} diff --git a/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.kt b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.kt new file mode 100644 index 00000000..09bb6acb --- /dev/null +++ b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.kt @@ -0,0 +1,7 @@ +class Solution { + fun mostVisited(n: Int, rounds: IntArray): List { + val s = rounds[0] + val e = rounds[rounds.size - 1] + return if (s <= e) (s..e).toList() else (1..e).toList() + (s..n).toList() + } +} diff --git a/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.py b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.py new file mode 100644 index 00000000..b84a7504 --- /dev/null +++ b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.py @@ -0,0 +1,8 @@ +class Solution: + def mostVisited(self, n: int, rounds: list[int]) -> list[int]: + s, e = rounds[0], rounds[-1] + return ( + list(range(s, e + 1)) + if s <= e + else list(range(1, e + 1)) + list(range(s, n + 1)) + ) diff --git a/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.py2 b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.py2 new file mode 100644 index 00000000..40d73222 --- /dev/null +++ b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def mostVisited(self, n, rounds): + """ + :type n: int + :type rounds: List[int] + :rtype: List[int] + """ + s, e = rounds[0], rounds[-1] + if s <= e: + return list(range(s, e + 1)) + else: + return list(range(1, e + 1)) + list(range(s, n + 1)) diff --git a/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.rb b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.rb new file mode 100644 index 00000000..3f18cb72 --- /dev/null +++ b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.rb @@ -0,0 +1,11 @@ +# @param {Integer} n +# @param {Integer[]} rounds +# @return {Integer[]} +def most_visited(n, rounds) + s, e = rounds[0], rounds[-1] + if s <= e + (s..e).to_a + else + (1..e).to_a + (s..n).to_a + end +end diff --git a/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.rs b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.rs new file mode 100644 index 00000000..32c4f944 --- /dev/null +++ b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn most_visited(n: i32, rounds: Vec) -> Vec { + let s = rounds[0]; + let e = *rounds.last().unwrap(); + if s <= e { + (s..=e).collect() + } else { + (1..=e).chain(s..=n).collect() + } + } +} diff --git a/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.swift b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.swift new file mode 100644 index 00000000..21adafba --- /dev/null +++ b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.swift @@ -0,0 +1,11 @@ +class Solution { + func mostVisited(_ n: Int, _ rounds: [Int]) -> [Int] { + let s = rounds[0] + let e = rounds[rounds.count - 1] + if s <= e { + return Array(s...e) + } else { + return Array(1...e) + Array(s...n) + } + } +} diff --git a/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.ts b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.ts new file mode 100644 index 00000000..a6c5d259 --- /dev/null +++ b/tests/1501-2000/1560. most-visited-sector-in-a-circular-track/sol.ts @@ -0,0 +1,14 @@ +function mostVisited(n: number, rounds: number[]): number[] { + const s = rounds[0]; + const e = rounds[rounds.length - 1]; + if (s <= e) { + const ans: number[] = []; + for (let i = s; i <= e; i++) ans.push(i); + return ans; + } else { + const ans: number[] = []; + for (let i = 1; i <= e; i++) ans.push(i); + for (let i = s; i <= n; i++) ans.push(i); + return ans; + } +} diff --git a/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/manifest.yaml b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/manifest.yaml new file mode 100644 index 00000000..64a642f1 --- /dev/null +++ b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/manifest.yaml @@ -0,0 +1,380 @@ +entry: + id: 1561 + title: "maximum-number-of-coins-you-can-get" + params: + piles: + type: array + items: + type: int + call: + cpp: "Solution().maxCoins({piles})" + rust: "Solution::max_coins({piles})" + python3: "Solution().maxCoins({piles})" + python2: "Solution().maxCoins({piles})" + ruby: "max_coins({piles})" + java: "new Solution().maxCoins({piles})" + csharp: "new Solution().MaxCoins({piles})" + kotlin: "Solution().maxCoins({piles})" + go: "maxCoins({piles})" + dart: "Solution().maxCoins({piles})" + swift: "Solution().maxCoins({piles})" + typescript: "maxCoins({piles})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxCoins(piles, {result})" + checker: | + class Checker: + def maxCoins(self, piles, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + a = sorted(piles) + expected = sum(a[len(a) - 2 - 2 * i] for i in range(len(a) // 3)) + return result == expected + +seed: 1561 + +tests: + - name: example-one + in: + piles: [2, 4, 1, 2, 7, 8] + out: 9 + - name: example-two + in: + piles: [2, 4, 5] + out: 4 + - name: example-three + in: + piles: [9, 8, 7, 6, 5, 1, 2, 3, 4] + out: 18 + - name: all-ones-three + in: + piles: [1, 1, 1] + out: 1 + - name: consecutive-three + in: + piles: [1, 2, 3] + out: 2 + - name: consecutive-six + in: + piles: [1, 2, 3, 4, 5, 6] + out: 8 + - name: paired-values + in: + piles: [1, 1, 2, 2, 3, 3] + out: 5 + - name: all-ones-nine + in: + piles: [1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 3 + - name: maximum-single-triplet + in: + piles: [10000, 10000, 10000] + out: 10000 + - name: alternating-extremes + in: + piles: [1, 10000, 1, 10000, 1, 10000] + out: 10001 + - name: equal-six + in: + piles: [5, 5, 5, 5, 5, 5] + out: 10 + - name: consecutive-twelve + in: + piles: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + out: 32 + - name: separated-values + in: + piles: [10, 20, 30, 40, 50, 60] + out: 80 + - name: repeated-triples + in: + piles: [3, 3, 3, 4, 4, 4, 5, 5, 5] + out: 13 + - name: repeated-high-values + in: + piles: [8, 1, 8, 1, 8, 1] + out: 9 + - name: low-and-high-groups + in: + piles: [2, 2, 2, 9, 9, 9] + out: 11 + - name: arithmetic-six + in: + piles: [1, 4, 7, 10, 13, 16] + out: 20 + - name: descending-six + in: + piles: [6, 5, 4, 3, 2, 1] + out: 8 + - name: descending-fifteen + in: + piles: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 10, 9, 8, 7, 6] + out: 40 + - name: mixed-large-twelve + in: + piles: [1, 100, 2, 99, 3, 98, 4, 97, 5, 96, 6, 95] + out: 296 + - name: duplicated-descending + in: + piles: [12, 12, 11, 11, 10, 10, 9, 9, 8, 8, 7, 7] + out: 42 + - name: paired-consecutive + in: + piles: [1, 2, 2, 3, 3, 4] + out: 5 + - name: hundreds-nine + in: + piles: [100, 200, 300, 400, 500, 600, 700, 800, 900] + out: 1800 + - name: paired-six-values + in: + piles: [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6] + out: 18 + - name: multiples-seven + in: + piles: [7, 14, 21, 28, 35, 42] + out: 56 + - name: primes + in: + piles: [2, 3, 5, 7, 11, 13] + out: 16 + - name: descending-nine + in: + piles: [99, 98, 97, 96, 95, 94, 93, 92, 91] + out: 288 + - name: fifty-one-to-one + in: + piles: [51, 52, 53, 54, 55, 56] + out: 108 + - name: lower-bound-random + in: + piles: [1, 3, 1, 2, 2, 1, 3, 2, 1] + out: 6 + - name: high-duplicates + in: + piles: [9999, 1, 9999, 1, 9999, 1, 10000, 2, 10000, 2, 10000, 2] + out: 30000 + - name: large-structured + in: + piles: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + 63, + 64, + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + 99, + 100, + 101, + 102, + 103, + 104, + 105, + 106, + 107, + 108, + 109, + 110, + 111, + 112, + 113, + 114, + 115, + 116, + 117, + 118, + 119, + 120, + 121, + 122, + 123, + 124, + 125, + 126, + 127, + 128, + 129, + 130, + 131, + 132, + 133, + 134, + 135, + 136, + 137, + 138, + 139, + 140, + 141, + 142, + 143, + 144, + 145, + 146, + 147, + 148, + 149, + 150, + ] + out: 5000 + - name: generated-small + in: + piles: + gen: "array" + len: 3 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" + - name: generated-medium + in: + piles: + gen: "array" + len: 30 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" + - name: generated-large + in: + piles: + gen: "array" + len: 300 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" + - name: generated-near-limit + in: + piles: + gen: "array" + len: 99999 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" + - name: generated-max-limit + in: + piles: + gen: "array" + len: 99999 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.cpp b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.cpp new file mode 100644 index 00000000..c308242d --- /dev/null +++ b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int maxCoins(vector& piles) { + sort(piles.begin(), piles.end()); + int l = 0; + int r = piles.size(); + int count = 0; + for (int i = 0; i < piles.size()/3; i++) { + count += piles[r-2]; + l += 1; + r -= 2; + } + return count; + } +}; diff --git a/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.cs b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.cs new file mode 100644 index 00000000..6c409096 --- /dev/null +++ b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.cs @@ -0,0 +1,14 @@ +public class Solution { + public int MaxCoins(int[] piles) { + Array.Sort(piles); + int l = 0; + int r = piles.Length; + int count = 0; + for (int i = 0; i < piles.Length/3; i++) { + count += piles[r-2]; + l += 1; + r -= 2; + } + return count; + } +} diff --git a/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.dart b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.dart new file mode 100644 index 00000000..603cdbfa --- /dev/null +++ b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.dart @@ -0,0 +1,14 @@ +class Solution { + int maxCoins(List piles) { + piles.sort(); + int l = 0; + int r = piles.length; + int count = 0; + for (int i = 0; i < piles.length ~/ 3; i++) { + count += piles[r-2]; + l += 1; + r -= 2; + } + return count; + } +} diff --git a/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.go b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.go new file mode 100644 index 00000000..b5f93f9f --- /dev/null +++ b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.go @@ -0,0 +1,12 @@ +func maxCoins(piles []int) int { + sort.Ints(piles) + l := 0 + r := len(piles) + count := 0 + for i := 0; i < len(piles)/3; i++ { + count += piles[r-2] + l += 1 + r -= 2 + } + return count +} diff --git a/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.java b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.java new file mode 100644 index 00000000..cb3e4a22 --- /dev/null +++ b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.java @@ -0,0 +1,14 @@ +class Solution { + public int maxCoins(int[] piles) { + java.util.Arrays.sort(piles); + int l = 0; + int r = piles.length; + int count = 0; + for (int i = 0; i < piles.length / 3; i++) { + count += piles[r-2]; + l += 1; + r -= 2; + } + return count; + } +} diff --git a/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.kt b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.kt new file mode 100644 index 00000000..b67f15a1 --- /dev/null +++ b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun maxCoins(piles: IntArray): Int { + piles.sort() + var l = 0 + var r = piles.size + var count = 0 + for (i in 0 until piles.size / 3) { + count += piles[r-2] + l += 1 + r -= 2 + } + return count + } +} diff --git a/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.py b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.py new file mode 100644 index 00000000..e8ae3288 --- /dev/null +++ b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.py @@ -0,0 +1,11 @@ +class Solution: + def maxCoins(self, piles: List[int]) -> int: + l = 0 + r = len(piles) + count = 0 + piles.sort() + for i in range(len(piles) // 3): + count += piles[r - 2] + l += 1 + r -= 2 + return count diff --git a/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.py2 b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.py2 new file mode 100644 index 00000000..ff16e2c7 --- /dev/null +++ b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def maxCoins(self, piles): + """ + :type piles: List[int] + :rtype: int + """ + piles.sort() + l = 0 + r = len(piles) + count = 0 + for i in range(len(piles)//3): + count += piles[r-2] + l += 1 + r -= 2 + return count diff --git a/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.rb b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.rb new file mode 100644 index 00000000..d7f65661 --- /dev/null +++ b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[]} piles +# @return {Integer} +def max_coins(piles) + piles.sort! + l = 0 + r = piles.length + count = 0 + (piles.length / 3).times do + count += piles[r-2] + l += 1 + r -= 2 + end + count +end diff --git a/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.rs b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.rs new file mode 100644 index 00000000..0c086eed --- /dev/null +++ b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn max_coins(piles: Vec) -> i32 { + let mut piles = piles; + piles.sort(); + let mut l = 0; + let mut r = piles.len(); + let mut count = 0; + for _ in 0..piles.len()/3 { + count += piles[r-2]; + l += 1; + r -= 2; + } + count + } +} diff --git a/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.swift b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.swift new file mode 100644 index 00000000..80b1a2b7 --- /dev/null +++ b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.swift @@ -0,0 +1,14 @@ +class Solution { + func maxCoins(_ piles: [Int]) -> Int { + var piles = piles.sorted() + var l = 0 + var r = piles.count + var count = 0 + for _ in 0..<(piles.count/3) { + count += piles[r-2] + l += 1 + r -= 2 + } + return count + } +} diff --git a/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.ts b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.ts new file mode 100644 index 00000000..d605efc7 --- /dev/null +++ b/tests/1501-2000/1561. maximum-number-of-coins-you-can-get/sol.ts @@ -0,0 +1,12 @@ +function maxCoins(piles: number[]): number { + piles.sort((a, b) => a - b); + let l = 0; + let r = piles.length; + let count = 0; + for (let i = 0; i < Math.floor(piles.length / 3); i++) { + count += piles[r - 2]; + l += 1; + r -= 2; + } + return count; +} diff --git a/tests/1501-2000/1562. find-latest-group-of-size-m/manifest.yaml b/tests/1501-2000/1562. find-latest-group-of-size-m/manifest.yaml new file mode 100644 index 00000000..17d4fae0 --- /dev/null +++ b/tests/1501-2000/1562. find-latest-group-of-size-m/manifest.yaml @@ -0,0 +1,252 @@ +entry: + id: 1562 + title: "find-latest-group-of-size-m" + params: + arr: + type: array + items: + type: int + m: + type: int + call: + cpp: "Solution().findLatestStep({arr}, {m})" + rust: "Solution::find_latest_step({arr}, {m})" + python3: "Solution().findLatestStep({arr}, {m})" + python2: "Solution().findLatestStep({arr}, {m})" + ruby: "find_latest_step({arr}, {m})" + java: "new Solution().findLatestStep({arr}, {m})" + csharp: "new Solution().FindLatestStep({arr}, {m})" + kotlin: "Solution().findLatestStep({arr}, {m})" + go: "findLatestStep({arr}, {m})" + dart: "Solution().findLatestStep({arr}, {m})" + swift: "Solution().findLatestStep({arr}, {m})" + typescript: "findLatestStep({arr}, {m})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().findLatestStep(arr, m, {result})" + checker: | + class Checker: + def findLatestStep(self, arr, m, result): + n = len(arr) + if not isinstance(result, int) or isinstance(result, bool): + return False + if m == n: + return result == n + lengths = [0] * (n + 2) + latest = -1 + for step, position in enumerate(arr): + left = lengths[position - 1] + right = lengths[position + 1] + if left == m or right == m: + latest = step + length = left + right + 1 + lengths[position - left] = length + lengths[position + right] = length + return result == latest + +seed: 1562 + +tests: + - name: two-increasing-single + in: + arr: [1, 2] + m: 1 + out: 1 + - name: two-increasing-whole + in: + arr: [1, 2] + m: 2 + out: 2 + - name: two-decreasing-single + in: + arr: [2, 1] + m: 1 + out: 1 + - name: two-decreasing-whole + in: + arr: [2, 1] + m: 2 + out: 2 + - name: three-single-late + in: + arr: [3, 1, 2] + m: 1 + out: 2 + - name: three-no-pair + in: + arr: [3, 1, 2] + m: 2 + out: -1 + - name: three-whole + in: + arr: [3, 1, 2] + m: 3 + out: 3 + - name: three-alternate-single + in: + arr: [1, 3, 2] + m: 1 + out: 2 + - name: three-alternate-no-pair + in: + arr: [1, 3, 2] + m: 2 + out: -1 + - name: three-alternate-whole + in: + arr: [1, 3, 2] + m: 3 + out: 3 + - name: three-middle-single + in: + arr: [2, 3, 1] + m: 1 + out: 1 + - name: three-middle-pair + in: + arr: [2, 3, 1] + m: 2 + out: 2 + - name: three-middle-whole + in: + arr: [2, 3, 1] + m: 3 + out: 3 + - name: three-reverse-single + in: + arr: [3, 2, 1] + m: 1 + out: 1 + - name: three-reverse-pair + in: + arr: [3, 2, 1] + m: 2 + out: 2 + - name: three-reverse-whole + in: + arr: [3, 2, 1] + m: 3 + out: 3 + - name: example-one + in: + arr: [3, 5, 1, 2, 4] + m: 1 + out: 4 + - name: example-one-no-pair + in: + arr: [3, 5, 1, 2, 4] + m: 2 + out: -1 + - name: example-two + in: + arr: [3, 1, 5, 4, 2] + m: 2 + out: -1 + - name: increasing-four-single + in: + arr: [1, 2, 3, 4] + m: 1 + out: 1 + - name: increasing-four-pair + in: + arr: [1, 2, 3, 4] + m: 2 + out: 2 + - name: increasing-four-triple + in: + arr: [1, 2, 3, 4] + m: 3 + out: 3 + - name: increasing-four-whole + in: + arr: [1, 2, 3, 4] + m: 4 + out: 4 + - name: decreasing-four-single + in: + arr: [4, 3, 2, 1] + m: 1 + out: 1 + - name: decreasing-four-pair + in: + arr: [4, 3, 2, 1] + m: 2 + out: 2 + - name: decreasing-four-triple + in: + arr: [4, 3, 2, 1] + m: 3 + out: 3 + - name: decreasing-four-whole + in: + arr: [4, 3, 2, 1] + m: 4 + out: 4 + - name: five-mixed-single + in: + arr: [2, 4, 1, 5, 3] + m: 1 + out: 3 + - name: five-mixed-pair + in: + arr: [2, 4, 1, 5, 3] + m: 2 + out: 4 + - name: five-mixed-triple-absent + in: + arr: [2, 4, 1, 5, 3] + m: 3 + out: -1 + - name: five-mixed-four-absent + in: + arr: [2, 4, 1, 5, 3] + m: 4 + out: -1 + - name: five-right-single + in: + arr: [5, 1, 4, 2, 3] + m: 1 + out: 3 + - name: five-right-pair + in: + arr: [5, 1, 4, 2, 3] + m: 2 + out: 4 + - name: five-right-triple-absent + in: + arr: [5, 1, 4, 2, 3] + m: 3 + out: -1 + - name: five-right-whole + in: + arr: [5, 1, 4, 2, 3] + m: 5 + out: 5 + - name: six-mixed-pair + in: + arr: [6, 1, 3, 5, 2, 4] + m: 2 + out: 5 + - name: six-mixed-triple + in: + arr: [6, 1, 3, 5, 2, 4] + m: 3 + out: 5 + - name: six-mixed-four-absent + in: + arr: [6, 1, 3, 5, 2, 4] + m: 4 + out: -1 + - name: six-mixed-whole + in: + arr: [6, 1, 3, 5, 2, 4] + m: 6 + out: 6 diff --git a/tests/1501-2000/1562. find-latest-group-of-size-m/sol.cpp b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.cpp new file mode 100644 index 00000000..ff191e06 --- /dev/null +++ b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int findLatestStep(vector& arr, int m) { + int n = arr.size(); + if (m == n) return m; + + vector groups(n + 2, 0); + int latestStep = -1; + + for (int i = 0; i < n; i++) { + int idx = arr[i]; + int left = groups[idx - 1]; + int right = groups[idx + 1]; + + if (left == m || right == m) latestStep = i; + + groups[idx - left] = groups[idx + right] = left + right + 1; + } + + return latestStep; + } +}; diff --git a/tests/1501-2000/1562. find-latest-group-of-size-m/sol.cs b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.cs new file mode 100644 index 00000000..5f5fb067 --- /dev/null +++ b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.cs @@ -0,0 +1,21 @@ +public class Solution { + public int FindLatestStep(int[] arr, int m) { + int n = arr.Length; + if (m == n) return m; + + int[] groups = new int[n + 2]; + int latestStep = -1; + + for (int i = 0; i < n; i++) { + int idx = arr[i]; + int left = groups[idx - 1]; + int right = groups[idx + 1]; + + if (left == m || right == m) latestStep = i; + + groups[idx - left] = groups[idx + right] = left + right + 1; + } + + return latestStep; + } +} diff --git a/tests/1501-2000/1562. find-latest-group-of-size-m/sol.dart b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.dart new file mode 100644 index 00000000..41796b4b --- /dev/null +++ b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.dart @@ -0,0 +1,21 @@ +class Solution { + int findLatestStep(List arr, int m) { + int n = arr.length; + if (m == n) return m; + + List groups = List.filled(n + 2, 0); + int latestStep = -1; + + for (int i = 0; i < n; i++) { + int idx = arr[i]; + int left = groups[idx - 1]; + int right = groups[idx + 1]; + + if (left == m || right == m) latestStep = i; + + groups[idx - left] = groups[idx + right] = left + right + 1; + } + + return latestStep; + } +} diff --git a/tests/1501-2000/1562. find-latest-group-of-size-m/sol.go b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.go new file mode 100644 index 00000000..cb9949ba --- /dev/null +++ b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.go @@ -0,0 +1,25 @@ +func findLatestStep(arr []int, m int) int { + n := len(arr) + if m == n { + return m + } + + groups := make([]int, n+2) + latestStep := -1 + + for i, val := range arr { + idx := val + left := groups[idx-1] + right := groups[idx+1] + + if left == m || right == m { + latestStep = i + } + + size := left + right + 1 + groups[idx-left] = size + groups[idx+right] = size + } + + return latestStep +} diff --git a/tests/1501-2000/1562. find-latest-group-of-size-m/sol.java b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.java new file mode 100644 index 00000000..376bb9fa --- /dev/null +++ b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.java @@ -0,0 +1,21 @@ +class Solution { + public int findLatestStep(int[] arr, int m) { + int n = arr.length; + if (m == n) return m; + + int[] groups = new int[n + 2]; + int latestStep = -1; + + for (int i = 0; i < n; i++) { + int idx = arr[i]; + int left = groups[idx - 1]; + int right = groups[idx + 1]; + + if (left == m || right == m) latestStep = i; + + groups[idx - left] = groups[idx + right] = left + right + 1; + } + + return latestStep; + } +} diff --git a/tests/1501-2000/1562. find-latest-group-of-size-m/sol.kt b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.kt new file mode 100644 index 00000000..3512d4c2 --- /dev/null +++ b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.kt @@ -0,0 +1,23 @@ +class Solution { + fun findLatestStep(arr: IntArray, m: Int): Int { + val n = arr.size + if (m == n) return m + + val groups = IntArray(n + 2) + var latestStep = -1 + + for (i in 0 until n) { + val idx = arr[i] + val left = groups[idx - 1] + val right = groups[idx + 1] + + if (left == m || right == m) latestStep = i + + val size = left + right + 1 + groups[idx - left] = size + groups[idx + right] = size + } + + return latestStep + } +} diff --git a/tests/1501-2000/1562. find-latest-group-of-size-m/sol.py b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.py new file mode 100644 index 00000000..2c32795d --- /dev/null +++ b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.py @@ -0,0 +1,25 @@ +class Solution(object): + def findLatestStep(self, arr, m): + """ + :type arr: List[int] + :type m: int + :rtype: int + """ + n = len(arr) + if m == n: + return m + + groups = [0] * (n + 2) + latest_step = -1 + + for i in range(n): + index = arr[i] + left = groups[index - 1] + right = groups[index + 1] + + if left == m or right == m: + latest_step = i + + groups[index - left] = groups[index + right] = left + right + 1 + + return latest_step diff --git a/tests/1501-2000/1562. find-latest-group-of-size-m/sol.py2 b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.py2 new file mode 100644 index 00000000..c812827f --- /dev/null +++ b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.py2 @@ -0,0 +1,25 @@ +class Solution(object): + def findLatestStep(self, arr, m): + """ + :type arr: List[int] + :type m: int + :rtype: int + """ + n = len(arr) + if m == n: + return m + + groups = [0] * (n + 2) + latest_step = -1 + + for i in range(n): + index = arr[i] + left = groups[index - 1] + right = groups[index + 1] + + if left == m or right == m: + latest_step = i + + groups[index - left] = groups[index + right] = left + right + 1 + + return latest_step diff --git a/tests/1501-2000/1562. find-latest-group-of-size-m/sol.rb b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.rb new file mode 100644 index 00000000..d7e50849 --- /dev/null +++ b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.rb @@ -0,0 +1,22 @@ +# @param {Integer[]} arr +# @param {Integer} m +# @return {Integer} +def find_latest_step(arr, m) + n = arr.length + return m if m == n + + groups = Array.new(n + 2, 0) + latest_step = -1 + + arr.each_with_index do |val, i| + idx = val + left = groups[idx - 1] + right = groups[idx + 1] + + latest_step = i if left == m || right == m + + groups[idx - left] = groups[idx + right] = left + right + 1 + end + + latest_step +end diff --git a/tests/1501-2000/1562. find-latest-group-of-size-m/sol.rs b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.rs new file mode 100644 index 00000000..328e2e19 --- /dev/null +++ b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn find_latest_step(arr: Vec, m: i32) -> i32 { + let n = arr.len(); + if m as usize == n { return m; } + + let mut groups = vec![0; n + 2]; + let mut latest_step = -1; + + for i in 0..n { + let idx = arr[i] as usize; + let left = groups[idx - 1]; + let right = groups[idx + 1]; + + if left == m || right == m { + latest_step = i as i32; + } + + let new_len = left + right + 1; + groups[idx - left as usize] = new_len; + groups[idx + right as usize] = new_len; + } + + latest_step + } +} diff --git a/tests/1501-2000/1562. find-latest-group-of-size-m/sol.swift b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.swift new file mode 100644 index 00000000..3a120088 --- /dev/null +++ b/tests/1501-2000/1562. find-latest-group-of-size-m/sol.swift @@ -0,0 +1,25 @@ +class Solution { + func findLatestStep(_ arr: [Int], _ m: Int) -> Int { + let n = arr.count + if m == n { return m } + + var groups = [Int](repeating: 0, count: n + 2) + var latestStep = -1 + + for i in 0..& stoneValue) { + int n = stoneValue.size(); + vector sv(n + 1, 0); + for (int i = 0; i < n; ++i) sv[i + 1] = sv[i] + stoneValue[i]; + vector> memo(n + 1, vector(n + 1, -1)); + return helper(sv, 0, n, memo); + } + +private: + int helper(vector& sv, int fro, int to, vector>& memo) { + if (to - fro == 1) return 0; + if (memo[fro][to] != -1) return memo[fro][to]; + + int target = (sv[to] + sv[fro]) / 2; + int lo = fro, hi = to; + while (lo < hi) { + int mid = (lo + hi) / 2; + if (sv[mid] < target) lo = mid + 1; + else hi = mid; + } + int mid = lo; + + int dist = 0; + int res = 0; + bool explore_more = true; + while (explore_more) { + explore_more = false; + vector candidates = {mid - dist, mid + dist}; + for (int i : candidates) { + if (fro < i && i <= to) { + int left = sv[i] - sv[fro]; + int right = sv[to] - sv[i]; + if (res / 2 <= left && left <= right) { + res = max(res, left + helper(sv, fro, i, memo)); + explore_more = true; + } + if (left >= right && right >= res / 2) { + res = max(res, right + helper(sv, i, to, memo)); + explore_more = true; + } + } + } + dist++; + } + memo[fro][to] = res; + return res; + } +}; diff --git a/tests/1501-2000/1563. stone-game-v/sol.cs b/tests/1501-2000/1563. stone-game-v/sol.cs new file mode 100644 index 00000000..b68dca29 --- /dev/null +++ b/tests/1501-2000/1563. stone-game-v/sol.cs @@ -0,0 +1,52 @@ +public class Solution { + public int StoneGameV(int[] stoneValue) { + int n = stoneValue.Length; + int[] sv = new int[n + 1]; + for (int i = 0; i < n; i++) sv[i + 1] = sv[i] + stoneValue[i]; + int[,] memo = new int[n + 1, n + 1]; + for (int i = 0; i <= n; i++) + for (int j = 0; j <= n; j++) + memo[i, j] = -1; + return Helper(sv, 0, n, memo); + } + + private int Helper(int[] sv, int fro, int to, int[,] memo) { + if (to - fro == 1) return 0; + if (memo[fro, to] != -1) return memo[fro, to]; + + int target = (sv[to] + sv[fro]) / 2; + int lo = fro, hi = to; + while (lo < hi) { + int mid = (lo + hi) / 2; + if (sv[mid] < target) lo = mid + 1; + else hi = mid; + } + int pivot = lo; + + int dist = 0; + int res = 0; + bool explore_more = true; + int maxDist = Math.Max(pivot - fro, to - pivot); + while (explore_more && dist <= maxDist) { + explore_more = false; + int[] candidates = {pivot - dist, pivot + dist}; + foreach (int i in candidates) { + if (fro < i && i <= to) { + int left = sv[i] - sv[fro]; + int right = sv[to] - sv[i]; + if (res / 2 <= left && left <= right) { + res = Math.Max(res, left + Helper(sv, fro, i, memo)); + explore_more = true; + } + if (left >= right && right >= res / 2) { + res = Math.Max(res, right + Helper(sv, i, to, memo)); + explore_more = true; + } + } + } + dist++; + } + memo[fro, to] = res; + return res; + } +} diff --git a/tests/1501-2000/1563. stone-game-v/sol.dart b/tests/1501-2000/1563. stone-game-v/sol.dart new file mode 100644 index 00000000..f07a4d6c --- /dev/null +++ b/tests/1501-2000/1563. stone-game-v/sol.dart @@ -0,0 +1,48 @@ +class Solution { + int stoneGameV(List stoneValue) { + int n = stoneValue.length; + List sv = List.filled(n + 1, 0); + for (int i = 0; i < n; i++) { + sv[i + 1] = sv[i] + stoneValue[i]; + } + List> memo = List.generate(n + 1, (_) => List.filled(n + 1, -1)); + return _helper(sv, 0, n, memo); + } + + int _helper(List sv, int fro, int to, List> memo) { + if (to - fro == 1) return 0; + if (memo[fro][to] != -1) return memo[fro][to]; + + int target = (sv[to] + sv[fro]) ~/ 2; + int lo = fro, hi = to; + while (lo < hi) { + int mid = (lo + hi) ~/ 2; + if (sv[mid] < target) lo = mid + 1; else hi = mid; + } + int mid = lo; + + int dist = 0; + int res = 0; + bool exploreMore = true; + while (exploreMore) { + exploreMore = false; + for (int i in [mid - dist, mid + dist]) { + if (fro < i && i <= to) { + int left = sv[i] - sv[fro]; + int right = sv[to] - sv[i]; + if (res ~/ 2 <= left && left <= right) { + res = res > left + _helper(sv, fro, i, memo) ? res : left + _helper(sv, fro, i, memo); + exploreMore = true; + } + if (left >= right && right >= res ~/ 2) { + res = res > right + _helper(sv, i, to, memo) ? res : right + _helper(sv, i, to, memo); + exploreMore = true; + } + } + } + dist++; + } + memo[fro][to] = res; + return res; + } +} diff --git a/tests/1501-2000/1563. stone-game-v/sol.go b/tests/1501-2000/1563. stone-game-v/sol.go new file mode 100644 index 00000000..c4218452 --- /dev/null +++ b/tests/1501-2000/1563. stone-game-v/sol.go @@ -0,0 +1,66 @@ +func stoneGameV(stoneValue []int) int { + n := len(stoneValue) + sv := make([]int, n+1) + for i := 0; i < n; i++ { + sv[i+1] = sv[i] + stoneValue[i] + } + memo := make([][]int, n+1) + for i := range memo { + memo[i] = make([]int, n+1) + for j := range memo[i] { + memo[i][j] = -1 + } + } + return helper(sv, 0, n, memo) +} + +func helper(sv []int, fro, to int, memo [][]int) int { + if to - fro == 1 { + return 0 + } + if memo[fro][to] != -1 { + return memo[fro][to] + } + + target := (sv[to] + sv[fro]) / 2 + lo, hi := fro, to + for lo < hi { + mid := (lo + hi) / 2 + if sv[mid] < target { + lo = mid + 1 + } else { + hi = mid + } + } + mid := lo + + dist := 0 + res := 0 + exploreMore := true + for exploreMore { + exploreMore = false + candidates := []int{mid - dist, mid + dist} + for _, i := range candidates { + if fro < i && i <= to { + left := sv[i] - sv[fro] + right := sv[to] - sv[i] + if res/2 <= left && left <= right { + res = max(res, left + helper(sv, fro, i, memo)) + exploreMore = true + } + if left >= right && right >= res/2 { + res = max(res, right + helper(sv, i, to, memo)) + exploreMore = true + } + } + } + dist++ + } + memo[fro][to] = res + return res +} + +func max(a, b int) int { + if a > b { return a } + return b +} diff --git a/tests/1501-2000/1563. stone-game-v/sol.java b/tests/1501-2000/1563. stone-game-v/sol.java new file mode 100644 index 00000000..fe52ccac --- /dev/null +++ b/tests/1501-2000/1563. stone-game-v/sol.java @@ -0,0 +1,51 @@ +class Solution { + public int stoneGameV(int[] stoneValue) { + int n = stoneValue.length; + int[] sv = new int[n + 1]; + for (int i = 0; i < n; i++) { + sv[i + 1] = sv[i] + stoneValue[i]; + } + int[][] memo = new int[n + 1][n + 1]; + for (int[] row : memo) java.util.Arrays.fill(row, -1); + return helper(sv, 0, n, memo); + } + + private int helper(int[] sv, int fro, int to, int[][] memo) { + if (to - fro == 1) return 0; + if (memo[fro][to] != -1) return memo[fro][to]; + + int target = (sv[to] + sv[fro]) / 2; + int lo = fro, hi = to; + while (lo < hi) { + int mid = (lo + hi) / 2; + if (sv[mid] < target) lo = mid + 1; + else hi = mid; + } + int mid = lo; + + int dist = 0; + int res = 0; + boolean explore_more = true; + while (explore_more) { + explore_more = false; + int[] candidates = {mid - dist, mid + dist}; + for (int i : candidates) { + if (fro < i && i <= to) { + int left = sv[i] - sv[fro]; + int right = sv[to] - sv[i]; + if (res / 2 <= left && left <= right) { + res = Math.max(res, left + helper(sv, fro, i, memo)); + explore_more = true; + } + if (left >= right && right >= res / 2) { + res = Math.max(res, right + helper(sv, i, to, memo)); + explore_more = true; + } + } + } + dist++; + } + memo[fro][to] = res; + return res; + } +} diff --git a/tests/1501-2000/1563. stone-game-v/sol.kt b/tests/1501-2000/1563. stone-game-v/sol.kt new file mode 100644 index 00000000..a8af7ffc --- /dev/null +++ b/tests/1501-2000/1563. stone-game-v/sol.kt @@ -0,0 +1,47 @@ +class Solution { + fun stoneGameV(stoneValue: IntArray): Int { + val n = stoneValue.size + val sv = IntArray(n + 1) + for (i in 0 until n) sv[i + 1] = sv[i] + stoneValue[i] + val memo = Array(n + 1) { IntArray(n + 1) { -1 } } + return helper(sv, 0, n, memo) + } + + private fun helper(sv: IntArray, fro: Int, to: Int, memo: Array): Int { + if (to - fro == 1) return 0 + if (memo[fro][to] != -1) return memo[fro][to] + + val target = (sv[to] + sv[fro]) / 2 + var lo = fro + var hi = to + while (lo < hi) { + val mid = (lo + hi) / 2 + if (sv[mid] < target) lo = mid + 1 else hi = mid + } + val mid = lo + + var dist = 0 + var res = 0 + var exploreMore = true + while (exploreMore) { + exploreMore = false + for (i in intArrayOf(mid - dist, mid + dist)) { + if (fro < i && i <= to) { + val left = sv[i] - sv[fro] + val right = sv[to] - sv[i] + if (res / 2 <= left && left <= right) { + res = maxOf(res, left + helper(sv, fro, i, memo)) + exploreMore = true + } + if (left >= right && right >= res / 2) { + res = maxOf(res, right + helper(sv, i, to, memo)) + exploreMore = true + } + } + } + dist++ + } + memo[fro][to] = res + return res + } +} diff --git a/tests/1501-2000/1563. stone-game-v/sol.py b/tests/1501-2000/1563. stone-game-v/sol.py new file mode 100644 index 00000000..e52cf1b2 --- /dev/null +++ b/tests/1501-2000/1563. stone-game-v/sol.py @@ -0,0 +1,34 @@ +from itertools import accumulate +from bisect import bisect_left +from functools import cache + + +class Solution: + def stoneGameV(self, stoneValue: List[int]) -> int: + + sv = [0, *accumulate(stoneValue)] + + @cache + def helper(fro, to): + if to - fro == 1: + return 0 + + mid = bisect_left(sv, (sv[to] + sv[fro]) // 2) + + dist = res = 0 + explore_more = True + while explore_more: + explore_more = False + for i in [mid - dist, mid + dist]: + if fro < i <= to: + left, right = sv[i] - sv[fro], sv[to] - sv[i] + if res // 2 <= left <= right: + res = max(res, left + helper(fro, i)) + explore_more = True + if left >= right >= res // 2: + res = max(res, right + helper(i, to)) + explore_more = True + dist += 1 + return res + + return helper(0, len(stoneValue)) diff --git a/tests/1501-2000/1563. stone-game-v/sol.py2 b/tests/1501-2000/1563. stone-game-v/sol.py2 new file mode 100644 index 00000000..e5318198 --- /dev/null +++ b/tests/1501-2000/1563. stone-game-v/sol.py2 @@ -0,0 +1,42 @@ +class Solution(object): + def stoneGameV(self, stoneValue): + """ + :type stoneValue: List[int] + :rtype: int + """ + from bisect import bisect_left + + sv = [0] + for value in stoneValue: + sv.append(sv[-1] + value) + + memo = {} + def helper(fro, to): + if to - fro == 1: + return 0 + key = (fro, to) + if key in memo: + return memo[key] + + mid = bisect_left(sv, (sv[to] + sv[fro]) // 2) + + dist = 0 + res = 0 + explore_more = True + while explore_more: + explore_more = False + for i in [mid - dist, mid + dist]: + if fro < i <= to: + left = sv[i] - sv[fro] + right = sv[to] - sv[i] + if res // 2 <= left <= right: + res = max(res, left + helper(fro, i)) + explore_more = True + if left >= right >= res // 2: + res = max(res, right + helper(i, to)) + explore_more = True + dist += 1 + memo[key] = res + return res + + return helper(0, len(stoneValue)) diff --git a/tests/1501-2000/1563. stone-game-v/sol.rb b/tests/1501-2000/1563. stone-game-v/sol.rb new file mode 100644 index 00000000..19c01bcd --- /dev/null +++ b/tests/1501-2000/1563. stone-game-v/sol.rb @@ -0,0 +1,41 @@ +# @param {Integer[]} stone_value +# @return {Integer} +def stone_game_v(stone_value) + sv = [0] + stone_value.reduce([]) { |acc, x| acc << (acc.empty? ? x : acc.last + x) } + memo = {} + + helper = lambda do |fro, to| + return 0 if to - fro == 1 + key = [fro, to] + return memo[key] if memo.key?(key) + + mid = sv.bsearch_index { |x| x >= (sv[to] + sv[fro]) / 2.0 } || to + mid = [mid, to].min + + dist = 0 + res = 0 + explore_more = true + while explore_more + explore_more = false + [mid - dist, mid + dist].each do |i| + if fro < i && i <= to + left = sv[i] - sv[fro] + right = sv[to] - sv[i] + if res / 2 <= left && left <= right + res = [res, left + helper.call(fro, i)].max + explore_more = true + end + if left >= right && right >= res / 2 + res = [res, right + helper.call(i, to)].max + explore_more = true + end + end + end + dist += 1 + end + memo[key] = res + res + end + + helper.call(0, stone_value.length) +end diff --git a/tests/1501-2000/1563. stone-game-v/sol.rs b/tests/1501-2000/1563. stone-game-v/sol.rs new file mode 100644 index 00000000..b6dfa7c6 --- /dev/null +++ b/tests/1501-2000/1563. stone-game-v/sol.rs @@ -0,0 +1,49 @@ +impl Solution { + pub fn stone_game_v(stone_value: Vec) -> i32 { + let n = stone_value.len(); + let mut sv = vec![0; n + 1]; + for i in 0..n { + sv[i + 1] = sv[i] + stone_value[i]; + } + let mut memo = vec![vec![-1; n + 1]; n + 1]; + Self::helper(&sv, 0, n, &mut memo) + } + + fn helper(sv: &Vec, fro: usize, to: usize, memo: &mut Vec>) -> i32 { + if to - fro == 1 { return 0; } + if memo[fro][to] != -1 { return memo[fro][to]; } + + let target = (sv[to] + sv[fro]) / 2; + let mut lo = fro; + let mut hi = to; + while lo < hi { + let mid = (lo + hi) / 2; + if sv[mid] < target { lo = mid + 1; } else { hi = mid; } + } + let mid = lo; + + let mut dist = 0; + let mut res = 0; + let mut explore_more = true; + while explore_more { + explore_more = false; + for i in [mid - dist, mid + dist] { + if fro < i && i <= to { + let left = sv[i] - sv[fro]; + let right = sv[to] - sv[i]; + if res / 2 <= left && left <= right { + res = res.max(left + Self::helper(sv, fro, i, memo)); + explore_more = true; + } + if left >= right && right >= res / 2 { + res = res.max(right + Self::helper(sv, i, to, memo)); + explore_more = true; + } + } + } + dist += 1; + } + memo[fro][to] = res; + res + } +} diff --git a/tests/1501-2000/1563. stone-game-v/sol.swift b/tests/1501-2000/1563. stone-game-v/sol.swift new file mode 100644 index 00000000..2841f754 --- /dev/null +++ b/tests/1501-2000/1563. stone-game-v/sol.swift @@ -0,0 +1,49 @@ +class Solution { + func stoneGameV(_ stoneValue: [Int]) -> Int { + let n = stoneValue.count + var sv = [Int](repeating: 0, count: n + 1) + for i in 0.. Int { + if to - fro == 1 { return 0 } + if memo[fro][to] != -1 { return memo[fro][to] } + + let target = (sv[to] + sv[fro]) / 2 + var lo = fro, hi = to + while lo < hi { + let mid = (lo + hi) / 2 + if sv[mid] < target { lo = mid + 1 } else { hi = mid } + } + let pivot = lo + + var dist = 0 + var res = 0 + var exploreMore = true + let maxDist = max(pivot - fro, to - pivot) + while exploreMore && dist <= maxDist { + exploreMore = false + for i in [pivot - dist, pivot + dist] { + if fro < i && i <= to { + let left = sv[i] - sv[fro] + let right = sv[to] - sv[i] + if res / 2 <= left && left <= right { + res = max(res, left + helper(sv, fro, i, &memo)) + exploreMore = true + } + if left >= right && right >= res / 2 { + res = max(res, right + helper(sv, i, to, &memo)) + exploreMore = true + } + } + } + dist += 1 + } + memo[fro][to] = res + return res + } +} diff --git a/tests/1501-2000/1563. stone-game-v/sol.ts b/tests/1501-2000/1563. stone-game-v/sol.ts new file mode 100644 index 00000000..84d110d9 --- /dev/null +++ b/tests/1501-2000/1563. stone-game-v/sol.ts @@ -0,0 +1,51 @@ +function stoneGameV(stoneValue: number[]): number { + const n = stoneValue.length; + const sv: number[] = new Array(n + 1).fill(0); + for (let i = 0; i < n; i++) sv[i + 1] = sv[i] + stoneValue[i]; + + const memo: number[][] = Array.from({ length: n + 1 }, () => + new Array(n + 1).fill(-1), + ); + + function helper(fro: number, to: number): number { + if (to - fro === 1) return 0; + if (memo[fro][to] !== -1) return memo[fro][to]; + + const target = Math.floor((sv[to] + sv[fro]) / 2); + let lo = fro, + hi = to; + while (lo < hi) { + const mid = Math.floor((lo + hi) / 2); + if (sv[mid] < target) lo = mid + 1; + else hi = mid; + } + const pivot = lo; + + let dist = 0; + let res = 0; + let exploreMore = true; + const maxDist = Math.max(pivot - fro, to - pivot); + while (exploreMore && dist <= maxDist) { + exploreMore = false; + for (const i of [pivot - dist, pivot + dist]) { + if (fro < i && i <= to) { + const left = sv[i] - sv[fro]; + const right = sv[to] - sv[i]; + if (Math.floor(res / 2) <= left && left <= right) { + res = Math.max(res, left + helper(fro, i)); + exploreMore = true; + } + if (left >= right && right >= Math.floor(res / 2)) { + res = Math.max(res, right + helper(i, to)); + exploreMore = true; + } + } + } + dist += 1; + } + memo[fro][to] = res; + return res; + } + + return helper(0, n); +} diff --git a/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/manifest.yaml b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/manifest.yaml new file mode 100644 index 00000000..91f4f4a0 --- /dev/null +++ b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/manifest.yaml @@ -0,0 +1,354 @@ +entry: + id: 1566 + title: "detect-pattern-of-length-m-repeated-k-or-more-times" + params: + arr: + type: array + items: + type: int + m: + type: int + k: + type: int + call: + cpp: "Solution().containsPattern({arr}, {m}, {k})" + rust: "Solution::contains_pattern({arr}, {m}, {k})" + python3: "Solution().containsPattern({arr}, {m}, {k})" + python2: "Solution().containsPattern({arr}, {m}, {k})" + ruby: "contains_pattern({arr}, {m}, {k})" + java: "new Solution().containsPattern({arr}, {m}, {k})" + csharp: "new Solution().ContainsPattern({arr}, {m}, {k})" + kotlin: "Solution().containsPattern({arr}, {m}, {k})" + go: "containsPattern({arr}, {m}, {k})" + dart: "Solution().containsPattern({arr}, {m}, {k})" + swift: "Solution().containsPattern({arr}, {m}, {k})" + typescript: "containsPattern({arr}, {m}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().containsPattern(arr, m, k, {result})" + checker: | + class Checker: + def containsPattern(self, arr, m, k, result): + expected = False + for start in range(len(arr) - m * k + 1): + ok = True + for offset in range(m * (k - 1)): + if arr[start + offset] != arr[start + offset + m]: + ok = False + break + if ok: + expected = True + break + return result is expected + +seed: 1566 + +tests: + - name: example-one + in: + arr: [1, 2, 4, 4, 4, 4] + m: 1 + k: 3 + out: true + - name: example-two + in: + arr: [1, 2, 1, 2, 1, 1, 1, 3] + m: 2 + k: 2 + out: true + - name: example-three + in: + arr: [1, 2, 1, 2, 1, 3] + m: 2 + k: 3 + out: false + - name: minimum-length-positive + in: + arr: [1, 1] + m: 1 + k: 2 + out: true + - name: minimum-length-negative + in: + arr: [1, 2] + m: 1 + k: 2 + out: false + - name: whole-array-repeat + in: + arr: [7, 8, 7, 8] + m: 2 + k: 2 + out: true + - name: whole-array-not-repeat + in: + arr: [7, 8, 8, 7] + m: 2 + k: 2 + out: false + - name: single-value-four + in: + arr: [5, 5, 5, 5, 5, 5] + m: 1 + k: 6 + out: true + - name: single-value-insufficient + in: + arr: [5, 5, 5, 5, 5] + m: 1 + k: 6 + out: false + - name: repeated-middle + in: + arr: [9, 3, 4, 3, 4, 3, 4, 8] + m: 2 + k: 3 + out: true + - name: repeated-prefix + in: + arr: [2, 3, 2, 3, 2, 3, 9] + m: 2 + k: 3 + out: true + - name: repeated-suffix + in: + arr: [9, 2, 3, 2, 3, 2, 3] + m: 2 + k: 3 + out: true + - name: mismatch-last-block + in: + arr: [1, 2, 1, 2, 1, 3] + m: 2 + k: 3 + out: false + - name: overlapping-looking-not-enough + in: + arr: [1, 1, 2, 1, 1, 3] + m: 2 + k: 2 + out: false + - name: block-length-three + in: + arr: [1, 2, 3, 1, 2, 3, 1, 2, 3] + m: 3 + k: 3 + out: true + - name: block-length-three-mismatch + in: + arr: [1, 2, 3, 1, 2, 4, 1, 2, 3] + m: 3 + k: 3 + out: false + - name: duplicate-values-block + in: + arr: [2, 2, 1, 2, 2, 1, 2, 2, 1] + m: 3 + k: 3 + out: true + - name: high-values + in: + arr: [100, 99, 100, 99, 100, 99] + m: 2 + k: 3 + out: true + - name: high-values-mismatch + in: + arr: [100, 99, 100, 98, 100, 99] + m: 2 + k: 3 + out: false + - name: m-larger-than-array + in: + arr: [1, 2, 3, 4] + m: 5 + k: 2 + out: false + - name: k-larger-than-array + in: + arr: [1, 1, 1, 1] + m: 1 + k: 5 + out: false + - name: exact-fit-three + in: + arr: [4, 5, 6, 4, 5, 6] + m: 3 + k: 2 + out: true + - name: exact-fit-false + in: + arr: [4, 5, 6, 4, 5, 7] + m: 3 + k: 2 + out: false + - name: later-valid-pattern + in: + arr: [1, 2, 3, 4, 8, 9, 8, 9, 8, 9] + m: 2 + k: 3 + out: true + - name: early-near-match-later-valid + in: + arr: [1, 2, 1, 3, 6, 7, 6, 7] + m: 2 + k: 2 + out: true + - name: all-distinct + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8] + m: 1 + k: 2 + out: false + - name: alternating-single + in: + arr: [1, 2, 1, 2, 1, 2, 1, 2] + m: 1 + k: 2 + out: false + - name: alternating-pair + in: + arr: [1, 2, 1, 2, 1, 2, 1, 2] + m: 2 + k: 4 + out: true + - name: constant-pair + in: + arr: [3, 3, 3, 3, 3, 3, 3, 3] + m: 2 + k: 4 + out: true + - name: constant-triple + in: + arr: [3, 3, 3, 3, 3, 3, 3, 3] + m: 3 + k: 2 + out: true + - name: mixed-duplicate-no-pattern + in: + arr: [1, 1, 2, 2, 1, 1, 2, 3] + m: 2 + k: 3 + out: false + - name: pattern-after-noise + in: + arr: [8, 7, 6, 2, 4, 2, 4, 2, 4, 5] + m: 2 + k: 3 + out: true + - name: one-repeat-only + in: + arr: [1, 2, 1, 2, 3, 4] + m: 2 + k: 3 + out: false + - name: m-one-run-at-end + in: + arr: [1, 2, 3, 4, 4, 4, 4] + m: 1 + k: 4 + out: true + - name: m-one-run-below-k + in: + arr: [1, 2, 3, 4, 4, 4, 2] + m: 1 + k: 4 + out: false + - name: generator-constant + in: + arr: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 1 + elemType: "int" + m: + gen: "int" + min: 1 + max: 10 + k: + gen: "int" + min: 2 + max: 5 + - name: generator-binary + in: + arr: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 2 + elemType: "int" + m: + gen: "int" + min: 1 + max: 10 + k: + gen: "int" + min: 2 + max: 5 + - name: generator-small-values + in: + arr: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 5 + elemType: "int" + m: + gen: "int" + min: 1 + max: 10 + k: + gen: "int" + min: 2 + max: 5 + - name: generator-wide-values + in: + arr: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + m: + gen: "int" + min: 1 + max: 10 + k: + gen: "int" + min: 2 + max: 5 + - name: generator-long-periodic-domain + in: + arr: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 10 + elemType: "int" + m: + gen: "int" + min: 1 + max: 10 + k: + gen: "int" + min: 2 + max: 5 diff --git a/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.cpp b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.cpp new file mode 100644 index 00000000..02edd4f8 --- /dev/null +++ b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + bool containsPattern(vector& arr, int m, int k) { + for (int i = 0; i <= (int)arr.size() - m * k; i++) { + bool match = true; + for (int j = 0; j < m * (k - 1); j++) { + if (arr[i + j] != arr[i + j + m]) { + match = false; + break; + } + } + if (match) return true; + } + return false; + } +}; diff --git a/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.cs b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.cs new file mode 100644 index 00000000..8550ebcb --- /dev/null +++ b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public bool ContainsPattern(int[] arr, int m, int k) { + for (int i = 0; i <= arr.Length - m * k; i++) { + bool match = true; + for (int j = 0; j < m * (k - 1); j++) { + if (arr[i + j] != arr[i + j + m]) { + match = false; + break; + } + } + if (match) return true; + } + return false; + } +} diff --git a/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.dart b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.dart new file mode 100644 index 00000000..9f2300fd --- /dev/null +++ b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.dart @@ -0,0 +1,15 @@ +class Solution { + bool containsPattern(List arr, int m, int k) { + for (int i = 0; i <= arr.length - m * k; i++) { + bool match = true; + for (int j = 0; j < m * (k - 1); j++) { + if (arr[i + j] != arr[i + j + m]) { + match = false; + break; + } + } + if (match) return true; + } + return false; + } +} diff --git a/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.go b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.go new file mode 100644 index 00000000..983f1a86 --- /dev/null +++ b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.go @@ -0,0 +1,15 @@ +func containsPattern(arr []int, m int, k int) bool { + for i := 0; i <= len(arr) - m*k; i++ { + match := true + for j := 0; j < m*(k-1); j++ { + if arr[i+j] != arr[i+j+m] { + match = false + break + } + } + if match { + return true + } + } + return false +} diff --git a/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.java b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.java new file mode 100644 index 00000000..9b2386c7 --- /dev/null +++ b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.java @@ -0,0 +1,15 @@ +class Solution { + public boolean containsPattern(int[] arr, int m, int k) { + for (int i = 0; i <= arr.length - m * k; i++) { + boolean match = true; + for (int j = 0; j < m * (k - 1); j++) { + if (arr[i + j] != arr[i + j + m]) { + match = false; + break; + } + } + if (match) return true; + } + return false; + } +} diff --git a/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.kt b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.kt new file mode 100644 index 00000000..88b79910 --- /dev/null +++ b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun containsPattern(arr: IntArray, m: Int, k: Int): Boolean { + for (i in 0..arr.size - m * k) { + var match = true + for (j in 0 until m * (k - 1)) { + if (arr[i + j] != arr[i + j + m]) { + match = false + break + } + } + if (match) return true + } + return false + } +} diff --git a/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.py b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.py new file mode 100644 index 00000000..85bac61a --- /dev/null +++ b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.py @@ -0,0 +1,12 @@ +# Python version (for reference) +class Solution: + def containsPattern(self, arr, m, k): + for i in range(len(arr) - m * k + 1): + match = True + for j in range(m * (k - 1)): + if arr[i + j] != arr[i + j + m]: + match = False + break + if match: + return True + return False diff --git a/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.py2 b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.py2 new file mode 100644 index 00000000..22b06ab8 --- /dev/null +++ b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.py2 @@ -0,0 +1,17 @@ +class Solution(object): + def containsPattern(self, arr, m, k): + """ + :type arr: List[int] + :type m: int + :type k: int + :rtype: bool + """ + for i in range(len(arr) - m * k + 1): + match = True + for j in range(m * (k - 1)): + if arr[i + j] != arr[i + j + m]: + match = False + break + if match: + return True + return False diff --git a/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.rb b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.rb new file mode 100644 index 00000000..236b3aa4 --- /dev/null +++ b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.rb @@ -0,0 +1,17 @@ +# @param {Integer[]} arr +# @param {Integer} m +# @param {Integer} k +# @return {Boolean} +def contains_pattern(arr, m, k) + (0..(arr.length - m * k)).each do |i| + match = true + (0...(m * (k - 1))).each do |j| + if arr[i + j] != arr[i + j + m] + match = false + break + end + end + return true if match + end + false +end diff --git a/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.rs b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.rs new file mode 100644 index 00000000..d8c1e9e4 --- /dev/null +++ b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.rs @@ -0,0 +1,22 @@ +impl Solution { + pub fn contains_pattern(arr: Vec, m: i32, k: i32) -> bool { + let m = m as usize; + let k = k as usize; + if m * k > arr.len() { + return false; + } + for i in 0..=arr.len() - m * k { + let mut match_found = true; + for j in 0..m * (k - 1) { + if arr[i + j] != arr[i + j + m] { + match_found = false; + break; + } + } + if match_found { + return true; + } + } + false + } +} diff --git a/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.swift b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.swift new file mode 100644 index 00000000..45403f10 --- /dev/null +++ b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func containsPattern(_ arr: [Int], _ m: Int, _ k: Int) -> Bool { + if m * k > arr.count { return false } + for i in 0...(arr.count - m * k) { + var match = true + for j in 0..<(m * (k - 1)) { + if arr[i + j] != arr[i + j + m] { + match = false + break + } + } + if match { return true } + } + return false + } +} diff --git a/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.ts b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.ts new file mode 100644 index 00000000..c6c6bd5d --- /dev/null +++ b/tests/1501-2000/1566. detect-pattern-of-length-m-repeated-k-or-more-times/sol.ts @@ -0,0 +1,13 @@ +function containsPattern(arr: number[], m: number, k: number): boolean { + for (let i = 0; i <= arr.length - m * k; i++) { + let match = true; + for (let j = 0; j < m * (k - 1); j++) { + if (arr[i + j] !== arr[i + j + m]) { + match = false; + break; + } + } + if (match) return true; + } + return false; +} diff --git a/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/manifest.yaml b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/manifest.yaml new file mode 100644 index 00000000..3fef7b9c --- /dev/null +++ b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/manifest.yaml @@ -0,0 +1,254 @@ +entry: + id: 1567 + title: "maximum-length-of-subarray-with-positive-product" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().getMaxLen({nums})" + rust: "Solution::get_max_len({nums})" + python3: "Solution().getMaxLen({nums})" + python2: "Solution().getMaxLen({nums})" + ruby: "get_max_len({nums})" + java: "new Solution().getMaxLen({nums})" + csharp: "new Solution().GetMaxLen({nums})" + kotlin: "Solution().getMaxLen({nums})" + go: "getMaxLen({nums})" + dart: "Solution().getMaxLen({nums})" + swift: "Solution().getMaxLen({nums})" + typescript: "getMaxLen({nums})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().getMaxLen(nums, {result})" + checker: | + class Checker: + def getMaxLen(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + pos = neg = best = 0 + for value in nums: + if value == 0: + pos = neg = 0 + elif value > 0: + pos += 1 + neg = neg + 1 if neg else 0 + else: + old_pos = pos + pos = neg + 1 if neg else 0 + neg = old_pos + 1 + best = max(best, pos) + return result == best + +seed: 1567 + +tests: + - name: example-all-positive + in: + nums: [1, -2, -3, 4] + out: 4 + - name: example-zero-prefix + in: + nums: [0, 1, -2, -3, -4] + out: 3 + - name: example-zero-suffix + in: + nums: [-1, -2, -3, 0, 1] + out: 2 + - name: one-positive + in: + nums: [7] + out: 1 + - name: one-negative + in: + nums: [-7] + out: 0 + - name: one-zero + in: + nums: [0] + out: 0 + - name: two-negative + in: + nums: [-1, -1] + out: 2 + - name: two-positive + in: + nums: [2, 3] + out: 2 + - name: positive-negative + in: + nums: [2, -3] + out: 1 + - name: negative-positive + in: + nums: [-3, 2] + out: 1 + - name: zero-separated-pair + in: + nums: [1, 0, -2, -4] + out: 2 + - name: odd-negatives-prefix-drop + in: + nums: [-1, 2, -3, 4, -5] + out: 4 + - name: odd-negatives-suffix-drop + in: + nums: [1, -2, 3, -4, 5, -6, 7] + out: 5 + - name: alternating-signs + in: + nums: [1, -1, 1, -1, 1, -1] + out: 5 + - name: alternating-start-negative + in: + nums: [-1, 1, -1, 1, -1, 1] + out: 5 + - name: zeros-between-runs + in: + nums: [-1, 0, 1, -1, 0, -1, -1, 0] + out: 2 + - name: all-negative-odd + in: + nums: [-1, -2, -3, -4, -5] + out: 4 + - name: all-negative-even + in: + nums: [-1, -2, -3, -4, -5, -6] + out: 6 + - name: all-zero + in: + nums: [0, 0, 0, 0] + out: 0 + - name: negative-zero-pair + in: + nums: [-4, 0, -8] + out: 0 + - name: mixed-short + in: + nums: [1, -2, 0, -3, 4, -5, -6] + out: 3 + - name: positives-around-odd-run + in: + nums: [2, -1, -2, -3, 4] + out: 3 + - name: negative-run-with-zero + in: + nums: [-1, -2, -3, 0, -4, -5] + out: 2 + - name: values-near-int-limit + in: + nums: [1000000000, -1000000000, -999999999, 1] + out: 4 + - name: minimum-values + in: + nums: [-1000000000, -1000000000, 0, -1000000000] + out: 2 + - name: long-positive-block + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + out: 10 + - name: long-odd-block + in: + nums: [-1, 2, 3, 4, -5, 6, 7, 8, 9] + out: 9 + - name: zero-at-each-boundary + in: + nums: [0, -1, -2, 0, 3, -4, -5, 0] + out: 3 + - name: best-middle-subarray + in: + nums: [-1, 0, 1, -2, -3, 4, 0, -5] + out: 4 + - name: repeated-negative-pairs + in: + nums: [-1, -1, 0, -2, -2, -2, -2, 0] + out: 4 + - name: isolated-negatives + in: + nums: [1, 1, -1, 1, 1, 0, 1, -1, 1] + out: 2 + - name: signed-values + in: + nums: [9, -8, -7, 6, -5, 4, -3, -2, 1] + out: 7 + - name: zero-after-even-run + in: + nums: [-2, 3, -4, 5, 0, -6, 7, -8] + out: 4 + - name: zero-before-even-run + in: + nums: [0, -2, 3, -4, 5, -6] + out: 4 + - name: all-positive-large-values + in: + nums: [1000000000, 999999999, 500000000, 1, 42] + out: 5 + - name: generated-small-mixed + in: + nums: + gen: "array" + len: 23 + of: + gen: "int" + min: -10 + max: 10 + distinct: false + sorted: false + elemType: "int" + - name: generated-medium-mixed + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: -1000000000 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + - name: generated-large-binary-signs + in: + nums: + gen: "array" + len: 10000 + of: + gen: "int" + min: -1 + max: 1 + distinct: false + sorted: false + elemType: "int" + - name: generated-near-limit-values + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: -1000000000 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + - name: generated-maximum-length + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: -1000000000 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.cpp b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.cpp new file mode 100644 index 00000000..09f5e710 --- /dev/null +++ b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int getMaxLen(vector& nums) { + int posLen = 0, negLen = 0, maxLen = 0; + for (int num : nums) { + if (num == 0) { + posLen = 0; + negLen = 0; + } else if (num > 0) { + posLen++; + negLen = negLen > 0 ? negLen + 1 : 0; + } else { + int temp = posLen; + posLen = negLen > 0 ? negLen + 1 : 0; + negLen = temp + 1; + } + maxLen = max(maxLen, posLen); + } + return maxLen; + } +}; diff --git a/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.cs b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.cs new file mode 100644 index 00000000..13e62a1c --- /dev/null +++ b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public int GetMaxLen(int[] nums) { + int posLen = 0, negLen = 0, maxLen = 0; + foreach (int num in nums) { + if (num == 0) { + posLen = 0; + negLen = 0; + } else if (num > 0) { + posLen++; + negLen = negLen > 0 ? negLen + 1 : 0; + } else { + int temp = posLen; + posLen = negLen > 0 ? negLen + 1 : 0; + negLen = temp + 1; + } + maxLen = Math.Max(maxLen, posLen); + } + return maxLen; + } +} diff --git a/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.dart b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.dart new file mode 100644 index 00000000..e68255b5 --- /dev/null +++ b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.dart @@ -0,0 +1,20 @@ +class Solution { + int getMaxLen(List nums) { + int posLen = 0, negLen = 0, maxLen = 0; + for (int num in nums) { + if (num == 0) { + posLen = 0; + negLen = 0; + } else if (num > 0) { + posLen++; + negLen = negLen > 0 ? negLen + 1 : 0; + } else { + int temp = posLen; + posLen = negLen > 0 ? negLen + 1 : 0; + negLen = temp + 1; + } + if (posLen > maxLen) maxLen = posLen; + } + return maxLen; + } +} diff --git a/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.go b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.go new file mode 100644 index 00000000..7822ec29 --- /dev/null +++ b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.go @@ -0,0 +1,28 @@ +func getMaxLen(nums []int) int { + posLen, negLen, maxLen := 0, 0, 0 + for _, num := range nums { + if num == 0 { + posLen = 0 + negLen = 0 + } else if num > 0 { + posLen++ + if negLen > 0 { + negLen++ + } else { + negLen = 0 + } + } else { + temp := posLen + if negLen > 0 { + posLen = negLen + 1 + } else { + posLen = 0 + } + negLen = temp + 1 + } + if posLen > maxLen { + maxLen = posLen + } + } + return maxLen +} diff --git a/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.java b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.java new file mode 100644 index 00000000..f95fe4b6 --- /dev/null +++ b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.java @@ -0,0 +1,22 @@ +class Solution { + public int getMaxLen(int[] nums) { + int posLen = 0, negLen = 0, maxLen = 0; + for (int num : nums) { + if (num == 0) { + posLen = 0; + negLen = 0; + } else if (num > 0) { + posLen++; + if (negLen > 0) negLen++; + else negLen = 0; + } else { + int temp = posLen; + if (negLen > 0) posLen = negLen + 1; + else posLen = 0; + negLen = temp + 1; + } + maxLen = Math.max(maxLen, posLen); + } + return maxLen; + } +} diff --git a/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.kt b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.kt new file mode 100644 index 00000000..e10e2ff4 --- /dev/null +++ b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.kt @@ -0,0 +1,26 @@ +class Solution { + fun getMaxLen(nums: IntArray): Int { + var posLen = 0 + var negLen = 0 + var maxLen = 0 + for (num in nums) { + when { + num == 0 -> { + posLen = 0 + negLen = 0 + } + num > 0 -> { + posLen++ + negLen = if (negLen > 0) negLen + 1 else 0 + } + else -> { + val temp = posLen + posLen = if (negLen > 0) negLen + 1 else 0 + negLen = temp + 1 + } + } + maxLen = maxOf(maxLen, posLen) + } + return maxLen + } +} diff --git a/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.py b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.py new file mode 100644 index 00000000..836e776a --- /dev/null +++ b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.py @@ -0,0 +1,16 @@ +class Solution: + def getMaxLen(self, nums: List[int]) -> int: + pos_len = neg_len = max_len = 0 + for num in nums: + if num == 0: + pos_len = 0 + neg_len = 0 + elif num > 0: + pos_len += 1 + neg_len = neg_len + 1 if neg_len > 0 else 0 + else: + temp = pos_len + pos_len = neg_len + 1 if neg_len > 0 else 0 + neg_len = temp + 1 + max_len = max(max_len, pos_len) + return max_len diff --git a/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.py2 b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.py2 new file mode 100644 index 00000000..e14e4688 --- /dev/null +++ b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def getMaxLen(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + pos_len = 0 + neg_len = 0 + max_len = 0 + for num in nums: + if num == 0: + pos_len = 0 + neg_len = 0 + elif num > 0: + pos_len += 1 + neg_len = neg_len + 1 if neg_len > 0 else 0 + else: + temp = pos_len + pos_len = neg_len + 1 if neg_len > 0 else 0 + neg_len = temp + 1 + max_len = max(max_len, pos_len) + return max_len diff --git a/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.rb b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.rb new file mode 100644 index 00000000..14492352 --- /dev/null +++ b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.rb @@ -0,0 +1,22 @@ +# @param {Integer[]} nums +# @return {Integer} +def get_max_len(nums) + pos_len = 0 + neg_len = 0 + max_len = 0 + nums.each do |num| + if num == 0 + pos_len = 0 + neg_len = 0 + elsif num > 0 + pos_len += 1 + neg_len = neg_len > 0 ? neg_len + 1 : 0 + else + temp = pos_len + pos_len = neg_len > 0 ? neg_len + 1 : 0 + neg_len = temp + 1 + end + max_len = [max_len, pos_len].max + end + max_len +end diff --git a/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.rs b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.rs new file mode 100644 index 00000000..3199b018 --- /dev/null +++ b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn get_max_len(nums: Vec) -> i32 { + let (mut pos_len, mut neg_len, mut max_len) = (0, 0, 0); + for &num in nums.iter() { + if num == 0 { + pos_len = 0; + neg_len = 0; + } else if num > 0 { + pos_len += 1; + neg_len = if neg_len > 0 { neg_len + 1 } else { 0 }; + } else { + let temp = pos_len; + pos_len = if neg_len > 0 { neg_len + 1 } else { 0 }; + neg_len = temp + 1; + } + max_len = max_len.max(pos_len); + } + max_len + } +} diff --git a/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.swift b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.swift new file mode 100644 index 00000000..695a8c47 --- /dev/null +++ b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func getMaxLen(_ nums: [Int]) -> Int { + var posLen = 0, negLen = 0, maxLen = 0 + for num in nums { + if num == 0 { + posLen = 0 + negLen = 0 + } else if num > 0 { + posLen += 1 + negLen = negLen > 0 ? negLen + 1 : 0 + } else { + let temp = posLen + posLen = negLen > 0 ? negLen + 1 : 0 + negLen = temp + 1 + } + maxLen = max(maxLen, posLen) + } + return maxLen + } +} diff --git a/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.ts b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.ts new file mode 100644 index 00000000..e114da34 --- /dev/null +++ b/tests/1501-2000/1567. maximum-length-of-subarray-with-positive-product/sol.ts @@ -0,0 +1,20 @@ +function getMaxLen(nums: number[]): number { + let posLen = 0, + negLen = 0, + maxLen = 0; + for (const num of nums) { + if (num === 0) { + posLen = 0; + negLen = 0; + } else if (num > 0) { + posLen++; + negLen = negLen > 0 ? negLen + 1 : 0; + } else { + const temp = posLen; + posLen = negLen > 0 ? negLen + 1 : 0; + negLen = temp + 1; + } + maxLen = Math.max(maxLen, posLen); + } + return maxLen; +} diff --git a/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/manifest.yaml b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/manifest.yaml new file mode 100644 index 00000000..57271c00 --- /dev/null +++ b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/manifest.yaml @@ -0,0 +1,364 @@ +entry: + id: 1568 + title: "minimum-number-of-days-to-disconnect-island" + params: + grid: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().minDays({grid})" + rust: "Solution::min_days({grid})" + python3: "Solution().minDays({grid})" + python2: "Solution().minDays({grid})" + ruby: "min_days({grid})" + java: "new Solution().minDays({grid})" + csharp: "new Solution().MinDays({grid})" + kotlin: "Solution().minDays({grid})" + go: "minDays({grid})" + dart: "Solution().minDays({grid})" + swift: "Solution().minDays({grid})" + typescript: "minDays({grid})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minDays(grid, {result})" + checker: | + class Checker: + def minDays(self, grid, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + a = [row[:] for row in grid] + m, n = len(a), len(a[0]) + def islands(): + seen = set() + count = 0 + for r in range(m): + for c in range(n): + if a[r][c] == 1 and (r, c) not in seen: + count += 1 + stack = [(r, c)] + seen.add((r, c)) + while stack: + x, y = stack.pop() + for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)): + nx, ny = x + dx, y + dy + if 0 <= nx < m and 0 <= ny < n and a[nx][ny] == 1 and (nx, ny) not in seen: + seen.add((nx, ny)) + stack.append((nx, ny)) + return count + if islands() != 1: + expected = 0 + else: + expected = 2 + for r in range(m): + for c in range(n): + if a[r][c] == 1: + a[r][c] = 0 + if islands() != 1: + expected = 1 + a[r][c] = 1 + if expected == 1: + break + if expected == 1: + break + return result == expected + +seed: 1568 + +tests: + - name: example-block + in: + grid: + - [0, 1, 1, 0] + - [0, 1, 1, 0] + - [0, 0, 0, 0] + out: 2 + - name: two-horizontal + in: + grid: + - [1, 1] + out: 2 + - name: single-cell + in: + grid: + - [1] + out: 1 + - name: single-water + in: + grid: + - [0] + out: 0 + - name: separated-corners + in: + grid: + - [1, 0, 1] + out: 0 + - name: horizontal-three + in: + grid: + - [1, 1, 1] + out: 1 + - name: vertical-three + in: + grid: + - [1] + - [1] + - [1] + out: 1 + - name: full-two-by-two + in: + grid: + - [1, 1] + - [1, 1] + out: 2 + - name: line-with-gap + in: + grid: + - [1, 1, 0, 1] + out: 0 + - name: diagonal-pair + in: + grid: + - [1, 0] + - [0, 1] + out: 0 + - name: l-shape + in: + grid: + - [1, 0] + - [1, 1] + out: 1 + - name: l-shape-four + in: + grid: + - [1, 0] + - [1, 1] + - [0, 1] + out: 1 + - name: plus-shape + in: + grid: + - [0, 1, 0] + - [1, 1, 1] + - [0, 1, 0] + out: 1 + - name: hollow-ring + in: + grid: + - [1, 1, 1] + - [1, 0, 1] + - [1, 1, 1] + out: 2 + - name: two-by-three-full + in: + grid: + - [1, 1, 1] + - [1, 1, 1] + out: 2 + - name: two-by-three-split + in: + grid: + - [1, 1, 0] + - [0, 1, 1] + out: 1 + - name: two-islands + in: + grid: + - [1, 0, 0, 1] + - [1, 0, 0, 1] + out: 0 + - name: bridge-one + in: + grid: + - [1, 0, 1] + - [1, 1, 1] + out: 1 + - name: bridge-two + in: + grid: + - [1, 1, 0, 1, 1] + - [0, 1, 1, 1, 0] + out: 1 + - name: sparse-connected + in: + grid: + - [1, 1, 0, 0] + - [0, 1, 1, 0] + - [0, 0, 1, 1] + out: 1 + - name: sparse-disconnected + in: + grid: + - [1, 1, 0, 0] + - [0, 0, 0, 1] + - [1, 0, 0, 1] + out: 0 + - name: solid-three-by-three + in: + grid: + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + out: 2 + - name: cross-with-tail + in: + grid: + - [0, 1, 0, 0] + - [1, 1, 1, 0] + - [0, 1, 0, 1] + - [0, 0, 0, 1] + out: 0 + - name: two-components-large + in: + grid: + - [1, 1, 0, 0, 1] + - [1, 0, 0, 1, 1] + - [0, 0, 0, 0, 0] + out: 0 + - name: narrow-zigzag + in: + grid: + - [1, 1, 0] + - [0, 1, 1] + - [1, 0, 1] + out: 0 + - name: thick-zigzag + in: + grid: + - [1, 1, 0, 0] + - [0, 1, 1, 0] + - [0, 0, 1, 1] + - [0, 0, 0, 1] + out: 1 + - name: four-by-four-full + in: + grid: + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - [1, 1, 1, 1] + out: 2 + - name: four-by-four-ring + in: + grid: + - [1, 1, 1, 1] + - [1, 0, 0, 1] + - [1, 0, 0, 1] + - [1, 1, 1, 1] + out: 2 + - name: five-horizontal + in: + grid: + - [1, 1, 1, 1, 1] + out: 1 + - name: five-vertical + in: + grid: + - [1] + - [1] + - [1] + - [1] + - [1] + out: 1 + - name: isolated-middle + in: + grid: + - [0, 0, 0, 0, 0] + - [0, 1, 1, 1, 0] + - [0, 0, 0, 0, 0] + out: 1 + - name: disconnected-three + in: + grid: + - [1, 0, 1, 0, 1] + - [0, 0, 0, 0, 0] + out: 0 + - name: one-cell-neck + in: + grid: + - [1, 1, 0, 0] + - [1, 1, 1, 1] + - [0, 0, 1, 1] + out: 1 + - name: full-five-by-two + in: + grid: + - [1, 1] + - [1, 1] + - [1, 1] + - [1, 1] + - [1, 1] + out: 2 + - name: checkerboard + in: + grid: + - [1, 0, 1, 0] + - [0, 1, 0, 1] + - [1, 0, 1, 0] + - [0, 1, 0, 1] + out: 0 + - name: single-row-gap + in: + grid: + - [1, 1, 1, 0, 1, 1] + out: 0 + - name: winding-one-component + in: + grid: + - [1, 1, 1, 0] + - [0, 0, 1, 0] + - [0, 1, 1, 1] + - [0, 1, 0, 0] + out: 1 + - name: generated-square-stress + in: + grid: + gen: array + len: 30 + of: + gen: array + len: 30 + of: + gen: int + min: 0 + max: 1 + elemType: int + seed: 1568001 + - name: generated-rectangular-stress + in: + grid: + gen: array + len: 20 + of: + gen: array + len: 30 + of: + gen: int + min: 0 + max: 1 + elemType: int + seed: 1568002 + - name: generated-single-row-stress + in: + grid: + gen: array + len: 1 + of: + gen: array + len: 30 + of: + gen: int + min: 0 + max: 1 + elemType: int + seed: 1568003 diff --git a/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.cpp b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.cpp new file mode 100644 index 00000000..d2a2e84d --- /dev/null +++ b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + int minDays(vector>& grid) { + auto countIslands = [&]() { + int rows = grid.size(), cols = grid[0].size(); + vector> seen(rows, vector(cols, false)); + int islands = 0; + int dirs[4][2] = {{-1,0},{1,0},{0,-1},{0,1}}; + + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + if (grid[i][j] == 1 && !seen[i][j]) { + islands++; + stack> st; + st.push({i,j}); + seen[i][j] = true; + while (!st.empty()) { + auto [x,y] = st.top(); + st.pop(); + for (auto& d : dirs) { + int nx = x + d[0], ny = y + d[1]; + if (nx >= 0 && nx < rows && ny >= 0 && ny < cols && grid[nx][ny] == 1 && !seen[nx][ny]) { + seen[nx][ny] = true; + st.push({nx,ny}); + } + } + } + } + } + } + return islands; + }; + + if (countIslands() != 1) return 0; + + for (int i = 0; i < grid.size(); i++) { + for (int j = 0; j < grid[0].size(); j++) { + if (grid[i][j] == 1) { + grid[i][j] = 0; + if (countIslands() != 1) return 1; + grid[i][j] = 1; + } + } + } + return 2; + } +}; diff --git a/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.cs b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.cs new file mode 100644 index 00000000..eb88f9c2 --- /dev/null +++ b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.cs @@ -0,0 +1,45 @@ +public class Solution { + public int MinDays(int[][] grid) { + int CountIslands() { + int rows = grid.Length, cols = grid[0].Length; + bool[,] seen = new bool[rows, cols]; + int islands = 0; + int[,] dirs = {{-1,0},{1,0},{0,-1},{0,1}}; + + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + if (grid[i][j] == 1 && !seen[i,j]) { + islands++; + var stack = new Stack<(int,int)>(); + stack.Push((i,j)); + seen[i,j] = true; + while (stack.Count > 0) { + var (x,y) = stack.Pop(); + for (int d = 0; d < 4; d++) { + int nx = x + dirs[d,0], ny = y + dirs[d,1]; + if (nx >= 0 && nx < rows && ny >= 0 && ny < cols && grid[nx][ny] == 1 && !seen[nx,ny]) { + seen[nx,ny] = true; + stack.Push((nx,ny)); + } + } + } + } + } + } + return islands; + } + + if (CountIslands() != 1) return 0; + + for (int i = 0; i < grid.Length; i++) { + for (int j = 0; j < grid[0].Length; j++) { + if (grid[i][j] == 1) { + grid[i][j] = 0; + if (CountIslands() != 1) return 1; + grid[i][j] = 1; + } + } + } + return 2; + } +} diff --git a/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.dart b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.dart new file mode 100644 index 00000000..5b0137cd --- /dev/null +++ b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.dart @@ -0,0 +1,45 @@ +class Solution { + int minDays(List> grid) { + int countIslands() { + List> seen = List.generate( + grid.length, (_) => List.filled(grid[0].length, false)); + List> dirs = [[-1,0],[1,0],[0,-1],[0,1]]; + int islands = 0; + + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[0].length; j++) { + if (grid[i][j] == 1 && !seen[i][j]) { + islands++; + List> stack = [[i,j]]; + seen[i][j] = true; + while (stack.isNotEmpty) { + List cell = stack.removeLast(); + for (List d in dirs) { + int nx = cell[0] + d[0]; + int ny = cell[1] + d[1]; + if (nx >= 0 && nx < grid.length && ny >= 0 && ny < grid[0].length && grid[nx][ny] == 1 && !seen[nx][ny]) { + seen[nx][ny] = true; + stack.add([nx,ny]); + } + } + } + } + } + } + return islands; + } + + if (countIslands() != 1) return 0; + + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[0].length; j++) { + if (grid[i][j] == 1) { + grid[i][j] = 0; + if (countIslands() != 1) return 1; + grid[i][j] = 1; + } + } + } + return 2; + } +} diff --git a/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.go b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.go new file mode 100644 index 00000000..cbab80bc --- /dev/null +++ b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.go @@ -0,0 +1,49 @@ +func minDays(grid [][]int) int { + countIslands := func() int { + seen := make([][]bool, len(grid)) + for i := range seen { + seen[i] = make([]bool, len(grid[0])) + } + islands := 0 + dirs := [][]int{{-1,0},{1,0},{0,-1},{0,1}} + + for i := 0; i < len(grid); i++ { + for j := 0; j < len(grid[0]); j++ { + if grid[i][j] == 1 && !seen[i][j] { + islands++ + stack := [][]int{{i, j}} + seen[i][j] = true + for len(stack) > 0 { + cell := stack[len(stack)-1] + stack = stack[:len(stack)-1] + for _, d := range dirs { + nx, ny := cell[0]+d[0], cell[1]+d[1] + if nx >= 0 && nx < len(grid) && ny >= 0 && ny < len(grid[0]) && grid[nx][ny] == 1 && !seen[nx][ny] { + seen[nx][ny] = true + stack = append(stack, []int{nx, ny}) + } + } + } + } + } + } + return islands + } + + if countIslands() != 1 { + return 0 + } + + for i := 0; i < len(grid); i++ { + for j := 0; j < len(grid[0]); j++ { + if grid[i][j] == 1 { + grid[i][j] = 0 + if countIslands() != 1 { + return 1 + } + grid[i][j] = 1 + } + } + } + return 2 +} diff --git a/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.java b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.java new file mode 100644 index 00000000..f019a0a0 --- /dev/null +++ b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.java @@ -0,0 +1,48 @@ +class Solution { + public int minDays(int[][] grid) { + if (countIslands(grid) != 1) return 0; + + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[0].length; j++) { + if (grid[i][j] == 1) { + grid[i][j] = 0; + if (countIslands(grid) != 1) return 1; + grid[i][j] = 1; + } + } + } + return 2; + } + + private int countIslands(int[][] grid) { + boolean[][] seen = new boolean[grid.length][grid[0].length]; + int islands = 0; + + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[0].length; j++) { + if (grid[i][j] == 1 && !seen[i][j]) { + islands++; + dfs(grid, i, j, seen); + } + } + } + return islands; + } + + private void dfs(int[][] grid, int r, int c, boolean[][] seen) { + int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}}; + java.util.Stack stack = new java.util.Stack<>(); + stack.push(new int[]{r, c}); + while (!stack.isEmpty()) { + int[] cell = stack.pop(); + int x = cell[0], y = cell[1]; + for (int[] d : dirs) { + int nx = x + d[0], ny = y + d[1]; + if (nx >= 0 && nx < grid.length && ny >= 0 && ny < grid[0].length && grid[nx][ny] == 1 && !seen[nx][ny]) { + seen[nx][ny] = true; + stack.push(new int[]{nx, ny}); + } + } + } + } +} diff --git a/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.kt b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.kt new file mode 100644 index 00000000..5cc06e11 --- /dev/null +++ b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.kt @@ -0,0 +1,45 @@ +class Solution { + fun minDays(grid: Array): Int { + fun countIslands(): Int { + val seen = Array(grid.size) { BooleanArray(grid[0].size) } + var islands = 0 + val dirs = arrayOf(intArrayOf(-1,0), intArrayOf(1,0), intArrayOf(0,-1), intArrayOf(0,1)) + + for (i in grid.indices) { + for (j in grid[0].indices) { + if (grid[i][j] == 1 && !seen[i][j]) { + islands++ + val stack = java.util.ArrayDeque() + stack.push(intArrayOf(i, j)) + seen[i][j] = true + while (stack.isNotEmpty()) { + val cell = stack.pop() + for (d in dirs) { + val nx = cell[0] + d[0] + val ny = cell[1] + d[1] + if (nx in grid.indices && ny in grid[0].indices && grid[nx][ny] == 1 && !seen[nx][ny]) { + seen[nx][ny] = true + stack.push(intArrayOf(nx, ny)) + } + } + } + } + } + } + return islands + } + + if (countIslands() != 1) return 0 + + for (i in grid.indices) { + for (j in grid[0].indices) { + if (grid[i][j] == 1) { + grid[i][j] = 0 + if (countIslands() != 1) return 1 + grid[i][j] = 1 + } + } + } + return 2 + } +} diff --git a/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.py b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.py new file mode 100644 index 00000000..b6e9b818 --- /dev/null +++ b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.py @@ -0,0 +1,40 @@ +class Solution: + def minDays(self, grid: List[List[int]]) -> int: + def count_islands(): + seen = set() + + def dfs(r, c): + stack = [(r, c)] + while stack: + x, y = stack.pop() + for nx, ny in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]: + if ( + 0 <= nx < len(grid) + and 0 <= ny < len(grid[0]) + and grid[nx][ny] == 1 + and (nx, ny) not in seen + ): + seen.add((nx, ny)) + stack.append((nx, ny)) + + islands = 0 + for i in range(len(grid)): + for j in range(len(grid[0])): + if grid[i][j] == 1 and (i, j) not in seen: + islands += 1 + seen.add((i, j)) + dfs(i, j) + return islands + + if count_islands() != 1: + return 0 + + for i in range(len(grid)): + for j in range(len(grid[0])): + if grid[i][j] == 1: + grid[i][j] = 0 + if count_islands() != 1: + return 1 + grid[i][j] = 1 + + return 2 diff --git a/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.py2 b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.py2 new file mode 100644 index 00000000..546cc8b2 --- /dev/null +++ b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.py2 @@ -0,0 +1,39 @@ +class Solution(object): + def minDays(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + def count_islands(): + seen = set() + + def dfs(r, c): + stack = [(r, c)] + while stack: + x, y = stack.pop() + for nx, ny in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]: + if 0 <= nx < len(grid) and 0 <= ny < len(grid[0]) and grid[nx][ny] == 1 and (nx, ny) not in seen: + seen.add((nx, ny)) + stack.append((nx, ny)) + + islands = 0 + for i in range(len(grid)): + for j in range(len(grid[0])): + if grid[i][j] == 1 and (i, j) not in seen: + islands += 1 + seen.add((i, j)) + dfs(i, j) + return islands + + if count_islands() != 1: + return 0 + + for i in range(len(grid)): + for j in range(len(grid[0])): + if grid[i][j] == 1: + grid[i][j] = 0 + if count_islands() != 1: + return 1 + grid[i][j] = 1 + + return 2 diff --git a/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.rb b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.rb new file mode 100644 index 00000000..3862053c --- /dev/null +++ b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.rb @@ -0,0 +1,45 @@ +# @param {Integer[][]} grid +# @return {Integer} +def min_days(grid) + count_islands = lambda do + seen = Set.new + dfs = lambda do |r, c| + stack = [[r, c]] + while !stack.empty? + x, y = stack.pop + [[x-1, y], [x+1, y], [x, y-1], [x, y+1]].each do |nx, ny| + if nx >= 0 && nx < grid.length && ny >= 0 && ny < grid[0].length && grid[nx][ny] == 1 && !seen.include?([nx, ny]) + seen.add([nx, ny]) + stack << [nx, ny] + end + end + end + end + + islands = 0 + (0...grid.length).each do |i| + (0...grid[0].length).each do |j| + if grid[i][j] == 1 && !seen.include?([i, j]) + islands += 1 + seen.add([i, j]) + dfs.call(i, j) + end + end + end + islands + end + + return 0 if count_islands.call != 1 + + (0...grid.length).each do |i| + (0...grid[0].length).each do |j| + if grid[i][j] == 1 + grid[i][j] = 0 + return 1 if count_islands.call != 1 + grid[i][j] = 1 + end + end + end + + 2 +end diff --git a/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.rs b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.rs new file mode 100644 index 00000000..d3bb6e89 --- /dev/null +++ b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.rs @@ -0,0 +1,51 @@ +impl Solution { + pub fn min_days(grid: Vec>) -> i32 { + let mut grid = grid; + let dirs = [(-1,0),(1,0),(0,-1),(0,1)]; + + fn count_islands(grid: &Vec>, dirs: &[(i32,i32)]) -> i32 { + let rows = grid.len(); + let cols = grid[0].len(); + let mut seen = vec![vec![false; cols]; rows]; + let mut islands = 0; + + for i in 0..rows { + for j in 0..cols { + if grid[i][j] == 1 && !seen[i][j] { + islands += 1; + let mut stack = vec![(i as i32, j as i32)]; + seen[i][j] = true; + while let Some((x,y)) = stack.pop() { + for &(dx,dy) in dirs { + let nx = x + dx; + let ny = y + dy; + if nx >= 0 && nx < rows as i32 && ny >= 0 && ny < cols as i32 && grid[nx as usize][ny as usize] == 1 && !seen[nx as usize][ny as usize] { + seen[nx as usize][ny as usize] = true; + stack.push((nx,ny)); + } + } + } + } + } + } + islands + } + + if count_islands(&grid, &dirs) != 1 { + return 0; + } + + for i in 0..grid.len() { + for j in 0..grid[0].len() { + if grid[i][j] == 1 { + grid[i][j] = 0; + if count_islands(&grid, &dirs) != 1 { + return 1; + } + grid[i][j] = 1; + } + } + } + 2 + } +} diff --git a/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.swift b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.swift new file mode 100644 index 00000000..7acc2992 --- /dev/null +++ b/tests/1501-2000/1568. minimum-number-of-days-to-disconnect-island/sol.swift @@ -0,0 +1,50 @@ +class Solution { + func minDays(_ grid: [[Int]]) -> Int { + var grid = grid + let dirs = [(-1,0),(1,0),(0,-1),(0,1)] + + func countIslands() -> Int { + var seen = Set<[Int]>() + var islands = 0 + + for i in 0..= 0 && nx < grid.count && ny >= 0 && ny < grid[0].count && grid[nx][ny] == 1 && !seen.contains([nx,ny]) { + seen.insert([nx,ny]) + stack.append([nx,ny]) + } + } + } + } + } + } + return islands + } + + if countIslands() != 1 { + return 0 + } + + for i in 0.. { + const seen = new Set(); + let islands = 0; + const dirs = [ + [-1, 0], + [1, 0], + [0, -1], + [0, 1], + ]; + + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[0].length; j++) { + if (grid[i][j] === 1 && !seen.has(`${i},${j}`)) { + islands++; + const stack = [[i, j]]; + seen.add(`${i},${j}`); + while (stack.length > 0) { + const cell = stack.pop()!; + for (const d of dirs) { + const nx = cell[0] + d[0]; + const ny = cell[1] + d[1]; + if ( + nx >= 0 && + nx < grid.length && + ny >= 0 && + ny < grid[0].length && + grid[nx][ny] === 1 && + !seen.has(`${nx},${ny}`) + ) { + seen.add(`${nx},${ny}`); + stack.push([nx, ny]); + } + } + } + } + } + } + return islands; + }; + + if (countIslands() !== 1) return 0; + + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[0].length; j++) { + if (grid[i][j] === 1) { + grid[i][j] = 0; + if (countIslands() !== 1) return 1; + grid[i][j] = 1; + } + } + } + return 2; +} diff --git a/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/manifest.yaml b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/manifest.yaml new file mode 100644 index 00000000..809f706f --- /dev/null +++ b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/manifest.yaml @@ -0,0 +1,256 @@ +entry: + id: 1569 + title: "number-of-ways-to-reorder-array-to-get-same-bst" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().numOfWays({nums})" + rust: "Solution::num_of_ways({nums})" + python3: "Solution().numOfWays({nums})" + python2: "Solution().numOfWays({nums})" + ruby: "num_of_ways({nums})" + java: "new Solution().numOfWays({nums})" + csharp: "new Solution().NumOfWays({nums})" + kotlin: "Solution().numOfWays({nums})" + go: "numOfWays({nums})" + dart: "Solution().numOfWays({nums})" + swift: "Solution().numOfWays({nums})" + typescript: "numOfWays({nums})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().numOfWays(nums, {result})" + checker: | + class Checker: + def numOfWays(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + mod = 1000000007 + n = len(nums) + comb = [[0] * (n + 1) for _ in range(n + 1)] + for i in range(n + 1): + comb[i][0] = comb[i][i] = 1 + for j in range(1, i): + comb[i][j] = (comb[i - 1][j - 1] + comb[i - 1][j]) % mod + def ways(values): + if len(values) <= 2: + return 1 + root = values[0] + left = [x for x in values[1:] if x < root] + right = [x for x in values[1:] if x > root] + return comb[len(left) + len(right)][len(left)] * ways(left) % mod * ways(right) % mod + return result == (ways(nums) - 1) % mod + +seed: 1569 + +tests: + - name: single + in: + nums: [1] + out: 0 + - name: two-ascending + in: + nums: [1, 2] + out: 0 + - name: two-descending + in: + nums: [2, 1] + out: 0 + - name: ascending-three + in: + nums: [1, 2, 3] + out: 0 + - name: descending-three + in: + nums: [3, 2, 1] + out: 0 + - name: balanced-three + in: + nums: [2, 1, 3] + out: 1 + - name: balanced-three-reordered + in: + nums: [2, 3, 1] + out: 1 + - name: skewed-root + in: + nums: [3, 1, 2] + out: 0 + - name: left-chain-four + in: + nums: [4, 1, 2, 3] + out: 0 + - name: descending-four + in: + nums: [4, 3, 2, 1] + out: 0 + - name: two-balanced-subtrees + in: + nums: [2, 1, 4, 3] + out: 2 + - name: root-with-unbalanced-right + in: + nums: [3, 1, 2, 4] + out: 2 + - name: example-two-a + in: + nums: [3, 4, 1, 2, 5] + out: 5 + - name: example-two-b + in: + nums: [3, 4, 5, 1, 2] + out: 5 + - name: six-mixed + in: + nums: [4, 2, 1, 3, 6, 5] + out: 19 + - name: left-subtree-chain + in: + nums: [5, 3, 2, 1, 4] + out: 2 + - name: root-minimum + in: + nums: [5, 1, 2, 3, 4] + out: 0 + - name: two-independent-pairs + in: + nums: [1, 3, 2, 5, 4] + out: 2 + - name: five-mixed + in: + nums: [4, 1, 3, 2, 5] + out: 3 + - name: six-balanced-ish + in: + nums: [6, 3, 1, 2, 5, 4] + out: 5 + - name: six-root-middle + in: + nums: [6, 2, 1, 4, 3, 5] + out: 7 + - name: perfect-seven + in: + nums: [4, 2, 6, 1, 3, 5, 7] + out: 79 + - name: seven-right-chain + in: + nums: [4, 1, 2, 3, 5, 6, 7] + out: 19 + - name: perfect-seven-alternate + in: + nums: [4, 2, 1, 3, 6, 5, 7] + out: 79 + - name: two-balanced-levels + in: + nums: [5, 3, 1, 2, 4, 7, 6] + out: 44 + - name: seven-root-high + in: + nums: [7, 4, 2, 1, 3, 6, 5] + out: 19 + - name: perfect-eight + in: + nums: [8, 4, 2, 1, 3, 6, 5, 7] + out: 79 + - name: eight-mixed + in: + nums: [5, 2, 1, 4, 3, 8, 6, 7] + out: 104 + - name: nine-balanced + in: + nums: [6, 1, 3, 2, 5, 4, 8, 7, 9] + out: 335 + - name: ten-mixed + in: + nums: [7, 3, 1, 2, 5, 4, 6, 10, 8, 9] + out: 1679 + - name: ten-left-heavy + in: + nums: [5, 4, 3, 2, 1, 6, 7, 8, 9, 10] + out: 125 + - name: ten-left-heavy-root-six + in: + nums: [6, 5, 4, 3, 2, 1, 7, 8, 9, 10] + out: 125 + - name: ten-irregular + in: + nums: [8, 3, 1, 2, 6, 4, 5, 10, 9, 7] + out: 1619 + - name: ten-two-sided + in: + nums: [10, 5, 2, 1, 4, 3, 8, 7, 6, 9] + out: 629 + - name: ten-root-minimum + in: + nums: [10, 1, 2, 3, 4, 5, 6, 7, 8, 9] + out: 0 + - name: generated-small-permutation + in: + nums: + gen: "array" + len: 10 + of: + gen: "int" + min: 1 + max: 10 + distinct: true + sorted: false + elemType: "int" + - name: generated-medium-permutation + in: + nums: + gen: "array" + len: 50 + of: + gen: "int" + min: 1 + max: 50 + distinct: true + sorted: false + elemType: "int" + - name: generated-large-permutation + in: + nums: + gen: "array" + len: 200 + of: + gen: "int" + min: 1 + max: 200 + distinct: true + sorted: false + elemType: "int" + - name: generated-near-limit-permutation + in: + nums: + gen: "array" + len: 500 + of: + gen: "int" + min: 1 + max: 500 + distinct: true + sorted: false + elemType: "int" + - name: generated-limit-permutation + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000 + distinct: true + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.cpp b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.cpp new file mode 100644 index 00000000..1378be46 --- /dev/null +++ b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int numOfWays(vector& nums) { + const int MOD = 1000000007; + int n = nums.size(); + + vector> nCr(n+1, vector(n+1, 0)); + for (int i = 0; i <= n; i++) { + nCr[i][0] = nCr[i][i] = 1; + for (int j = 1; j < i; j++) { + nCr[i][j] = (nCr[i-1][j-1] + nCr[i-1][j]) % MOD; + } + } + + function&)> dfs = [&](vector& arr) -> long long { + if (arr.size() <= 2) return 1; + int root = arr[0]; + vector left, right; + for (int i = 1; i < arr.size(); i++) { + if (arr[i] < root) left.push_back(arr[i]); + else right.push_back(arr[i]); + } + long long leftWays = dfs(left); + long long rightWays = dfs(right); + int L = left.size(), R = right.size(); + return (nCr[L+R][L] * leftWays % MOD * rightWays) % MOD; + }; + + return (int)((dfs(nums) - 1 + MOD) % MOD); + } +}; diff --git a/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.cs b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.cs new file mode 100644 index 00000000..5a1a8a54 --- /dev/null +++ b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.cs @@ -0,0 +1,28 @@ +public class Solution { + public int NumOfWays(int[] nums) { + const int MOD = 1000000007; + int n = nums.Length; + + long[,] nCr = new long[n+1, n+1]; + for (int i = 0; i <= n; i++) { + nCr[i,0] = nCr[i,i] = 1; + for (int j = 1; j < i; j++) { + nCr[i,j] = (nCr[i-1,j-1] + nCr[i-1,j]) % MOD; + } + } + + Func dfs = null; + dfs = (arr) => { + if (arr.Length <= 2) return 1; + int root = arr[0]; + var left = arr.Skip(1).Where(x => x < root).ToArray(); + var right = arr.Skip(1).Where(x => x > root).ToArray(); + long leftWays = dfs(left); + long rightWays = dfs(right); + int L = left.Length, R = right.Length; + return (nCr[L+R, L] * leftWays % MOD * rightWays) % MOD; + }; + + return (int)((dfs(nums) - 1 + MOD) % MOD); + } +} diff --git a/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.dart b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.dart new file mode 100644 index 00000000..d367f454 --- /dev/null +++ b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.dart @@ -0,0 +1,28 @@ +class Solution { + int numOfWays(List nums) { + const MOD = 1000000007; + int n = nums.length; + + List> nCr = List.generate(n+1, (_) => List.filled(n+1, 0)); + for (int i = 0; i <= n; i++) { + nCr[i][0] = 1; + nCr[i][i] = 1; + for (int j = 1; j < i; j++) { + nCr[i][j] = (nCr[i-1][j-1] + nCr[i-1][j]) % MOD; + } + } + + int dfs(List arr) { + if (arr.length <= 2) return 1; + int root = arr[0]; + List left = arr.sublist(1).where((x) => x < root).toList(); + List right = arr.sublist(1).where((x) => x > root).toList(); + int leftWays = dfs(left); + int rightWays = dfs(right); + int L = left.length, R = right.length; + return (nCr[L+R][L] * leftWays % MOD * rightWays) % MOD; + } + + return (dfs(nums) - 1) % MOD; + } +} diff --git a/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.go b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.go new file mode 100644 index 00000000..a6a5f175 --- /dev/null +++ b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.go @@ -0,0 +1,37 @@ +func numOfWays(nums []int) int { + const MOD = 1000000007 + n := len(nums) + + nCr := make([][]int64, n+1) + for i := range nCr { + nCr[i] = make([]int64, n+1) + nCr[i][0] = 1 + nCr[i][i] = 1 + for j := 1; j < i; j++ { + nCr[i][j] = (nCr[i-1][j-1] + nCr[i-1][j]) % MOD + } + } + + var dfs func([]int) int64 + dfs = func(arr []int) int64 { + if len(arr) <= 2 { + return 1 + } + root := arr[0] + left := make([]int, 0) + right := make([]int, 0) + for _, x := range arr[1:] { + if x < root { + left = append(left, x) + } else { + right = append(right, x) + } + } + leftWays := dfs(left) + rightWays := dfs(right) + L, R := len(left), len(right) + return (nCr[L+R][L] * leftWays % MOD * rightWays) % MOD + } + + return int((dfs(nums) - 1) % MOD) +} diff --git a/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.java b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.java new file mode 100644 index 00000000..b1859f94 --- /dev/null +++ b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.java @@ -0,0 +1,27 @@ +class Solution { + public int numOfWays(int[] nums) { + final int MOD = 1000000007; + int n = nums.length; + + long[][] nCr = new long[n+1][n+1]; + for (int i = 0; i <= n; i++) { + nCr[i][0] = nCr[i][i] = 1; + for (int j = 1; j < i; j++) { + nCr[i][j] = (nCr[i-1][j-1] + nCr[i-1][j]) % MOD; + } + } + + return (int)((dfs(nums, nCr) - 1 + MOD) % MOD); + } + + private long dfs(int[] nums, long[][] nCr) { + if (nums.length <= 2) return 1; + int root = nums[0]; + int[] left = Arrays.stream(nums).skip(1).filter(x -> x < root).toArray(); + int[] right = Arrays.stream(nums).skip(1).filter(x -> x > root).toArray(); + long leftWays = dfs(left, nCr); + long rightWays = dfs(right, nCr); + int L = left.length, R = right.length; + return (nCr[L+R][L] * leftWays % 1000000007 * rightWays) % 1000000007; + } +} diff --git a/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.kt b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.kt new file mode 100644 index 00000000..660c216d --- /dev/null +++ b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.kt @@ -0,0 +1,29 @@ +class Solution { + fun numOfWays(nums: IntArray): Int { + val MOD = 1000000007 + val n = nums.size + + val nCr = Array(n+1) { LongArray(n+1) } + for (i in 0..n) { + nCr[i][0] = 1 + nCr[i][i] = 1 + for (j in 1 until i) { + nCr[i][j] = (nCr[i-1][j-1] + nCr[i-1][j]) % MOD + } + } + + fun dfs(arr: IntArray): Long { + if (arr.size <= 2) return 1 + val root = arr[0] + val left = arr.filter { it < root }.toIntArray() + val right = arr.filter { it > root }.toIntArray() + val leftWays = dfs(left) + val rightWays = dfs(right) + val L = left.size + val R = right.size + return (nCr[L+R][L] * leftWays % MOD * rightWays) % MOD + } + + return ((dfs(nums) - 1) % MOD).toInt() + } +} diff --git a/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.py b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.py new file mode 100644 index 00000000..dfa6de1a --- /dev/null +++ b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.py @@ -0,0 +1,27 @@ +class Solution: + def numOfWays(self, nums: List[int]) -> int: + MOD = 1000000007 + n = len(nums) + + # Precompute Pascal's triangle + nCr = [[0] * (n + 1) for _ in range(n + 1)] + for i in range(n + 1): + nCr[i][0] = nCr[i][i] = 1 + for j in range(1, i): + nCr[i][j] = (nCr[i - 1][j - 1] + nCr[i - 1][j]) % MOD + + def dfs(nums): + if len(nums) <= 2: + return 1 + + root = nums[0] + left = [x for x in nums[1:] if x < root] + right = [x for x in nums[1:] if x > root] + + left_ways = dfs(left) + right_ways = dfs(right) + L, R = len(left), len(right) + + return (nCr[L + R][L] * left_ways % MOD * right_ways) % MOD + + return (dfs(nums) - 1) % MOD diff --git a/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.py2 b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.py2 new file mode 100644 index 00000000..b9729287 --- /dev/null +++ b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.py2 @@ -0,0 +1,27 @@ +class Solution(object): + def numOfWays(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + MOD = 1000000007 + n = len(nums) + + nCr = [[0] * (n+1) for _ in range(n+1)] + for i in range(n+1): + nCr[i][0] = nCr[i][i] = 1 + for j in range(1, i): + nCr[i][j] = (nCr[i-1][j-1] + nCr[i-1][j]) % MOD + + def dfs(nums): + if len(nums) <= 2: + return 1 + root = nums[0] + left = [x for x in nums[1:] if x < root] + right = [x for x in nums[1:] if x > root] + left_ways = dfs(left) + right_ways = dfs(right) + L, R = len(left), len(right) + return (nCr[L+R][L] * left_ways % MOD * right_ways) % MOD + + return (dfs(nums) - 1) % MOD diff --git a/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.rb b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.rb new file mode 100644 index 00000000..46afc0cb --- /dev/null +++ b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.rb @@ -0,0 +1,27 @@ +# @param {Integer[]} nums +# @return {Integer} +def num_of_ways(nums) + mod = 1000000007 + n = nums.length + + ncr = Array.new(n+1) { Array.new(n+1, 0) } + (0..n).each do |i| + ncr[i][0] = ncr[i][i] = 1 + (1...i).each do |j| + ncr[i][j] = (ncr[i-1][j-1] + ncr[i-1][j]) % mod + end + end + + dfs = lambda do |arr| + return 1 if arr.length <= 2 + root = arr[0] + left = arr[1..].select { |x| x < root } + right = arr[1..].select { |x| x > root } + left_ways = dfs.call(left) + right_ways = dfs.call(right) + l, r = left.length, right.length + (ncr[l+r][l] * left_ways % mod * right_ways) % mod + end + + (dfs.call(nums) - 1) % mod +end diff --git a/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.rs b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.rs new file mode 100644 index 00000000..b6883c4d --- /dev/null +++ b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.rs @@ -0,0 +1,30 @@ +impl Solution { + pub fn num_of_ways(nums: Vec) -> i32 { + const MOD: i64 = 1000000007; + let n = nums.len(); + + let mut ncr = vec![vec![0i64; n+1]; n+1]; + for i in 0..=n { + ncr[i][0] = 1; + ncr[i][i] = 1; + for j in 1..i { + ncr[i][j] = (ncr[i-1][j-1] + ncr[i-1][j]) % MOD; + } + } + + fn dfs(nums: &[i32], ncr: &Vec>) -> i64 { + if nums.len() <= 2 { return 1; } + let root = nums[0]; + let left: Vec = nums[1..].iter().filter(|&&x| x < root).cloned().collect(); + let right: Vec = nums[1..].iter().filter(|&&x| x > root).cloned().collect(); + let left_ways = dfs(&left, ncr); + let right_ways = dfs(&right, ncr); + let l = left.len(); + let r = right.len(); + return (ncr[l+r][l] * left_ways % 1000000007 * right_ways) % 1000000007; + } + + let result = dfs(&nums, &ncr); + (((result - 1) % MOD + MOD) % MOD) as i32 + } +} diff --git a/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.swift b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.swift new file mode 100644 index 00000000..c0731518 --- /dev/null +++ b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.swift @@ -0,0 +1,30 @@ +class Solution { + func numOfWays(_ nums: [Int]) -> Int { + let MOD = 1000000007 + let n = nums.count + + var nCr = Array(repeating: Array(repeating: 0, count: n+1), count: n+1) + for i in 0...n { + nCr[i][0] = 1 + nCr[i][i] = 1 + if i > 0 { + for j in 1.. Int { + if arr.count <= 2 { return 1 } + let root = arr[0] + let left = arr.dropFirst().filter { $0 < root } + let right = arr.dropFirst().filter { $0 > root } + let leftWays = dfs(Array(left)) + let rightWays = dfs(Array(right)) + let L = left.count, R = right.count + return (nCr[L+R][L] * leftWays % MOD * rightWays) % MOD + } + + return (dfs(nums) - 1 + MOD) % MOD + } +} diff --git a/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.ts b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.ts new file mode 100644 index 00000000..a8d50251 --- /dev/null +++ b/tests/1501-2000/1569. number-of-ways-to-reorder-array-to-get-same-bst/sol.ts @@ -0,0 +1,28 @@ +function numOfWays(nums: number[]): number { + const MOD = 1000000007n; + const n = nums.length; + + const nCr: bigint[][] = Array.from({ length: n + 1 }, () => + new Array(n + 1).fill(0n), + ); + for (let i = 0; i <= n; i++) { + nCr[i][0] = nCr[i][i] = 1n; + for (let j = 1; j < i; j++) { + nCr[i][j] = (nCr[i - 1][j - 1] + nCr[i - 1][j]) % MOD; + } + } + + const dfs = (arr: number[]): bigint => { + if (arr.length <= 2) return 1n; + const root = arr[0]; + const left = arr.slice(1).filter((x) => x < root); + const right = arr.slice(1).filter((x) => x > root); + const leftWays = dfs(left); + const rightWays = dfs(right); + const L = left.length, + R = right.length; + return (((nCr[L + R][L] * leftWays) % MOD) * rightWays) % MOD; + }; + + return Number((dfs(nums) - 1n + MOD) % MOD); +} diff --git a/tests/1501-2000/1572. matrix-diagonal-sum/manifest.yaml b/tests/1501-2000/1572. matrix-diagonal-sum/manifest.yaml new file mode 100644 index 00000000..7f294575 --- /dev/null +++ b/tests/1501-2000/1572. matrix-diagonal-sum/manifest.yaml @@ -0,0 +1,893 @@ +entry: + id: 1572 + title: "matrix-diagonal-sum" + params: + mat: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().diagonalSum({mat})" + rust: "Solution::diagonal_sum({mat})" + python3: "Solution().diagonalSum({mat})" + python2: "Solution().diagonalSum({mat})" + ruby: "diagonal_sum({mat})" + java: "new Solution().diagonalSum({mat})" + csharp: "new Solution().DiagonalSum({mat})" + kotlin: "Solution().diagonalSum({mat})" + go: "diagonalSum({mat})" + dart: "Solution().diagonalSum({mat})" + swift: "Solution().diagonalSum({mat})" + typescript: "diagonalSum({mat})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().diagonalSum(mat, {result})" + checker: | + class Checker: + def diagonalSum(self, mat, result): + n = len(mat) + expected = sum(mat[i][i] + mat[i][n - 1 - i] for i in range(n)) + if n % 2 == 1: + expected -= mat[n // 2][n // 2] + return result == expected + +seed: 1572 + +tests: + - name: example-3x3 + in: + mat: + elemType: "int" + value: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + out: 25 + - name: example-4x4 + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - [1, 1, 1, 1] + out: 8 + - name: single-five + in: + mat: + elemType: "int" + value: + - [5] + out: 5 + - name: single-minimum + in: + mat: + elemType: "int" + value: + - [1] + out: 1 + - name: single-maximum + in: + mat: + elemType: "int" + value: + - [100] + out: 100 + - name: 2x2-minimum + in: + mat: + elemType: "int" + value: + - [1, 1] + - [1, 1] + out: 4 + - name: 2x2-maximum + in: + mat: + elemType: "int" + value: + - [100, 100] + - [100, 100] + out: 400 + - name: 2x2-asymmetric + in: + mat: + elemType: "int" + value: + - [1, 2] + - [3, 4] + out: 10 + - name: 3x3-center-counted-once + in: + mat: + elemType: "int" + value: + - [10, 20, 30] + - [40, 50, 60] + - [70, 80, 90] + out: 250 + - name: 3x3-corners + in: + mat: + elemType: "int" + value: + - [100, 1, 100] + - [1, 1, 1] + - [100, 1, 100] + out: 401 + - name: 3x3-alternating + in: + mat: + elemType: "int" + value: + - [1, 100, 1] + - [100, 1, 100] + - [1, 100, 1] + out: 5 + - name: 4x4-sequential + in: + mat: + elemType: "int" + value: + - [1, 2, 3, 4] + - [5, 6, 7, 8] + - [9, 10, 11, 12] + - [13, 14, 15, 16] + out: 68 + - name: 4x4-corners-high + in: + mat: + elemType: "int" + value: + - [100, 1, 1, 100] + - [1, 100, 100, 1] + - [1, 100, 100, 1] + - [100, 1, 1, 100] + out: 800 + - name: 5x5-sequential + in: + mat: + elemType: "int" + value: + - [1, 2, 3, 4, 5] + - [6, 7, 8, 9, 10] + - [11, 12, 13, 14, 15] + - [16, 17, 18, 19, 20] + - [21, 22, 23, 24, 25] + out: 117 + - name: 5x5-all-maximum + in: + mat: + elemType: "int" + value: + - [100, 100, 100, 100, 100] + - [100, 100, 100, 100, 100] + - [100, 100, 100, 100, 100] + - [100, 100, 100, 100, 100] + - [100, 100, 100, 100, 100] + out: 900 + - name: 5x5-center-low + in: + mat: + elemType: "int" + value: + - [100, 1, 1, 1, 100] + - [1, 100, 1, 100, 1] + - [1, 1, 1, 1, 1] + - [1, 100, 1, 100, 1] + - [100, 1, 1, 1, 100] + out: 801 + - name: 6x6-sequential + in: + mat: + elemType: "int" + value: + - [1, 2, 3, 4, 5, 6] + - [7, 8, 9, 10, 11, 12] + - [13, 14, 15, 16, 17, 18] + - [19, 20, 21, 22, 23, 24] + - [25, 26, 27, 28, 29, 30] + - [31, 32, 33, 34, 35, 36] + out: 222 + - name: 7x7-sequential + in: + mat: + elemType: "int" + value: + - [1, 2, 3, 4, 5, 6, 7] + - [8, 9, 10, 11, 12, 13, 14] + - [15, 16, 17, 18, 19, 20, 21] + - [22, 23, 24, 25, 26, 27, 28] + - [29, 30, 31, 32, 33, 34, 35] + - [36, 37, 38, 39, 40, 41, 42] + - [43, 44, 45, 46, 47, 48, 49] + out: 325 + - name: 8x8-sequential + in: + mat: + elemType: "int" + value: + - [1, 2, 3, 4, 5, 6, 7, 8] + - [9, 10, 11, 12, 13, 14, 15, 16] + - [17, 18, 19, 20, 21, 22, 23, 24] + - [25, 26, 27, 28, 29, 30, 31, 32] + - [33, 34, 35, 36, 37, 38, 39, 40] + - [41, 42, 43, 44, 45, 46, 47, 48] + - [49, 50, 51, 52, 53, 54, 55, 56] + - [57, 58, 59, 60, 61, 62, 63, 64] + out: 520 + - name: 9x9-sequential + in: + mat: + elemType: "int" + value: + - [1, 2, 3, 4, 5, 6, 7, 8, 9] + - [10, 11, 12, 13, 14, 15, 16, 17, 18] + - [19, 20, 21, 22, 23, 24, 25, 26, 27] + - [28, 29, 30, 31, 32, 33, 34, 35, 36] + - [37, 38, 39, 40, 41, 42, 43, 44, 45] + - [46, 47, 48, 49, 50, 51, 52, 53, 54] + - [55, 56, 57, 58, 59, 60, 61, 62, 63] + - [64, 65, 66, 67, 68, 69, 70, 71, 72] + - [73, 74, 75, 76, 77, 78, 79, 80, 81] + out: 697 + - name: 10x10-sequential + in: + mat: + elemType: "int" + value: + - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] + - [21, 22, 23, 24, 25, 26, 27, 28, 29, 30] + - [31, 32, 33, 34, 35, 36, 37, 38, 39, 40] + - [41, 42, 43, 44, 45, 46, 47, 48, 49, 50] + - [51, 52, 53, 54, 55, 56, 57, 58, 59, 60] + - [61, 62, 63, 64, 65, 66, 67, 68, 69, 70] + - [71, 72, 73, 74, 75, 76, 77, 78, 79, 80] + - [81, 82, 83, 84, 85, 86, 87, 88, 89, 90] + - [91, 92, 93, 94, 95, 96, 97, 98, 99, 100] + out: 1010 + - name: 10x10-all-one + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 20 + - name: 10x10-all-hundred + in: + mat: + elemType: "int" + value: + - [100, 100, 100, 100, 100, 100, 100, 100, 100, 100] + - [100, 100, 100, 100, 100, 100, 100, 100, 100, 100] + - [100, 100, 100, 100, 100, 100, 100, 100, 100, 100] + - [100, 100, 100, 100, 100, 100, 100, 100, 100, 100] + - [100, 100, 100, 100, 100, 100, 100, 100, 100, 100] + - [100, 100, 100, 100, 100, 100, 100, 100, 100, 100] + - [100, 100, 100, 100, 100, 100, 100, 100, 100, 100] + - [100, 100, 100, 100, 100, 100, 100, 100, 100, 100] + - [100, 100, 100, 100, 100, 100, 100, 100, 100, 100] + - [100, 100, 100, 100, 100, 100, 100, 100, 100, 100] + out: 2000 + - name: 11x11-diagonal-high + in: + mat: + elemType: "int" + value: + - [100, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100] + - [1, 100, 1, 1, 1, 1, 1, 1, 1, 100, 1] + - [1, 1, 100, 1, 1, 1, 1, 1, 1, 100, 1] + - [1, 1, 1, 100, 1, 1, 1, 100, 1, 1, 1] + - [1, 1, 1, 1, 100, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 100, 1, 1, 1, 100, 1, 1, 1] + - [1, 1, 100, 1, 1, 1, 1, 1, 100, 1, 1] + - [1, 100, 1, 1, 1, 1, 1, 1, 1, 100, 1] + - [100, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100] + out: 1605 + - name: 3x3-repeated-pattern + in: + mat: + elemType: "int" + value: + - [2, 2, 2] + - [2, 2, 2] + - [2, 2, 2] + out: 10 + - name: 4x4-repeated-pattern + in: + mat: + elemType: "int" + value: + - [3, 3, 3, 3] + - [3, 3, 3, 3] + - [3, 3, 3, 3] + - [3, 3, 3, 3] + out: 24 + - name: 5x5-border-high + in: + mat: + elemType: "int" + value: + - [100, 100, 100, 100, 100] + - [100, 1, 1, 1, 100] + - [100, 1, 1, 1, 100] + - [100, 1, 1, 1, 100] + - [100, 100, 100, 100, 100] + out: 405 + - name: 2x2-distinct + in: + mat: + elemType: "int" + value: + - [7, 13] + - [29, 41] + out: 90 + - name: 3x3-mixed-boundaries + in: + mat: + elemType: "int" + value: + - [1, 50, 100] + - [99, 50, 2] + - [3, 49, 100] + out: 254 + - name: 6x6-all-one + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1] + out: 12 + - name: 7x7-all-hundred + in: + mat: + elemType: "int" + value: + - [100, 100, 100, 100, 100, 100, 100] + - [100, 100, 100, 100, 100, 100, 100] + - [100, 100, 100, 100, 100, 100, 100] + - [100, 100, 100, 100, 100, 100, 100] + - [100, 100, 100, 100, 100, 100, 100] + - [100, 100, 100, 100, 100, 100, 100] + - [100, 100, 100, 100, 100, 100, 100] + out: 1300 + - name: 8x8-checkerboard + in: + mat: + elemType: "int" + value: + - [1, 100, 1, 100, 1, 100, 1, 100] + - [100, 1, 100, 1, 100, 1, 100, 1] + - [1, 100, 1, 100, 1, 100, 1, 100] + - [100, 1, 100, 1, 100, 1, 100, 1] + - [1, 100, 1, 100, 1, 100, 1, 100] + - [100, 1, 100, 1, 100, 1, 100, 1] + - [1, 100, 1, 100, 1, 100, 1, 100] + - [100, 1, 100, 1, 100, 1, 100, 1] + out: 808 + - name: 9x9-checkerboard + in: + mat: + elemType: "int" + value: + - [1, 100, 1, 100, 1, 100, 1, 100, 1] + - [100, 1, 100, 1, 100, 1, 100, 1, 100] + - [1, 100, 1, 100, 1, 100, 1, 100, 1] + - [100, 1, 100, 1, 100, 1, 100, 1, 100] + - [1, 100, 1, 100, 1, 100, 1, 100, 1] + - [100, 1, 100, 1, 100, 1, 100, 1, 100] + - [1, 100, 1, 100, 1, 100, 1, 100, 1] + - [100, 1, 100, 1, 100, 1, 100, 1, 100] + - [1, 100, 1, 100, 1, 100, 1, 100, 1] + out: 17 + - name: 12x12-all-seven + in: + mat: + elemType: "int" + value: + - [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7] + - [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7] + - [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7] + - [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7] + - [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7] + - [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7] + - [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7] + - [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7] + - [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7] + - [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7] + - [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7] + - [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7] + out: 168 + - name: 15x15-all-one + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 29 + - name: 20x20-all-hundred + in: + mat: + elemType: "int" + value: + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - [ + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + out: 4000 diff --git a/tests/1501-2000/1572. matrix-diagonal-sum/sol.cpp b/tests/1501-2000/1572. matrix-diagonal-sum/sol.cpp new file mode 100644 index 00000000..4e0a3152 --- /dev/null +++ b/tests/1501-2000/1572. matrix-diagonal-sum/sol.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int diagonalSum(vector>& mat) { + int summ = 0; + int n = mat.size(); + for (int i = 0; i < n; i++) { + summ += mat[i][i]; + summ += mat[i][n - 1 - i]; + } + if (n % 2 == 1) { + summ -= mat[n / 2][n / 2]; + } + return summ; + } +}; diff --git a/tests/1501-2000/1572. matrix-diagonal-sum/sol.cs b/tests/1501-2000/1572. matrix-diagonal-sum/sol.cs new file mode 100644 index 00000000..69dec568 --- /dev/null +++ b/tests/1501-2000/1572. matrix-diagonal-sum/sol.cs @@ -0,0 +1,14 @@ +public class Solution { + public int DiagonalSum(int[][] mat) { + int summ = 0; + int n = mat.Length; + for (int i = 0; i < n; i++) { + summ += mat[i][i]; + summ += mat[i][n - 1 - i]; + } + if (n % 2 == 1) { + summ -= mat[n / 2][n / 2]; + } + return summ; + } +} diff --git a/tests/1501-2000/1572. matrix-diagonal-sum/sol.dart b/tests/1501-2000/1572. matrix-diagonal-sum/sol.dart new file mode 100644 index 00000000..dcb243d8 --- /dev/null +++ b/tests/1501-2000/1572. matrix-diagonal-sum/sol.dart @@ -0,0 +1,14 @@ +class Solution { + int diagonalSum(List> mat) { + int summ = 0; + int n = mat.length; + for (int i = 0; i < n; i++) { + summ += mat[i][i]; + summ += mat[i][n - 1 - i]; + } + if (n % 2 == 1) { + summ -= mat[n ~/ 2][n ~/ 2]; + } + return summ; + } +} diff --git a/tests/1501-2000/1572. matrix-diagonal-sum/sol.go b/tests/1501-2000/1572. matrix-diagonal-sum/sol.go new file mode 100644 index 00000000..d5f16ace --- /dev/null +++ b/tests/1501-2000/1572. matrix-diagonal-sum/sol.go @@ -0,0 +1,12 @@ +func diagonalSum(mat [][]int) int { + summ := 0 + n := len(mat) + for i := 0; i < n; i++ { + summ += mat[i][i] + summ += mat[i][n-1-i] + } + if n%2 == 1 { + summ -= mat[n/2][n/2] + } + return summ +} diff --git a/tests/1501-2000/1572. matrix-diagonal-sum/sol.java b/tests/1501-2000/1572. matrix-diagonal-sum/sol.java new file mode 100644 index 00000000..e787105e --- /dev/null +++ b/tests/1501-2000/1572. matrix-diagonal-sum/sol.java @@ -0,0 +1,14 @@ +class Solution { + public int diagonalSum(int[][] mat) { + int summ = 0; + int n = mat.length; + for (int i = 0; i < n; i++) { + summ += mat[i][i]; + summ += mat[i][n - 1 - i]; + } + if (n % 2 == 1) { + summ -= mat[n / 2][n / 2]; + } + return summ; + } +} diff --git a/tests/1501-2000/1572. matrix-diagonal-sum/sol.kt b/tests/1501-2000/1572. matrix-diagonal-sum/sol.kt new file mode 100644 index 00000000..87cba2e7 --- /dev/null +++ b/tests/1501-2000/1572. matrix-diagonal-sum/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun diagonalSum(mat: Array): Int { + var summ = 0 + val n = mat.size + for (i in 0 until n) { + summ += mat[i][i] + summ += mat[i][n - 1 - i] + } + if (n % 2 == 1) { + summ -= mat[n / 2][n / 2] + } + return summ + } +} diff --git a/tests/1501-2000/1572. matrix-diagonal-sum/sol.py b/tests/1501-2000/1572. matrix-diagonal-sum/sol.py new file mode 100644 index 00000000..a1df3f24 --- /dev/null +++ b/tests/1501-2000/1572. matrix-diagonal-sum/sol.py @@ -0,0 +1,13 @@ +class Solution: + def diagonalSum(self, mat: List[List[int]]) -> int: + + summ = 0 + + for i in range(len(mat)): + summ += mat[i][i] + summ += mat[i][len(mat) - 1 - i] + + if len(mat) % 2 == 1: + summ -= mat[len(mat) // 2][len(mat) // 2] + + return summ diff --git a/tests/1501-2000/1572. matrix-diagonal-sum/sol.py2 b/tests/1501-2000/1572. matrix-diagonal-sum/sol.py2 new file mode 100644 index 00000000..93162bdc --- /dev/null +++ b/tests/1501-2000/1572. matrix-diagonal-sum/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def diagonalSum(self, mat): + """ + :type mat: List[List[int]] + :rtype: int + """ + summ = 0 + n = len(mat) + for i in range(n): + summ += mat[i][i] + summ += mat[i][n - 1 - i] + if n % 2 == 1: + summ -= mat[n // 2][n // 2] + return summ diff --git a/tests/1501-2000/1572. matrix-diagonal-sum/sol.rb b/tests/1501-2000/1572. matrix-diagonal-sum/sol.rb new file mode 100644 index 00000000..eda0ea40 --- /dev/null +++ b/tests/1501-2000/1572. matrix-diagonal-sum/sol.rb @@ -0,0 +1,12 @@ +# @param {Integer[][]} mat +# @return {Integer} +def diagonal_sum(mat) + summ = 0 + n = mat.length + (0...n).each do |i| + summ += mat[i][i] + summ += mat[i][n - 1 - i] + end + summ -= mat[n / 2][n / 2] if n.odd? + summ +end diff --git a/tests/1501-2000/1572. matrix-diagonal-sum/sol.rs b/tests/1501-2000/1572. matrix-diagonal-sum/sol.rs new file mode 100644 index 00000000..759b0636 --- /dev/null +++ b/tests/1501-2000/1572. matrix-diagonal-sum/sol.rs @@ -0,0 +1,14 @@ +impl Solution { + pub fn diagonal_sum(mat: Vec>) -> i32 { + let mut summ = 0; + let n = mat.len(); + for i in 0..n { + summ += mat[i][i]; + summ += mat[i][n - 1 - i]; + } + if n % 2 == 1 { + summ -= mat[n / 2][n / 2]; + } + summ + } +} diff --git a/tests/1501-2000/1572. matrix-diagonal-sum/sol.swift b/tests/1501-2000/1572. matrix-diagonal-sum/sol.swift new file mode 100644 index 00000000..0a02782c --- /dev/null +++ b/tests/1501-2000/1572. matrix-diagonal-sum/sol.swift @@ -0,0 +1,14 @@ +class Solution { + func diagonalSum(_ mat: [[Int]]) -> Int { + var summ = 0 + let n = mat.count + for i in 0.. c == '1'); + + if (totalOnes == 0) { + long n = s.Length; + return (int)(((n - 1) * (n - 2) / 2) % MOD); + } + + if (totalOnes % 3 != 0) return 0; + + long onesPerPart = totalOnes / 3; + long firstSplitWays = 0, secondSplitWays = 0, count = 0; + + foreach (char c in s) { + if (c == '1') count++; + if (count == onesPerPart) { + firstSplitWays++; + } else if (count == 2 * onesPerPart) { + secondSplitWays++; + } + } + + return (int)((firstSplitWays * secondSplitWays) % MOD); + } +} diff --git a/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.dart b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.dart new file mode 100644 index 00000000..b3c62ade --- /dev/null +++ b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.dart @@ -0,0 +1,27 @@ +class Solution { + int numWays(String s) { + const MOD = 1000000007; + int totalOnes = s.split('').where((c) => c == '1').length; + + if (totalOnes == 0) { + int n = s.length; + return ((n - 1) * (n - 2) ~/ 2) % MOD; + } + + if (totalOnes % 3 != 0) return 0; + + int onesPerPart = totalOnes ~/ 3; + int firstSplitWays = 0, secondSplitWays = 0, count = 0; + + for (int i = 0; i < s.length; i++) { + if (s[i] == '1') count++; + if (count == onesPerPart) { + firstSplitWays++; + } else if (count == 2 * onesPerPart) { + secondSplitWays++; + } + } + + return (firstSplitWays * secondSplitWays) % MOD; + } +} diff --git a/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.go b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.go new file mode 100644 index 00000000..61ff3c43 --- /dev/null +++ b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.go @@ -0,0 +1,34 @@ +func numWays(s string) int { + const MOD = 1000000007 + totalOnes := 0 + for _, ch := range s { + if ch == '1' { + totalOnes++ + } + } + + if totalOnes == 0 { + n := int64(len(s)) + return int(((n - 1) * (n - 2) / 2) % MOD) + } + + if totalOnes%3 != 0 { + return 0 + } + + onesPerPart := totalOnes / 3 + var firstSplitWays, secondSplitWays, count int64 + + for _, ch := range s { + if ch == '1' { + count++ + } + if count == int64(onesPerPart) { + firstSplitWays++ + } else if count == int64(2*onesPerPart) { + secondSplitWays++ + } + } + + return int((firstSplitWays * secondSplitWays) % MOD) +} diff --git a/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.java b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.java new file mode 100644 index 00000000..00a4ecf0 --- /dev/null +++ b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.java @@ -0,0 +1,31 @@ +class Solution { + public int numWays(String s) { + final int MOD = 1_000_000_007; + long totalOnes = 0; + for (char c : s.toCharArray()) { + if (c == '1') totalOnes++; + } + + if (totalOnes == 0) { + long n = s.length(); + return (int)(((n - 1) * (n - 2) / 2) % MOD); + } + + if (totalOnes % 3 != 0) return 0; + + long onesPerPart = totalOnes / 3; + long firstSplitWays = 0, secondSplitWays = 0; + long count = 0; + + for (char c : s.toCharArray()) { + if (c == '1') count++; + if (count == onesPerPart) { + firstSplitWays++; + } else if (count == 2 * onesPerPart) { + secondSplitWays++; + } + } + + return (int)((firstSplitWays * secondSplitWays) % MOD); + } +} diff --git a/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.kt b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.kt new file mode 100644 index 00000000..bbfc0935 --- /dev/null +++ b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.kt @@ -0,0 +1,29 @@ +class Solution { + fun numWays(s: String): Int { + val MOD = 1_000_000_007 + val totalOnes = s.count { it == '1' } + + if (totalOnes == 0) { + val n = s.length.toLong() + return ((n - 1) * (n - 2) / 2 % MOD).toInt() + } + + if (totalOnes % 3 != 0) return 0 + + val onesPerPart = totalOnes / 3 + var firstSplitWays = 0L + var secondSplitWays = 0L + var count = 0 + + for (c in s) { + if (c == '1') count++ + if (count == onesPerPart) { + firstSplitWays++ + } else if (count == 2 * onesPerPart) { + secondSplitWays++ + } + } + + return ((firstSplitWays * secondSplitWays) % MOD).toInt() + } +} diff --git a/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.py b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.py new file mode 100644 index 00000000..8a27ddcf --- /dev/null +++ b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.py @@ -0,0 +1,29 @@ +class Solution(object): + def numWays(self, s): + """ + :type s: str + :rtype: int + """ + MOD = 10**9 + 7 + total_ones = s.count("1") + + if total_ones == 0: + n = len(s) + return ((n - 1) * (n - 2) // 2) % MOD + + if total_ones % 3 != 0: + return 0 + + ones_per_part = total_ones // 3 + first_split_ways = second_split_ways = 0 + count = 0 + + for i in range(len(s)): + if s[i] == "1": + count += 1 + if count == ones_per_part: + first_split_ways += 1 + elif count == 2 * ones_per_part: + second_split_ways += 1 + + return (first_split_ways * second_split_ways) % MOD diff --git a/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.py2 b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.py2 new file mode 100644 index 00000000..b6fee812 --- /dev/null +++ b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.py2 @@ -0,0 +1,29 @@ +class Solution(object): + def numWays(self, s): + """ + :type s: str + :rtype: int + """ + MOD = 10**9 + 7 + total_ones = s.count('1') + + if total_ones == 0: + n = len(s) + return ((n - 1) * (n - 2) // 2) % MOD + + if total_ones % 3 != 0: + return 0 + + ones_per_part = total_ones // 3 + first_split_ways = second_split_ways = 0 + count = 0 + + for i in range(len(s)): + if s[i] == '1': + count += 1 + if count == ones_per_part: + first_split_ways += 1 + elif count == 2 * ones_per_part: + second_split_ways += 1 + + return (first_split_ways * second_split_ways) % MOD diff --git a/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.rb b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.rb new file mode 100644 index 00000000..8f421113 --- /dev/null +++ b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.rb @@ -0,0 +1,29 @@ +# @param {String} s +# @return {Integer} +def num_ways(s) + mod = 10**9 + 7 + total_ones = s.count('1') + + if total_ones == 0 + n = s.length + return ((n - 1) * (n - 2) / 2) % mod + end + + return 0 if total_ones % 3 != 0 + + ones_per_part = total_ones / 3 + first_split_ways = 0 + second_split_ways = 0 + count = 0 + + s.each_char do |ch| + count += 1 if ch == '1' + if count == ones_per_part + first_split_ways += 1 + elsif count == 2 * ones_per_part + second_split_ways += 1 + end + end + + (first_split_ways * second_split_ways) % mod +end diff --git a/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.rs b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.rs new file mode 100644 index 00000000..35e8339d --- /dev/null +++ b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.rs @@ -0,0 +1,33 @@ +impl Solution { + pub fn num_ways(s: String) -> i32 { + const MOD: i64 = 1_000_000_007; + let total_ones = s.bytes().filter(|&b| b == b'1').count() as i64; + + if total_ones == 0 { + let n = s.len() as i64; + return (((n - 1) * (n - 2) / 2) % MOD) as i32; + } + + if total_ones % 3 != 0 { + return 0; + } + + let ones_per_part = total_ones / 3; + let mut first_split_ways = 0i64; + let mut second_split_ways = 0i64; + let mut count = 0i64; + + for byte in s.bytes() { + if byte == b'1' { + count += 1; + } + if count == ones_per_part { + first_split_ways += 1; + } else if count == 2 * ones_per_part { + second_split_ways += 1; + } + } + + ((first_split_ways * second_split_ways) % MOD) as i32 + } +} diff --git a/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.swift b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.swift new file mode 100644 index 00000000..ab149b75 --- /dev/null +++ b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.swift @@ -0,0 +1,33 @@ +class Solution { + func numWays(_ s: String) -> Int { + let MOD = 1_000_000_007 + let totalOnes = s.filter { $0 == "1" }.count + + if totalOnes == 0 { + let n = s.count + return ((n - 1) * (n - 2) / 2) % MOD + } + + if totalOnes % 3 != 0 { + return 0 + } + + let onesPerPart = totalOnes / 3 + var firstSplitWays = 0 + var secondSplitWays = 0 + var count = 0 + + for ch in s { + if ch == "1" { + count += 1 + } + if count == onesPerPart { + firstSplitWays += 1 + } else if count == 2 * onesPerPart { + secondSplitWays += 1 + } + } + + return (firstSplitWays * secondSplitWays) % MOD + } +} diff --git a/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.ts b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.ts new file mode 100644 index 00000000..8c49f796 --- /dev/null +++ b/tests/1501-2000/1573. number-of-ways-to-split-a-string/sol.ts @@ -0,0 +1,27 @@ +function numWays(s: string): number { + const MOD = 1000000007; + const totalOnes = s.split("").filter((c) => c === "1").length; + + if (totalOnes === 0) { + const n = s.length; + return (((n - 1) * (n - 2)) / 2) % MOD; + } + + if (totalOnes % 3 !== 0) return 0; + + const onesPerPart = Math.floor(totalOnes / 3); + let firstSplitWays = 0, + secondSplitWays = 0, + count = 0; + + for (const ch of s) { + if (ch === "1") count++; + if (count === onesPerPart) { + firstSplitWays++; + } else if (count === 2 * onesPerPart) { + secondSplitWays++; + } + } + + return (firstSplitWays * secondSplitWays) % MOD; +} diff --git a/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/manifest.yaml b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/manifest.yaml new file mode 100644 index 00000000..07ebc31f --- /dev/null +++ b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/manifest.yaml @@ -0,0 +1,252 @@ +entry: + id: 1574 + title: "shortest-subarray-to-be-removed-to-make-array-sorted" + params: + arr: + type: array + items: + type: int + call: + cpp: "Solution().findLengthOfShortestSubarray({arr})" + rust: "Solution::find_length_of_shortest_subarray({arr})" + python3: "Solution().findLengthOfShortestSubarray({arr})" + python2: "Solution().findLengthOfShortestSubarray({arr})" + ruby: "find_length_of_shortest_subarray({arr})" + java: "new Solution().findLengthOfShortestSubarray({arr})" + csharp: "new Solution().FindLengthOfShortestSubarray({arr})" + kotlin: "Solution().findLengthOfShortestSubarray({arr})" + go: "findLengthOfShortestSubarray({arr})" + dart: "Solution().findLengthOfShortestSubarray({arr})" + swift: "Solution().findLengthOfShortestSubarray({arr})" + typescript: "findLengthOfShortestSubarray({arr})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().check(arr, {result})" + checker: | + class Checker: + def check(self, arr, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + n = len(arr) + right = n - 1 + while right > 0 and arr[right - 1] <= arr[right]: + right -= 1 + if right == 0: + return result == 0 + best = right + left = 0 + while left == 0 or (left < n and arr[left - 1] <= arr[left]): + while right < n and arr[left] > arr[right]: + right += 1 + best = min(best, right - left - 1) + left += 1 + if left >= n: + break + return result == best +seed: 1574 +tests: + - name: example-one + in: + arr: [1, 2, 3, 10, 4, 2, 3, 5] + out: 3 + - name: example-two + in: + arr: [5, 4, 3, 2, 1] + out: 4 + - name: already-sorted + in: + arr: [1, 2, 3] + out: 0 + - name: single-element + in: + arr: [7] + out: 0 + - name: two-descending + in: + arr: [2, 1] + out: 1 + - name: equal-values + in: + arr: [4, 4, 4, 4] + out: 0 + - name: remove-prefix + in: + arr: [10, 1, 2, 3, 4] + out: 1 + - name: remove-suffix + in: + arr: [1, 2, 3, 0] + out: 1 + - name: valley + in: + arr: [1, 2, 0, 3, 4] + out: 1 + - name: two-valleys + in: + arr: [1, 5, 2, 3, 0, 4] + out: 4 + - name: late-drop + in: + arr: [1, 2, 3, 4, 8, 6, 7, 9] + out: 1 + - name: early-drop + in: + arr: [1, 3, 2, 4, 5, 6] + out: 1 + - name: bridge-equal + in: + arr: [1, 2, 6, 3, 4, 6] + out: 1 + - name: descending-three + in: + arr: [3, 2, 1] + out: 2 + - name: increasing-four + in: + arr: [0, 1, 2, 3] + out: 0 + - name: zeroes + in: + arr: [0, 0, 1, 0, 0, 2] + out: 1 + - name: large-values + in: + arr: [1000000000, 999999999, 1000000000] + out: 1 + - name: repeated-drop + in: + arr: [1, 4, 3, 2, 5] + out: 2 + - name: best-middle + in: + arr: [1, 2, 7, 3, 4, 5, 6, 8] + out: 1 + - name: best-prefix-over-middle + in: + arr: [9, 1, 2, 3, 8, 10] + out: 1 + - name: long-decreasing + in: + arr: [9, 8, 7, 6, 5, 4, 3] + out: 6 + - name: plateau-then-drop + in: + arr: [2, 2, 2, 1, 2, 2] + out: 1 + - name: alternating-small + in: + arr: [1, 0, 1, 0, 1] + out: 3 + - name: sorted-negative-not-allowed + in: + arr: [0, 1, 1, 2, 2, 3] + out: 0 + - name: remove-four-middle + in: + arr: [1, 2, 10, 9, 8, 7, 3, 4] + out: 4 + - name: crossing-one + in: + arr: [1, 2, 5, 3, 4, 6] + out: 1 + - name: crossing-two + in: + arr: [1, 4, 5, 2, 3, 6] + out: 2 + - name: all-max + in: + arr: [1000000000, 1000000000] + out: 0 + - name: min-values + in: + arr: [0, 0, 0, 0, 0] + out: 0 + - name: one-kept-left + in: + arr: [5, 1, 0, 0] + out: 2 + - name: one-kept-right + in: + arr: [3, 2, 1, 4] + out: 2 + - name: nested-plateau + in: + arr: [1, 3, 3, 2, 2, 4] + out: 2 + - name: sorted-with-spike + in: + arr: [1, 2, 3, 100, 4, 5, 6] + out: 1 + - name: two-spikes + in: + arr: [1, 50, 2, 3, 40, 4, 5] + out: 4 + - name: edge-spike + in: + arr: [0, 1000000000, 1] + out: 1 + - name: generated-random-small + in: + arr: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 1000 + distinct: false + sorted: false + elemType: "int" + - name: generated-near-limit + in: + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: 0 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + - name: generated-large-low-range + in: + arr: + gen: "array" + len: 50000 + of: + gen: "int" + min: 0 + max: 20 + distinct: false + sorted: false + elemType: "int" + - name: generated-large-values + in: + arr: + gen: "array" + len: 75000 + of: + gen: "int" + min: 999999000 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + - name: generated-medium + in: + arr: + gen: "array" + len: 10000 + of: + gen: "int" + min: 0 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.cpp b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.cpp new file mode 100644 index 00000000..f121496f --- /dev/null +++ b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int findLengthOfShortestSubarray(vector& arr) { + int n = arr.size(); + int right = n - 1; + while (right > 0 && arr[right - 1] <= arr[right]) { + right--; + } + if (right == 0) return 0; + int answer = right; + int left = 0; + while (left == 0 || (left < n && arr[left - 1] <= arr[left])) { + while (right < n && arr[left] > arr[right]) { + right++; + } + answer = min(answer, right - left - 1); + left++; + if (left >= n) break; + } + return answer; + } +}; diff --git a/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.cs b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.cs new file mode 100644 index 00000000..dc4157d7 --- /dev/null +++ b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.cs @@ -0,0 +1,21 @@ +public class Solution { + public int FindLengthOfShortestSubarray(int[] arr) { + int n = arr.Length; + int right = n - 1; + while (right > 0 && arr[right - 1] <= arr[right]) { + right--; + } + if (right == 0) return 0; + int answer = right; + int left = 0; + while (left == 0 || (left < n && arr[left - 1] <= arr[left])) { + while (right < n && arr[left] > arr[right]) { + right++; + } + answer = Math.Min(answer, right - left - 1); + left++; + if (left >= n) break; + } + return answer; + } +} diff --git a/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.dart b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.dart new file mode 100644 index 00000000..2d445806 --- /dev/null +++ b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.dart @@ -0,0 +1,21 @@ +class Solution { + int findLengthOfShortestSubarray(List arr) { + int n = arr.length; + int right = n - 1; + while (right > 0 && arr[right - 1] <= arr[right]) { + right--; + } + if (right == 0) return 0; + int answer = right; + int left = 0; + while (left == 0 || (left < n && arr[left - 1] <= arr[left])) { + while (right < n && arr[left] > arr[right]) { + right++; + } + answer = answer < (right - left - 1) ? answer : (right - left - 1); + left++; + if (left >= n) break; + } + return answer; + } +} diff --git a/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.go b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.go new file mode 100644 index 00000000..52aeb5d6 --- /dev/null +++ b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.go @@ -0,0 +1,25 @@ +func findLengthOfShortestSubarray(arr []int) int { + n := len(arr) + right := n - 1 + for right > 0 && arr[right-1] <= arr[right] { + right-- + } + if right == 0 { + return 0 + } + answer := right + left := 0 + for left == 0 || (left < n && arr[left-1] <= arr[left]) { + for right < n && arr[left] > arr[right] { + right++ + } + if right-left-1 < answer { + answer = right - left - 1 + } + left++ + if left >= n { + break + } + } + return answer +} diff --git a/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.java b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.java new file mode 100644 index 00000000..d0fbc0f4 --- /dev/null +++ b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.java @@ -0,0 +1,21 @@ +class Solution { + public int findLengthOfShortestSubarray(int[] arr) { + int n = arr.length; + int right = n - 1; + while (right > 0 && arr[right - 1] <= arr[right]) { + right--; + } + if (right == 0) return 0; + int answer = right; + int left = 0; + while (left == 0 || (left < n && arr[left - 1] <= arr[left])) { + while (right < n && arr[left] > arr[right]) { + right++; + } + answer = Math.min(answer, right - left - 1); + left++; + if (left >= n) break; + } + return answer; + } +} diff --git a/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.kt b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.kt new file mode 100644 index 00000000..24b1f7e0 --- /dev/null +++ b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.kt @@ -0,0 +1,21 @@ +class Solution { + fun findLengthOfShortestSubarray(arr: IntArray): Int { + val n = arr.size + var right = n - 1 + while (right > 0 && arr[right - 1] <= arr[right]) { + right-- + } + if (right == 0) return 0 + var answer = right + var left = 0 + while (left == 0 || (left < n && arr[left - 1] <= arr[left])) { + while (right < n && arr[left] > arr[right]) { + right++ + } + answer = minOf(answer, right - left - 1) + left++ + if (left >= n) break + } + return answer + } +} diff --git a/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.py b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.py new file mode 100644 index 00000000..e3d0696a --- /dev/null +++ b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.py @@ -0,0 +1,18 @@ +class Solution: + def findLengthOfShortestSubarray(self, arr): + n = len(arr) + right = n - 1 + while right > 0 and arr[right - 1] <= arr[right]: + right -= 1 + if right == 0: + return 0 + answer = right + left = 0 + while left == 0 or (left < n and arr[left - 1] <= arr[left]): + while right < n and arr[left] > arr[right]: + right += 1 + answer = min(answer, right - left - 1) + left += 1 + if left >= n: + break + return answer diff --git a/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.py2 b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.py2 new file mode 100644 index 00000000..b9a339b5 --- /dev/null +++ b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def findLengthOfShortestSubarray(self, arr): + """ + :type arr: List[int] + :rtype: int + """ + n = len(arr) + right = n - 1 + while right > 0 and arr[right - 1] <= arr[right]: + right -= 1 + if right == 0: + return 0 + answer = right + left = 0 + while left == 0 or (left < n and arr[left - 1] <= arr[left]): + while right < n and arr[left] > arr[right]: + right += 1 + answer = min(answer, right - left - 1) + left += 1 + if left >= n: + break + return answer diff --git a/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.rb b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.rb new file mode 100644 index 00000000..bfa69cbd --- /dev/null +++ b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.rb @@ -0,0 +1,21 @@ +# @param {Integer[]} arr +# @return {Integer} +def find_length_of_shortest_subarray(arr) + n = arr.length + right = n - 1 + while right > 0 && arr[right - 1] <= arr[right] + right -= 1 + end + return 0 if right == 0 + answer = right + left = 0 + while left == 0 || (left < n && arr[left - 1] <= arr[left]) + while right < n && arr[left] > arr[right] + right += 1 + end + answer = [answer, right - left - 1].min + left += 1 + break if left >= n + end + answer +end diff --git a/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.rs b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.rs new file mode 100644 index 00000000..6d361815 --- /dev/null +++ b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn find_length_of_shortest_subarray(arr: Vec) -> i32 { + let n = arr.len(); + let mut right = n - 1; + while right > 0 && arr[right - 1] <= arr[right] { + right -= 1; + } + if right == 0 { + return 0; + } + let mut answer = right as i32; + let mut left = 0; + while left == 0 || (left < n && arr[left - 1] <= arr[left]) { + while right < n && arr[left] > arr[right] { + right += 1; + } + answer = answer.min((right - left - 1) as i32); + left += 1; + if left >= n { + break; + } + } + answer + } +} diff --git a/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.swift b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.swift new file mode 100644 index 00000000..b8926eae --- /dev/null +++ b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.swift @@ -0,0 +1,21 @@ +class Solution { + func findLengthOfShortestSubarray(_ arr: [Int]) -> Int { + let n = arr.count + var right = n - 1 + while right > 0 && arr[right - 1] <= arr[right] { + right -= 1 + } + if right == 0 { return 0 } + var answer = right + var left = 0 + while left == 0 || (left < n && arr[left - 1] <= arr[left]) { + while right < n && arr[left] > arr[right] { + right += 1 + } + answer = min(answer, right - left - 1) + left += 1 + if left >= n { break } + } + return answer + } +} diff --git a/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.ts b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.ts new file mode 100644 index 00000000..bdbb18b0 --- /dev/null +++ b/tests/1501-2000/1574. shortest-subarray-to-be-removed-to-make-array-sorted/sol.ts @@ -0,0 +1,19 @@ +function findLengthOfShortestSubarray(arr: number[]): number { + const n = arr.length; + let right = n - 1; + while (right > 0 && arr[right - 1] <= arr[right]) { + right--; + } + if (right === 0) return 0; + let answer = right; + let left = 0; + while (left === 0 || (left < n && arr[left - 1] <= arr[left])) { + while (right < n && arr[left] > arr[right]) { + right++; + } + answer = Math.min(answer, right - left - 1); + left++; + if (left >= n) break; + } + return answer; +} diff --git a/tests/1501-2000/1575. count-all-possible-routes/manifest.yaml b/tests/1501-2000/1575. count-all-possible-routes/manifest.yaml new file mode 100644 index 00000000..ce73f207 --- /dev/null +++ b/tests/1501-2000/1575. count-all-possible-routes/manifest.yaml @@ -0,0 +1,415 @@ +entry: + id: 1575 + title: "count-all-possible-routes" + params: + locations: + type: array + items: + type: int + startCity: + type: int + finish: + type: int + fuel: + type: int + call: + cpp: "Solution().countRoutes({locations}, {startCity}, {finish}, {fuel})" + rust: "Solution::count_routes({locations}, {startCity}, {finish}, {fuel})" + python3: "Solution().countRoutes({locations}, {startCity}, {finish}, {fuel})" + python2: "Solution().countRoutes({locations}, {startCity}, {finish}, {fuel})" + ruby: "count_routes({locations}, {startCity}, {finish}, {fuel})" + java: "new Solution().countRoutes({locations}, {startCity}, {finish}, {fuel})" + csharp: "new Solution().CountRoutes({locations}, {startCity}, {finish}, {fuel})" + kotlin: "Solution().countRoutes({locations}, {startCity}, {finish}, {fuel})" + go: "countRoutes({locations}, {startCity}, {finish}, {fuel})" + dart: "Solution().countRoutes({locations}, {startCity}, {finish}, {fuel})" + swift: "Solution().countRoutes({locations}, {startCity}, {finish}, {fuel})" + typescript: "countRoutes({locations}, {startCity}, {finish}, {fuel})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().countRoutes(locations, startCity, finish, fuel, {result})" + checker: | + class Checker: + def countRoutes(self, locations, start, finish, fuel, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + mod = 1000000007 + memo = {} + def dp(city, left): + key = (city, left) + if key in memo: + return memo[key] + total = 1 if city == finish else 0 + for nxt, pos in enumerate(locations): + cost = abs(pos - locations[city]) + if nxt != city and cost <= left: + total = (total + dp(nxt, left - cost)) % mod + memo[key] = total + return total + return result == dp(start, fuel) + +seed: 1575 + +tests: + - name: "example_two" + in: + locations: [4, 3, 1] + startCity: 1 + finish: 0 + fuel: 6 + out: 5 + - name: "example_three_unreachable" + in: + locations: [5, 2, 1] + startCity: 0 + finish: 2 + fuel: 3 + out: 0 + - name: "two_cities_one_fuel" + in: + locations: [1, 2] + startCity: 0 + finish: 1 + fuel: 1 + out: 1 + - name: "same_city_no_fuel" + in: + locations: [1, 10] + startCity: 0 + finish: 0 + fuel: 1 + out: 1 + - name: "same_city_with_round_trip" + in: + locations: [1, 2] + startCity: 0 + finish: 0 + fuel: 2 + out: 2 + - name: "three_evenly_spaced" + in: + locations: [1, 3, 5] + startCity: 0 + finish: 2 + fuel: 4 + out: 2 + - name: "three_evenly_spaced_more_fuel" + in: + locations: [1, 3, 5] + startCity: 0 + finish: 2 + fuel: 6 + out: 2 + - name: "finish_start_reversed" + in: + locations: [1, 4, 7] + startCity: 2 + finish: 0 + fuel: 6 + out: 2 + - name: "large_gap_unreachable" + in: + locations: [1, 100, 200] + startCity: 0 + finish: 2 + fuel: 100 + out: 0 + - name: "large_gap_exact" + in: + locations: [1, 100, 200] + startCity: 0 + finish: 2 + fuel: 199 + out: 2 + - name: "four_linear_low_fuel" + in: + locations: [1, 2, 3, 4] + startCity: 0 + finish: 3 + fuel: 3 + out: 4 + - name: "four_linear_detour" + in: + locations: [1, 2, 3, 4] + startCity: 0 + finish: 3 + fuel: 5 + out: 16 + - name: "four_linear_more_routes" + in: + locations: [1, 2, 3, 4] + startCity: 1 + finish: 2 + fuel: 6 + out: 27 + - name: "unsorted_locations" + in: + locations: [10, 1, 7, 3] + startCity: 0 + finish: 3 + fuel: 9 + out: 2 + - name: "negative_coordinates_not_allowed_but_small" + in: + locations: [1, 5, 9, 14] + startCity: 3 + finish: 0 + fuel: 13 + out: 4 + - name: "five_sparse" + in: + locations: [2, 11, 20, 35, 50] + startCity: 0 + finish: 4 + fuel: 48 + out: 8 + - name: "five_clustered" + in: + locations: [10, 11, 12, 13, 14] + startCity: 0 + finish: 4 + fuel: 8 + out: 216 + - name: "finish_is_start_clustered" + in: + locations: [10, 11, 12, 13, 14] + startCity: 2 + finish: 2 + fuel: 4 + out: 17 + - name: "six_exact_path" + in: + locations: [3, 8, 14, 21, 29, 38] + startCity: 0 + finish: 5 + fuel: 35 + out: 16 + - name: "six_multiple_paths" + in: + locations: [3, 8, 14, 21, 29, 38] + startCity: 0 + finish: 5 + fuel: 42 + out: 16 + - name: "duplicate_distance_patterns" + in: + locations: [1, 4, 7, 10, 13] + startCity: 1 + finish: 3 + fuel: 9 + out: 2 + - name: "minimum_fuel_to_finish" + in: + locations: [2, 20, 35, 60] + startCity: 0 + finish: 3 + fuel: 58 + out: 4 + - name: "one_less_than_minimum" + in: + locations: [2, 20, 35, 60] + startCity: 0 + finish: 3 + fuel: 57 + out: 0 + - name: "seven_dense" + in: + locations: [1, 2, 4, 7, 11, 16, 22] + startCity: 0 + finish: 6 + fuel: 21 + out: 32 + - name: "seven_dense_same_city" + in: + locations: [1, 2, 4, 7, 11, 16, 22] + startCity: 3 + finish: 3 + fuel: 10 + out: 7 + - name: "large_coordinates_small_fuel" + in: + locations: [1, 100000, 500000000, 1000000000] + startCity: 0 + finish: 1 + fuel: 200 + out: 0 + - name: "large_coordinates_reachable" + in: + locations: [1, 201, 500000000, 1000000000] + startCity: 0 + finish: 1 + fuel: 200 + out: 1 + - name: "eight_mixed" + in: + locations: [4, 9, 15, 16, 23, 31, 40, 52] + startCity: 2 + finish: 6 + fuel: 30 + out: 24 + - name: "eight_low_fuel" + in: + locations: [4, 9, 15, 16, 23, 31, 40, 52] + startCity: 2 + finish: 6 + fuel: 24 + out: 0 + - name: "nine_close" + in: + locations: [100, 101, 103, 106, 110, 115, 121, 128, 136] + startCity: 0 + finish: 8 + fuel: 12 + out: 0 + - name: "ten_close_same" + in: + locations: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + startCity: 4 + finish: 4 + fuel: 10 + out: 7507 + - name: "ten_close_route" + in: + locations: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + startCity: 0 + finish: 9 + fuel: 10 + out: 256 + - name: "twenty_sparse" + in: + locations: + [ + 1, + 11, + 21, + 31, + 41, + 51, + 61, + 71, + 81, + 91, + 101, + 111, + 121, + 131, + 141, + 151, + 161, + 171, + 181, + 191, + ] + startCity: 0 + finish: 19 + fuel: 190 + out: 262144 + - name: "twenty_sparse_extra" + in: + locations: + [ + 1, + 11, + 21, + 31, + 41, + 51, + 61, + 71, + 81, + 91, + 101, + 111, + 121, + 131, + 141, + 151, + 161, + 171, + 181, + 191, + ] + startCity: 0 + finish: 19 + fuel: 200 + out: 262144 + - name: "example_one" + in: + locations: [2, 3, 6, 8, 4] + startCity: 1 + finish: 3 + fuel: 5 + out: 4 + - name: "generated_small_distinct" + in: + locations: + gen: "array" + len: 10 + of: + gen: "int" + min: 1 + max: 100 + distinct: true + startCity: 0 + finish: 1 + fuel: 30 + - name: "generated_medium_distinct" + in: + locations: + gen: "array" + len: 25 + of: + gen: "int" + min: 1 + max: 10000 + distinct: true + startCity: 0 + finish: 1 + fuel: 80 + - name: "generated_dense_distinct" + in: + locations: + gen: "array" + len: 50 + of: + gen: "int" + min: 1 + max: 1000000 + distinct: true + startCity: 0 + finish: 1 + fuel: 120 + - name: "generated_large_distinct" + in: + locations: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: true + startCity: 0 + finish: 1 + fuel: 200 + - name: "generated_clustered_distinct" + in: + locations: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 10000 + distinct: true + startCity: 0 + finish: 1 + fuel: 200 diff --git a/tests/1501-2000/1575. count-all-possible-routes/sol.cpp b/tests/1501-2000/1575. count-all-possible-routes/sol.cpp new file mode 100644 index 00000000..6ad10928 --- /dev/null +++ b/tests/1501-2000/1575. count-all-possible-routes/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int countRoutes(vector& locations, int start, int finish, int fuel) { + const int MOD = 1000000007; + int n = locations.size(); + vector> dp(n, vector(fuel + 1, 0)); + for (int city = 0; city < n; city++) { + dp[city][0] = (city == finish) ? 1 : 0; + } + for (int left = 1; left <= fuel; left++) { + for (int city = 0; city < n; city++) { + int total = (city == finish) ? 1 : 0; + for (int nxt = 0; nxt < n; nxt++) { + if (nxt != city) { + int cost = abs(locations[nxt] - locations[city]); + if (cost <= left) { + total = (total + dp[nxt][left - cost]) % MOD; + } + } + } + dp[city][left] = total; + } + } + return dp[start][fuel]; + } +}; diff --git a/tests/1501-2000/1575. count-all-possible-routes/sol.cs b/tests/1501-2000/1575. count-all-possible-routes/sol.cs new file mode 100644 index 00000000..a20521bb --- /dev/null +++ b/tests/1501-2000/1575. count-all-possible-routes/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public int CountRoutes(int[] locations, int start, int finish, int fuel) { + const int MOD = 1000000007; + int n = locations.Length; + int[,] dp = new int[n, fuel + 1]; + for (int city = 0; city < n; city++) { + dp[city, 0] = (city == finish) ? 1 : 0; + } + for (int left = 1; left <= fuel; left++) { + for (int city = 0; city < n; city++) { + int total = (city == finish) ? 1 : 0; + for (int nxt = 0; nxt < n; nxt++) { + if (nxt != city) { + int cost = Math.Abs(locations[nxt] - locations[city]); + if (cost <= left) { + total = (total + dp[nxt, left - cost]) % MOD; + } + } + } + dp[city, left] = total; + } + } + return dp[start, fuel]; + } +} diff --git a/tests/1501-2000/1575. count-all-possible-routes/sol.dart b/tests/1501-2000/1575. count-all-possible-routes/sol.dart new file mode 100644 index 00000000..3c0d224a --- /dev/null +++ b/tests/1501-2000/1575. count-all-possible-routes/sol.dart @@ -0,0 +1,25 @@ +class Solution { + int countRoutes(List locations, int start, int finish, int fuel) { + final MOD = 1000000007; + int n = locations.length; + List> dp = List.generate(n, (_) => List.filled(fuel + 1, 0)); + for (int city = 0; city < n; city++) { + dp[city][0] = (city == finish) ? 1 : 0; + } + for (int left = 1; left <= fuel; left++) { + for (int city = 0; city < n; city++) { + int total = (city == finish) ? 1 : 0; + for (int nxt = 0; nxt < n; nxt++) { + if (nxt != city) { + int cost = (locations[nxt] - locations[city]).abs(); + if (cost <= left) { + total = (total + dp[nxt][left - cost]) % MOD; + } + } + } + dp[city][left] = total; + } + } + return dp[start][fuel]; + } +} diff --git a/tests/1501-2000/1575. count-all-possible-routes/sol.go b/tests/1501-2000/1575. count-all-possible-routes/sol.go new file mode 100644 index 00000000..a55b8ac5 --- /dev/null +++ b/tests/1501-2000/1575. count-all-possible-routes/sol.go @@ -0,0 +1,38 @@ +func countRoutes(locations []int, start int, finish int, fuel int) int { + const MOD = 1000000007 + n := len(locations) + dp := make([][]int, n) + for i := range dp { + dp[i] = make([]int, fuel+1) + } + for city := 0; city < n; city++ { + if city == finish { + dp[city][0] = 1 + } + } + for left := 1; left <= fuel; left++ { + for city := 0; city < n; city++ { + total := 0 + if city == finish { + total = 1 + } + for nxt := 0; nxt < n; nxt++ { + if nxt != city { + cost := abs(locations[nxt] - locations[city]) + if cost <= left { + total = (total + dp[nxt][left-cost]) % MOD + } + } + } + dp[city][left] = total + } + } + return dp[start][fuel] +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} diff --git a/tests/1501-2000/1575. count-all-possible-routes/sol.java b/tests/1501-2000/1575. count-all-possible-routes/sol.java new file mode 100644 index 00000000..dd425921 --- /dev/null +++ b/tests/1501-2000/1575. count-all-possible-routes/sol.java @@ -0,0 +1,25 @@ +class Solution { + public int countRoutes(int[] locations, int start, int finish, int fuel) { + final int MOD = 1000000007; + int n = locations.length; + int[][] dp = new int[n][fuel + 1]; + for (int city = 0; city < n; city++) { + dp[city][0] = (city == finish) ? 1 : 0; + } + for (int left = 1; left <= fuel; left++) { + for (int city = 0; city < n; city++) { + int total = (city == finish) ? 1 : 0; + for (int nxt = 0; nxt < n; nxt++) { + if (nxt != city) { + int cost = Math.abs(locations[nxt] - locations[city]); + if (cost <= left) { + total = (total + dp[nxt][left - cost]) % MOD; + } + } + } + dp[city][left] = total; + } + } + return dp[start][fuel]; + } +} diff --git a/tests/1501-2000/1575. count-all-possible-routes/sol.kt b/tests/1501-2000/1575. count-all-possible-routes/sol.kt new file mode 100644 index 00000000..b3f16758 --- /dev/null +++ b/tests/1501-2000/1575. count-all-possible-routes/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun countRoutes(locations: IntArray, start: Int, finish: Int, fuel: Int): Int { + val MOD = 1000000007 + val n = locations.size + val dp = Array(n) { IntArray(fuel + 1) } + for (city in 0 until n) { + dp[city][0] = if (city == finish) 1 else 0 + } + for (left in 1..fuel) { + for (city in 0 until n) { + var total = if (city == finish) 1 else 0 + for (nxt in 0 until n) { + if (nxt != city) { + val cost = Math.abs(locations[nxt] - locations[city]) + if (cost <= left) { + total = (total + dp[nxt][left - cost]) % MOD + } + } + } + dp[city][left] = total + } + } + return dp[start][fuel] + } +} diff --git a/tests/1501-2000/1575. count-all-possible-routes/sol.py b/tests/1501-2000/1575. count-all-possible-routes/sol.py new file mode 100644 index 00000000..6b5b3fff --- /dev/null +++ b/tests/1501-2000/1575. count-all-possible-routes/sol.py @@ -0,0 +1,18 @@ +class Solution: + MOD = 1000000007 + + def countRoutes(self, locations, start, finish, fuel): + n = len(locations) + dp = [[0] * (fuel + 1) for _ in range(n)] + for city in range(n): + dp[city][0] = 1 if city == finish else 0 + for left in range(1, fuel + 1): + for city in range(n): + total = 1 if city == finish else 0 + for nxt in range(n): + if nxt != city: + cost = abs(locations[nxt] - locations[city]) + if cost <= left: + total = (total + dp[nxt][left - cost]) % self.MOD + dp[city][left] = total + return dp[start][fuel] diff --git a/tests/1501-2000/1575. count-all-possible-routes/sol.py2 b/tests/1501-2000/1575. count-all-possible-routes/sol.py2 new file mode 100644 index 00000000..2040c06e --- /dev/null +++ b/tests/1501-2000/1575. count-all-possible-routes/sol.py2 @@ -0,0 +1,24 @@ +class Solution(object): + def countRoutes(self, locations, start, finish, fuel): + """ + :type locations: List[int] + :type start: int + :type finish: int + :type fuel: int + :rtype: int + """ + MOD = 1000000007 + n = len(locations) + dp = [[0] * (fuel + 1) for _ in range(n)] + for city in range(n): + dp[city][0] = 1 if city == finish else 0 + for left in range(1, fuel + 1): + for city in range(n): + total = 1 if city == finish else 0 + for nxt in range(n): + if nxt != city: + cost = abs(locations[nxt] - locations[city]) + if cost <= left: + total = (total + dp[nxt][left - cost]) % MOD + dp[city][left] = total + return dp[start][fuel] diff --git a/tests/1501-2000/1575. count-all-possible-routes/sol.rb b/tests/1501-2000/1575. count-all-possible-routes/sol.rb new file mode 100644 index 00000000..a21310d4 --- /dev/null +++ b/tests/1501-2000/1575. count-all-possible-routes/sol.rb @@ -0,0 +1,28 @@ +# @param {Integer[]} locations +# @param {Integer} start +# @param {Integer} finish +# @param {Integer} fuel +# @return {Integer} +def count_routes(locations, start, finish, fuel) + mod = 1000000007 + n = locations.length + dp = Array.new(n) { Array.new(fuel + 1, 0) } + (0...n).each do |city| + dp[city][0] = (city == finish) ? 1 : 0 + end + (1..fuel).each do |left| + (0...n).each do |city| + total = (city == finish) ? 1 : 0 + (0...n).each do |nxt| + if nxt != city + cost = (locations[nxt] - locations[city]).abs + if cost <= left + total = (total + dp[nxt][left - cost]) % mod + end + end + end + dp[city][left] = total + end + end + dp[start][fuel] +end diff --git a/tests/1501-2000/1575. count-all-possible-routes/sol.rs b/tests/1501-2000/1575. count-all-possible-routes/sol.rs new file mode 100644 index 00000000..0b82c797 --- /dev/null +++ b/tests/1501-2000/1575. count-all-possible-routes/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn count_routes(locations: Vec, start: i32, finish: i32, fuel: i32) -> i32 { + const MOD: i32 = 1000000007; + let n = locations.len(); + let mut dp = vec![vec![0; (fuel as usize) + 1]; n]; + for city in 0..n { + dp[city][0] = if city == finish as usize { 1 } else { 0 }; + } + for left in 1..=(fuel as usize) { + for city in 0..n { + let mut total = if city == finish as usize { 1 } else { 0 }; + for nxt in 0..n { + if nxt != city { + let cost = (locations[nxt] - locations[city]).abs() as usize; + if cost <= left { + total = (total + dp[nxt][left - cost]) % MOD; + } + } + } + dp[city][left] = total; + } + } + dp[start as usize][fuel as usize] + } +} diff --git a/tests/1501-2000/1575. count-all-possible-routes/sol.swift b/tests/1501-2000/1575. count-all-possible-routes/sol.swift new file mode 100644 index 00000000..a3ea7c93 --- /dev/null +++ b/tests/1501-2000/1575. count-all-possible-routes/sol.swift @@ -0,0 +1,25 @@ +class Solution { + func countRoutes(_ locations: [Int], _ start: Int, _ finish: Int, _ fuel: Int) -> Int { + let MOD = 1000000007 + let n = locations.count + var dp = [[Int]](repeating: [Int](repeating: 0, count: fuel + 1), count: n) + for city in 0.. + new Array(fuel + 1).fill(0), + ); + for (let city = 0; city < n; city++) { + dp[city][0] = city === finish ? 1 : 0; + } + for (let left = 1; left <= fuel; left++) { + for (let city = 0; city < n; city++) { + let total = city === finish ? 1 : 0; + for (let nxt = 0; nxt < n; nxt++) { + if (nxt !== city) { + const cost = Math.abs(locations[nxt] - locations[city]); + if (cost <= left) { + total = (total + dp[nxt][left - cost]) % MOD; + } + } + } + dp[city][left] = total; + } + } + return dp[start][fuel]; +} diff --git a/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/manifest.yaml b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/manifest.yaml new file mode 100644 index 00000000..67229795 --- /dev/null +++ b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/manifest.yaml @@ -0,0 +1,186 @@ +entry: + id: 1576 + title: "replace-all-s-to-avoid-consecutive-repeating-characters" + params: + s: + type: string + call: + cpp: "Solution().modifyString({s})" + rust: "Solution::modify_string({s})" + python3: "Solution().modifyString({s})" + python2: "Solution().modifyString({s})" + ruby: "modify_string({s})" + java: "new Solution().modifyString({s})" + csharp: "new Solution().ModifyString({s})" + kotlin: "Solution().modifyString({s})" + go: "modifyString({s})" + dart: "Solution().modifyString({s})" + swift: "Solution().modifyString({s})" + typescript: "modifyString({s})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().modifyString(s, {result})" + checker: | + class Checker: + def modifyString(self, s, result): + if not isinstance(result, str) or len(result) != len(s): + return False + for original, actual in zip(s, result): + if original != '?' and actual != original: + return False + if original == '?' and not ('a' <= actual <= 'z'): + return False + return all(result[i] != result[i - 1] for i in range(1, len(result))) + +seed: 1576 + +tests: + - name: "example_question_prefix" + in: + s: "?zs" + - name: "example_middle_question" + in: + s: "ubv?w" + - name: "single_question" + in: + s: "?" + - name: "single_fixed" + in: + s: "a" + - name: "two_questions" + in: + s: "??" + - name: "three_questions" + in: + s: "???" + - name: "question_suffix" + in: + s: "abc?" + - name: "question_prefix" + in: + s: "?abc" + - name: "alternating_fixed" + in: + s: "ababab" + - name: "all_fixed_alphabet" + in: + s: "abcdefghijklmnopqrstuvwxyz" + - name: "question_between_different" + in: + s: "a?b" + - name: "question_between_a_and_a" + in: + s: "a?a" + - name: "question_between_a_and_b" + in: + s: "a?b?c" + - name: "question_between_b_and_a" + in: + s: "b?a" + - name: "two_question_gap" + in: + s: "a??b" + - name: "three_question_gap" + in: + s: "a???b" + - name: "question_runs_edges" + in: + s: "???abc???" + - name: "question_runs_inside" + in: + s: "ab???cd" + - name: "isolated_questions" + in: + s: "a?b?c?d" + - name: "repeated_question_runs" + in: + s: "a??b??c??d" + - name: "near_full_length_fixed" + in: + s: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv" + - name: "max_length_all_questions" + in: + s: "????????????????????????????????????????????????????????????????????????????????????????????????????" + - name: "max_length_alternating" + in: + s: "abababababababababababababababababababababababababababababababababababababababababababababababababab" + - name: "max_length_question_edges" + in: + s: "?abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopq?" + - name: "max_length_periodic_questions" + in: + s: "a?b?c?d?e?f?g?h?i?j?k?l?m?n?o?p?q?r?s?t?u?v?w?x?y?z?a?b?c?d?e?f?g?h?i?j?k?l?m?n?o?p?q?r?s?t?u?" + - name: "digits_not_allowed_fixed_letters" + in: + s: "q?w?e?r?t?y?u?i?o?p" + - name: "alternating_question_fixed" + in: + s: "?a?b?c?d?e?f?g" + - name: "long_question_prefix" + in: + s: "??????????abcdefghij" + - name: "long_question_suffix" + in: + s: "abcdefghij??????????" + - name: "long_question_middle" + in: + s: "abcdefghij??????????klmnopqrst" + - name: "letters_around_a_run" + in: + s: "m????n" + - name: "letters_around_b_run" + in: + s: "a????b" + - name: "mixed_short_runs" + in: + s: "?a??b???c??d?" + - name: "every_other_question" + in: + s: "?a?b?c?d?e?f?g?h?i?j" + - name: "question_between_same_neighbors" + in: + s: "x?x?x" + - name: "question_run_with_boundary_choices" + in: + s: "z????z" + - name: "mixed_alphabet_case" + in: + s: "l?m?n?o?p?q?r?s?t?u?v?w?x?y?z" + - name: "generated_short_mixed" + in: + s: + gen: "str" + len: 1 + alphabet: "?" + - name: "generated_medium_mixed" + in: + s: + gen: "str" + len: 25 + alphabet: "?" + - name: "generated_long_mixed" + in: + s: + gen: "str" + len: 99 + alphabet: "?" + - name: "generated_question_heavy" + in: + s: + gen: "str" + len: 100 + alphabet: "?" + - name: "generated_full_alphabet" + in: + s: + gen: "str" + len: 100 + alphabet: "?" diff --git a/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.cpp b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.cpp new file mode 100644 index 00000000..79aada4a --- /dev/null +++ b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + string modifyString(string s) { + int n = s.size(); + for (int i = 0; i < n; i++) { + if (s[i] == '?') { + char left = i > 0 ? s[i-1] : ' '; + char right = i+1 < n ? s[i+1] : ' '; + if (left != 'a' && right != 'a') { + s[i] = 'a'; + } else if (left != 'b' && right != 'b') { + s[i] = 'b'; + } else { + s[i] = 'c'; + } + } + } + return s; + } +}; diff --git a/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.cs b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.cs new file mode 100644 index 00000000..4bbdaed9 --- /dev/null +++ b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public string ModifyString(string s) { + char[] arr = s.ToCharArray(); + int n = arr.Length; + for (int i = 0; i < n; i++) { + if (arr[i] == '?') { + char left = i > 0 ? arr[i-1] : ' '; + char right = i+1 < n ? arr[i+1] : ' '; + if (left != 'a' && right != 'a') { + arr[i] = 'a'; + } else if (left != 'b' && right != 'b') { + arr[i] = 'b'; + } else { + arr[i] = 'c'; + } + } + } + return new string(arr); + } +} diff --git a/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.dart b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.dart new file mode 100644 index 00000000..b6130493 --- /dev/null +++ b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.dart @@ -0,0 +1,20 @@ +class Solution { + String modifyString(String s) { + List arr = s.split(''); + int n = arr.length; + for (int i = 0; i < n; i++) { + if (arr[i] == '?') { + String left = i > 0 ? arr[i-1] : ' '; + String right = i+1 < n ? arr[i+1] : ' '; + if (left != 'a' && right != 'a') { + arr[i] = 'a'; + } else if (left != 'b' && right != 'b') { + arr[i] = 'b'; + } else { + arr[i] = 'c'; + } + } + } + return arr.join(); + } +} diff --git a/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.go b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.go new file mode 100644 index 00000000..02f4cd8b --- /dev/null +++ b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.go @@ -0,0 +1,24 @@ +func modifyString(s string) string { + arr := []byte(s) + n := len(arr) + for i := 0; i < n; i++ { + if arr[i] == '?' { + var left byte = ' ' + if i > 0 { + left = arr[i-1] + } + var right byte = ' ' + if i+1 < n { + right = arr[i+1] + } + if left != 'a' && right != 'a' { + arr[i] = 'a' + } else if left != 'b' && right != 'b' { + arr[i] = 'b' + } else { + arr[i] = 'c' + } + } + } + return string(arr) +} diff --git a/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.java b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.java new file mode 100644 index 00000000..59b23e2a --- /dev/null +++ b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.java @@ -0,0 +1,20 @@ +class Solution { + public String modifyString(String s) { + char[] arr = s.toCharArray(); + int n = arr.length; + for (int i = 0; i < n; i++) { + if (arr[i] == '?') { + char left = i > 0 ? arr[i-1] : ' '; + char right = i+1 < n ? arr[i+1] : ' '; + if (left != 'a' && right != 'a') { + arr[i] = 'a'; + } else if (left != 'b' && right != 'b') { + arr[i] = 'b'; + } else { + arr[i] = 'c'; + } + } + } + return new String(arr); + } +} diff --git a/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.kt b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.kt new file mode 100644 index 00000000..53ba71d4 --- /dev/null +++ b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.kt @@ -0,0 +1,18 @@ +class Solution { + fun modifyString(s: String): String { + val arr = s.toCharArray() + val n = arr.size + for (i in 0 until n) { + if (arr[i] == '?') { + val left = if (i > 0) arr[i-1] else ' ' + val right = if (i+1 < n) arr[i+1] else ' ' + arr[i] = when { + left != 'a' && right != 'a' -> 'a' + left != 'b' && right != 'b' -> 'b' + else -> 'c' + } + } + } + return String(arr) + } +} diff --git a/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.py b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.py new file mode 100644 index 00000000..69bb3e40 --- /dev/null +++ b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.py @@ -0,0 +1,18 @@ +class Solution: + def modifyString(self, s: str) -> str: + s = list(s) + n = len(s) + + for i in range(n): + if s[i] == "?": + left = s[i - 1] if i > 0 else " " + right = s[i + 1] if i + 1 < n else " " + + if left != "a" and right != "a": + s[i] = "a" + elif left != "b" and right != "b": + s[i] = "b" + else: + s[i] = "c" + + return "".join(s) diff --git a/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.py2 b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.py2 new file mode 100644 index 00000000..24fc8139 --- /dev/null +++ b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.py2 @@ -0,0 +1,19 @@ +class Solution(object): + def modifyString(self, s): + """ + :type s: str + :rtype: str + """ + s = list(s) + n = len(s) + for i in range(n): + if s[i] == '?': + left = s[i-1] if i > 0 else ' ' + right = s[i+1] if i+1 < n else ' ' + if left != 'a' and right != 'a': + s[i] = 'a' + elif left != 'b' and right != 'b': + s[i] = 'b' + else: + s[i] = 'c' + return "".join(s) diff --git a/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.rb b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.rb new file mode 100644 index 00000000..9c4820a9 --- /dev/null +++ b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.rb @@ -0,0 +1,18 @@ +def modify_string(s) + s = s.chars + n = s.length + (0...n).each do |i| + if s[i] == '?' + left = i > 0 ? s[i-1] : ' ' + right = i+1 < n ? s[i+1] : ' ' + if left != 'a' && right != 'a' + s[i] = 'a' + elsif left != 'b' && right != 'b' + s[i] = 'b' + else + s[i] = 'c' + end + end + end + s.join +end diff --git a/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.rs b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.rs new file mode 100644 index 00000000..ffde9eb2 --- /dev/null +++ b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn modify_string(s: String) -> String { + let mut chars: Vec = s.chars().collect(); + let n = chars.len(); + for i in 0..n { + if chars[i] == '?' { + let left = if i > 0 { chars[i-1] } else { ' ' }; + let right = if i+1 < n { chars[i+1] } else { ' ' }; + if left != 'a' && right != 'a' { + chars[i] = 'a'; + } else if left != 'b' && right != 'b' { + chars[i] = 'b'; + } else { + chars[i] = 'c'; + } + } + } + chars.into_iter().collect() + } +} diff --git a/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.swift b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.swift new file mode 100644 index 00000000..af119c7f --- /dev/null +++ b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func modifyString(_ s: String) -> String { + var arr = Array(s) + let n = arr.count + for i in 0.. 0 ? arr[i-1] : " " + let right: Character = i+1 < n ? arr[i+1] : " " + if left != "a" && right != "a" { + arr[i] = "a" + } else if left != "b" && right != "b" { + arr[i] = "b" + } else { + arr[i] = "c" + } + } + } + return String(arr) + } +} diff --git a/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.ts b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.ts new file mode 100644 index 00000000..a20a60a4 --- /dev/null +++ b/tests/1501-2000/1576. replace-all-s-to-avoid-consecutive-repeating-characters/sol.ts @@ -0,0 +1,18 @@ +function modifyString(s: string): string { + const arr: string[] = s.split(""); + const n = arr.length; + for (let i = 0; i < n; i++) { + if (arr[i] === "?") { + const left: string = i > 0 ? arr[i - 1] : " "; + const right: string = i + 1 < n ? arr[i + 1] : " "; + if (left !== "a" && right !== "a") { + arr[i] = "a"; + } else if (left !== "b" && right !== "b") { + arr[i] = "b"; + } else { + arr[i] = "c"; + } + } + } + return arr.join(""); +} diff --git a/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/manifest.yaml b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/manifest.yaml new file mode 100644 index 00000000..21afb50c --- /dev/null +++ b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/manifest.yaml @@ -0,0 +1,358 @@ +entry: + id: 1577 + title: "number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers" + params: + nums1: + type: array + items: + type: int + nums2: + type: array + items: + type: int + call: + cpp: "Solution().numTriplets({nums1}, {nums2})" + rust: "Solution::num_triplets({nums1}, {nums2})" + python3: "Solution().numTriplets({nums1}, {nums2})" + python2: "Solution().numTriplets({nums1}, {nums2})" + ruby: "num_triplets({nums1}, {nums2})" + java: "new Solution().numTriplets({nums1}, {nums2})" + csharp: "new Solution().NumTriplets({nums1}, {nums2})" + kotlin: "Solution().numTriplets({nums1}, {nums2})" + go: "numTriplets({nums1}, {nums2})" + dart: "Solution().numTriplets({nums1}, {nums2})" + swift: "Solution().numTriplets({nums1}, {nums2})" + typescript: "numTriplets({nums1}, {nums2})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().numTriplets(nums1, nums2, {result})" + checker: | + class Checker: + def numTriplets(self, nums1, nums2, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + + def count(a, b): + pairs = {} + for i in range(len(b)): + for j in range(i + 1, len(b)): + product = b[i] * b[j] + pairs[product] = pairs.get(product, 0) + 1 + return sum(pairs.get(value * value, 0) for value in a) + + expected = count(nums1, nums2) + count(nums2, nums1) + return result == expected + +seed: 1577001 + +tests: + - name: "example_one" + in: + nums1: [7, 4] + nums2: [5, 2, 8, 9] + out: 1 + - name: "example_two_duplicates" + in: + nums1: [1, 1] + nums2: [1, 1, 1] + out: 9 + - name: "example_three" + in: + nums1: [7, 7, 8, 3] + nums2: [1, 2, 9, 7] + out: 2 + - name: "single_equal_values" + in: + nums1: [1] + nums2: [1] + out: 0 + - name: "single_mismatch" + in: + nums1: [1] + nums2: [2] + out: 0 + - name: "reverse_single_mismatch" + in: + nums1: [2] + nums2: [1] + out: 0 + - name: "two_by_two_equal" + in: + nums1: [2, 2] + nums2: [2, 2] + out: 4 + - name: "three_by_two_equal" + in: + nums1: [3, 3, 3] + nums2: [3, 3] + out: 9 + - name: "small_no_products" + in: + nums1: [1, 2, 3] + nums2: [1, 2, 3] + out: 0 + - name: "mixed_small_products" + in: + nums1: [1, 2, 4] + nums2: [1, 2, 4] + out: 2 + - name: "three_equal_tens" + in: + nums1: [10, 10, 10] + nums2: [10, 10, 10] + out: 18 + - name: "maximum_single_against_pair" + in: + nums1: [100000] + nums2: [100000, 100000] + out: 1 + - name: "maximum_pair_against_single" + in: + nums1: [100000, 100000] + nums2: [100000] + out: 1 + - name: "four_equal_ones" + in: + nums1: [1, 1, 1, 1] + nums2: [1, 1, 1, 1] + out: 48 + - name: "four_by_three_equal_twos" + in: + nums1: [2, 2, 2, 2] + nums2: [2, 2, 2] + out: 30 + - name: "disjoint_values" + in: + nums1: [1, 2, 3, 4] + nums2: [5, 6, 7, 8] + out: 0 + - name: "square_products" + in: + nums1: [5, 10, 15] + nums2: [1, 25, 100] + out: 2 + - name: "overlap_without_square" + in: + nums1: [6, 10] + nums2: [2, 3, 5, 6] + out: 0 + - name: "several_square_matches" + in: + nums1: [4, 9, 16] + nums2: [2, 8, 3, 48] + out: 2 + - name: "duplicate_two_values" + in: + nums1: [1, 1, 2, 2] + nums2: [1, 1, 2, 2] + out: 8 + - name: "nonmatching_progression" + in: + nums1: [2, 3, 4] + nums2: [4, 6, 9] + out: 0 + - name: "scaled_values" + in: + nums1: [12, 18, 20] + nums2: [3, 4, 6, 9] + out: 0 + - name: "two_squares_no_pair" + in: + nums1: [25, 36] + nums2: [5, 6, 10] + out: 0 + - name: "sequential_disjoint" + in: + nums1: [7, 8, 9, 10] + nums2: [1, 2, 3, 4, 5] + out: 0 + - name: "large_squares_without_match" + in: + nums1: [11, 13] + nums2: [121, 143, 169] + out: 0 + - name: "perfect_square_sequence" + in: + nums1: [1, 4, 9, 16] + nums2: [1, 2, 3, 4] + out: 3 + - name: "multiples_with_one_match" + in: + nums1: [2, 5, 8] + nums2: [4, 10, 20, 25] + out: 1 + - name: "three_multiples" + in: + nums1: [15, 20, 25] + nums2: [3, 5, 10, 15] + out: 0 + - name: "medium_values" + in: + nums1: [50, 75] + nums2: [5, 10, 15, 25] + out: 0 + - name: "nearby_large_values" + in: + nums1: [99, 100, 101] + nums2: [1, 10, 99, 100] + out: 0 + - name: "thousands" + in: + nums1: [1000, 2000] + nums2: [10, 20, 40, 100] + out: 0 + - name: "repeated_one_two" + in: + nums1: [1, 2, 1, 2, 1] + nums2: [1, 2, 1, 2] + out: 13 + - name: "three_six_nine" + in: + nums1: [3, 6, 9, 12] + nums2: [3, 6, 9] + out: 1 + - name: "fourteen_family" + in: + nums1: [14, 21] + nums2: [7, 14, 21, 42] + out: 0 + - name: "powers_of_two_overlap" + in: + nums1: [2, 4, 8, 16] + nums2: [1, 2, 4, 8] + out: 4 + - name: "generated_small" + seed: 157701 + in: + nums1: + gen: "array" + len: + gen: "int" + min: 1 + max: 25 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + nums2: + gen: "array" + len: + gen: "int" + min: 1 + max: 25 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + - name: "generated_medium" + seed: 157702 + in: + nums1: + gen: "array" + len: + gen: "int" + min: 100 + max: 250 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + nums2: + gen: "array" + len: + gen: "int" + min: 100 + max: 250 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_dense" + seed: 157703 + in: + nums1: + gen: "array" + len: 500 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: "int" + nums2: + gen: "array" + len: 500 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_near_limit_a" + seed: 157704 + in: + nums1: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + nums2: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_near_limit_b" + seed: 157705 + in: + nums1: + gen: "array" + len: 999 + of: + gen: "int" + min: 99900 + max: 100000 + distinct: false + sorted: false + elemType: "int" + nums2: + gen: "array" + len: 998 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.cpp b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.cpp new file mode 100644 index 00000000..0caf98b0 --- /dev/null +++ b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int numTriplets(vector& nums1, vector& nums2) { + auto count_pairs = [](vector& numsA, vector& numsB) { + unordered_map freq; + for (int i = 0; i < numsB.size(); i++) { + for (int j = i + 1; j < numsB.size(); j++) { + long long prod = (long long)numsB[i] * numsB[j]; + freq[prod]++; + } + } + int count = 0; + for (int num : numsA) { + long long sq = (long long)num * num; + count += freq[sq]; + } + return count; + }; + return count_pairs(nums1, nums2) + count_pairs(nums2, nums1); + } +}; diff --git a/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.cs b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.cs new file mode 100644 index 00000000..00ce0016 --- /dev/null +++ b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public int NumTriplets(int[] nums1, int[] nums2) { + int CountPairs(int[] numsA, int[] numsB) { + var freq = new Dictionary(); + for (int i = 0; i < numsB.Length; i++) { + for (int j = i + 1; j < numsB.Length; j++) { + long prod = (long)numsB[i] * numsB[j]; + freq[prod] = freq.GetValueOrDefault(prod, 0) + 1; + } + } + int count = 0; + foreach (int num in numsA) { + long sq = (long)num * num; + count += freq.GetValueOrDefault(sq, 0); + } + return count; + } + return CountPairs(nums1, nums2) + CountPairs(nums2, nums1); + } +} diff --git a/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.dart b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.dart new file mode 100644 index 00000000..5fbebb08 --- /dev/null +++ b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.dart @@ -0,0 +1,19 @@ +class Solution { + int numTriplets(List nums1, List nums2) { + int countPairs(List numsA, List numsB) { + Map freq = {}; + for (int i = 0; i < numsB.length; i++) { + for (int j = i + 1; j < numsB.length; j++) { + int prod = numsB[i] * numsB[j]; + freq[prod] = (freq[prod] ?? 0) + 1; + } + } + int count = 0; + for (int num in numsA) { + count += freq[num * num] ?? 0; + } + return count; + } + return countPairs(nums1, nums2) + countPairs(nums2, nums1); + } +} diff --git a/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.go b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.go new file mode 100644 index 00000000..819a33fa --- /dev/null +++ b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.go @@ -0,0 +1,17 @@ +func numTriplets(nums1 []int, nums2 []int) int { + countPairs := func(numsA, numsB []int) int { + freq := make(map[int]int) + for i := 0; i < len(numsB); i++ { + for j := i + 1; j < len(numsB); j++ { + prod := numsB[i] * numsB[j] + freq[prod]++ + } + } + count := 0 + for _, num := range numsA { + count += freq[num*num] + } + return count + } + return countPairs(nums1, nums2) + countPairs(nums2, nums1) +} diff --git a/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.java b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.java new file mode 100644 index 00000000..6b6b1f64 --- /dev/null +++ b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.java @@ -0,0 +1,20 @@ +class Solution { + public int numTriplets(int[] nums1, int[] nums2) { + return countPairs(nums1, nums2) + countPairs(nums2, nums1); + } + + private int countPairs(int[] numsA, int[] numsB) { + Map freq = new HashMap<>(); + for (int i = 0; i < numsB.length; i++) { + for (int j = i + 1; j < numsB.length; j++) { + long prod = (long) numsB[i] * numsB[j]; + freq.put(prod, freq.getOrDefault(prod, 0) + 1); + } + } + int count = 0; + for (int num : numsA) { + count += freq.getOrDefault((long) num * num, 0); + } + return count; + } +} diff --git a/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.kt b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.kt new file mode 100644 index 00000000..48709df6 --- /dev/null +++ b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.kt @@ -0,0 +1,19 @@ +class Solution { + fun numTriplets(nums1: IntArray, nums2: IntArray): Int { + fun countPairs(numsA: IntArray, numsB: IntArray): Int { + val freq = mutableMapOf() + for (i in numsB.indices) { + for (j in i + 1 until numsB.size) { + val prod = numsB[i].toLong() * numsB[j] + freq[prod] = freq.getOrDefault(prod, 0) + 1 + } + } + var count = 0 + for (num in numsA) { + count += freq.getOrDefault(num.toLong() * num, 0) + } + return count + } + return countPairs(nums1, nums2) + countPairs(nums2, nums1) + } +} diff --git a/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.py b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.py new file mode 100644 index 00000000..1179dfbc --- /dev/null +++ b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.py @@ -0,0 +1,26 @@ +from collections import Counter + + +class Solution(object): + def numTriplets(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: int + """ + + def count_pairs(numsA, numsB): + count = 0 + freq = Counter() + + for i in range(len(numsB)): + for j in range(i + 1, len(numsB)): + prod = numsB[i] * numsB[j] + freq[prod] += 1 + + for num in numsA: + sq = num * num + count += freq[sq] + return count + + return count_pairs(nums1, nums2) + count_pairs(nums2, nums1) diff --git a/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.py2 b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.py2 new file mode 100644 index 00000000..d43cf513 --- /dev/null +++ b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def numTriplets(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: int + """ + def count_pairs(numsA, numsB): + count = 0 + freq = {} + for i in range(len(numsB)): + for j in range(i + 1, len(numsB)): + prod = numsB[i] * numsB[j] + freq[prod] = freq.get(prod, 0) + 1 + for num in numsA: + sq = num * num + count += freq.get(sq, 0) + return count + + return count_pairs(nums1, nums2) + count_pairs(nums2, nums1) diff --git a/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.rb b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.rb new file mode 100644 index 00000000..8154e055 --- /dev/null +++ b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.rb @@ -0,0 +1,21 @@ +# @param {Integer[]} nums1 +# @param {Integer[]} nums2 +# @return {Integer} +def num_triplets(nums1, nums2) + def count_pairs(numsA, numsB) + freq = Hash.new(0) + (0...numsB.length).each do |i| + (i+1...numsB.length).each do |j| + prod = numsB[i] * numsB[j] + freq[prod] += 1 + end + end + count = 0 + numsA.each do |num| + count += freq[num * num] + end + count + end + + count_pairs(nums1, nums2) + count_pairs(nums2, nums1) +end diff --git a/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.rs b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.rs new file mode 100644 index 00000000..f65dd311 --- /dev/null +++ b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn num_triplets(nums1: Vec, nums2: Vec) -> i32 { + fn count_pairs(nums_a: &Vec, nums_b: &Vec) -> i32 { + use std::collections::HashMap; + let mut freq: HashMap = HashMap::new(); + for i in 0..nums_b.len() { + for j in (i+1)..nums_b.len() { + let prod = nums_b[i] as i64 * nums_b[j] as i64; + *freq.entry(prod).or_insert(0) += 1; + } + } + let mut count = 0; + for &num in nums_a { + let sq = num as i64 * num as i64; + count += freq.get(&sq).copied().unwrap_or(0); + } + count + } + count_pairs(&nums1, &nums2) + count_pairs(&nums2, &nums1) + } +} diff --git a/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.swift b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.swift new file mode 100644 index 00000000..b116a660 --- /dev/null +++ b/tests/1501-2000/1577. number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/sol.swift @@ -0,0 +1,19 @@ +class Solution { + func numTriplets(_ nums1: [Int], _ nums2: [Int]) -> Int { + func countPairs(_ numsA: [Int], _ numsB: [Int]) -> Int { + var freq: [Int: Int] = [:] + for i in 0.. { + const freq: Map = new Map(); + for (let i = 0; i < numsB.length; i++) { + for (let j = i + 1; j < numsB.length; j++) { + const prod = numsB[i] * numsB[j]; + freq.set(prod, (freq.get(prod) || 0) + 1); + } + } + let count = 0; + for (const num of numsA) { + count += freq.get(num * num) || 0; + } + return count; + }; + return countPairs(nums1, nums2) + countPairs(nums2, nums1); +} diff --git a/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/manifest.yaml b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/manifest.yaml new file mode 100644 index 00000000..ce0a9fd1 --- /dev/null +++ b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/manifest.yaml @@ -0,0 +1,227 @@ +entry: + id: 1578 + title: "minimum-time-to-make-rope-colorful" + params: + colors: + type: string + neededTime: + type: array + items: + type: int + call: + cpp: "Solution().minCost({colors}, {neededTime})" + rust: "Solution::min_cost({colors}, {neededTime})" + python3: "Solution().minCost({colors}, {neededTime})" + python2: "Solution().minCost({colors}, {neededTime})" + ruby: "min_cost({colors}, {neededTime})" + java: "new Solution().minCost({colors}, {neededTime})" + csharp: "new Solution().MinCost({colors}, {neededTime})" + kotlin: "Solution().minCost({colors}, {neededTime})" + go: "minCost({colors}, {neededTime})" + dart: "Solution().minCost({colors}, {neededTime})" + swift: "Solution().minCost({colors}, {neededTime})" + typescript: "minCost({colors}, {neededTime})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minCost(colors, neededTime, {result})" + checker: | + class Checker: + def minCost(self, colors, neededTime, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + keep = 0 + removed = 0 + for i, value in enumerate(neededTime): + if i == 0 or colors[i] != colors[i - 1]: + keep = value + else: + removed += min(keep, value) + keep = max(keep, value) + return result == removed + +seed: 1578001 + +tests: + - name: example-one + in: + colors: "abaac" + neededTime: [1, 2, 3, 4, 5] + out: 3 + - name: example-two-already-colorful + in: + colors: "abc" + neededTime: [1, 2, 3] + out: 0 + - name: example-three + in: + colors: "aabaa" + neededTime: [1, 2, 3, 4, 1] + out: 2 + - name: single-balloon + in: + colors: "z" + neededTime: [10000] + out: 0 + - name: two-equal-low-first + in: + colors: "aa" + neededTime: [1, 9] + out: 1 + - name: two-equal-high-first + in: + colors: "aa" + neededTime: [9, 1] + out: 1 + - name: two-different + in: + colors: "ab" + neededTime: [10000, 1] + out: 0 + - name: all-equal-increasing + in: + colors: "aaaa" + neededTime: [1, 2, 3, 4] + out: 6 + - name: all-equal-decreasing + in: + colors: "aaaa" + neededTime: [4, 3, 2, 1] + out: 6 + - name: all-equal-middle-maximum + in: + colors: "aaaaa" + neededTime: [5, 1, 9, 2, 4] + out: 12 + - name: leading-run + in: + colors: "aaab" + neededTime: [5, 1, 7, 3] + out: 6 + - name: trailing-run + in: + colors: "baaab" + neededTime: [8, 5, 1, 7, 2] + out: 6 + - name: separated-runs + in: + colors: "aabbcc" + neededTime: [1, 9, 2, 8, 3, 7] + out: 6 + - name: triple-middle + in: + colors: "abbba" + neededTime: [2, 9, 1, 4, 8] + out: 5 + - name: alternating-colors + in: + colors: "abababab" + neededTime: [10, 1, 9, 2, 8, 3, 7, 4] + out: 0 + - name: long-single-run + in: + colors: "bbbbbb" + neededTime: [6, 5, 4, 3, 2, 1] + out: 15 + - name: repeated-pairs + in: + colors: "aabbbaacc" + neededTime: [2, 3, 10, 1, 4, 7, 8, 2, 9] + out: 16 + - name: maximum-times + in: + colors: "aaaaa" + neededTime: [10000, 10000, 10000, 10000, 10000] + out: 40000 + - name: max-and-min-run + in: + colors: "aaabbb" + neededTime: [10000, 1, 10000, 2, 9999, 3] + out: 10006 + - name: three-colors-runs + in: + colors: "cccccddd" + neededTime: [4, 1, 8, 2, 7, 3, 9, 1] + out: 18 + - name: no-removal-long + in: + colors: "abcdefghij" + neededTime: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + out: 0 + - name: adjacent-runs-with-peaks + in: + colors: "aabcccbba" + neededTime: [3, 8, 2, 1, 10, 4, 6, 9, 5] + out: 14 + - name: one-run-each-letter + in: + colors: "aabbccddeeff" + neededTime: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + out: 36 + - name: runs-of-four + in: + colors: "aaaabbbb" + neededTime: [4, 3, 2, 1, 8, 7, 6, 5] + out: 24 + - name: alternating-runs + in: + colors: "aabbaa" + neededTime: [9, 2, 8, 1, 7, 3] + out: 6 + - name: all-low-equal + in: + colors: "zzzzz" + neededTime: [1, 1, 1, 1, 1] + out: 4 + - name: isolated-expensive + in: + colors: "aabaaac" + neededTime: [2, 100, 3, 4, 1, 8, 9] + out: 7 + - name: two-runs-with-single + in: + colors: "aaabaaa" + neededTime: [1, 2, 10, 50, 3, 4, 5] + out: 10 + - name: mixed-small-values + in: + colors: "abbaccca" + neededTime: [2, 5, 1, 4, 3, 6, 2, 8] + out: 6 + - name: long-two-color-runs + in: + colors: "aaaaabbbbb" + neededTime: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] + out: 36 + - name: high-value-single-preserved + in: + colors: "xxxyxxx" + neededTime: [2, 3, 100, 10000, 1, 4, 5] + out: 10 + - name: runs-touching-boundaries + in: + colors: "aabbccaa" + neededTime: [10, 1, 2, 9, 3, 8, 7, 4] + out: 10 + - name: repeated-color-after-break + in: + colors: "aaabacaaa" + neededTime: [3, 2, 1, 9, 8, 7, 6, 5, 4] + out: 12 + - name: all-distinct-lowercase + in: + colors: "qwertyuiop" + neededTime: [10000, 9999, 1, 5000, 2, 4000, 3, 3000, 4, 2000] + out: 0 + - name: final-long-run + in: + colors: "abcddeeee" + neededTime: [1, 2, 3, 4, 5, 6, 7, 8, 9] + out: 25 diff --git a/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.cpp b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.cpp new file mode 100644 index 00000000..562d5926 --- /dev/null +++ b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int minCost(string colors, vector& neededTime) { + int n = colors.length(); + int sum = 0; + for (int i = 1; i < n; i++) { + if (colors[i] == colors[i - 1]) { + sum += min(neededTime[i], neededTime[i - 1]); + neededTime[i] = max(neededTime[i], neededTime[i - 1]); + } + } + return sum; + } +}; diff --git a/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.cs b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.cs new file mode 100644 index 00000000..00bc0056 --- /dev/null +++ b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.cs @@ -0,0 +1,12 @@ +public class Solution { + public int MinCost(string colors, int[] neededTime) { + int sum = 0; + for (int i = 1; i < colors.Length; i++) { + if (colors[i] == colors[i - 1]) { + sum += Math.Min(neededTime[i], neededTime[i - 1]); + neededTime[i] = Math.Max(neededTime[i], neededTime[i - 1]); + } + } + return sum; + } +} diff --git a/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.dart b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.dart new file mode 100644 index 00000000..2b8a2f36 --- /dev/null +++ b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.dart @@ -0,0 +1,12 @@ +class Solution { + int minCost(String colors, List neededTime) { + var sum = 0; + for (var i = 1; i < colors.length; i++) { + if (colors[i] == colors[i - 1]) { + sum += neededTime[i] < neededTime[i - 1] ? neededTime[i] : neededTime[i - 1]; + neededTime[i] = neededTime[i] > neededTime[i - 1] ? neededTime[i] : neededTime[i - 1]; + } + } + return sum; + } +} diff --git a/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.go b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.go new file mode 100644 index 00000000..4369ea18 --- /dev/null +++ b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.go @@ -0,0 +1,15 @@ +func minCost(colors string, neededTime []int) int { + n := len(colors) + sum := 0 + for i := 1; i < n; i++ { + if colors[i] == colors[i-1] { + if neededTime[i] < neededTime[i-1] { + sum += neededTime[i] + neededTime[i] = neededTime[i-1] + } else { + sum += neededTime[i-1] + } + } + } + return sum +} diff --git a/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.java b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.java new file mode 100644 index 00000000..5414ce53 --- /dev/null +++ b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int minCost(String colors, int[] neededTime) { + int n = colors.length(); + int sum = 0; + for (int i = 1; i < n; i++) { + if (colors.charAt(i) == colors.charAt(i - 1)) { + sum += Math.min(neededTime[i], neededTime[i - 1]); + neededTime[i] = Math.max(neededTime[i], neededTime[i - 1]); + } + } + return sum; + } +} diff --git a/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.kt b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.kt new file mode 100644 index 00000000..23ff42f5 --- /dev/null +++ b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.kt @@ -0,0 +1,12 @@ +class Solution { + fun minCost(colors: String, neededTime: IntArray): Int { + var sum = 0 + for (i in 1 until colors.length) { + if (colors[i] == colors[i - 1]) { + sum += minOf(neededTime[i], neededTime[i - 1]) + neededTime[i] = maxOf(neededTime[i], neededTime[i - 1]) + } + } + return sum + } +} diff --git a/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.py b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.py new file mode 100644 index 00000000..c1b57d77 --- /dev/null +++ b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.py @@ -0,0 +1,8 @@ +class Solution(object): + def minCost(self, colors, neededTime): + n, sum_ = len(colors), 0 + for i in range(1, n): + if colors[i] == colors[i - 1]: + sum_ += min(neededTime[i], neededTime[i - 1]) + neededTime[i] = max(neededTime[i], neededTime[i - 1]) + return sum_ diff --git a/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.py2 b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.py2 new file mode 100644 index 00000000..c1b57d77 --- /dev/null +++ b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.py2 @@ -0,0 +1,8 @@ +class Solution(object): + def minCost(self, colors, neededTime): + n, sum_ = len(colors), 0 + for i in range(1, n): + if colors[i] == colors[i - 1]: + sum_ += min(neededTime[i], neededTime[i - 1]) + neededTime[i] = max(neededTime[i], neededTime[i - 1]) + return sum_ diff --git a/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.rb b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.rb new file mode 100644 index 00000000..3cda8211 --- /dev/null +++ b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.rb @@ -0,0 +1,14 @@ +# @param {String} colors +# @param {Integer[]} needed_time +# @return {Integer} +def min_cost(colors, needed_time) + n = colors.length + sum_ = 0 + (1...n).each do |i| + if colors[i] == colors[i - 1] + sum_ += [needed_time[i], needed_time[i - 1]].min + needed_time[i] = [needed_time[i], needed_time[i - 1]].max + end + end + sum_ +end diff --git a/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.rs b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.rs new file mode 100644 index 00000000..dd565d14 --- /dev/null +++ b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn min_cost(colors: String, needed_time: Vec) -> i32 { + let chars: Vec = colors.chars().collect(); + let n = chars.len(); + let mut sum = 0; + let mut time = needed_time; + for i in 1..n { + if chars[i] == chars[i - 1] { + sum += time[i].min(time[i - 1]); + time[i] = time[i].max(time[i - 1]); + } + } + sum + } +} diff --git a/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.swift b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.swift new file mode 100644 index 00000000..802b635e --- /dev/null +++ b/tests/1501-2000/1578. minimum-time-to-make-rope-colorful/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func minCost(_ colors: String, _ neededTime: [Int]) -> Int { + let n = colors.count + var sum = 0 + var time = neededTime // local mutable copy + let chars = Array(colors) + for i in 1..>& edges) { + sort(edges.begin(), edges.end(), [](const vector& a, const vector& b) { + return a[0] > b[0]; + }); + vector parentA(n + 1), parentB(n + 1); + vector rankA(n + 1, 0), rankB(n + 1, 0); + iota(parentA.begin(), parentA.end(), 0); + iota(parentB.begin(), parentB.end(), 0); + + function&, int)> find = [&](vector& parent, int x) { + if (parent[x] != x) parent[x] = find(parent, parent[x]); + return parent[x]; + }; + + auto unionSet = [&](vector& parent, vector& rank, int x, int y) { + int rootX = find(parent, x); + int rootY = find(parent, y); + if (rootX == rootY) return false; + if (rank[rootX] < rank[rootY]) { + parent[rootX] = rootY; + } else if (rank[rootX] > rank[rootY]) { + parent[rootY] = rootX; + } else { + parent[rootX] = rootY; + rank[rootY]++; + } + return true; + }; + + int removed = 0; + int aliceEdges = 0, bobEdges = 0; + for (auto& e : edges) { + if (e[0] == 3) { + if (unionSet(parentA, rankA, e[1], e[2])) { + unionSet(parentB, rankB, e[1], e[2]); + aliceEdges++; + bobEdges++; + } else { + removed++; + } + } else if (e[0] == 2) { + if (unionSet(parentB, rankB, e[1], e[2])) { + bobEdges++; + } else { + removed++; + } + } else { + if (unionSet(parentA, rankA, e[1], e[2])) { + aliceEdges++; + } else { + removed++; + } + } + } + return (bobEdges == n - 1 && aliceEdges == n - 1) ? removed : -1; + } +}; diff --git a/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.cs b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.cs new file mode 100644 index 00000000..4d304554 --- /dev/null +++ b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.cs @@ -0,0 +1,62 @@ +public class Solution { + public int MaxNumEdgesToRemove(int n, int[][] edges) { + Array.Sort(edges, (a, b) => b[0].CompareTo(a[0])); + int[] parentA = new int[n + 1]; + int[] parentB = new int[n + 1]; + for (int i = 0; i <= n; i++) { + parentA[i] = i; + parentB[i] = i; + } + int[] rankA = new int[n + 1]; + int[] rankB = new int[n + 1]; + + int Find(int[] parent, int x) { + if (parent[x] != x) { + parent[x] = Find(parent, parent[x]); + } + return parent[x]; + } + + bool Union(int[] parent, int[] rank, int x, int y) { + int rootX = Find(parent, x); + int rootY = Find(parent, y); + if (rootX == rootY) return false; + if (rank[rootX] < rank[rootY]) { + parent[rootX] = rootY; + } else if (rank[rootX] > rank[rootY]) { + parent[rootY] = rootX; + } else { + parent[rootX] = rootY; + rank[rootY]++; + } + return true; + } + + int removed = 0; + int aliceEdges = 0, bobEdges = 0; + foreach (var e in edges) { + if (e[0] == 3) { + if (Union(parentA, rankA, e[1], e[2])) { + Union(parentB, rankB, e[1], e[2]); + aliceEdges++; + bobEdges++; + } else { + removed++; + } + } else if (e[0] == 2) { + if (Union(parentB, rankB, e[1], e[2])) { + bobEdges++; + } else { + removed++; + } + } else { + if (Union(parentA, rankA, e[1], e[2])) { + aliceEdges++; + } else { + removed++; + } + } + } + return (bobEdges == n - 1 && aliceEdges == n - 1) ? removed : -1; + } +} diff --git a/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.dart b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.dart new file mode 100644 index 00000000..129f93c9 --- /dev/null +++ b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.dart @@ -0,0 +1,59 @@ +class Solution { + int maxNumEdgesToRemove(int n, List> edges) { + edges.sort((a, b) => b[0].compareTo(a[0])); + List parentA = List.generate(n + 1, (i) => i); + List parentB = List.generate(n + 1, (i) => i); + List rankA = List.filled(n + 1, 0); + List rankB = List.filled(n + 1, 0); + + int find(List parent, int x) { + if (parent[x] != x) { + parent[x] = find(parent, parent[x]); + } + return parent[x]; + } + + bool union(List parent, List rank, int x, int y) { + int rootX = find(parent, x); + int rootY = find(parent, y); + if (rootX == rootY) return false; + if (rank[rootX] < rank[rootY]) { + parent[rootX] = rootY; + } else if (rank[rootX] > rank[rootY]) { + parent[rootY] = rootX; + } else { + parent[rootX] = rootY; + rank[rootY]++; + } + return true; + } + + int removed = 0; + int aliceEdges = 0; + int bobEdges = 0; + for (var e in edges) { + if (e[0] == 3) { + if (union(parentA, rankA, e[1], e[2])) { + union(parentB, rankB, e[1], e[2]); + aliceEdges++; + bobEdges++; + } else { + removed++; + } + } else if (e[0] == 2) { + if (union(parentB, rankB, e[1], e[2])) { + bobEdges++; + } else { + removed++; + } + } else { + if (union(parentA, rankA, e[1], e[2])) { + aliceEdges++; + } else { + removed++; + } + } + } + return (bobEdges == n - 1 && aliceEdges == n - 1) ? removed : -1; + } +} diff --git a/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.go b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.go new file mode 100644 index 00000000..ebbfdb27 --- /dev/null +++ b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.go @@ -0,0 +1,69 @@ +func maxNumEdgesToRemove(n int, edges [][]int) int { + sort.Slice(edges, func(i, j int) bool { + return edges[i][0] > edges[j][0] + }) + parentA := make([]int, n+1) + parentB := make([]int, n+1) + for i := range parentA { + parentA[i] = i + parentB[i] = i + } + rankA := make([]int, n+1) + rankB := make([]int, n+1) + + var find func(parent []int, x int) int + find = func(parent []int, x int) int { + if parent[x] != x { + parent[x] = find(parent, parent[x]) + } + return parent[x] + } + + union := func(parent []int, rank []int, x, y int) bool { + rootX := find(parent, x) + rootY := find(parent, y) + if rootX == rootY { + return false + } + if rank[rootX] < rank[rootY] { + parent[rootX] = rootY + } else if rank[rootX] > rank[rootY] { + parent[rootY] = rootX + } else { + parent[rootX] = rootY + rank[rootY]++ + } + return true + } + + removed := 0 + aliceEdges := 0 + bobEdges := 0 + for _, e := range edges { + if e[0] == 3 { + if union(parentA, rankA, e[1], e[2]) { + union(parentB, rankB, e[1], e[2]) + aliceEdges++ + bobEdges++ + } else { + removed++ + } + } else if e[0] == 2 { + if union(parentB, rankB, e[1], e[2]) { + bobEdges++ + } else { + removed++ + } + } else { + if union(parentA, rankA, e[1], e[2]) { + aliceEdges++ + } else { + removed++ + } + } + } + if bobEdges == n-1 && aliceEdges == n-1 { + return removed + } + return -1 +} diff --git a/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.java b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.java new file mode 100644 index 00000000..5db830b5 --- /dev/null +++ b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.java @@ -0,0 +1,75 @@ +class Solution { + public int maxNumEdgesToRemove(int n, int[][] edges) { + Arrays.sort(edges, (a, b) -> b[0] - a[0]); + int[] parentA = new int[n + 1]; + int[] parentB = new int[n + 1]; + for (int i = 0; i <= n; i++) { + parentA[i] = i; + parentB[i] = i; + } + int[] rankA = new int[n + 1]; + int[] rankB = new int[n + 1]; + + java.util.function.BiFunction find = new java.util.function.BiFunction() { + @Override + public Integer apply(int[] parent, Integer x) { + if (parent[x] != x) { + parent[x] = apply(parent, parent[x]); + } + return parent[x]; + } + }; + + java.util.function.BiFunction union = new java.util.function.BiFunction() { + @Override + public Boolean apply(int[] parent, int[] rank) { + return false; + } + }; + // need a closure-like approach; use a helper method would be cleaner but this is fine + class UnionHelper { + boolean union(int[] parent, int[] rank, int x, int y) { + int rootX = find.apply(parent, x); + int rootY = find.apply(parent, y); + if (rootX == rootY) return false; + if (rank[rootX] < rank[rootY]) { + parent[rootX] = rootY; + } else if (rank[rootX] > rank[rootY]) { + parent[rootY] = rootX; + } else { + parent[rootX] = rootY; + rank[rootY]++; + } + return true; + } + } + UnionHelper helper = new UnionHelper(); + + int removed = 0; + int aliceEdges = 0, bobEdges = 0; + for (int[] e : edges) { + if (e[0] == 3) { + if (helper.union(parentA, rankA, e[1], e[2])) { + helper.union(parentB, rankB, e[1], e[2]); + aliceEdges++; + bobEdges++; + } else { + removed++; + } + } else if (e[0] == 2) { + if (helper.union(parentB, rankB, e[1], e[2])) { + bobEdges++; + } else { + removed++; + } + } else { + if (helper.union(parentA, rankA, e[1], e[2])) { + aliceEdges++; + } else { + removed++; + } + } + } + return (bobEdges == n - 1 && aliceEdges == n - 1) ? removed : -1; + } +} diff --git a/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.kt b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.kt new file mode 100644 index 00000000..0cada639 --- /dev/null +++ b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.kt @@ -0,0 +1,63 @@ +class Solution { + fun maxNumEdgesToRemove(n: Int, edges: Array): Int { + edges.sortByDescending { it[0] } + val parentA = IntArray(n + 1) { it } + val parentB = IntArray(n + 1) { it } + val rankA = IntArray(n + 1) + val rankB = IntArray(n + 1) + + fun find(parent: IntArray, x: Int): Int { + if (parent[x] != x) { + parent[x] = find(parent, parent[x]) + } + return parent[x] + } + + fun union(parent: IntArray, rank: IntArray, x: Int, y: Int): Boolean { + val rootX = find(parent, x) + val rootY = find(parent, y) + if (rootX == rootY) return false + if (rank[rootX] < rank[rootY]) { + parent[rootX] = rootY + } else if (rank[rootX] > rank[rootY]) { + parent[rootY] = rootX + } else { + parent[rootX] = rootY + rank[rootY]++ + } + return true + } + + var removed = 0 + var aliceEdges = 0 + var bobEdges = 0 + for (e in edges) { + when (e[0]) { + 3 -> { + if (union(parentA, rankA, e[1], e[2])) { + union(parentB, rankB, e[1], e[2]) + aliceEdges++ + bobEdges++ + } else { + removed++ + } + } + 2 -> { + if (union(parentB, rankB, e[1], e[2])) { + bobEdges++ + } else { + removed++ + } + } + else -> { + if (union(parentA, rankA, e[1], e[2])) { + aliceEdges++ + } else { + removed++ + } + } + } + } + return if (bobEdges == n - 1 && aliceEdges == n - 1) removed else -1 + } +} diff --git a/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.py b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.py new file mode 100644 index 00000000..572ef57e --- /dev/null +++ b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.py @@ -0,0 +1,50 @@ +class DSU: + def __init__(self, n): + self.parent = [i for i in range(n)] + self.rank = [0] * n + + def find(self, x): + if self.parent[x] != x: + self.parent[x] = self.find(self.parent[x]) + return self.parent[x] + + def union(self, x, y): + xset, yset = self.find(x), self.find(y) + if xset != yset: + if self.rank[xset] < self.rank[yset]: + self.parent[xset] = yset + elif self.rank[xset] > self.rank[yset]: + self.parent[yset] = xset + else: + self.parent[xset] = yset + self.rank[yset] += 1 + return True + return False + + +class Solution: + def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int: + edges.sort(reverse=True) + dsu_alice = DSU(n + 1) + dsu_bob = DSU(n + 1) + removed_edge = 0 + alice_edges, bob_edges = 0, 0 + for edge in edges: + if edge[0] == 3: + if dsu_alice.union(edge[1], edge[2]): + dsu_bob.union(edge[1], edge[2]) + alice_edges += 1 + bob_edges += 1 + else: + removed_edge += 1 + elif edge[0] == 2: + if dsu_bob.union(edge[1], edge[2]): + bob_edges += 1 + else: + removed_edge += 1 + else: + if dsu_alice.union(edge[1], edge[2]): + alice_edges += 1 + else: + removed_edge += 1 + return removed_edge if bob_edges == n - 1 == alice_edges else -1 diff --git a/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.py2 b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.py2 new file mode 100644 index 00000000..18dfcd08 --- /dev/null +++ b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.py2 @@ -0,0 +1,54 @@ +class Solution(object): + def maxNumEdgesToRemove(self, n, edges): + """ + :type n: int + :type edges: List[List[int]] + :rtype: int + """ + edges.sort(key=lambda x: x[0], reverse=True) + parentA = list(range(n + 1)) + parentB = list(range(n + 1)) + rankA = [0] * (n + 1) + rankB = [0] * (n + 1) + + def find(parent, x): + if parent[x] != x: + parent[x] = find(parent, parent[x]) + return parent[x] + + def union(parent, rank, x, y): + root_x = find(parent, x) + root_y = find(parent, y) + if root_x == root_y: + return False + if rank[root_x] < rank[root_y]: + parent[root_x] = root_y + elif rank[root_x] > rank[root_y]: + parent[root_y] = root_x + else: + parent[root_x] = root_y + rank[root_y] += 1 + return True + + removed = 0 + alice_edges = 0 + bob_edges = 0 + for e in edges: + if e[0] == 3: + if union(parentA, rankA, e[1], e[2]): + union(parentB, rankB, e[1], e[2]) + alice_edges += 1 + bob_edges += 1 + else: + removed += 1 + elif e[0] == 2: + if union(parentB, rankB, e[1], e[2]): + bob_edges += 1 + else: + removed += 1 + else: + if union(parentA, rankA, e[1], e[2]): + alice_edges += 1 + else: + removed += 1 + return removed if bob_edges == n - 1 and alice_edges == n - 1 else -1 diff --git a/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.rb b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.rb new file mode 100644 index 00000000..19973e6a --- /dev/null +++ b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.rb @@ -0,0 +1,60 @@ +# @param {Integer} n +# @param {Integer[][]} edges +# @return {Integer} +def max_num_edges_to_remove(n, edges) + edges.sort_by! { |e| -e[0] } + parentA = (0..n).to_a + parentB = (0..n).to_a + rankA = Array.new(n + 1, 0) + rankB = Array.new(n + 1, 0) + + find = ->(parent, x) { + if parent[x] != x + parent[x] = find.call(parent, parent[x]) + end + parent[x] + } + + union = ->(parent, rank, x, y) { + root_x = find.call(parent, x) + root_y = find.call(parent, y) + return false if root_x == root_y + if rank[root_x] < rank[root_y] + parent[root_x] = root_y + elsif rank[root_x] > rank[root_y] + parent[root_y] = root_x + else + parent[root_x] = root_y + rank[root_y] += 1 + end + true + } + + removed = 0 + alice_edges = 0 + bob_edges = 0 + edges.each do |e| + if e[0] == 3 + if union.call(parentA, rankA, e[1], e[2]) + union.call(parentB, rankB, e[1], e[2]) + alice_edges += 1 + bob_edges += 1 + else + removed += 1 + end + elsif e[0] == 2 + if union.call(parentB, rankB, e[1], e[2]) + bob_edges += 1 + else + removed += 1 + end + else + if union.call(parentA, rankA, e[1], e[2]) + alice_edges += 1 + else + removed += 1 + end + end + end + bob_edges == n - 1 && alice_edges == n - 1 ? removed : -1 +end diff --git a/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.rs b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.rs new file mode 100644 index 00000000..eea1d039 --- /dev/null +++ b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.rs @@ -0,0 +1,62 @@ +impl Solution { + pub fn max_num_edges_to_remove(n: i32, edges: Vec>) -> i32 { + let n = n as usize; + let mut edges = edges; + edges.sort_by(|a, b| b[0].cmp(&a[0])); + let mut parentA = (0..=n).collect::>(); + let mut parentB = (0..=n).collect::>(); + let mut rankA = vec![0; n + 1]; + let mut rankB = vec![0; n + 1]; + + fn find(parent: &mut Vec, x: usize) -> usize { + if parent[x] != x { + parent[x] = find(parent, parent[x]); + } + parent[x] + } + + fn union_set(parent: &mut Vec, rank: &mut Vec, x: usize, y: usize) -> bool { + let root_x = find(parent, x); + let root_y = find(parent, y); + if root_x == root_y { return false; } + if rank[root_x] < rank[root_y] { + parent[root_x] = root_y; + } else if rank[root_x] > rank[root_y] { + parent[root_y] = root_x; + } else { + parent[root_x] = root_y; + rank[root_y] += 1; + } + true + } + + let mut removed = 0; + let mut alice_edges = 0; + let mut bob_edges = 0; + for e in edges { + let (t, u, v) = (e[0] as usize, e[1] as usize, e[2] as usize); + if t == 3 { + if union_set(&mut parentA, &mut rankA, u, v) { + union_set(&mut parentB, &mut rankB, u, v); + alice_edges += 1; + bob_edges += 1; + } else { + removed += 1; + } + } else if t == 2 { + if union_set(&mut parentB, &mut rankB, u, v) { + bob_edges += 1; + } else { + removed += 1; + } + } else { + if union_set(&mut parentA, &mut rankA, u, v) { + alice_edges += 1; + } else { + removed += 1; + } + } + } + if bob_edges == n as i32 - 1 && alice_edges == n as i32 - 1 { removed } else { -1 } + } +} diff --git a/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.swift b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.swift new file mode 100644 index 00000000..31bdd281 --- /dev/null +++ b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.swift @@ -0,0 +1,60 @@ +class Solution { + func maxNumEdgesToRemove(_ n: Int, _ edges: [[Int]]) -> Int { + var edges = edges + edges.sort { $0[0] > $1[0] } + var parentA = Array(0...n) + var parentB = Array(0...n) + var rankA = Array(repeating: 0, count: n + 1) + var rankB = Array(repeating: 0, count: n + 1) + + func find(_ parent: inout [Int], _ x: Int) -> Int { + if parent[x] != x { + parent[x] = find(&parent, parent[x]) + } + return parent[x] + } + + func union(_ parent: inout [Int], _ rank: inout [Int], _ x: Int, _ y: Int) -> Bool { + let rootX = find(&parent, x) + let rootY = find(&parent, y) + if rootX == rootY { return false } + if rank[rootX] < rank[rootY] { + parent[rootX] = rootY + } else if rank[rootX] > rank[rootY] { + parent[rootY] = rootX + } else { + parent[rootX] = rootY + rank[rootY] += 1 + } + return true + } + + var removed = 0 + var aliceEdges = 0 + var bobEdges = 0 + for e in edges { + if e[0] == 3 { + if union(&parentA, &rankA, e[1], e[2]) { + union(&parentB, &rankB, e[1], e[2]) + aliceEdges += 1 + bobEdges += 1 + } else { + removed += 1 + } + } else if e[0] == 2 { + if union(&parentB, &rankB, e[1], e[2]) { + bobEdges += 1 + } else { + removed += 1 + } + } else { + if union(&parentA, &rankA, e[1], e[2]) { + aliceEdges += 1 + } else { + removed += 1 + } + } + } + return (bobEdges == n - 1 && aliceEdges == n - 1) ? removed : -1 + } +} diff --git a/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.ts b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.ts new file mode 100644 index 00000000..f738ecc2 --- /dev/null +++ b/tests/1501-2000/1579. remove-max-number-of-edges-to-keep-graph-fully-traversable/sol.ts @@ -0,0 +1,62 @@ +function maxNumEdgesToRemove(n: number, edges: number[][]): number { + edges.sort((a, b) => b[0] - a[0]); + const parentA: number[] = Array.from({ length: n + 1 }, (_, i) => i); + const parentB: number[] = Array.from({ length: n + 1 }, (_, i) => i); + const rankA: number[] = new Array(n + 1).fill(0); + const rankB: number[] = new Array(n + 1).fill(0); + + function find(parent: number[], x: number): number { + if (parent[x] !== x) { + parent[x] = find(parent, parent[x]); + } + return parent[x]; + } + + function union( + parent: number[], + rank: number[], + x: number, + y: number, + ): boolean { + const rootX = find(parent, x); + const rootY = find(parent, y); + if (rootX === rootY) return false; + if (rank[rootX] < rank[rootY]) { + parent[rootX] = rootY; + } else if (rank[rootX] > rank[rootY]) { + parent[rootY] = rootX; + } else { + parent[rootX] = rootY; + rank[rootY]++; + } + return true; + } + + let removed = 0; + let aliceEdges = 0; + let bobEdges = 0; + for (const e of edges) { + if (e[0] === 3) { + if (union(parentA, rankA, e[1], e[2])) { + union(parentB, rankB, e[1], e[2]); + aliceEdges++; + bobEdges++; + } else { + removed++; + } + } else if (e[0] === 2) { + if (union(parentB, rankB, e[1], e[2])) { + bobEdges++; + } else { + removed++; + } + } else { + if (union(parentA, rankA, e[1], e[2])) { + aliceEdges++; + } else { + removed++; + } + } + } + return bobEdges === n - 1 && aliceEdges === n - 1 ? removed : -1; +} diff --git a/tests/1501-2000/1582. special-positions-in-a-binary-matrix/manifest.yaml b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/manifest.yaml new file mode 100644 index 00000000..dbd4d259 --- /dev/null +++ b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/manifest.yaml @@ -0,0 +1,377 @@ +entry: + id: 1582 + title: "special-positions-in-a-binary-matrix" + params: + mat: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().numSpecial({mat})" + rust: "Solution::num_special({mat})" + python3: "Solution().numSpecial({mat})" + python2: "Solution().numSpecial({mat})" + ruby: "num_special({mat})" + java: "new Solution().numSpecial({mat})" + csharp: "new Solution().NumSpecial({mat})" + kotlin: "Solution().numSpecial({mat})" + go: "numSpecial({mat})" + dart: "Solution().numSpecial({mat})" + swift: "Solution().numSpecial({mat})" + typescript: "numSpecial({mat})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().numSpecial(mat, {result})" + checker: | + class Checker: + def numSpecial(self, mat, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + rows = [sum(row) for row in mat] + cols = [sum(mat[i][j] for i in range(len(mat))) for j in range(len(mat[0]))] + expected = sum( + mat[i][j] == 1 and rows[i] == 1 and cols[j] == 1 + for i in range(len(mat)) + for j in range(len(mat[0])) + ) + return result == expected +seed: 1582 +tests: + - name: example-one + in: + mat: + - [1, 0, 0] + - [0, 0, 1] + - [1, 0, 0] + out: 1 + - name: example-two + in: + mat: + - [1, 0, 0] + - [0, 1, 0] + - [0, 0, 1] + out: 3 + - name: single-zero + in: + mat: + - [0] + out: 0 + - name: single-one + in: + mat: + - [1] + out: 1 + - name: one-row-single-one + in: + mat: + - [0, 0, 1, 0, 0] + out: 1 + - name: one-row-many-ones + in: + mat: + - [1, 0, 1, 0, 1] + out: 0 + - name: one-column-single-one + in: + mat: + - [0] + - [1] + - [0] + - [0] + out: 1 + - name: one-column-many-ones + in: + mat: + - [1] + - [0] + - [1] + out: 0 + - name: all-zero-2x2 + in: + mat: + - [0, 0] + - [0, 0] + out: 0 + - name: all-one-2x3 + in: + mat: + - [1, 1, 1] + - [1, 1, 1] + out: 0 + - name: diagonal-4 + in: + mat: + - [1, 0, 0, 0] + - [0, 1, 0, 0] + - [0, 0, 1, 0] + - [0, 0, 0, 1] + out: 4 + - name: anti-diagonal-4 + in: + mat: + - [0, 0, 0, 1] + - [0, 0, 1, 0] + - [0, 1, 0, 0] + - [1, 0, 0, 0] + out: 4 + - name: two-collisions + in: + mat: + - [1, 1, 0] + - [0, 1, 0] + - [0, 0, 1] + out: 1 + - name: blocked-column + in: + mat: + - [1, 0, 0] + - [1, 0, 1] + - [0, 0, 0] + out: 0 + - name: isolated-corners + in: + mat: + - [1, 0, 0, 0] + - [0, 0, 0, 1] + - [0, 0, 0, 0] + out: 2 + - name: dense-with-center + in: + mat: + - [1, 1, 1] + - [1, 0, 1] + - [1, 1, 1] + out: 0 + - name: sparse-rectangular + in: + mat: + - [0, 1, 0, 0, 0] + - [0, 0, 0, 0, 1] + - [1, 0, 0, 0, 0] + out: 3 + - name: three-special-one-conflict + in: + mat: + - [1, 0, 0, 0] + - [0, 0, 1, 0] + - [0, 0, 0, 0] + - [0, 0, 1, 1] + out: 1 + - name: alternating-5x5 + in: + mat: + - [1, 0, 1, 0, 1] + - [0, 1, 0, 1, 0] + - [1, 0, 1, 0, 1] + - [0, 1, 0, 1, 0] + - [1, 0, 1, 0, 1] + out: 0 + - name: permutation-5 + in: + mat: + - [0, 0, 1, 0, 0] + - [1, 0, 0, 0, 0] + - [0, 0, 0, 0, 1] + - [0, 1, 0, 0, 0] + - [0, 0, 0, 1, 0] + out: 5 + - name: repeated-row + in: + mat: + - [1, 0, 0, 1] + - [1, 0, 0, 1] + - [0, 1, 0, 0] + out: 1 + - name: repeated-column + in: + mat: + - [1, 1, 0] + - [0, 0, 1] + - [1, 1, 0] + - [0, 0, 0] + out: 1 + - name: exactly-one-per-row-shared-column + in: + mat: + - [0, 1, 0, 0] + - [0, 1, 0, 0] + - [0, 1, 0, 0] + - [0, 0, 0, 1] + out: 1 + - name: exactly-one-per-column-shared-row + in: + mat: + - [1, 0, 1, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + out: 0 + - name: six-diagonal + in: + mat: + - [1, 0, 0, 0, 0, 0] + - [0, 1, 0, 0, 0, 0] + - [0, 0, 1, 0, 0, 0] + - [0, 0, 0, 1, 0, 0] + - [0, 0, 0, 0, 1, 0] + - [0, 0, 0, 0, 0, 1] + out: 6 + - name: tall-sparse + in: + mat: + - [0, 0, 0, 0] + - [0, 1, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 1] + - [0, 0, 0, 0] + - [1, 0, 0, 0] + - [0, 0, 0, 0] + out: 3 + - name: wide-sparse + in: + mat: + - [0, 0, 1, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 1] + out: 2 + - name: border-ones + in: + mat: + - [1, 1, 1, 1] + - [1, 0, 0, 1] + - [1, 0, 0, 1] + - [1, 1, 1, 1] + out: 0 + - name: four-corners-5x5 + in: + mat: + - [1, 0, 0, 0, 1] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - [1, 0, 0, 0, 1] + out: 0 + - name: isolated-cross + in: + mat: + - [0, 0, 1, 0, 0] + - [0, 0, 1, 0, 0] + - [1, 1, 1, 1, 1] + - [0, 0, 1, 0, 0] + - [0, 0, 1, 0, 0] + out: 0 + - name: two-by-five-two-special + in: + mat: + - [1, 0, 0, 0, 0] + - [0, 0, 0, 0, 1] + out: 2 + - name: three-by-two-one-special + in: + mat: + - [1, 1] + - [0, 0] + - [0, 1] + out: 0 + - name: seven-by-seven-permutation + in: + mat: + - [0, 0, 0, 1, 0, 0, 0] + - [0, 1, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 1, 0] + - [1, 0, 0, 0, 0, 0, 0] + - [0, 0, 1, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 1] + - [0, 0, 0, 0, 1, 0, 0] + out: 7 + - name: seven-by-seven-no-special + in: + mat: + - [1, 1, 0, 0, 0, 0, 0] + - [0, 1, 1, 0, 0, 0, 0] + - [0, 0, 1, 1, 0, 0, 0] + - [0, 0, 0, 1, 1, 0, 0] + - [0, 0, 0, 0, 1, 1, 0] + - [0, 0, 0, 0, 0, 1, 1] + - [1, 0, 0, 0, 0, 0, 1] + out: 0 + - name: eight-by-three + in: + mat: + - [1, 0, 0] + - [0, 1, 0] + - [0, 0, 1] + - [0, 0, 0] + - [0, 0, 0] + - [0, 0, 0] + - [0, 0, 0] + - [0, 0, 0] + out: 3 + - name: three-by-eight + in: + mat: + - [1, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 1, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 1, 0] + out: 3 + - name: all-zero-10x10 + in: + mat: + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + out: 0 + - name: generated-single-row + in: + mat: + gen: array + len: 1 + of: + gen: array + len: 100 + of: + gen: int + min: 0 + max: 1 + elemType: int + seed: 1582001 + - name: generated-single-column + in: + mat: + gen: array + len: 100 + of: + gen: array + len: 1 + of: + gen: int + min: 0 + max: 1 + elemType: int + seed: 1582002 + - name: generated-max-square + in: + mat: + gen: array + len: 100 + of: + gen: array + len: 100 + of: + gen: int + min: 0 + max: 1 + elemType: int + seed: 1582003 diff --git a/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.cpp b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.cpp new file mode 100644 index 00000000..cf24a3ad --- /dev/null +++ b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int numSpecial(vector>& mat) { + int m = mat.size(), n = mat[0].size(); + vector row(m, 0), col(n, 0); + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (mat[i][j] == 1) { + row[i]++; + col[j]++; + } + } + } + + int result = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (mat[i][j] == 1 && row[i] == 1 && col[j] == 1) { + result++; + } + } + } + return result; + } +}; diff --git a/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.cs b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.cs new file mode 100644 index 00000000..b4d9ce1e --- /dev/null +++ b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.cs @@ -0,0 +1,26 @@ +public class Solution { + public int NumSpecial(int[][] mat) { + int m = mat.Length, n = mat[0].Length; + int[] row = new int[m]; + int[] col = new int[n]; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (mat[i][j] == 1) { + row[i]++; + col[j]++; + } + } + } + + int result = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (mat[i][j] == 1 && row[i] == 1 && col[j] == 1) { + result++; + } + } + } + return result; + } +} diff --git a/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.dart b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.dart new file mode 100644 index 00000000..13171160 --- /dev/null +++ b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.dart @@ -0,0 +1,26 @@ +class Solution { + int numSpecial(List> mat) { + int m = mat.length, n = mat[0].length; + List row = List.filled(m, 0); + List col = List.filled(n, 0); + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (mat[i][j] == 1) { + row[i]++; + col[j]++; + } + } + } + + int result = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (mat[i][j] == 1 && row[i] == 1 && col[j] == 1) { + result++; + } + } + } + return result; + } +} diff --git a/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.go b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.go new file mode 100644 index 00000000..c4aa3909 --- /dev/null +++ b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.go @@ -0,0 +1,24 @@ +func numSpecial(mat [][]int) int { + m, n := len(mat), len(mat[0]) + row := make([]int, m) + col := make([]int, n) + + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if mat[i][j] == 1 { + row[i]++ + col[j]++ + } + } + } + + result := 0 + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if mat[i][j] == 1 && row[i] == 1 && col[j] == 1 { + result++ + } + } + } + return result +} diff --git a/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.java b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.java new file mode 100644 index 00000000..3e502c52 --- /dev/null +++ b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.java @@ -0,0 +1,26 @@ +class Solution { + public int numSpecial(int[][] mat) { + int m = mat.length, n = mat[0].length; + int[] row = new int[m]; + int[] col = new int[n]; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (mat[i][j] == 1) { + row[i]++; + col[j]++; + } + } + } + + int result = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (mat[i][j] == 1 && row[i] == 1 && col[j] == 1) { + result++; + } + } + } + return result; + } +} diff --git a/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.kt b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.kt new file mode 100644 index 00000000..8cdb56f0 --- /dev/null +++ b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.kt @@ -0,0 +1,27 @@ +class Solution { + fun numSpecial(mat: Array): Int { + val m = mat.size + val n = mat[0].size + val row = IntArray(m) + val col = IntArray(n) + + for (i in 0 until m) { + for (j in 0 until n) { + if (mat[i][j] == 1) { + row[i]++ + col[j]++ + } + } + } + + var result = 0 + for (i in 0 until m) { + for (j in 0 until n) { + if (mat[i][j] == 1 && row[i] == 1 && col[j] == 1) { + result++ + } + } + } + return result + } +} diff --git a/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.py b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.py new file mode 100644 index 00000000..b1bbdf13 --- /dev/null +++ b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.py @@ -0,0 +1,17 @@ +class Solution: + def numSpecial(self, mat): + m, n = len(mat), len(mat[0]) + row = [0] * m + col = [0] * n + + for i in range(m): + for j in range(n): + if mat[i][j] == 1: + row[i] += 1 + col[j] += 1 + + return sum( + mat[i][j] == 1 and row[i] == 1 and col[j] == 1 + for i in range(m) + for j in range(n) + ) diff --git a/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.py2 b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.py2 new file mode 100644 index 00000000..beecc7a8 --- /dev/null +++ b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def numSpecial(self, mat): + """ + :type mat: List[List[int]] + :rtype: int + """ + m, n = len(mat), len(mat[0]) + row = [0] * m + col = [0] * n + + for i in range(m): + for j in range(n): + if mat[i][j] == 1: + row[i] += 1 + col[j] += 1 + + return sum( + mat[i][j] == 1 and row[i] == 1 and col[j] == 1 + for i in range(m) + for j in range(n) + ) diff --git a/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.rb b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.rb new file mode 100644 index 00000000..ef6c0537 --- /dev/null +++ b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.rb @@ -0,0 +1,24 @@ +# @param {Integer[][]} mat +# @return {Integer} +def num_special(mat) + m, n = mat.size, mat[0].size + row = Array.new(m, 0) + col = Array.new(n, 0) + + (0...m).each do |i| + (0...n).each do |j| + if mat[i][j] == 1 + row[i] += 1 + col[j] += 1 + end + end + end + + result = 0 + (0...m).each do |i| + (0...n).each do |j| + result += 1 if mat[i][j] == 1 && row[i] == 1 && col[j] == 1 + end + end + result +end diff --git a/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.rs b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.rs new file mode 100644 index 00000000..fa562a49 --- /dev/null +++ b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.rs @@ -0,0 +1,27 @@ +impl Solution { + pub fn num_special(mat: Vec>) -> i32 { + let m = mat.len(); + let n = mat[0].len(); + let mut row = vec![0; m]; + let mut col = vec![0; n]; + + for i in 0..m { + for j in 0..n { + if mat[i][j] == 1 { + row[i] += 1; + col[j] += 1; + } + } + } + + let mut result = 0; + for i in 0..m { + for j in 0..n { + if mat[i][j] == 1 && row[i] == 1 && col[j] == 1 { + result += 1; + } + } + } + result + } +} diff --git a/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.swift b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.swift new file mode 100644 index 00000000..2c77e149 --- /dev/null +++ b/tests/1501-2000/1582. special-positions-in-a-binary-matrix/sol.swift @@ -0,0 +1,26 @@ +class Solution { + func numSpecial(_ mat: [[Int]]) -> Int { + let m = mat.count, n = mat[0].count + var row = [Int](repeating: 0, count: m) + var col = [Int](repeating: 0, count: n) + + for i in 0..>& preferences, vector>& pairs) { + vector graph(n); + for (auto& p : pairs) { + graph[p[0]] = p[1]; + graph[p[1]] = p[0]; + } + + vector> rank(n, vector(n)); + for (int i = 0; i < n; i++) { + for (int j = 0; j < preferences[i].size(); j++) { + rank[i][preferences[i][j]] = j; + } + } + + int ans = 0; + for (int u = 0; u < n; u++) { + int v = graph[u]; + bool unhappy = false; + for (int a : preferences[u]) { + if (a == v) break; + int av = graph[a]; + if (rank[a][u] < rank[a][av]) { + unhappy = true; + break; + } + } + if (unhappy) ans++; + } + return ans; + } +}; diff --git a/tests/1501-2000/1583. count-unhappy-friends/sol.cs b/tests/1501-2000/1583. count-unhappy-friends/sol.cs new file mode 100644 index 00000000..61b94875 --- /dev/null +++ b/tests/1501-2000/1583. count-unhappy-friends/sol.cs @@ -0,0 +1,33 @@ +public class Solution { + public int UnhappyFriends(int n, int[][] preferences, int[][] pairs) { + int[] graph = new int[n]; + foreach (var p in pairs) { + graph[p[0]] = p[1]; + graph[p[1]] = p[0]; + } + + int[][] rank = new int[n][]; + for (int i = 0; i < n; i++) { + rank[i] = new int[n]; + for (int j = 0; j < preferences[i].Length; j++) { + rank[i][preferences[i][j]] = j; + } + } + + int ans = 0; + for (int u = 0; u < n; u++) { + int v = graph[u]; + bool unhappy = false; + foreach (int a in preferences[u]) { + if (a == v) break; + int av = graph[a]; + if (rank[a][u] < rank[a][av]) { + unhappy = true; + break; + } + } + if (unhappy) ans++; + } + return ans; + } +} diff --git a/tests/1501-2000/1583. count-unhappy-friends/sol.dart b/tests/1501-2000/1583. count-unhappy-friends/sol.dart new file mode 100644 index 00000000..3f55575b --- /dev/null +++ b/tests/1501-2000/1583. count-unhappy-friends/sol.dart @@ -0,0 +1,32 @@ +class Solution { + int unhappyFriends(int n, List> preferences, List> pairs) { + List graph = List.filled(n, 0); + for (var p in pairs) { + graph[p[0]] = p[1]; + graph[p[1]] = p[0]; + } + + List> rank = List.generate(n, (_) => List.filled(n, 0)); + for (int i = 0; i < n; i++) { + for (int j = 0; j < preferences[i].length; j++) { + rank[i][preferences[i][j]] = j; + } + } + + int ans = 0; + for (int u = 0; u < n; u++) { + int v = graph[u]; + bool unhappy = false; + for (int a in preferences[u]) { + if (a == v) break; + int av = graph[a]; + if (rank[a][u] < rank[a][av]) { + unhappy = true; + break; + } + } + if (unhappy) ans++; + } + return ans; + } +} diff --git a/tests/1501-2000/1583. count-unhappy-friends/sol.go b/tests/1501-2000/1583. count-unhappy-friends/sol.go new file mode 100644 index 00000000..dd52def4 --- /dev/null +++ b/tests/1501-2000/1583. count-unhappy-friends/sol.go @@ -0,0 +1,35 @@ +func unhappyFriends(n int, preferences [][]int, pairs [][]int) int { + graph := make([]int, n) + for _, p := range pairs { + graph[p[0]] = p[1] + graph[p[1]] = p[0] + } + + rank := make([][]int, n) + for i := range rank { + rank[i] = make([]int, n) + for j, e := range preferences[i] { + rank[i][e] = j + } + } + + ans := 0 + for u := 0; u < n; u++ { + v := graph[u] + unhappy := false + for _, a := range preferences[u] { + if a == v { + break + } + av := graph[a] + if rank[a][u] < rank[a][av] { + unhappy = true + break + } + } + if unhappy { + ans++ + } + } + return ans +} diff --git a/tests/1501-2000/1583. count-unhappy-friends/sol.java b/tests/1501-2000/1583. count-unhappy-friends/sol.java new file mode 100644 index 00000000..de80ecef --- /dev/null +++ b/tests/1501-2000/1583. count-unhappy-friends/sol.java @@ -0,0 +1,32 @@ +class Solution { + public int unhappyFriends(int n, int[][] preferences, int[][] pairs) { + int[] graph = new int[n]; + for (int[] p : pairs) { + graph[p[0]] = p[1]; + graph[p[1]] = p[0]; + } + + int[][] rank = new int[n][n]; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n - 1; j++) { + rank[i][preferences[i][j]] = j; + } + } + + int ans = 0; + for (int u = 0; u < n; u++) { + int v = graph[u]; + boolean unhappy = false; + for (int a : preferences[u]) { + if (a == v) break; + int av = graph[a]; + if (rank[a][u] < rank[a][av]) { + unhappy = true; + break; + } + } + if (unhappy) ans++; + } + return ans; + } +} diff --git a/tests/1501-2000/1583. count-unhappy-friends/sol.kt b/tests/1501-2000/1583. count-unhappy-friends/sol.kt new file mode 100644 index 00000000..c899d47f --- /dev/null +++ b/tests/1501-2000/1583. count-unhappy-friends/sol.kt @@ -0,0 +1,32 @@ +class Solution { + fun unhappyFriends(n: Int, preferences: Array, pairs: Array): Int { + val graph = IntArray(n) + for (p in pairs) { + graph[p[0]] = p[1] + graph[p[1]] = p[0] + } + + val rank = Array(n) { IntArray(n) } + for (i in 0 until n) { + for (j in preferences[i].indices) { + rank[i][preferences[i][j]] = j + } + } + + var ans = 0 + for (u in 0 until n) { + val v = graph[u] + var unhappy = false + for (a in preferences[u]) { + if (a == v) break + val av = graph[a] + if (rank[a][u] < rank[a][av]) { + unhappy = true + break + } + } + if (unhappy) ans++ + } + return ans + } +} diff --git a/tests/1501-2000/1583. count-unhappy-friends/sol.py b/tests/1501-2000/1583. count-unhappy-friends/sol.py new file mode 100644 index 00000000..3035c3b5 --- /dev/null +++ b/tests/1501-2000/1583. count-unhappy-friends/sol.py @@ -0,0 +1,39 @@ +class Solution: + def unhappyFriends( + self, n: int, preferences: List[List[int]], pairs: List[List[int]] + ) -> int: + # x: u, y + # u: x, v + + # x is unhappy when x's upper candidates were paired somebody less preferable than him. + # Check happiness one by one. + + graph = dict() + for u, v in pairs: + graph[u] = v + graph[v] = u + + rank = [[0 for _ in range(n)] for _ in range(n)] + for i in range(len(preferences)): + for j, e in enumerate(preferences[i]): + rank[i][e] = j + + def check(u): + v = graph[u] + + lst = [] + for a in preferences[u]: + if a == v: + break + av = graph[a] + if rank[a][u] < rank[a][av]: + return True + + return False + + ans = 0 + for i in range(n): + if check(i): + ans += 1 + + return ans diff --git a/tests/1501-2000/1583. count-unhappy-friends/sol.py2 b/tests/1501-2000/1583. count-unhappy-friends/sol.py2 new file mode 100644 index 00000000..1088346b --- /dev/null +++ b/tests/1501-2000/1583. count-unhappy-friends/sol.py2 @@ -0,0 +1,33 @@ +class Solution(object): + def unhappyFriends(self, n, preferences, pairs): + """ + :type n: int + :type preferences: List[List[int]] + :type pairs: List[List[int]] + :rtype: int + """ + graph = {} + for u, v in pairs: + graph[u] = v + graph[v] = u + + rank = [[0] * n for _ in range(n)] + for i in range(n): + for j, e in enumerate(preferences[i]): + rank[i][e] = j + + def check(u): + v = graph[u] + for a in preferences[u]: + if a == v: + break + av = graph[a] + if rank[a][u] < rank[a][av]: + return True + return False + + ans = 0 + for i in range(n): + if check(i): + ans += 1 + return ans diff --git a/tests/1501-2000/1583. count-unhappy-friends/sol.rb b/tests/1501-2000/1583. count-unhappy-friends/sol.rb new file mode 100644 index 00000000..74f5691a --- /dev/null +++ b/tests/1501-2000/1583. count-unhappy-friends/sol.rb @@ -0,0 +1,34 @@ +# @param {Integer} n +# @param {Integer[][]} preferences +# @param {Integer[][]} pairs +# @return {Integer} +def unhappy_friends(n, preferences, pairs) + graph = {} + pairs.each do |u, v| + graph[u] = v + graph[v] = u + end + + rank = Array.new(n) { Array.new(n, 0) } + (0...n).each do |i| + preferences[i].each_with_index do |e, j| + rank[i][e] = j + end + end + + check = lambda do |u| + v = graph[u] + preferences[u].each do |a| + break if a == v + av = graph[a] + return true if rank[a][u] < rank[a][av] + end + false + end + + ans = 0 + (0...n).each do |i| + ans += 1 if check.call(i) + end + ans +end diff --git a/tests/1501-2000/1583. count-unhappy-friends/sol.rs b/tests/1501-2000/1583. count-unhappy-friends/sol.rs new file mode 100644 index 00000000..d829846a --- /dev/null +++ b/tests/1501-2000/1583. count-unhappy-friends/sol.rs @@ -0,0 +1,36 @@ +impl Solution { + pub fn unhappy_friends(n: i32, preferences: Vec>, pairs: Vec>) -> i32 { + let n = n as usize; + let mut graph = vec![0; n]; + for p in &pairs { + let u = p[0] as usize; + let v = p[1] as usize; + graph[u] = v; + graph[v] = u; + } + + let mut rank = vec![vec![0; n]; n]; + for i in 0..n { + for (j, &e) in preferences[i].iter().enumerate() { + rank[i][e as usize] = j; + } + } + + let mut ans = 0; + for u in 0..n { + let v = graph[u]; + let mut unhappy = false; + for &a in &preferences[u] { + let a = a as usize; + if a == v { break; } + let av = graph[a]; + if rank[a][u] < rank[a][av] { + unhappy = true; + break; + } + } + if unhappy { ans += 1; } + } + ans + } +} diff --git a/tests/1501-2000/1583. count-unhappy-friends/sol.swift b/tests/1501-2000/1583. count-unhappy-friends/sol.swift new file mode 100644 index 00000000..901373ea --- /dev/null +++ b/tests/1501-2000/1583. count-unhappy-friends/sol.swift @@ -0,0 +1,32 @@ +class Solution { + func unhappyFriends(_ n: Int, _ preferences: [[Int]], _ pairs: [[Int]]) -> Int { + var graph = [Int](repeating: 0, count: n) + for p in pairs { + graph[p[0]] = p[1] + graph[p[1]] = p[0] + } + + var rank = [[Int]](repeating: [Int](repeating: 0, count: n), count: n) + for i in 0.. + new Array(n).fill(0), + ); + for (let i = 0; i < n; i++) { + preferences[i].forEach((e, j) => { + rank[i][e] = j; + }); + } + + let ans = 0; + for (let u = 0; u < n; u++) { + const v = graph[u]; + let unhappy = false; + for (const a of preferences[u]) { + if (a === v) break; + const av = graph[a]; + if (rank[a][u] < rank[a][av]) { + unhappy = true; + break; + } + } + if (unhappy) ans++; + } + return ans; +} diff --git a/tests/1501-2000/1584. min-cost-to-connect-all-points/manifest.yaml b/tests/1501-2000/1584. min-cost-to-connect-all-points/manifest.yaml new file mode 100644 index 00000000..1328efb8 --- /dev/null +++ b/tests/1501-2000/1584. min-cost-to-connect-all-points/manifest.yaml @@ -0,0 +1,412 @@ +entry: + id: 1584 + title: "min-cost-to-connect-all-points" + params: + points: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().minCostConnectPoints({points})" + rust: "Solution::min_cost_connect_points({points})" + python3: "Solution().minCostConnectPoints({points})" + python2: "Solution().minCostConnectPoints({points})" + ruby: "min_cost_connect_points({points})" + java: "new Solution().minCostConnectPoints({points})" + csharp: "new Solution().MinCostConnectPoints({points})" + kotlin: "Solution().minCostConnectPoints({points})" + go: "minCostConnectPoints({points})" + dart: "Solution().minCostConnectPoints({points})" + swift: "Solution().minCostConnectPoints({points})" + typescript: "minCostConnectPoints({points})" +judge: + type: "exact" +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().minCostConnectPoints(points, {result})" + checker: | + class Checker: + def minCostConnectPoints(self, points, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + n = len(points) + if n <= 0: + return False + best = [10**30] * n + used = [False] * n + best[0] = 0 + total = 0 + for _ in range(n): + u = -1 + for i in range(n): + if not used[i] and (u == -1 or best[i] < best[u]): + u = i + used[u] = True + total += best[u] + for v in range(n): + if not used[v]: + d = abs(points[u][0] - points[v][0]) + abs(points[u][1] - points[v][1]) + if d < best[v]: + best[v] = d + return result == total +seed: 1584 +tests: + - name: example-one + in: + points: + - [0, 0] + - [2, 2] + - [3, 10] + - [5, 2] + - [7, 0] + out: 20 + - name: example-two + in: + points: + - [3, 12] + - [-2, 5] + - [-4, 1] + out: 18 + - name: two-horizontal + in: + points: + - [0, 0] + - [10, 0] + out: 10 + - name: two-vertical + in: + points: + - [4, -3] + - [4, 8] + out: 11 + - name: three-horizontal + in: + points: + - [-5, 2] + - [0, 2] + - [9, 2] + out: 14 + - name: three-vertical + in: + points: + - [7, -9] + - [7, -2] + - [7, 6] + out: 15 + - name: unit-square + in: + points: + - [0, 0] + - [0, 1] + - [1, 0] + - [1, 1] + out: 3 + - name: rectangle + in: + points: + - [-3, -2] + - [-3, 4] + - [8, -2] + - [8, 4] + out: 23 + - name: diagonal-three + in: + points: + - [-4, -4] + - [0, 0] + - [9, 9] + out: 26 + - name: mixed-sign + in: + points: + - [-10, 5] + - [-3, -4] + - [2, 7] + - [11, -1] + out: 47 + - name: duplicate-x + in: + points: + - [0, -10] + - [0, -1] + - [0, 4] + - [3, 4] + - [9, 4] + out: 23 + - name: duplicate-y + in: + points: + - [-8, 0] + - [-2, 0] + - [5, 0] + - [5, 6] + - [12, 6] + out: 26 + - name: negative-line + in: + points: + - [-20, -7] + - [-15, -7] + - [-1, -7] + - [13, -7] + out: 33 + - name: positive-line + in: + points: + - [2, 11] + - [8, 11] + - [19, 11] + - [30, 11] + - [44, 11] + out: 42 + - name: cross + in: + points: + - [0, 0] + - [0, 6] + - [0, -6] + - [6, 0] + - [-6, 0] + out: 24 + - name: diamond + in: + points: + - [0, 5] + - [5, 0] + - [0, -5] + - [-5, 0] + out: 30 + - name: close-cluster + in: + points: + - [100, 100] + - [101, 100] + - [100, 102] + - [103, 101] + - [102, 104] + - [105, 103] + out: 14 + - name: far-cluster + in: + points: + - [-1000000, -1000000] + - [-999999, -1000000] + - [1000000, 1000000] + - [999999, 1000000] + out: 4000000 + - name: staggered-six + in: + points: + - [0, 0] + - [2, 5] + - [5, 1] + - [8, 7] + - [12, 3] + - [15, 9] + out: 38 + - name: zigzag-six + in: + points: + - [0, 0] + - [4, 10] + - [8, 0] + - [12, 10] + - [16, 0] + - [20, 10] + out: 46 + - name: staircase + in: + points: + - [-3, -3] + - [-2, -1] + - [0, 0] + - [3, 1] + - [7, 3] + - [12, 6] + out: 24 + - name: eight-horizontal + in: + points: + - [-7, 4] + - [-4, 4] + - [-1, 4] + - [2, 4] + - [6, 4] + - [11, 4] + - [17, 4] + - [24, 4] + out: 31 + - name: eight-vertical + in: + points: + - [9, -20] + - [9, -14] + - [9, -9] + - [9, -1] + - [9, 4] + - [9, 12] + - [9, 19] + - [9, 27] + out: 47 + - name: rectangle-border + in: + points: + - [0, 0] + - [10, 0] + - [20, 0] + - [0, 10] + - [20, 10] + - [0, 20] + - [10, 20] + - [20, 20] + out: 70 + - name: central-point + in: + points: + - [-10, -10] + - [-10, 10] + - [10, -10] + - [10, 10] + - [0, 0] + out: 80 + - name: asymmetric-five + in: + points: + - [-9, 2] + - [-2, 13] + - [4, -6] + - [17, 1] + - [21, 15] + out: 77 + - name: large-coordinate-line + in: + points: + - [-1000000, 1000000] + - [-500000, 1000000] + - [0, 1000000] + - [500000, 1000000] + - [1000000, 1000000] + out: 2000000 + - name: repeated-pattern + in: + points: + - [-6, -2] + - [-2, -6] + - [2, -2] + - [-2, 2] + - [2, 6] + - [6, 2] + out: 40 + - name: nine-grid + in: + points: + - [0, 0] + - [0, 3] + - [0, 7] + - [4, 0] + - [4, 3] + - [4, 7] + - [9, 0] + - [9, 3] + - [9, 7] + out: 30 + - name: ten-horizontal + in: + points: + - [-45, -3] + - [-36, -3] + - [-30, -3] + - [-22, -3] + - [-15, -3] + - [-9, -3] + - [-2, -3] + - [6, -3] + - [17, -3] + - [31, -3] + out: 76 + - name: ten-vertical + in: + points: + - [4, -50] + - [4, -41] + - [4, -33] + - [4, -24] + - [4, -18] + - [4, -11] + - [4, -3] + - [4, 8] + - [4, 19] + - [4, 35] + out: 85 + - name: twelve-line + in: + points: + - [0, 0] + - [1, 0] + - [3, 0] + - [6, 0] + - [10, 0] + - [15, 0] + - [21, 0] + - [28, 0] + - [36, 0] + - [45, 0] + - [55, 0] + - [66, 0] + out: 66 + - name: negative-grid + in: + points: + - [-8, -8] + - [-8, -4] + - [-8, 0] + - [-3, -8] + - [-3, -4] + - [-3, 0] + - [2, -8] + - [2, -4] + - [2, 0] + out: 34 + - name: fourteen-line + in: + points: + - [-30, 5] + - [-27, 5] + - [-21, 5] + - [-18, 5] + - [-10, 5] + - [-1, 5] + - [4, 5] + - [12, 5] + - [17, 5] + - [25, 5] + - [31, 5] + - [40, 5] + - [52, 5] + - [65, 5] + out: 95 + - name: sixteen-line + in: + points: + - [-80, -2] + - [-70, -2] + - [-61, -2] + - [-50, -2] + - [-42, -2] + - [-31, -2] + - [-20, -2] + - [-9, -2] + - [0, -2] + - [8, -2] + - [19, -2] + - [29, -2] + - [40, -2] + - [52, -2] + - [63, -2] + - [75, -2] + out: 155 diff --git a/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.cpp b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.cpp new file mode 100644 index 00000000..60887717 --- /dev/null +++ b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +#include + +class Solution { +public: + int minCostConnectPoints(vector>& points) { + int n = points.size(); + int minCost = 0; + vector visited(n, false); + priority_queue, vector>, greater>> pq; + pq.push({0, 0}); + unordered_map cache; + cache[0] = 0; + + while (!pq.empty()) { + auto [cost, u] = pq.top(); pq.pop(); + if (visited[u]) continue; + visited[u] = true; + minCost += cost; + for (int v = 0; v < n; v++) { + if (!visited[v]) { + int dist = abs(points[u][0] - points[v][0]) + abs(points[u][1] - points[v][1]); + if (dist < (cache.count(v) ? cache[v] : INT_MAX)) { + cache[v] = dist; + pq.push({dist, v}); + } + } + } + } + return minCost; + } +}; diff --git a/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.cs b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.cs new file mode 100644 index 00000000..3f88d404 --- /dev/null +++ b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.cs @@ -0,0 +1,28 @@ +using System; + +public class Solution { + public int MinCostConnectPoints(int[][] points) { + int n = points.Length; + int minCost = 0; + bool[] visited = new bool[n]; + int[] best = new int[n]; + for (int i = 0; i < n; i++) best[i] = int.MaxValue; + best[0] = 0; + + for (int step = 0; step < n; step++) { + int u = -1; + for (int i = 0; i < n; i++) { + if (!visited[i] && (u == -1 || best[i] < best[u])) u = i; + } + visited[u] = true; + minCost += best[u]; + for (int v = 0; v < n; v++) { + if (!visited[v]) { + int dist = Math.Abs(points[u][0] - points[v][0]) + Math.Abs(points[u][1] - points[v][1]); + if (dist < best[v]) best[v] = dist; + } + } + } + return minCost; + } +} diff --git a/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.dart b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.dart new file mode 100644 index 00000000..69902311 --- /dev/null +++ b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.dart @@ -0,0 +1,30 @@ +import 'dart:collection'; + +class Solution { + int minCostConnectPoints(List> points) { + int n = points.length; + int minCost = 0; + List visited = List.filled(n, false); + PriorityQueue> pq = PriorityQueue>((a, b) => a[0] - b[0]); + pq.add([0, 0]); + Map cache = {0: 0}; + + while (pq.isNotEmpty) { + List curr = pq.removeFirst(); + int cost = curr[0], u = curr[1]; + if (visited[u]) continue; + visited[u] = true; + minCost += cost; + for (int v = 0; v < n; v++) { + if (!visited[v]) { + int dist = (points[u][0] - points[v][0]).abs() + (points[u][1] - points[v][1]).abs(); + if (dist < (cache[v] ?? 1 << 31 - 1)) { + cache[v] = dist; + pq.add([dist, v]); + } + } + } + } + return minCost; + } +} diff --git a/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.go b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.go new file mode 100644 index 00000000..34af9539 --- /dev/null +++ b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.go @@ -0,0 +1,29 @@ +func minCostConnectPoints(points [][]int) int { + n := len(points) + minCost := 0 + visited := make([]bool, n) + best := make([]int, n) + for i := range best { best[i] = int(^uint(0) >> 1) } + best[0] = 0 + + for step := 0; step < n; step++ { + u := -1 + for i := 0; i < n; i++ { + if !visited[i] && (u == -1 || best[i] < best[u]) { u = i } + } + visited[u] = true + minCost += best[u] + for v := 0; v < n; v++ { + if !visited[v] { + dist := abs(points[u][0]-points[v][0]) + abs(points[u][1]-points[v][1]) + if dist < best[v] { best[v] = dist } + } + } + } + return minCost +} + +func abs(x int) int { + if x < 0 { return -x } + return x +} diff --git a/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.java b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.java new file mode 100644 index 00000000..9558408c --- /dev/null +++ b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.java @@ -0,0 +1,32 @@ +import java.util.PriorityQueue; +import java.util.HashMap; + +class Solution { + public int minCostConnectPoints(int[][] points) { + int n = points.length; + int minCost = 0; + boolean[] visited = new boolean[n]; + PriorityQueue pq = new PriorityQueue<>((a,b) -> a[0] - b[0]); + pq.offer(new int[]{0, 0}); + HashMap cache = new HashMap<>(); + cache.put(0, 0); + + while (!pq.isEmpty()) { + int[] curr = pq.poll(); + int cost = curr[0], u = curr[1]; + if (visited[u]) continue; + visited[u] = true; + minCost += cost; + for (int v = 0; v < n; v++) { + if (!visited[v]) { + int dist = Math.abs(points[u][0] - points[v][0]) + Math.abs(points[u][1] - points[v][1]); + if (dist < cache.getOrDefault(v, Integer.MAX_VALUE)) { + cache.put(v, dist); + pq.offer(new int[]{dist, v}); + } + } + } + } + return minCost; + } +} diff --git a/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.kt b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.kt new file mode 100644 index 00000000..67765b71 --- /dev/null +++ b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.kt @@ -0,0 +1,31 @@ +import java.util.PriorityQueue +import java.util.HashMap + +class Solution { + fun minCostConnectPoints(points: Array): Int { + val n = points.size + var minCost = 0 + val visited = BooleanArray(n) + val pq = PriorityQueue>(compareBy { it.first }) + pq.offer(Pair(0, 0)) + val cache = HashMap() + cache[0] = 0 + + while (pq.isNotEmpty()) { + val (cost, u) = pq.poll() + if (visited[u]) continue + visited[u] = true + minCost += cost + for (v in 0 until n) { + if (!visited[v]) { + val dist = Math.abs(points[u][0] - points[v][0]) + Math.abs(points[u][1] - points[v][1]) + if (dist < cache.getOrDefault(v, Int.MAX_VALUE)) { + cache[v] = dist + pq.offer(Pair(dist, v)) + } + } + } + } + return minCost + } +} diff --git a/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.py b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.py new file mode 100644 index 00000000..5841eb07 --- /dev/null +++ b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.py @@ -0,0 +1,31 @@ +import heapq +from typing import List + + +class Solution: + def minCostConnectPoints(self, points: List[List[int]]) -> int: + n = len(points) + min_cost = 0 + visited = [False] * n + pq = [(0, 0)] # (cost, vertex) + cache = {0: 0} + + while pq: + cost, u = heapq.heappop(pq) + + if visited[u]: + continue + + visited[u] = True + min_cost += cost + + for v in range(n): + if not visited[v]: + dist = abs(points[u][0] - points[v][0]) + abs( + points[u][1] - points[v][1] + ) + if dist < cache.get(v, float("inf")): + cache[v] = dist + heapq.heappush(pq, (dist, v)) + + return min_cost diff --git a/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.py2 b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.py2 new file mode 100644 index 00000000..515701c5 --- /dev/null +++ b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.py2 @@ -0,0 +1,26 @@ +class Solution(object): + def minCostConnectPoints(self, points): + """ + :type points: List[List[int]] + :rtype: int + """ + import heapq + n = len(points) + min_cost = 0 + visited = [False] * n + pq = [(0, 0)] + cache = {0: 0} + + while pq: + cost, u = heapq.heappop(pq) + if visited[u]: + continue + visited[u] = True + min_cost += cost + for v in range(n): + if not visited[v]: + dist = abs(points[u][0] - points[v][0]) + abs(points[u][1] - points[v][1]) + if dist < cache.get(v, float('inf')): + cache[v] = dist + heapq.heappush(pq, (dist, v)) + return min_cost diff --git a/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.rb b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.rb new file mode 100644 index 00000000..9f22d02c --- /dev/null +++ b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.rb @@ -0,0 +1,25 @@ +def min_cost_connect_points(points) + n = points.length + min_cost = 0 + visited = Array.new(n, false) + pq = [[0, 0]] + cache = {0 => 0} + + until pq.empty? + cost, u = pq.shift + next if visited[u] + visited[u] = true + min_cost += cost + (0...n).each do |v| + next if visited[v] + dist = (points[u][0] - points[v][0]).abs + (points[u][1] - points[v][1]).abs + if dist < (cache[v] || Float::INFINITY) + cache[v] = dist + # simple insert to maintain heap property + idx = pq.bsearch_index { |x| x[0] >= dist } || pq.length + pq.insert(idx, [dist, v]) + end + end + end + min_cost +end diff --git a/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.rs b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.rs new file mode 100644 index 00000000..a9072513 --- /dev/null +++ b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.rs @@ -0,0 +1,48 @@ +use std::collections::BinaryHeap; +use std::cmp::Ordering; + +#[derive(Eq, PartialEq)] +struct Item { + cost: i32, + node: usize, +} + +impl Ord for Item { + fn cmp(&self, other: &Self) -> Ordering { + other.cost.cmp(&self.cost) + } +} + +impl PartialOrd for Item { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Solution { + pub fn min_cost_connect_points(points: Vec>) -> i32 { + let n = points.len(); + let mut min_cost = 0; + let mut visited = vec![false; n]; + let mut pq = BinaryHeap::new(); + pq.push(Item { cost: 0, node: 0 }); + let mut cache: Vec = vec![i32::MAX; n]; + cache[0] = 0; + + while let Some(item) = pq.pop() { + if visited[item.node] { continue; } + visited[item.node] = true; + min_cost += item.cost; + for v in 0..n { + if !visited[v] { + let dist = (points[item.node][0] - points[v][0]).abs() + (points[item.node][1] - points[v][1]).abs(); + if dist < cache[v] { + cache[v] = dist; + pq.push(Item { cost: dist, node: v }); + } + } + } + } + min_cost + } +} diff --git a/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.swift b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.swift new file mode 100644 index 00000000..9aa094b4 --- /dev/null +++ b/tests/1501-2000/1584. min-cost-to-connect-all-points/sol.swift @@ -0,0 +1,29 @@ +import Foundation + +class Solution { + func minCostConnectPoints(_ points: [[Int]]) -> Int { + let n = points.count + var minCost = 0 + var visited = [Bool](repeating: false, count: n) + var pq = [(0, 0)] + var cache = [0: 0] + + while !pq.isEmpty { + pq.sort { $0.0 < $1.0 } + let (cost, u) = pq.removeFirst() + if visited[u] { continue } + visited[u] = true + minCost += cost + for v in 0..(); + cache.set(0, 0); + + while (pq.length > 0) { + pq.sort((a, b) => a[0] - b[0]); + const [cost, u] = pq.shift()!; + if (visited[u]) continue; + visited[u] = true; + minCost += cost; + for (let v = 0; v < n; v++) { + if (!visited[v]) { + const dist = + Math.abs(points[u][0] - points[v][0]) + + Math.abs(points[u][1] - points[v][1]); + if (dist < (cache.get(v) ?? Number.MAX_SAFE_INTEGER)) { + cache.set(v, dist); + pq.push([dist, v]); + } + } + } + } + return minCost; +} diff --git a/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/manifest.yaml b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/manifest.yaml new file mode 100644 index 00000000..30623673 --- /dev/null +++ b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/manifest.yaml @@ -0,0 +1,223 @@ +entry: + id: 1585 + title: check-if-string-is-transformable-with-substring-sort-operations + params: + s: + type: string + t: + type: string + call: + cpp: "Solution().isTransformable({s}, {t})" + rust: "Solution::is_transformable({s}, {t})" + python3: "Solution().isTransformable({s}, {t})" + python2: "Solution().isTransformable({s}, {t})" + ruby: "is_transformable({s}, {t})" + java: "new Solution().isTransformable({s}, {t})" + csharp: "new Solution().IsTransformable({s}, {t})" + kotlin: "Solution().isTransformable({s}, {t})" + go: "isTransformable({s}, {t})" + dart: "Solution().isTransformable({s}, {t})" + swift: "Solution().isTransformable({s}, {t})" + typescript: "isTransformable({s}, {t})" + +judge: + type: exact + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().isTransformable(s, t, {result})" + checker: | + from collections import deque + + class Checker: + def isTransformable(self, s, t, result): + if not isinstance(result, bool): + return False + if len(s) != len(t) or sorted(s) != sorted(t): + expected = False + else: + positions = [deque() for _ in range(10)] + for index, char in enumerate(s): + positions[ord(char) - 48].append(index) + expected = True + for char in t: + digit = ord(char) - 48 + if not positions[digit]: + expected = False + break + index = positions[digit].popleft() + for smaller in range(digit): + if positions[smaller] and positions[smaller][0] < index: + expected = False + break + if not expected: + break + return result is expected + +seed: 1585 + +tests: + - name: example-1 + in: + s: "84532" + t: "34852" + out: true + - name: example-2 + in: + s: "34521" + t: "23415" + out: true + - name: example-3 + in: + s: "12345" + t: "12435" + out: false + - name: one-digit + in: + s: "7" + t: "7" + out: true + - name: equal-digits + in: + s: "000000" + t: "000000" + out: true + - name: same-order-distinct + in: + s: "0123456789" + t: "0123456789" + out: true + - name: descending-to-ascending + in: + s: "9876543210" + t: "0123456789" + out: true + - name: ascending-to-descending + in: + s: "0123456789" + t: "9876543210" + out: false + - name: duplicate-blocks + in: + s: "11223344" + t: "22113344" + out: false + - name: smaller-blocked + in: + s: "102" + t: "201" + out: false + - name: zero-before-one + in: + s: "102345" + t: "012345" + out: true + - name: zero-after-one + in: + s: "012345" + t: "102345" + out: false + - name: impossible-count + in: + s: "1234" + t: "1233" + out: false + - name: impossible-length + in: + s: "123" + t: "1234" + out: false + - name: repeated-zeroes + in: + s: "909090" + t: "000999" + out: true + - name: blocked-repeated-zeroes + in: + s: "000999" + t: "909090" + out: false + - name: alternating-low-high + in: + s: "91919191" + t: "11119999" + out: true + - name: alternating-high-low + in: + s: "19191919" + t: "99991111" + out: false + - name: equal-middle + in: + s: "505050" + t: "055500" + out: false + - name: all-nines + in: + s: "9999999999" + t: "9999999999" + out: true + - name: permutation-rotated + in: + s: "1234567890" + t: "9012345678" + out: false + - name: low-digit-bubble + in: + s: "3210123" + t: "0123321" + out: false + - name: high-digit-cannot-cross + in: + s: "0123321" + t: "3210123" + out: false + - name: sparse-digits + in: + s: "80604020" + t: "02468000" + out: false + - name: sparse-digits-valid + in: + s: "86420000" + t: "00002468" + out: true + - name: ten-with-duplicates + in: + s: "9081726354" + t: "0123457896" + out: true + - name: local-sort-valid + in: + s: "543210" + t: "453210" + out: true + - name: local-sort-invalid + in: + s: "453210" + t: "543210" + out: false + - name: repeated-3 + in: + s: "333222111000" + t: "000111222333" + out: true + - name: reverse-repeated-3 + in: + s: "000111222333" + t: "333222111000" + out: false + - name: mixed-valid + in: + s: "8453284512" + t: "3485284125" + out: true + - name: mixed-invalid + in: + s: "3485284125" + t: "8453284512" + out: false diff --git a/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.cpp b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.cpp new file mode 100644 index 00000000..5bbf67a5 --- /dev/null +++ b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + bool isTransformable(string s, string t) { + string sc = s, tc = t; + sort(sc.begin(), sc.end()); + sort(tc.begin(), tc.end()); + if (sc != tc) return false; + + vector> pos(10); + for (int i = 0; i < s.size(); i++) { + pos[s[i]-'0'].push_back(i); + } + + for (char tt : t) { + int dig = tt-'0'; + int i = pos[dig].front(); + pos[dig].pop_front(); + for (int ii = 0; ii < dig; ii++) { + if (!pos[ii].empty() && pos[ii].front() < i) return false; + } + } + return true; + } +}; diff --git a/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.cs b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.cs new file mode 100644 index 00000000..8704f5a8 --- /dev/null +++ b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public bool IsTransformable(string s, string t) { + char[] sc = s.ToCharArray(); + char[] tc = t.ToCharArray(); + Array.Sort(sc); + Array.Sort(tc); + if (new string(sc) != new string(tc)) return false; + + var pos = new Queue[10]; + for (int i = 0; i < 10; i++) pos[i] = new Queue(); + for (int i = 0; i < s.Length; i++) pos[s[i]-'0'].Enqueue(i); + + foreach (char tt in t) { + int dig = tt-'0'; + int i = pos[dig].Dequeue(); + for (int ii = 0; ii < dig; ii++) { + if (pos[ii].Count > 0 && pos[ii].Peek() < i) return false; + } + } + return true; + } +} diff --git a/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.dart b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.dart new file mode 100644 index 00000000..59cee725 --- /dev/null +++ b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.dart @@ -0,0 +1,21 @@ +class Solution { + bool isTransformable(String s, String t) { + final sortedS = s.split('')..sort(); + final sortedT = t.split('')..sort(); + if (sortedS.join() != sortedT.join()) return false; + + List> pos = List.generate(10, (_) => []); + for (int i = 0; i < s.length; i++) { + pos[int.parse(s[i])].add(i); + } + + for (int i = 0; i < t.length; i++) { + int dig = int.parse(t[i]); + int idx = pos[dig].removeAt(0); + for (int ii = 0; ii < dig; ii++) { + if (pos[ii].isNotEmpty && pos[ii].first < idx) return false; + } + } + return true; + } +} diff --git a/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.go b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.go new file mode 100644 index 00000000..6d298fdf --- /dev/null +++ b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.go @@ -0,0 +1,23 @@ +func isTransformable(s string, t string) bool { + if len(s) != len(t) { return false } + sc := []byte(s) + tc := []byte(t) + sort.Slice(sc, func(i,j int) bool { return sc[i] < sc[j] }) + sort.Slice(tc, func(i,j int) bool { return tc[i] < tc[j] }) + if string(sc) != string(tc) { return false } + + pos := make([][]int, 10) + for i := range pos { pos[i] = []int{} } + for i, ss := range []byte(s) { + pos[int(ss-'0')] = append(pos[int(ss-'0')], i) + } + + for _, tt := range []byte(t) { + i := pos[int(tt-'0')][0] + pos[int(tt-'0')] = pos[int(tt-'0')][1:] + for ii := 0; ii < int(tt-'0'); ii++ { + if len(pos[ii]) > 0 && pos[ii][0] < i { return false } + } + } + return true +} diff --git a/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.java b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.java new file mode 100644 index 00000000..8fc76cfa --- /dev/null +++ b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.java @@ -0,0 +1,25 @@ +class Solution { + public boolean isTransformable(String s, String t) { + if (s.length() != t.length()) return false; + int n = s.length(); + int[][] positions = new int[10][n]; + int[] sizes = new int[10]; + for (int index = 0; index < n; index++) { + int digit = s.charAt(index) - '0'; + positions[digit][sizes[digit]++] = index; + } + int[] heads = new int[10]; + for (int index = 0; index < n; index++) { + int digit = t.charAt(index) - '0'; + if (heads[digit] == sizes[digit]) return false; + int sourceIndex = positions[digit][heads[digit]++]; + for (int smaller = 0; smaller < digit; smaller++) { + if (heads[smaller] < sizes[smaller] + && positions[smaller][heads[smaller]] < sourceIndex) { + return false; + } + } + } + return true; + } +} diff --git a/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.kt b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.kt new file mode 100644 index 00000000..28adc076 --- /dev/null +++ b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun isTransformable(s: String, t: String): Boolean { + if (s.toCharArray().sorted() != t.toCharArray().sorted()) return false + + val pos = Array(10) { ArrayDeque() } + s.forEachIndexed { i, ss -> pos[ss-'0'].addLast(i) } + + for (tt in t) { + val i = pos[tt-'0'].removeFirst() + for (ii in 0 until tt-'0') { + if (pos[ii].isNotEmpty() && pos[ii].first() < i) return false + } + } + return true + } +} diff --git a/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.py b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.py new file mode 100644 index 00000000..b6aed29d --- /dev/null +++ b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.py @@ -0,0 +1,15 @@ +class Solution: + def isTransformable(self, s: str, t: str) -> bool: + if sorted(s) != sorted(t): + return False # edge case + + pos = [deque() for _ in range(10)] + for i, ss in enumerate(s): + pos[int(ss)].append(i) + + for tt in t: + i = pos[int(tt)].popleft() + for ii in range(int(tt)): + if pos[ii] and pos[ii][0] < i: + return False # cannot swap + return True diff --git a/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.py2 b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.py2 new file mode 100644 index 00000000..c7170c56 --- /dev/null +++ b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.py2 @@ -0,0 +1,17 @@ +class Solution(object): + def isTransformable(self, s, t): + """ + :type s: str + :type t: str + :rtype: bool + """ + if sorted(s) != sorted(t): return False + + pos = [collections.deque() for _ in range(10)] + for i, ss in enumerate(s): pos[int(ss)].append(i) + + for tt in t: + i = pos[int(tt)].popleft() + for ii in range(int(tt)): + if pos[ii] and pos[ii][0] < i: return False + return True diff --git a/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.rb b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.rb new file mode 100644 index 00000000..de466c18 --- /dev/null +++ b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.rb @@ -0,0 +1,19 @@ +# @param {String} s +# @param {String} t +# @return {Boolean} +def is_transformable(s, t) + return false if s.chars.sort != t.chars.sort + + pos = Array.new(10) { [] } + s.each_char.with_index do |ss, i| + pos[ss.to_i] << i + end + + t.each_char do |tt| + i = pos[tt.to_i].shift + (0...tt.to_i).each do |ii| + return false if !pos[ii].empty? && pos[ii][0] < i + end + end + true +end diff --git a/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.rs b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.rs new file mode 100644 index 00000000..ef436d35 --- /dev/null +++ b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.rs @@ -0,0 +1,23 @@ +impl Solution { + pub fn is_transformable(s: String, t: String) -> bool { + let mut sc: Vec = s.chars().collect(); + let mut tc: Vec = t.chars().collect(); + sc.sort(); + tc.sort(); + if sc != tc { return false; } + + let mut pos: Vec> = vec![Vec::new(); 10]; + for (i, ch) in s.chars().enumerate() { + pos[ch.to_digit(10).unwrap() as usize].push(i); + } + + for ch in t.chars() { + let dig = ch.to_digit(10).unwrap() as usize; + let i = pos[dig].remove(0); + for ii in 0..dig { + if !pos[ii].is_empty() && pos[ii][0] < i { return false; } + } + } + true + } +} diff --git a/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.swift b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.swift new file mode 100644 index 00000000..44a1659a --- /dev/null +++ b/tests/1501-2000/1585. check-if-string-is-transformable-with-substring-sort-operations/sol.swift @@ -0,0 +1,19 @@ +class Solution { + func isTransformable(_ s: String, _ t: String) -> Bool { + if Array(s).sorted() != Array(t).sorted() { return false } + + var pos = [[Int]](repeating: [], count: 10) + for (i, ch) in s.enumerated() { + pos[Int(String(ch))!].append(i) + } + + for ch in t { + let dig = Int(String(ch))! + let i = pos[dig].removeFirst() + for ii in 0.. []); + for (let i = 0; i < s.length; i++) { + pos[parseInt(s[i])].push(i); + } + + for (const ch of t) { + const dig = parseInt(ch); + const i = pos[dig].shift()!; + for (let ii = 0; ii < dig; ii++) { + if (pos[ii].length > 0 && pos[ii][0] < i) return false; + } + } + return true; +} diff --git a/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/manifest.yaml b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/manifest.yaml new file mode 100644 index 00000000..ae26aac5 --- /dev/null +++ b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/manifest.yaml @@ -0,0 +1,404 @@ +entry: + id: 1588 + title: "sum-of-all-odd-length-subarrays" + params: + arr: + type: array + items: + type: int + call: + cpp: "Solution().sumOddLengthSubarrays({arr})" + rust: "Solution::sum_odd_length_subarrays({arr})" + python3: "Solution().sumOddLengthSubarrays({arr})" + python2: "Solution().sumOddLengthSubarrays({arr})" + ruby: "sum_odd_length_subarrays({arr})" + java: "new Solution().sumOddLengthSubarrays({arr})" + csharp: "new Solution().SumOddLengthSubarrays({arr})" + kotlin: "Solution().sumOddLengthSubarrays({arr})" + go: "sumOddLengthSubarrays({arr})" + dart: "Solution().sumOddLengthSubarrays({arr})" + swift: "Solution().sumOddLengthSubarrays({arr})" + typescript: "sumOddLengthSubarrays({arr})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().sumOddLengthSubarrays(arr, {result})" + checker: | + class Checker: + def sumOddLengthSubarrays(self, arr, result): + expected = 0 + for left in range(len(arr)): + running = 0 + for right in range(left, len(arr)): + running += arr[right] + if (right - left + 1) % 2 == 1: + expected += running + return result == expected + +seed: 1588 + +tests: + - name: example-one + in: + arr: [1, 4, 2, 5, 3] + out: 58 + - name: example-two + in: + arr: [1, 2] + out: 3 + - name: example-three + in: + arr: [10, 11, 12] + out: 66 + - name: single-one + in: + arr: [1] + out: 1 + - name: single-maximum + in: + arr: [1000] + out: 1000 + - name: two-equal + in: + arr: [7, 7] + out: 14 + - name: three-equal + in: + arr: [5, 5, 5] + out: 30 + - name: four-equal + in: + arr: [2, 2, 2, 2] + out: 20 + - name: five-equal + in: + arr: [9, 9, 9, 9, 9] + out: 171 + - name: increasing-five + in: + arr: [1, 2, 3, 4, 5] + out: 57 + - name: decreasing-five + in: + arr: [5, 4, 3, 2, 1] + out: 57 + - name: alternating-small + in: + arr: [1, 100, 1, 100, 1, 100] + out: 1414 + - name: alternating-large + in: + arr: [1000, 1, 1000, 1, 1000] + out: 11008 + - name: all-ones-seven + in: + arr: [1, 1, 1, 1, 1, 1, 1] + out: 44 + - name: powers-of-two + in: + arr: [1, 2, 4, 8, 16, 32, 64] + out: 688 + - name: mixed-small + in: + arr: [3, 1, 4, 1, 5, 9, 2, 6] + out: 234 + - name: mixed-large + in: + arr: [999, 1, 998, 2, 997, 3, 996, 4, 995] + out: 44965 + - name: length-ten-ones + in: + arr: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 110 + - name: length-ten-max + in: + arr: [1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000] + out: 110000 + - name: sparse-high-values + in: + arr: [1, 1, 1, 1000, 1, 1, 1, 1, 1000, 1] + out: 23087 + - name: repeated-cycle + in: + arr: [2, 4, 6, 2, 4, 6, 2, 4, 6] + out: 340 + - name: prime-prefix + in: + arr: [2, 3, 5, 7, 11, 13] + out: 187 + - name: near-maximum-seven + in: + arr: [999, 998, 997, 996, 995, 994, 993] + out: 43824 + - name: two-blocks + in: + arr: [10, 10, 1, 1, 10, 10] + out: 172 + - name: length-eleven + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + out: 876 + - name: length-twelve + in: + arr: [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + out: 1183 + - name: alternating-three-values + in: + arr: [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3] + out: 364 + - name: mostly-one + in: + arr: [1, 1, 1, 1, 1, 1, 100, 1, 1, 1, 1, 1, 1] + out: 2706 + - name: length-fifteen-ones + in: + arr: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 344 + - name: length-twenty-pattern + in: + arr: + [ + 1, + 10, + 100, + 1000, + 1, + 10, + 100, + 1000, + 1, + 10, + 100, + 1000, + 1, + 10, + 100, + 1000, + 1, + 10, + 100, + 1000, + ] + out: 211640 + - name: length-twenty-max + in: + arr: + [ + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + ] + out: 770000 + - name: length-twenty-five-ones + in: + arr: + [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + ] + out: 1469 + - name: length-thirty-ramp + in: + arr: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + ] + out: 38440 + - name: length-fifty-max + in: + arr: + [ + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + ] + out: 11050000 + - name: generated-random-small + in: + arr: + gen: "array" + len: 1 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + seed: 158801 + - name: generated-random-medium + in: + arr: + gen: "array" + len: 17 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + seed: 158802 + - name: generated-random-large + in: + arr: + gen: "array" + len: 50 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + seed: 158803 + - name: generated-near-limit + in: + arr: + gen: "array" + len: 99 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + seed: 158804 + - name: generated-maximum + in: + arr: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + seed: 158805 + - name: generated-maximum-low-values + in: + arr: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 10 + elemType: "int" + seed: 158806 diff --git a/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.cpp b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.cpp new file mode 100644 index 00000000..65474156 --- /dev/null +++ b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int sumOddLengthSubarrays(vector& arr) { + int s = accumulate(arr.begin(), arr.end(), 0); + int l = arr.size() - 1; + int i = 2; + while (l >= i) { + int j = 0; + int e = i; + while (e <= l) { + for (int k = j; k <= e; k++) { + s += arr[k]; + } + j++; + e++; + } + i += 2; + } + return s; + } +}; diff --git a/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.cs b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.cs new file mode 100644 index 00000000..3dc4bc3e --- /dev/null +++ b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public int SumOddLengthSubarrays(int[] arr) { + int s = arr.Sum(); + int l = arr.Length - 1; + int i = 2; + while (l >= i) { + int j = 0; + int e = i; + while (e <= l) { + for (int k = j; k <= e; k++) { + s += arr[k]; + } + j++; + e++; + } + i += 2; + } + return s; + } +} diff --git a/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.dart b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.dart new file mode 100644 index 00000000..75060d5d --- /dev/null +++ b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.dart @@ -0,0 +1,20 @@ +class Solution { + int sumOddLengthSubarrays(List arr) { + int s = arr.reduce((a, b) => a + b); + int l = arr.length - 1; + int i = 2; + while (l >= i) { + int j = 0; + int e = i; + while (e <= l) { + for (int k = j; k <= e; k++) { + s += arr[k]; + } + j++; + e++; + } + i += 2; + } + return s; + } +} diff --git a/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.go b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.go new file mode 100644 index 00000000..41203131 --- /dev/null +++ b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.go @@ -0,0 +1,21 @@ +func sumOddLengthSubarrays(arr []int) int { + s := 0 + for _, x := range arr { + s += x + } + l := len(arr) - 1 + i := 2 + for l >= i { + j := 0 + e := i + for e <= l { + for k := j; k <= e; k++ { + s += arr[k] + } + j++ + e++ + } + i += 2 + } + return s +} diff --git a/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.java b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.java new file mode 100644 index 00000000..a75ec7fc --- /dev/null +++ b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.java @@ -0,0 +1,19 @@ +class Solution { + public int sumOddLengthSubarrays(int[] arr) { + int s = 0; + for (int x : arr) s += x; + int l = arr.length - 1; + int i = 2; + while (l >= i) { + int j = 0; + int e = i; + while (e <= l) { + for (int k = j; k <= e; k++) s += arr[k]; + j++; + e++; + } + i += 2; + } + return s; + } +} diff --git a/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.kt b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.kt new file mode 100644 index 00000000..0f72acdc --- /dev/null +++ b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.kt @@ -0,0 +1,18 @@ +class Solution { + fun sumOddLengthSubarrays(arr: IntArray): Int { + var s = arr.sum() + var l = arr.size - 1 + var i = 2 + while (l >= i) { + var j = 0 + var e = i + while (e <= l) { + for (k in j..e) s += arr[k] + j++ + e++ + } + i += 2 + } + return s + } +} diff --git a/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.py b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.py new file mode 100644 index 00000000..123665e2 --- /dev/null +++ b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.py @@ -0,0 +1,14 @@ +class Solution(object): + def sumOddLengthSubarrays(self, arr): + s = sum(arr) + l = len(arr) - 1 + i = 2 + while l >= i: + j = 0 + e = i + while e <= l: + s += sum(arr[j : e + 1]) + j += 1 + e += 1 + i += 2 + return s diff --git a/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.py2 b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.py2 new file mode 100644 index 00000000..369a847f --- /dev/null +++ b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def sumOddLengthSubarrays(self, arr): + """ + :type arr: List[int] + :rtype: int + """ + s = sum(arr) + l = len(arr) - 1 + i = 2 + while l >= i: + j = 0 + e = i + while e <= l: + s += sum(arr[j:e+1]) + j += 1 + e += 1 + i += 2 + return s diff --git a/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.rb b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.rb new file mode 100644 index 00000000..f14bf0f6 --- /dev/null +++ b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.rb @@ -0,0 +1,18 @@ +# @param {Integer[]} arr +# @return {Integer} +def sum_odd_length_subarrays(arr) + s = arr.sum + l = arr.length - 1 + i = 2 + while l >= i + j = 0 + e = i + while e <= l + s += arr[j..e].sum + j += 1 + e += 1 + end + i += 2 + end + s +end diff --git a/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.rs b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.rs new file mode 100644 index 00000000..c203f90e --- /dev/null +++ b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn sum_odd_length_subarrays(arr: Vec) -> i32 { + let mut s: i32 = arr.iter().sum(); + let l = arr.len() - 1; + let mut i = 2; + while l >= i { + let mut j = 0; + let mut e = i; + while e <= l { + for k in j..=e { + s += arr[k]; + } + j += 1; + e += 1; + } + i += 2; + } + s + } +} diff --git a/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.swift b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.swift new file mode 100644 index 00000000..f4de790b --- /dev/null +++ b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func sumOddLengthSubarrays(_ arr: [Int]) -> Int { + var s = arr.reduce(0, +) + let l = arr.count - 1 + var i = 2 + while l >= i { + var j = 0 + var e = i + while e <= l { + for k in j...e { + s += arr[k] + } + j += 1 + e += 1 + } + i += 2 + } + return s + } +} diff --git a/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.ts b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.ts new file mode 100644 index 00000000..265c8a6a --- /dev/null +++ b/tests/1501-2000/1588. sum-of-all-odd-length-subarrays/sol.ts @@ -0,0 +1,18 @@ +function sumOddLengthSubarrays(arr: number[]): number { + let s = arr.reduce((a, b) => a + b, 0); + let l = arr.length - 1; + let i = 2; + while (l >= i) { + let j = 0; + let e = i; + while (e <= l) { + for (let k = j; k <= e; k++) { + s += arr[k]; + } + j++; + e++; + } + i += 2; + } + return s; +} diff --git a/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/manifest.yaml b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/manifest.yaml new file mode 100644 index 00000000..3db8034d --- /dev/null +++ b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/manifest.yaml @@ -0,0 +1,366 @@ +entry: + id: 1589 + title: maximum-sum-obtained-of-any-permutation + params: + nums: + type: array + items: + type: int + requests: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().maxSumRangeQuery({nums}, {requests})" + rust: "Solution::max_sum_range_query({nums}, {requests})" + python3: "Solution().maxSumRangeQuery({nums}, {requests})" + python2: "Solution().maxSumRangeQuery({nums}, {requests})" + ruby: "max_sum_range_query({nums}, {requests})" + java: "new Solution().maxSumRangeQuery({nums}, {requests})" + csharp: "new Solution().MaxSumRangeQuery({nums}, {requests})" + kotlin: "Solution().maxSumRangeQuery({nums}, {requests})" + go: "maxSumRangeQuery({nums}, {requests})" + dart: "Solution().maxSumRangeQuery({nums}, {requests})" + swift: "Solution().maxSumRangeQuery({nums}, {requests})" + typescript: "maxSumRangeQuery({nums}, {requests})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 512 +oracle: + python3: + call: "Checker().maxSumRangeQuery(nums, requests, {result})" + checker: | + class Checker: + def maxSumRangeQuery(self, nums, requests, result): + mod = 1000000007 + n = len(nums) + freq = [0] * (n + 1) + for left, right in requests: + freq[left] += 1 + freq[right + 1] -= 1 + cur = 0 + counts = [] + for i in range(n): + cur += freq[i] + counts.append(cur) + expected = sum(a * b for a, b in zip(sorted(nums), sorted(counts))) % mod + return isinstance(result, int) and result == expected +seed: 1589 +tests: + - name: example-one + in: + nums: [1, 2, 3, 4, 5] + requests: + - [1, 3] + - [0, 1] + out: 19 + - name: example-two + in: + nums: [1, 2, 3, 4, 5, 6] + requests: + - [0, 1] + out: 11 + - name: example-three + in: + nums: [1, 2, 3, 4, 5, 10] + requests: + - [0, 2] + - [1, 3] + - [1, 1] + out: 47 + - name: two-elements-full + in: + nums: [0, 100000] + requests: + - [0, 1] + out: 100000 + - name: one-position-repeated + in: + nums: [4, 9, 1] + requests: + - [1, 1] + - [1, 1] + - [1, 1] + out: 27 + - name: disjoint + in: + nums: [8, 1, 7, 2] + requests: + - [0, 0] + - [2, 3] + out: 17 + - name: all-singletons + in: + nums: [5, 2, 9, 1] + requests: + - [0, 0] + - [1, 1] + - [2, 2] + - [3, 3] + out: 17 + - name: nested + in: + nums: [3, 6, 2, 8, 4] + requests: + - [0, 4] + - [1, 3] + - [2, 2] + out: 49 + - name: duplicate-values + in: + nums: [7, 7, 7, 7] + requests: + - [0, 2] + - [1, 3] + out: 42 + - name: zeros + in: + nums: [0, 0, 4, 0, 2] + requests: + - [0, 4] + - [0, 0] + - [4, 4] + out: 12 + - name: descending + in: + nums: [10, 9, 8, 7, 6, 5] + requests: + - [0, 5] + - [0, 2] + - [3, 5] + out: 90 + - name: overlap-middle + in: + nums: [1, 3, 5, 7, 9] + requests: + - [0, 2] + - [1, 3] + - [2, 4] + out: 55 + - name: endpoint-heavy + in: + nums: [2, 11, 5, 3, 17] + requests: + - [0, 0] + - [4, 4] + - [0, 4] + - [0, 4] + out: 104 + - name: large-values + in: + nums: [100000, 99999, 99998, 99997] + requests: + - [0, 1] + - [1, 3] + - [0, 3] + out: 899988 + - name: narrow-overlap + in: + nums: [12, 4, 15, 3, 9, 7] + requests: + - [1, 4] + - [2, 3] + - [3, 5] + - [0, 0] + out: 101 + - name: alternating-singletons + in: + nums: [6, 1, 8, 2, 10, 3] + requests: + - [0, 0] + - [2, 2] + - [4, 4] + - [1, 5] + out: 48 + - name: many-identical-requests + in: + nums: [1, 4, 6, 8, 10] + requests: + - [0, 3] + - [0, 3] + - [0, 3] + - [1, 4] + out: 109 + - name: full-and-tail + in: + nums: [2, 4, 6, 8, 10, 12] + requests: + - [0, 5] + - [2, 5] + - [4, 5] + out: 100 + - name: prime-values + in: + nums: [2, 3, 5, 7, 11, 13, 17] + requests: + - [0, 6] + - [0, 2] + - [2, 5] + - [4, 4] + out: 144 + - name: uneven-coverage + in: + nums: [20, 1, 14, 3, 8, 6, 2] + requests: + - [0, 0] + - [0, 6] + - [1, 5] + - [1, 5] + - [3, 3] + out: 178 + - name: n-eight + in: + nums: [8, 6, 7, 5, 3, 0, 9, 1] + requests: + - [0, 7] + - [0, 3] + - [4, 7] + - [2, 6] + out: 113 + - name: no-zero-coverage + in: + nums: [5, 10, 15, 20, 25] + requests: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + out: 135 + - name: singleton-array-not-allowed + in: + nums: [42, 42] + requests: + - [0, 0] + - [1, 1] + - [0, 1] + out: 168 + - name: zero-request-position + in: + nums: [1, 2, 3, 4, 5, 6] + requests: + - [0, 0] + - [0, 0] + - [5, 5] + out: 17 + - name: high-frequency-center + in: + nums: [1, 2, 4, 8, 16, 32] + requests: + - [2, 2] + - [2, 2] + - [2, 2] + - [1, 3] + - [2, 4] + out: 204 + - name: max-n-small-values + in: + nums: [0, 1, 0, 1, 0, 1, 0, 1] + requests: + - [0, 7] + - [0, 7] + - [1, 6] + - [2, 5] + out: 16 + - name: reversed-interval-pattern + in: + nums: [13, 2, 21, 5, 8, 3] + requests: + - [0, 5] + - [0, 1] + - [4, 5] + - [1, 4] + out: 138 + - name: large-count + in: + nums: [1, 2, 3, 4, 5] + requests: + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [0, 0] + - [4, 4] + - [4, 4] + out: 33 + - name: large-alternating + in: + nums: [100000, 0, 99999, 1, 50000, 50000] + requests: + - [0, 5] + - [0, 0] + - [2, 4] + - [1, 5] + - [3, 3] + out: 949999 + - name: long-overlap + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + requests: + - [0, 9] + - [0, 8] + - [1, 9] + - [2, 7] + - [3, 6] + - [4, 5] + out: 260 + - name: repeated-full-range + in: + nums: [0, 100000, 99999, 42, 17, 80000, 1] + requests: + - [0, 6] + - [0, 6] + - [0, 6] + - [0, 6] + - [0, 6] + out: 1400295 + - name: sparse-large-indices + in: + nums: [9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99, 108] + requests: + - [0, 11] + - [0, 1] + - [10, 11] + - [5, 8] + - [3, 9] + out: 1773 + - name: dense-coverage + in: + nums: [1, 10, 100, 1000, 10000, 100000] + requests: + - [0, 0] + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [1, 5] + - [2, 5] + - [3, 5] + - [4, 5] + out: 666665 + - name: alternating-ranges + in: + nums: [31, 2, 47, 5, 19, 11, 23, 7, 29] + requests: + - [0, 2] + - [2, 4] + - [4, 6] + - [6, 8] + - [1, 7] + - [0, 8] + out: 622 + - name: maximum-request-volume + in: + nums: [100000, 99999, 99998, 99997, 99996] + requests: + - [0, 4] + - [0, 3] + - [1, 4] + - [1, 3] + - [2, 4] + - [0, 2] + out: 2199964 diff --git a/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.cpp b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.cpp new file mode 100644 index 00000000..2360cc10 --- /dev/null +++ b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + int maxSumRangeQuery(vector& nums, vector>& requests) { + vector> events; + const int MOD = 1e9+7; + + for (auto& req : requests) { + events.push_back({req[0], 1}); + events.push_back({req[1]+1, -1}); + } + + sort(events.begin(), events.end()); + + int cnt = 0; + int prev = -1; + unordered_map weight; + + for (auto& [pos, delta] : events) { + if (prev != -1 && cnt != 0) { + weight[cnt] += pos - prev; + } + prev = pos; + cnt += delta; + } + + vector> wList(weight.begin(), weight.end()); + sort(wList.begin(), wList.end(), [](auto& a, auto& b) { + return a.first > b.first; + }); + + sort(nums.rbegin(), nums.rend()); + long long ans = 0; + int idx = 0; + + for (auto& [wg, num] : wList) { + for (long long i = 0; i < num; i++) { + ans = (ans + nums[idx] * wg) % MOD; + idx++; + } + } + + return ans; + } +}; diff --git a/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.cs b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.cs new file mode 100644 index 00000000..f092d7b3 --- /dev/null +++ b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.cs @@ -0,0 +1,44 @@ +public class Solution { + public int MaxSumRangeQuery(int[] nums, int[][] requests) { + var events = new List<(int, int)>(); + const int MOD = 1_000_000_007; + + foreach (var req in requests) { + events.Add((req[0], 1)); + events.Add((req[1]+1, -1)); + } + + events.Sort((a, b) => a.Item1.CompareTo(b.Item1)); + + int cnt = 0; + int prev = -1; + var weight = new Dictionary(); + + foreach (var (pos, delta) in events) { + if (prev != -1 && cnt != 0) { + if (!weight.ContainsKey(cnt)) weight[cnt] = 0; + weight[cnt] += pos - prev; + } + prev = pos; + cnt += delta; + } + + var sorted = weight.OrderByDescending(kv => kv.Key).ToList(); + + Array.Sort(nums); + Array.Reverse(nums); + long ans = 0; + int idx = 0; + + foreach (var kv in sorted) { + long wg = kv.Key; + long num = kv.Value; + for (long i = 0; i < num; i++) { + ans = (ans + (long)nums[idx] * wg) % MOD; + idx++; + } + } + + return (int)ans; + } +} diff --git a/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.dart b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.dart new file mode 100644 index 00000000..1a0ef673 --- /dev/null +++ b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.dart @@ -0,0 +1,43 @@ +class Solution { + int maxSumRangeQuery(List nums, List> requests) { + List> events = []; + int mod = 1000000007; + + for (var req in requests) { + events.add([req[0], 1]); + events.add([req[1]+1, -1]); + } + + events.sort((a, b) => a[0].compareTo(b[0])); + + int cnt = 0; + int prev = -1; + Map weight = {}; + + for (var e in events) { + if (prev != -1 && cnt != 0) { + weight[cnt] = (weight[cnt] ?? 0) + (e[0] - prev); + } + prev = e[0]; + cnt += e[1]; + } + + var sorted = weight.entries.toList() + ..sort((a, b) => b.key.compareTo(a.key)); + + nums.sort((a, b) => b.compareTo(a)); + int ans = 0; + int idx = 0; + + for (var entry in sorted) { + int wg = entry.key; + int num = entry.value; + for (int i = 0; i < num; i++) { + ans = (ans + nums[idx] * wg) % mod; + idx++; + } + } + + return ans; + } +} diff --git a/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.go b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.go new file mode 100644 index 00000000..2d9beb45 --- /dev/null +++ b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.go @@ -0,0 +1,54 @@ +func maxSumRangeQuery(nums []int, requests [][]int) int { + type event struct { + pos int + delta int + } + events := make([]event, 0, len(requests)*2) + mod := 1000000007 + + for _, req := range requests { + events = append(events, event{req[0], 1}) + events = append(events, event{req[1]+1, -1}) + } + + sort.Slice(events, func(i, j int) bool { + return events[i].pos < events[j].pos + }) + + cnt := 0 + prev := -1 + weight := make(map[int]int64) + + for _, e := range events { + if prev != -1 && cnt != 0 { + weight[cnt] += int64(e.pos - prev) + } + prev = e.pos + cnt += e.delta + } + + type wItem struct { + cnt int + num int64 + } + wList := make([]wItem, 0, len(weight)) + for k, v := range weight { + wList = append(wList, wItem{k, v}) + } + sort.Slice(wList, func(i, j int) bool { + return wList[i].cnt > wList[j].cnt + }) + + sort.Sort(sort.Reverse(sort.IntSlice(nums))) + ans := 0 + idx := 0 + + for _, item := range wList { + for i := int64(0); i < item.num; i++ { + ans = (ans + nums[idx]*item.cnt) % mod + idx++ + } + } + + return ans +} diff --git a/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.java b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.java new file mode 100644 index 00000000..d9725a4c --- /dev/null +++ b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.java @@ -0,0 +1,50 @@ +class Solution { + public int maxSumRangeQuery(int[] nums, int[][] requests) { + List events = new ArrayList<>(); + int mod = 1000000007; + + for (int[] req : requests) { + events.add(new int[]{req[0], 1}); + events.add(new int[]{req[1]+1, -1}); + } + + events.sort((a, b) -> Integer.compare(a[0], b[0])); + + int cnt = 0; + int prev = -1; + Map weight = new HashMap<>(); + + for (int[] e : events) { + if (prev != -1 && cnt != 0) { + weight.put(cnt, weight.getOrDefault(cnt, 0L) + (e[0] - prev)); + } + prev = e[0]; + cnt += e[1]; + } + + List> sorted = new ArrayList<>(weight.entrySet()); + sorted.sort((a, b) -> Integer.compare(b.getKey(), a.getKey())); + + Arrays.sort(nums); + // reverse + for (int i = 0, j = nums.length-1; i < j; i++, j--) { + int tmp = nums[i]; + nums[i] = nums[j]; + nums[j] = tmp; + } + + long ans = 0; + int idx = 0; + + for (Map.Entry entry : sorted) { + long wg = entry.getKey(); + long num = entry.getValue(); + for (long k = 0; k < num; k++) { + ans = (ans + (long)nums[idx] * wg) % mod; + idx++; + } + } + + return (int)ans; + } +} diff --git a/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.kt b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.kt new file mode 100644 index 00000000..c584bbcb --- /dev/null +++ b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.kt @@ -0,0 +1,40 @@ +class Solution { + fun maxSumRangeQuery(nums: IntArray, requests: Array): Int { + val events = mutableListOf>() + val mod = 1000000007 + + for (req in requests) { + events.add(Pair(req[0], 1)) + events.add(Pair(req[1]+1, -1)) + } + + events.sortBy { it.first } + + var cnt = 0 + var prev = -1 + val weight = mutableMapOf() + + for ((pos, delta) in events) { + if (prev != -1 && cnt != 0) { + weight[cnt] = weight.getOrDefault(cnt, 0L) + (pos - prev) + } + prev = pos + cnt += delta + } + + val sorted = weight.toList().sortedByDescending { it.first } + + nums.sortDescending() + var ans = 0L + var idx = 0 + + for ((wg, num) in sorted) { + repeat(num.toInt()) { + ans = (ans + nums[idx].toLong() * wg) % mod + idx++ + } + } + + return ans.toInt() + } +} diff --git a/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.py b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.py new file mode 100644 index 00000000..54e6d154 --- /dev/null +++ b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.py @@ -0,0 +1,41 @@ +from typing import List + + +class Solution: + def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int: + events: list[tuple[int, int]] = [] + mod: int = int(1e9 + 7) + + for i in range(0, len(requests)): + start: int = requests[i][0] + end: int = requests[i][1] + + events.append((start, 1)) + events.append((end + 1, -1)) + + events.sort() + + cnt: int = 0 + prev: int = -1 + + weight: dict[int, int] = dict() + for i in range(0, len(events)): + if prev != -1 and cnt != 0: + weight[cnt] = weight.get(cnt, 0) + events[i][0] - prev + + prev = events[i][0] + cnt += events[i][1] + + weight_list = sorted(weight.items(), key=lambda x: x[0], reverse=True) + + i: int = 0 + nums.sort(reverse=True) + ans: int = 0 + + for wg, num in weight_list: + while num != 0: + ans = (ans + (nums[i] * wg) % mod) % mod + num -= 1 + i += 1 + + return ans diff --git a/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.py2 b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.py2 new file mode 100644 index 00000000..c47cd957 --- /dev/null +++ b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.py2 @@ -0,0 +1,38 @@ +class Solution(object): + def maxSumRangeQuery(self, nums, requests): + """ + :type nums: List[int] + :type requests: List[List[int]] + :rtype: int + """ + events = [] + mod = 10**9 + 7 + + for start, end in requests: + events.append((start, 1)) + events.append((end+1, -1)) + + events.sort() + + cnt = 0 + prev = -1 + weight = {} + + for pos, delta in events: + if prev != -1 and cnt != 0: + weight[cnt] = weight.get(cnt, 0) + pos - prev + prev = pos + cnt += delta + + weight_list = sorted(weight.items(), key=lambda x: x[0], reverse=True) + + nums.sort(reverse=True) + ans = 0 + i = 0 + + for wg, num in weight_list: + for _ in range(num): + ans = (ans + nums[i] * wg) % mod + i += 1 + + return ans diff --git a/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.rb b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.rb new file mode 100644 index 00000000..085c6242 --- /dev/null +++ b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.rb @@ -0,0 +1,41 @@ +# @param {Integer[]} nums +# @param {Integer[][]} requests +# @return {Integer} +def max_sum_range_query(nums, requests) + events = [] + mod = 10**9 + 7 + + requests.each do |start, end_| + events << [start, 1] + events << [end_+1, -1] + end + + events.sort! + + cnt = 0 + prev = -1 + weight = Hash.new(0) + + events.each do |pos, delta| + if prev != -1 && cnt != 0 + weight[cnt] += pos - prev + end + prev = pos + cnt += delta + end + + weight_list = weight.sort_by { |k, v| -k } + + nums.sort! { |a, b| b <=> a } + ans = 0 + i = 0 + + weight_list.each do |wg, num| + num.times do + ans = (ans + nums[i] * wg) % mod + i += 1 + end + end + + ans +end diff --git a/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.rs b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.rs new file mode 100644 index 00000000..9b5e8ee7 --- /dev/null +++ b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.rs @@ -0,0 +1,43 @@ +impl Solution { + pub fn max_sum_range_query(nums: Vec, requests: Vec>) -> i32 { + let mut events: Vec<(i32, i32)> = Vec::new(); + let mod_val = 1_000_000_007i64; + + for req in &requests { + events.push((req[0], 1)); + events.push((req[1]+1, -1)); + } + + events.sort(); + + let mut cnt = 0i64; + let mut prev = -1i64; + let mut weight: std::collections::HashMap = std::collections::HashMap::new(); + + for &(pos, delta) in &events { + if prev != -1 && cnt != 0 { + *weight.entry(cnt).or_insert(0) += (pos as i64 - prev); + } + prev = pos as i64; + cnt += delta as i64; + } + + let mut sorted: Vec<(i64, i64)> = weight.into_iter().collect(); + sorted.sort_by(|a, b| b.0.cmp(&a.0)); + + let mut nums_sorted = nums; + nums_sorted.sort_by(|a, b| b.cmp(a)); + + let mut ans = 0i64; + let mut idx = 0usize; + + for (wg, num) in sorted { + for _ in 0..num { + ans = (ans + nums_sorted[idx] as i64 * wg) % mod_val; + idx += 1; + } + } + + ans as i32 + } +} diff --git a/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.swift b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.swift new file mode 100644 index 00000000..b9db353b --- /dev/null +++ b/tests/1501-2000/1589. maximum-sum-obtained-of-any-permutation/sol.swift @@ -0,0 +1,40 @@ +class Solution { + func maxSumRangeQuery(_ nums: [Int], _ requests: [[Int]]) -> Int { + var events: [(Int, Int)] = [] + let mod = 1_000_000_007 + + for req in requests { + events.append((req[0], 1)) + events.append((req[1]+1, -1)) + } + + events.sort { $0.0 < $1.0 } + + var cnt = 0 + var prev = -1 + var weight: [Int: Int] = [:] + + for (pos, delta) in events { + if prev != -1 && cnt != 0 { + weight[cnt, default: 0] += pos - prev + } + prev = pos + cnt += delta + } + + let sorted = weight.sorted { $0.key > $1.key } + + var numsSorted = nums.sorted(by: >) + var ans = 0 + var idx = 0 + + for (wg, num) in sorted { + for _ in 0.. a[0] - b[0]); + + let cnt = 0; + let prev = -1; + let weight = new Map(); + + for (const [pos, delta] of events) { + if (prev !== -1 && cnt !== 0) { + weight.set(cnt, (weight.get(cnt) || 0) + (pos - prev)); + } + prev = pos; + cnt += delta; + } + + const sorted = Array.from(weight.entries()).sort((a, b) => b[0] - a[0]); + + nums.sort((a, b) => b - a); + let ans = 0; + let idx = 0; + + for (const [wg, num] of sorted) { + for (let i = 0; i < num; i++) { + ans = (ans + nums[idx] * wg) % mod; + idx++; + } + } + + return ans; +} diff --git a/tests/1501-2000/1590. make-sum-divisible-by-p/manifest.yaml b/tests/1501-2000/1590. make-sum-divisible-by-p/manifest.yaml new file mode 100644 index 00000000..16abd410 --- /dev/null +++ b/tests/1501-2000/1590. make-sum-divisible-by-p/manifest.yaml @@ -0,0 +1,287 @@ +entry: + id: 1590 + title: "make-sum-divisible-by-p" + params: + nums: + type: array + items: + type: int + p: + type: int + call: + cpp: "Solution().minSubarray({nums}, {p})" + rust: "Solution::min_subarray({nums}, {p})" + python3: "Solution().minSubarray({nums}, {p})" + python2: "Solution().minSubarray({nums}, {p})" + ruby: "min_subarray({nums}, {p})" + java: "new Solution().minSubarray({nums}, {p})" + csharp: "new Solution().MinSubarray({nums}, {p})" + kotlin: "Solution().minSubarray({nums}, {p})" + go: "minSubarray({nums}, {p})" + dart: "Solution().minSubarray({nums}, {p})" + swift: "Solution().minSubarray({nums}, {p})" + typescript: "minSubarray({nums}, {p})" +judge: + type: "exact" +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().minSubarray(nums, p, {result})" + checker: | + class Checker: + def minSubarray(self, nums, p, result): + total = sum(nums) + target = total % p + if target == 0: + expected = 0 + else: + last = {0: -1} + prefix = 0 + best = len(nums) + for i, value in enumerate(nums): + prefix = (prefix + value) % p + need = (prefix - target) % p + if need in last: + best = min(best, i - last[need]) + last[prefix] = i + expected = -1 if best == len(nums) else best + return result == expected +seed: 1590 +tests: + - name: example-one + in: + nums: [3, 1, 4, 2] + p: 6 + out: 1 + - name: example-two + in: + nums: [6, 3, 5, 2] + p: 9 + out: 2 + - name: already-divisible + in: + nums: [1, 2, 3] + p: 3 + out: 0 + - name: single-element-impossible + in: + nums: [1] + p: 2 + out: -1 + - name: single-element-divisible + in: + nums: [7] + p: 7 + out: 0 + - name: remove-one-at-start + in: + nums: [5, 2, 4] + p: 7 + out: 1 + - name: remove-one-at-end + in: + nums: [2, 4, 5] + p: 7 + out: 1 + - name: remove-middle-one + in: + nums: [8, 3, 2, 6] + p: 5 + out: -1 + - name: remove-two-middle + in: + nums: [6, 3, 5, 2] + p: 9 + out: 2 + - name: no-valid-proper-subarray + in: + nums: [1, 1] + p: 3 + out: -1 + - name: p-one + in: + nums: [9, 8, 7] + p: 1 + out: 0 + - name: repeated-residues + in: + nums: [4, 4, 4, 4] + p: 6 + out: 1 + - name: large-values-small-p + in: + nums: [1000000000, 1000000000, 1000000000] + p: 7 + out: -1 + - name: large-p + in: + nums: [1, 2, 3, 4] + p: 1000000000 + out: -1 + - name: duplicate-prefix-choice + in: + nums: [2, 1, 2, 1, 2] + p: 4 + out: 0 + - name: alternating-values + in: + nums: [1, 9, 1, 9, 1, 9] + p: 10 + out: 0 + - name: all-ones + in: + nums: [1, 1, 1, 1, 1, 1, 1] + p: 5 + out: 2 + - name: remainder-needs-whole-invalid + in: + nums: [2, 2, 2] + p: 4 + out: 1 + - name: length-two + in: + nums: [3, 5] + p: 4 + out: 0 + - name: length-three + in: + nums: [2, 6, 4] + p: 5 + out: 1 + - name: zero-target-with-large-p + in: + nums: [1000000000, 1000000000] + p: 1000000000 + out: 0 + - name: powers-and-prime + in: + nums: [2, 4, 8, 16, 32] + p: 13 + out: -1 + - name: best-longer-than-one + in: + nums: [1, 1, 1, 1, 1, 1] + p: 4 + out: 2 + - name: best-shorter-than-prefix + in: + nums: [10, 1, 1, 1, 1] + p: 6 + out: 2 + - name: prime-modulus + in: + nums: [11, 7, 5, 3, 2] + p: 11 + out: 4 + - name: many-equal + in: + nums: [6, 6, 6, 6, 6, 6, 6, 6] + p: 10 + out: 3 + - name: mixed-residues + in: + nums: [5, 12, 7, 3, 8, 11] + p: 9 + out: 2 + - name: no-single-but-pair + in: + nums: [1, 2, 4, 8] + p: 7 + out: 1 + - name: minimum-element-values + in: + nums: [1, 1, 2, 1, 1] + p: 6 + out: 0 + - name: near-int-limit-values + in: + nums: [999999999, 999999998, 999999997] + p: 1000000000 + out: -1 + - name: long-static-pattern + in: + nums: [17, 4, 23, 9, 12, 8, 31, 6, 5, 19] + p: 14 + out: 1 + - name: generator-small + in: + nums: + gen: "array" + len: 25 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: "int" + p: + gen: "int" + min: 2 + max: 1000 + - name: generator-medium + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + p: + gen: "int" + min: 2 + max: 1000000000 + - name: generator-large-one + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + p: + gen: "int" + min: 2 + max: 1000000000 + - name: generator-large-two + in: + nums: + gen: "array" + len: 99999 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + p: + gen: "int" + min: 2 + max: 1000000000 + - name: generator-large-three + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + p: + gen: "int" + min: 2 + max: 1000000000 diff --git a/tests/1501-2000/1590. make-sum-divisible-by-p/sol.cpp b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.cpp new file mode 100644 index 00000000..e80507d9 --- /dev/null +++ b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int minSubarray(vector& nums, int p) { + long long total = 0; + for (int num : nums) total += num; + int target = total % p; + if (target == 0) return 0; + + unordered_map mp; + mp[0] = -1; + int prefix = 0; + int res = nums.size(); + + for (int i = 0; i < nums.size(); i++) { + prefix = (prefix + nums[i]) % p; + int need = (prefix - target + p) % p; + + if (mp.count(need)) { + res = min(res, i - mp[need]); + } + + mp[prefix] = i; + } + + return res == nums.size() ? -1 : res; + } +}; diff --git a/tests/1501-2000/1590. make-sum-divisible-by-p/sol.cs b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.cs new file mode 100644 index 00000000..fdd3d90f --- /dev/null +++ b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public int MinSubarray(int[] nums, int p) { + long total = 0; + foreach (int num in nums) total += num; + int target = (int)(total % p); + if (target == 0) return 0; + + Dictionary mp = new Dictionary { [0] = -1 }; + int prefix = 0; + int res = nums.Length; + + for (int i = 0; i < nums.Length; i++) { + prefix = (prefix + nums[i]) % p; + int need = (prefix - target + p) % p; + + if (mp.ContainsKey(need)) { + res = Math.Min(res, i - mp[need]); + } + + mp[prefix] = i; + } + + return res == nums.Length ? -1 : res; + } +} diff --git a/tests/1501-2000/1590. make-sum-divisible-by-p/sol.dart b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.dart new file mode 100644 index 00000000..15b5a0f5 --- /dev/null +++ b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.dart @@ -0,0 +1,24 @@ +class Solution { + int minSubarray(List nums, int p) { + int total = nums.fold(0, (a, b) => a + b); + int target = total % p; + if (target == 0) return 0; + + Map mp = {0: -1}; + int prefix = 0; + int res = nums.length; + + for (int i = 0; i < nums.length; i++) { + prefix = (prefix + nums[i]) % p; + int need = (prefix - target + p) % p; + + if (mp.containsKey(need)) { + res = res < (i - mp[need]!) ? res : (i - mp[need]!); + } + + mp[prefix] = i; + } + + return res == nums.length ? -1 : res; + } +} diff --git a/tests/1501-2000/1590. make-sum-divisible-by-p/sol.go b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.go new file mode 100644 index 00000000..30cc32a6 --- /dev/null +++ b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.go @@ -0,0 +1,32 @@ +func minSubarray(nums []int, p int) int { + total := 0 + for _, num := range nums { + total += num + } + target := total % p + if target == 0 { + return 0 + } + + mp := map[int]int{0: -1} + prefix := 0 + res := len(nums) + + for i, x := range nums { + prefix = (prefix + x) % p + need := (prefix - target + p) % p + + if idx, ok := mp[need]; ok { + if i - idx < res { + res = i - idx + } + } + + mp[prefix] = i + } + + if res == len(nums) { + return -1 + } + return res +} diff --git a/tests/1501-2000/1590. make-sum-divisible-by-p/sol.java b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.java new file mode 100644 index 00000000..ae6661ad --- /dev/null +++ b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.java @@ -0,0 +1,26 @@ +class Solution { + public int minSubarray(int[] nums, int p) { + long total = 0; + for (int num : nums) total += num; + int target = (int)(total % p); + if (target == 0) return 0; + + Map mp = new HashMap<>(); + mp.put(0, -1); + int prefix = 0; + int res = nums.length; + + for (int i = 0; i < nums.length; i++) { + prefix = (prefix + nums[i]) % p; + int need = (prefix - target + p) % p; + + if (mp.containsKey(need)) { + res = Math.min(res, i - mp.get(need)); + } + + mp.put(prefix, i); + } + + return res == nums.length ? -1 : res; + } +} diff --git a/tests/1501-2000/1590. make-sum-divisible-by-p/sol.kt b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.kt new file mode 100644 index 00000000..a27602b5 --- /dev/null +++ b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.kt @@ -0,0 +1,26 @@ +class Solution { + fun minSubarray(nums: IntArray, p: Int): Int { + val total = nums.fold(0L) { sum, value -> sum + value.toLong() } + val modulus = p.toLong() + val target = total % modulus + if (target == 0L) return 0 + + val mp = mutableMapOf() + mp[0] = -1 + var prefix = 0L + var res = nums.size + + for (i in nums.indices) { + prefix = (prefix + nums[i].toLong()) % modulus + val need = (prefix - target + modulus) % modulus + + if (mp.containsKey(need)) { + res = minOf(res, i - mp[need]!!) + } + + mp[prefix] = i + } + + return if (res == nums.size) -1 else res + } +} diff --git a/tests/1501-2000/1590. make-sum-divisible-by-p/sol.py b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.py new file mode 100644 index 00000000..efcae387 --- /dev/null +++ b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.py @@ -0,0 +1,21 @@ +class Solution: + def minSubarray(self, nums: List[int], p: int) -> int: + total = sum(nums) + target = total % p + if target == 0: + return 0 + + mp = {0: -1} + prefix = 0 + res = len(nums) + + for i, x in enumerate(nums): + prefix = (prefix + x) % p + need = (prefix - target + p) % p + + if need in mp: + res = min(res, i - mp[need]) + + mp[prefix] = i + + return -1 if res == len(nums) else res diff --git a/tests/1501-2000/1590. make-sum-divisible-by-p/sol.py2 b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.py2 new file mode 100644 index 00000000..28b10455 --- /dev/null +++ b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.py2 @@ -0,0 +1,26 @@ +class Solution(object): + def minSubarray(self, nums, p): + """ + :type nums: List[int] + :type p: int + :rtype: int + """ + total = sum(nums) + target = total % p + if target == 0: + return 0 + + mp = {0: -1} + prefix = 0 + res = len(nums) + + for i, x in enumerate(nums): + prefix = (prefix + x) % p + need = (prefix - target + p) % p + + if need in mp: + res = min(res, i - mp[need]) + + mp[prefix] = i + + return -1 if res == len(nums) else res diff --git a/tests/1501-2000/1590. make-sum-divisible-by-p/sol.rb b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.rb new file mode 100644 index 00000000..3b281a7a --- /dev/null +++ b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.rb @@ -0,0 +1,25 @@ +# @param {Integer[]} nums +# @param {Integer} p +# @return {Integer} +def min_subarray(nums, p) + total = nums.sum + target = total % p + return 0 if target == 0 + + mp = {0 => -1} + prefix = 0 + res = nums.length + + nums.each_with_index do |x, i| + prefix = (prefix + x) % p + need = (prefix - target + p) % p + + if mp.key?(need) + res = [res, i - mp[need]].min + end + + mp[prefix] = i + end + + res == nums.length ? -1 : res +end diff --git a/tests/1501-2000/1590. make-sum-divisible-by-p/sol.rs b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.rs new file mode 100644 index 00000000..6cb9031c --- /dev/null +++ b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.rs @@ -0,0 +1,31 @@ +impl Solution { + pub fn min_subarray(nums: Vec, p: i32) -> i32 { + let total: i64 = nums.iter().map(|&x| x as i64).sum(); + let target = (total % p as i64) as i32; + if target == 0 { + return 0; + } + + let mut mp = std::collections::HashMap::new(); + mp.insert(0, -1); + let mut prefix = 0; + let mut res = nums.len() as i32; + + for (i, &x) in nums.iter().enumerate() { + prefix = (prefix + x) % p; + let need = (prefix - target + p) % p; + + if let Some(&idx) = mp.get(&need) { + res = res.min(i as i32 - idx); + } + + mp.insert(prefix, i as i32); + } + + if res == nums.len() as i32 { + -1 + } else { + res + } + } +} diff --git a/tests/1501-2000/1590. make-sum-divisible-by-p/sol.swift b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.swift new file mode 100644 index 00000000..a99689fc --- /dev/null +++ b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.swift @@ -0,0 +1,26 @@ +class Solution { + func minSubarray(_ nums: [Int], _ p: Int) -> Int { + let total = nums.reduce(0, +) + let target = total % p + if target == 0 { + return 0 + } + + var mp: [Int: Int] = [0: -1] + var prefix = 0 + var res = nums.count + + for (i, x) in nums.enumerated() { + prefix = (prefix + x) % p + let need = (prefix - target + p) % p + + if let idx = mp[need] { + res = min(res, i - idx) + } + + mp[prefix] = i + } + + return res == nums.count ? -1 : res + } +} diff --git a/tests/1501-2000/1590. make-sum-divisible-by-p/sol.ts b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.ts new file mode 100644 index 00000000..3d201107 --- /dev/null +++ b/tests/1501-2000/1590. make-sum-divisible-by-p/sol.ts @@ -0,0 +1,22 @@ +function minSubarray(nums: number[], p: number): number { + const total = nums.reduce((a, b) => a + b, 0); + const target = total % p; + if (target === 0) return 0; + + const mp: Map = new Map([[0, -1]]); + let prefix = 0; + let res = nums.length; + + for (let i = 0; i < nums.length; i++) { + prefix = (prefix + nums[i]) % p; + const need = (prefix - target + p) % p; + + if (mp.has(need)) { + res = Math.min(res, i - mp.get(need)!); + } + + mp.set(prefix, i); + } + + return res === nums.length ? -1 : res; +} diff --git a/tests/1501-2000/1591. strange-printer-ii/manifest.yaml b/tests/1501-2000/1591. strange-printer-ii/manifest.yaml new file mode 100644 index 00000000..a01b290a --- /dev/null +++ b/tests/1501-2000/1591. strange-printer-ii/manifest.yaml @@ -0,0 +1,435 @@ +entry: + id: 1591 + title: "strange-printer-ii" + params: + targetGrid: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().isPrintable({targetGrid})" + rust: "Solution::is_printable({targetGrid})" + python3: "Solution().isPrintable({targetGrid})" + python2: "Solution().isPrintable({targetGrid})" + ruby: "is_printable({targetGrid})" + java: "new Solution().isPrintable({targetGrid})" + csharp: "new Solution().IsPrintable({targetGrid})" + kotlin: "Solution().isPrintable({targetGrid})" + go: "isPrintable({targetGrid})" + dart: "Solution().isPrintable({targetGrid})" + swift: "Solution().isPrintable({targetGrid})" + typescript: "isPrintable({targetGrid})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().isPrintable(targetGrid, {result})" + checker: | + class Checker: + def isPrintable(self, targetGrid, result): + if not isinstance(result, bool): + return False + m, n = len(targetGrid), len(targetGrid[0]) + boxes = {} + for r in range(m): + for c in range(n): + color = targetGrid[r][c] + if color not in boxes: + boxes[color] = [r, r, c, c] + else: + box = boxes[color] + box[0] = min(box[0], r) + box[1] = max(box[1], r) + box[2] = min(box[2], c) + box[3] = max(box[3], c) + remaining = set(boxes) + while remaining: + removable = set() + for color in remaining: + r0, r1, c0, c1 = boxes[color] + ok = True + for r in range(r0, r1 + 1): + for c in range(c0, c1 + 1): + if targetGrid[r][c] not in (0, color): + ok = False + if ok: + removable.add(color) + if not removable: + expected = False + return result == expected + for color in removable: + r0, r1, c0, c1 = boxes[color] + for r in range(r0, r1 + 1): + for c in range(c0, c1 + 1): + targetGrid[r][c] = 0 + remaining -= removable + return result is True + +seed: 1591 + +tests: + - name: example-one + in: + targetGrid: + - [1, 1, 1, 1] + - [1, 2, 2, 1] + - [1, 2, 2, 1] + - [1, 1, 1, 1] + out: true + - name: example-two + in: + targetGrid: + - [1, 1, 1, 1] + - [1, 1, 3, 3] + - [1, 1, 3, 4] + - [5, 5, 1, 4] + out: true + - name: example-three + in: + targetGrid: + - [1, 2, 1] + - [2, 1, 2] + - [1, 2, 1] + out: false + - name: one-cell + in: + targetGrid: + - [7] + out: true + - name: two-by-two-checker + in: + targetGrid: + - [1, 2] + - [2, 1] + out: false + - name: two-by-three-checker + in: + targetGrid: + - [1, 2, 1] + - [2, 1, 2] + out: false + - name: nested-center + in: + targetGrid: + - [1, 1, 1, 1, 1] + - [1, 2, 2, 2, 1] + - [1, 2, 3, 2, 1] + - [1, 2, 2, 2, 1] + - [1, 1, 1, 1, 1] + out: true + - name: horizontal-stripes + in: + targetGrid: + - [1, 1, 1, 1] + - [2, 2, 2, 2] + - [3, 3, 3, 3] + - [4, 4, 4, 4] + out: true + - name: vertical-stripes + in: + targetGrid: + - [1, 2, 3, 4] + - [1, 2, 3, 4] + - [1, 2, 3, 4] + - [1, 2, 3, 4] + out: true + - name: diagonal-four + in: + targetGrid: + - [1, 2, 3, 4] + - [2, 3, 4, 1] + - [3, 4, 1, 2] + - [4, 1, 2, 3] + out: false + - name: three-color-cycle + in: + targetGrid: + - [1, 2, 3] + - [3, 1, 2] + - [2, 3, 1] + out: false + - name: removable-corner + in: + targetGrid: + - [1, 1, 2] + - [1, 1, 2] + - [3, 3, 2] + out: true + - name: overlapping-valid + in: + targetGrid: + - [1, 1, 2, 2] + - [1, 3, 3, 2] + - [1, 3, 3, 2] + - [1, 1, 2, 2] + out: true + - name: enclosing-invalid + in: + targetGrid: + - [1, 2, 1] + - [2, 1, 2] + - [1, 2, 1] + out: false + - name: isolated-colors + in: + targetGrid: + - [1, 1, 1, 1, 1] + - [1, 2, 3, 4, 1] + - [1, 5, 6, 7, 1] + - [1, 1, 1, 1, 1] + out: true + - name: repeated-cross + in: + targetGrid: + - [1, 1, 2, 1, 1] + - [1, 1, 2, 1, 1] + - [3, 3, 2, 3, 3] + - [1, 1, 2, 1, 1] + - [1, 1, 2, 1, 1] + out: true + - name: valid-cross-order + in: + targetGrid: + - [1, 1, 2, 1, 1] + - [1, 1, 2, 1, 1] + - [1, 1, 2, 1, 1] + - [1, 1, 2, 1, 1] + - [1, 1, 2, 1, 1] + out: true + - name: four-corners + in: + targetGrid: + - [1, 1, 1, 2] + - [1, 1, 1, 2] + - [3, 3, 3, 2] + - [3, 3, 3, 2] + out: true + - name: four-corners-cycle + in: + targetGrid: + - [1, 2, 2, 3] + - [1, 2, 2, 3] + - [4, 4, 4, 3] + - [4, 4, 4, 1] + out: true + - name: two-by-four-valid + in: + targetGrid: + - [1, 1, 2, 2] + - [1, 1, 2, 2] + out: true + - name: two-by-four-invalid + in: + targetGrid: + - [1, 2, 1, 2] + - [2, 1, 2, 1] + out: false + - name: three-color-border + in: + targetGrid: + - [1, 1, 1, 1, 1] + - [1, 2, 2, 2, 1] + - [3, 3, 3, 3, 3] + - [1, 2, 2, 2, 1] + - [1, 1, 1, 1, 1] + out: true + - name: valid-three-layer + in: + targetGrid: + - [1, 1, 1, 1, 1] + - [1, 2, 2, 2, 1] + - [1, 2, 3, 2, 1] + - [1, 2, 2, 2, 1] + - [1, 1, 1, 1, 1] + out: true + - name: sparse-six-colors + in: + targetGrid: + - [1, 1, 2, 2, 3, 3] + - [1, 1, 2, 2, 3, 3] + - [4, 4, 5, 5, 6, 6] + - [4, 4, 5, 5, 6, 6] + out: true + - name: sparse-cycle-six + in: + targetGrid: + - [1, 2, 3, 4, 5, 6] + - [6, 1, 2, 3, 4, 5] + - [5, 6, 1, 2, 3, 4] + - [4, 5, 6, 1, 2, 3] + out: false + - name: large-checker + in: + targetGrid: + - [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] + - [2, 1, 2, 1, 2, 1, 2, 1, 2, 1] + - [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] + - [2, 1, 2, 1, 2, 1, 2, 1, 2, 1] + - [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] + - [2, 1, 2, 1, 2, 1, 2, 1, 2, 1] + - [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] + - [2, 1, 2, 1, 2, 1, 2, 1, 2, 1] + - [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] + - [2, 1, 2, 1, 2, 1, 2, 1, 2, 1] + out: false + - name: three-by-three-ring-cycle + in: + targetGrid: + - [1, 2, 1] + - [3, 4, 3] + - [1, 2, 1] + out: true + - name: four-by-four-blocks + in: + targetGrid: + - [1, 1, 2, 2] + - [1, 1, 2, 2] + - [3, 3, 4, 4] + - [3, 3, 4, 4] + out: true + - name: four-by-four-cycle + in: + targetGrid: + - [1, 2, 3, 4] + - [4, 1, 2, 3] + - [3, 4, 1, 2] + - [2, 3, 4, 1] + out: false + - name: ten-by-ten-diagonal + in: + targetGrid: + - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - [2, 3, 4, 5, 6, 7, 8, 9, 10, 1] + - [3, 4, 5, 6, 7, 8, 9, 10, 1, 2] + - [4, 5, 6, 7, 8, 9, 10, 1, 2, 3] + - [5, 6, 7, 8, 9, 10, 1, 2, 3, 4] + - [6, 7, 8, 9, 10, 1, 2, 3, 4, 5] + - [7, 8, 9, 10, 1, 2, 3, 4, 5, 6] + - [8, 9, 10, 1, 2, 3, 4, 5, 6, 7] + - [9, 10, 1, 2, 3, 4, 5, 6, 7, 8] + - [10, 1, 2, 3, 4, 5, 6, 7, 8, 9] + out: false + - name: two-by-two-diagonal + in: + targetGrid: + - [11, 12] + - [12, 11] + out: false + - name: nested-four-colors + in: + targetGrid: + - [1, 1, 1, 1, 1, 1, 1] + - [1, 2, 2, 2, 2, 2, 1] + - [1, 2, 3, 3, 3, 2, 1] + - [1, 2, 3, 4, 3, 2, 1] + - [1, 2, 3, 3, 3, 2, 1] + - [1, 2, 2, 2, 2, 2, 1] + - [1, 1, 1, 1, 1, 1, 1] + out: true + - name: nested-four-colors-cycle + in: + targetGrid: + - [1, 2, 1, 2, 1] + - [2, 3, 2, 3, 2] + - [1, 2, 4, 2, 1] + - [2, 3, 2, 3, 2] + - [1, 2, 1, 2, 1] + out: false + - name: six-by-six-blocks + in: + targetGrid: + - [1, 1, 1, 2, 2, 2] + - [1, 1, 1, 2, 2, 2] + - [1, 1, 1, 2, 2, 2] + - [3, 3, 3, 4, 4, 4] + - [3, 3, 3, 4, 4, 4] + - [3, 3, 3, 4, 4, 4] + out: true + - name: six-by-six-cycle + in: + targetGrid: + - [1, 2, 3, 4, 5, 6] + - [2, 3, 4, 5, 6, 1] + - [3, 4, 5, 6, 1, 2] + - [4, 5, 6, 1, 2, 3] + - [5, 6, 1, 2, 3, 4] + - [6, 1, 2, 3, 4, 5] + out: false + - name: generated-small + in: + targetGrid: + gen: "array" + len: 4 + of: + gen: "array" + len: 4 + of: + gen: "int" + min: 1 + max: 4 + elemType: "int" + seed: 159101 + - name: generated-medium + in: + targetGrid: + gen: "array" + len: 12 + of: + gen: "array" + len: 12 + of: + gen: "int" + min: 1 + max: 12 + elemType: "int" + seed: 159102 + - name: generated-wide + in: + targetGrid: + gen: "array" + len: 1 + of: + gen: "array" + len: 60 + of: + gen: "int" + min: 1 + max: 60 + elemType: "int" + seed: 159103 + - name: generated-tall + in: + targetGrid: + gen: "array" + len: 60 + of: + gen: "array" + len: 1 + of: + gen: "int" + min: 1 + max: 60 + elemType: "int" + seed: 159104 + - name: generated-maximum + in: + targetGrid: + gen: "array" + len: 60 + of: + gen: "array" + len: 60 + of: + gen: "int" + min: 1 + max: 60 + elemType: "int" + seed: 159105 diff --git a/tests/1501-2000/1591. strange-printer-ii/sol.cpp b/tests/1501-2000/1591. strange-printer-ii/sol.cpp new file mode 100644 index 00000000..3d2000a1 --- /dev/null +++ b/tests/1501-2000/1591. strange-printer-ii/sol.cpp @@ -0,0 +1,53 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + bool isPrintable(vector>& targetGrid) { + int m = targetGrid.size(), n = targetGrid[0].size(); + unordered_map>> colors; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + colors[targetGrid[i][j]].push_back({i, j}); + } + } + + auto canRemove = [&](int color) -> bool { + auto& pos = colors[color]; + int mnR = pos[0].first, mxR = pos[0].first; + int mnC = pos[0].second, mxC = pos[0].second; + for (auto& p : pos) { + mnR = min(mnR, p.first); + mxR = max(mxR, p.first); + mnC = min(mnC, p.second); + mxC = max(mxC, p.second); + } + for (int i = mnR; i <= mxR; i++) { + for (int j = mnC; j <= mxC; j++) { + if (targetGrid[i][j] != color && targetGrid[i][j] > 0) return false; + } + } + for (int i = mnR; i <= mxR; i++) { + for (int j = mnC; j <= mxC; j++) { + targetGrid[i][j] = 0; + } + } + return true; + }; + + unordered_set colorSet; + for (auto& kv : colors) colorSet.insert(kv.first); + while (!colorSet.empty()) { + unordered_set removable; + for (int c : colorSet) { + if (canRemove(c)) removable.insert(c); + } + if (removable.empty()) return false; + for (int c : removable) colorSet.erase(c); + } + return true; + } +}; diff --git a/tests/1501-2000/1591. strange-printer-ii/sol.cs b/tests/1501-2000/1591. strange-printer-ii/sol.cs new file mode 100644 index 00000000..60a90a2a --- /dev/null +++ b/tests/1501-2000/1591. strange-printer-ii/sol.cs @@ -0,0 +1,47 @@ +public class Solution { + public bool IsPrintable(int[][] targetGrid) { + int m = targetGrid.Length; + int n = targetGrid[0].Length; + var colors = new Dictionary>(); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (!colors.ContainsKey(targetGrid[i][j])) colors[targetGrid[i][j]] = new List<(int, int)>(); + colors[targetGrid[i][j]].Add((i, j)); + } + } + + bool CanRemove(int color) { + var pos = colors[color]; + int mnR = pos[0].Item1, mxR = pos[0].Item1; + int mnC = pos[0].Item2, mxC = pos[0].Item2; + foreach (var (r, c) in pos) { + mnR = Math.Min(mnR, r); + mxR = Math.Max(mxR, r); + mnC = Math.Min(mnC, c); + mxC = Math.Max(mxC, c); + } + for (int i = mnR; i <= mxR; i++) { + for (int j = mnC; j <= mxC; j++) { + if (targetGrid[i][j] != color && targetGrid[i][j] > 0) return false; + } + } + for (int i = mnR; i <= mxR; i++) { + for (int j = mnC; j <= mxC; j++) { + targetGrid[i][j] = 0; + } + } + return true; + } + + var colorSet = new HashSet(colors.Keys); + while (colorSet.Count > 0) { + var removable = new HashSet(); + foreach (var c in colorSet) { + if (CanRemove(c)) removable.Add(c); + } + if (removable.Count == 0) return false; + colorSet.ExceptWith(removable); + } + return true; + } +} diff --git a/tests/1501-2000/1591. strange-printer-ii/sol.dart b/tests/1501-2000/1591. strange-printer-ii/sol.dart new file mode 100644 index 00000000..a837fe30 --- /dev/null +++ b/tests/1501-2000/1591. strange-printer-ii/sol.dart @@ -0,0 +1,43 @@ +class Solution { + bool isPrintable(List> targetGrid) { + int m = targetGrid.length; + int n = targetGrid[0].length; + Map>> colors = {}; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + colors.putIfAbsent(targetGrid[i][j], () => []).add([i, j]); + } + } + + bool canRemove(int color) { + var pos = colors[color]!; + int mnR = pos[0][0], mxR = pos[0][0]; + int mnC = pos[0][1], mxC = pos[0][1]; + for (var p in pos) { + if (p[0] < mnR) mnR = p[0]; + if (p[0] > mxR) mxR = p[0]; + if (p[1] < mnC) mnC = p[1]; + if (p[1] > mxC) mxC = p[1]; + } + for (int i = mnR; i <= mxR; i++) { + for (int j = mnC; j <= mxC; j++) { + if (targetGrid[i][j] != color && targetGrid[i][j] > 0) return false; + } + } + for (int i = mnR; i <= mxR; i++) { + for (int j = mnC; j <= mxC; j++) { + targetGrid[i][j] = 0; + } + } + return true; + } + + Set colorSet = colors.keys.toSet(); + while (colorSet.isNotEmpty) { + Set removable = colorSet.where((c) => canRemove(c)).toSet(); + if (removable.isEmpty) return false; + colorSet.removeAll(removable); + } + return true; + } +} diff --git a/tests/1501-2000/1591. strange-printer-ii/sol.go b/tests/1501-2000/1591. strange-printer-ii/sol.go new file mode 100644 index 00000000..cdb2a3fe --- /dev/null +++ b/tests/1501-2000/1591. strange-printer-ii/sol.go @@ -0,0 +1,53 @@ +func isPrintable(targetGrid [][]int) bool { + m, n := len(targetGrid), len(targetGrid[0]) + colors := make(map[int][][2]int) + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + colors[targetGrid[i][j]] = append(colors[targetGrid[i][j]], [2]int{i, j}) + } + } + + canRemove := func(color int) bool { + pos := colors[color] + mnR, mxR := pos[0][0], pos[0][0] + mnC, mxC := pos[0][1], pos[0][1] + for _, p := range pos { + if p[0] < mnR { mnR = p[0] } + if p[0] > mxR { mxR = p[0] } + if p[1] < mnC { mnC = p[1] } + if p[1] > mxC { mxC = p[1] } + } + for i := mnR; i <= mxR; i++ { + for j := mnC; j <= mxC; j++ { + if targetGrid[i][j] != color && targetGrid[i][j] > 0 { + return false + } + } + } + for i := mnR; i <= mxR; i++ { + for j := mnC; j <= mxC; j++ { + targetGrid[i][j] = 0 + } + } + return true + } + + colorSet := make(map[int]bool) + for c := range colors { + colorSet[c] = true + } + + for len(colorSet) > 0 { + removable := make([]int, 0) + for c := range colorSet { + if canRemove(c) { + removable = append(removable, c) + } + } + if len(removable) == 0 { return false } + for _, c := range removable { + delete(colorSet, c) + } + } + return true +} diff --git a/tests/1501-2000/1591. strange-printer-ii/sol.java b/tests/1501-2000/1591. strange-printer-ii/sol.java new file mode 100644 index 00000000..4cb3ff64 --- /dev/null +++ b/tests/1501-2000/1591. strange-printer-ii/sol.java @@ -0,0 +1,49 @@ +import java.util.*; + +class Solution { + public boolean isPrintable(int[][] targetGrid) { + int m = targetGrid.length, n = targetGrid[0].length; + Map> colors = new HashMap<>(); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + colors.computeIfAbsent(targetGrid[i][j], k -> new ArrayList<>()).add(new int[]{i, j}); + } + } + + Set colorSet = new HashSet<>(colors.keySet()); + while (!colorSet.isEmpty()) { + Set removable = new HashSet<>(); + for (int color : colorSet) { + if (canRemove(targetGrid, colors.get(color))) { + removable.add(color); + } + } + if (removable.isEmpty()) return false; + colorSet.removeAll(removable); + } + return true; + } + + private boolean canRemove(int[][] grid, List positions) { + int mnR = Integer.MAX_VALUE, mxR = Integer.MIN_VALUE; + int mnC = Integer.MAX_VALUE, mxC = Integer.MIN_VALUE; + for (int[] p : positions) { + mnR = Math.min(mnR, p[0]); + mxR = Math.max(mxR, p[0]); + mnC = Math.min(mnC, p[1]); + mxC = Math.max(mxC, p[1]); + } + int color = grid[positions.get(0)[0]][positions.get(0)[1]]; + for (int i = mnR; i <= mxR; i++) { + for (int j = mnC; j <= mxC; j++) { + if (grid[i][j] != color && grid[i][j] > 0) return false; + } + } + for (int i = mnR; i <= mxR; i++) { + for (int j = mnC; j <= mxC; j++) { + grid[i][j] = 0; + } + } + return true; + } +} diff --git a/tests/1501-2000/1591. strange-printer-ii/sol.kt b/tests/1501-2000/1591. strange-printer-ii/sol.kt new file mode 100644 index 00000000..f6964b24 --- /dev/null +++ b/tests/1501-2000/1591. strange-printer-ii/sol.kt @@ -0,0 +1,39 @@ +class Solution { + fun isPrintable(targetGrid: Array): Boolean { + val m = targetGrid.size + val n = targetGrid[0].size + val colors = mutableMapOf>>() + for (i in 0 until m) { + for (j in 0 until n) { + colors.getOrPut(targetGrid[i][j]) { mutableListOf() }.add(i to j) + } + } + + fun canRemove(color: Int): Boolean { + val pos = colors[color]!! + var mnR = pos.minOf { it.first } + var mxR = pos.maxOf { it.first } + var mnC = pos.minOf { it.second } + var mxC = pos.maxOf { it.second } + for (i in mnR..mxR) { + for (j in mnC..mxC) { + if (targetGrid[i][j] != color && targetGrid[i][j] > 0) return false + } + } + for (i in mnR..mxR) { + for (j in mnC..mxC) { + targetGrid[i][j] = 0 + } + } + return true + } + + val colorSet = colors.keys.toMutableSet() + while (colorSet.isNotEmpty()) { + val removable = colorSet.filter { canRemove(it) }.toSet() + if (removable.isEmpty()) return false + colorSet.removeAll(removable) + } + return true + } +} diff --git a/tests/1501-2000/1591. strange-printer-ii/sol.py b/tests/1501-2000/1591. strange-printer-ii/sol.py new file mode 100644 index 00000000..2ec11437 --- /dev/null +++ b/tests/1501-2000/1591. strange-printer-ii/sol.py @@ -0,0 +1,42 @@ +from collections import defaultdict +from itertools import product + + +class Solution: + def isPrintable(self, targetGrid: List[List[int]]) -> bool: + + def dp(color: int) -> bool: + + rows, cols = list(zip(*colors[color])) + + mn_r, mx_r, mn_c, mx_c = ( + min(rows), + max(rows) + 1, + min(cols), + max(cols) + 1, + ) + + for i, j in product(range(mn_r, mx_r), range(mn_c, mx_c)): + if targetGrid[i][j] != color and targetGrid[i][j] > 0: + return False + + for i in range(mn_r, mx_r): + targetGrid[i][mn_c:mx_c] = [0] * (mx_c - mn_c) + + return True + + m, n = len(targetGrid), len(targetGrid[0]) + colors = defaultdict(list) + + for i, j in product(range(m), range(n)): + colors[targetGrid[i][j]].append((i, j)) + + color_set = set(colors) + + while color_set: + tmp = set(filter(lambda x: dp(x), color_set)) + if not tmp: + return False + color_set -= tmp + + return True diff --git a/tests/1501-2000/1591. strange-printer-ii/sol.py2 b/tests/1501-2000/1591. strange-printer-ii/sol.py2 new file mode 100644 index 00000000..9ed46a56 --- /dev/null +++ b/tests/1501-2000/1591. strange-printer-ii/sol.py2 @@ -0,0 +1,34 @@ +class Solution(object): + def isPrintable(self, targetGrid): + """ + :type targetGrid: List[List[int]] + :rtype: bool + """ + from collections import defaultdict + from itertools import product + + def dp(color): + rows, cols = zip(*colors[color]) + mn_r, mx_r = min(rows), max(rows) + 1 + mn_c, mx_c = min(cols), max(cols) + 1 + + for i, j in product(range(mn_r, mx_r), range(mn_c, mx_c)): + if targetGrid[i][j] != color and targetGrid[i][j] > 0: + return False + + for i in range(mn_r, mx_r): + targetGrid[i][mn_c:mx_c] = [0] * (mx_c - mn_c) + return True + + m, n = len(targetGrid), len(targetGrid[0]) + colors = defaultdict(list) + for i, j in product(range(m), range(n)): + colors[targetGrid[i][j]].append((i, j)) + + color_set = set(colors) + while color_set: + tmp = set(filter(lambda x: dp(x), color_set)) + if not tmp: + return False + color_set -= tmp + return True diff --git a/tests/1501-2000/1591. strange-printer-ii/sol.rb b/tests/1501-2000/1591. strange-printer-ii/sol.rb new file mode 100644 index 00000000..9ed5b189 --- /dev/null +++ b/tests/1501-2000/1591. strange-printer-ii/sol.rb @@ -0,0 +1,38 @@ +# @param {Integer[][]} target_grid +# @return {Boolean} +def is_printable(target_grid) + colors = Hash.new { |h, k| h[k] = [] } + (0...target_grid.length).each do |i| + (0...target_grid[0].length).each do |j| + colors[target_grid[i][j]] << [i, j] + end + end + + def check_and_clear(grid, color, positions) + rows = positions.map(&:first) + cols = positions.map(&:last) + mn_r, mx_r = rows.min, rows.max + 1 + mn_c, mx_c = cols.min, cols.max + 1 + + (mn_r...mx_r).each do |i| + (mn_c...mx_c).each do |j| + return false if grid[i][j] != color && grid[i][j] > 0 + end + end + + (mn_r...mx_r).each do |i| + (mn_c...mx_c).each do |j| + grid[i][j] = 0 + end + end + true + end + + color_set = colors.keys.to_set + while !color_set.empty? + removable = color_set.select { |c| check_and_clear(target_grid, c, colors[c]) } + return false if removable.empty? + color_set -= removable + end + true +end diff --git a/tests/1501-2000/1591. strange-printer-ii/sol.rs b/tests/1501-2000/1591. strange-printer-ii/sol.rs new file mode 100644 index 00000000..daac11b3 --- /dev/null +++ b/tests/1501-2000/1591. strange-printer-ii/sol.rs @@ -0,0 +1,46 @@ +impl Solution { + pub fn is_printable(target_grid: Vec>) -> bool { + let mut grid = target_grid; + let m = grid.len(); + let n = grid[0].len(); + use std::collections::HashMap; + use std::collections::HashSet; + let mut colors: HashMap> = HashMap::new(); + for i in 0..m { + for j in 0..n { + colors.entry(grid[i][j]).or_insert_with(Vec::new).push((i, j)); + } + } + + fn can_remove(grid: &mut Vec>, color: i32, pos: &Vec<(usize, usize)>) -> bool { + let mn_r = pos.iter().map(|&(r, _)| r).min().unwrap(); + let mx_r = pos.iter().map(|&(r, _)| r).max().unwrap(); + let mn_c = pos.iter().map(|&(_, c)| c).min().unwrap(); + let mx_c = pos.iter().map(|&(_, c)| c).max().unwrap(); + for i in mn_r..=mx_r { + for j in mn_c..=mx_c { + if grid[i][j] != color && grid[i][j] > 0 { return false; } + } + } + for i in mn_r..=mx_r { + for j in mn_c..=mx_c { + grid[i][j] = 0; + } + } + true + } + + let mut color_set: HashSet = colors.keys().cloned().collect(); + while !color_set.is_empty() { + let mut removable: HashSet = HashSet::new(); + for &c in &color_set { + if can_remove(&mut grid, c, &colors[&c]) { + removable.insert(c); + } + } + if removable.is_empty() { return false; } + color_set = color_set.difference(&removable).cloned().collect(); + } + true + } +} diff --git a/tests/1501-2000/1591. strange-printer-ii/sol.swift b/tests/1501-2000/1591. strange-printer-ii/sol.swift new file mode 100644 index 00000000..4f8884b1 --- /dev/null +++ b/tests/1501-2000/1591. strange-printer-ii/sol.swift @@ -0,0 +1,43 @@ +class Solution { + func isPrintable(_ targetGrid: [[Int]]) -> Bool { + var grid = targetGrid + let m = grid.count, n = grid[0].count + var colors: [Int: [(Int, Int)]] = [:] + for i in 0.. Bool { + guard let pos = colors[color] else { return false } + var mnR = pos[0].0, mxR = pos[0].0 + var mnC = pos[0].1, mxC = pos[0].1 + for (r, c) in pos { + mnR = min(mnR, r) + mxR = max(mxR, r) + mnC = min(mnC, c) + mxC = max(mxC, c) + } + for i in mnR...mxR { + for j in mnC...mxC { + if grid[i][j] != color && grid[i][j] > 0 { return false } + } + } + for i in mnR...mxR { + for j in mnC...mxC { + grid[i][j] = 0 + } + } + return true + } + + var colorSet = Set(colors.keys) + while !colorSet.isEmpty { + let removable = colorSet.filter { canRemove($0) } + if removable.isEmpty { return false } + colorSet.subtract(removable) + } + return true + } +} diff --git a/tests/1501-2000/1591. strange-printer-ii/sol.ts b/tests/1501-2000/1591. strange-printer-ii/sol.ts new file mode 100644 index 00000000..dc9e1378 --- /dev/null +++ b/tests/1501-2000/1591. strange-printer-ii/sol.ts @@ -0,0 +1,47 @@ +function isPrintable(targetGrid: number[][]): boolean { + const m = targetGrid.length; + const n = targetGrid[0].length; + const colors: Map = new Map(); + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (!colors.has(targetGrid[i][j])) colors.set(targetGrid[i][j], []); + colors.get(targetGrid[i][j])!.push([i, j]); + } + } + + function canRemove(color: number): boolean { + const pos = colors.get(color)!; + let mnR = pos[0][0], + mxR = pos[0][0]; + let mnC = pos[0][1], + mxC = pos[0][1]; + for (const [r, c] of pos) { + mnR = Math.min(mnR, r); + mxR = Math.max(mxR, r); + mnC = Math.min(mnC, c); + mxC = Math.max(mxC, c); + } + for (let i = mnR; i <= mxR; i++) { + for (let j = mnC; j <= mxC; j++) { + if (targetGrid[i][j] !== color && targetGrid[i][j] > 0) return false; + } + } + for (let i = mnR; i <= mxR; i++) { + for (let j = mnC; j <= mxC; j++) { + targetGrid[i][j] = 0; + } + } + return true; + } + + const colorSet = new Set(colors.keys()); + while (colorSet.size > 0) { + const removable = new Set(); + for (const c of colorSet) { + if (canRemove(c)) removable.add(c); + } + if (removable.size === 0) return false; + removable.forEach((c) => colorSet.delete(c)); + } + return true; +} diff --git a/tests/1501-2000/1592. rearrange-spaces-between-words/manifest.yaml b/tests/1501-2000/1592. rearrange-spaces-between-words/manifest.yaml new file mode 100644 index 00000000..b169fe48 --- /dev/null +++ b/tests/1501-2000/1592. rearrange-spaces-between-words/manifest.yaml @@ -0,0 +1,220 @@ +entry: + id: 1592 + title: "rearrange-spaces-between-words" + params: + text: + type: string + call: + cpp: "Solution().reorderSpaces({text})" + rust: "Solution::reorder_spaces({text})" + python3: "Solution().reorderSpaces({text})" + python2: "Solution().reorderSpaces({text})" + ruby: "reorder_spaces({text})" + java: "new Solution().reorderSpaces({text})" + csharp: "new Solution().ReorderSpaces({text})" + kotlin: "Solution().reorderSpaces({text})" + go: "reorderSpaces({text})" + dart: "Solution().reorderSpaces({text})" + swift: "Solution().reorderSpaces({text})" + typescript: "reorderSpaces({text})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().reorderSpaces(text, {result})" + checker: | + class Checker: + def reorderSpaces(self, text, result): + words = text.split() + spaces = text.count(" ") + if len(words) == 1: + expected = words[0] + " " * spaces + else: + gap, extra = divmod(spaces, len(words) - 1) + expected = (" " * gap).join(words) + " " * extra + return result == expected + +seed: 1592 + +tests: + - name: example-leading-trailing + in: + text: " this is a sentence " + out: "this is a sentence" + - name: example-extra-at-end + in: + text: " practice makes perfect" + out: "practice makes perfect " + - name: one-word-many-spaces + in: + text: " hello " + out: "hello " + - name: one-word-no-spaces + in: + text: "word" + out: "word" + - name: two-words-even + in: + text: "a b" + out: "a b" + - name: two-words-leading-trailing + in: + text: " alpha beta " + out: "alpha beta" + - name: two-words-all-spaces-between + in: + text: "left right" + out: "left right" + - name: two-words-extra-trailing + in: + text: "x y " + out: "x y" + - name: no-spaces-three-words + in: + text: "one two three" + out: "one two three" + - name: three-words-remainder-one + in: + text: "a bb c " + out: "a bb c" + - name: three-words-remainder-two + in: + text: " a bb c" + out: "a bb c " + - name: four-words-zero-remainder + in: + text: " a b c d " + out: "a b c d " + - name: four-words-remainder + in: + text: "a b c d" + out: "a b c d " + - name: repeated-single-letters + in: + text: " a a a a " + out: "a a a a " + - name: repeated-words + in: + text: "go go go" + out: "go go go " + - name: irregular-internal-gaps + in: + text: "alpha beta gamma delta" + out: "alpha beta gamma delta " + - name: all-leading-spaces + in: + text: " hello world" + out: "hello world" + - name: all-trailing-spaces + in: + text: "hello world " + out: "hello world" + - name: alternating-gaps + in: + text: "a b c d e" + out: "a b c d e" + - name: punctuation-not-allowed-but-letters + in: + text: "abc xyz" + out: "abc xyz" + - name: long-word-single + in: + text: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv" + out: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv" + - name: long-two-word + in: + text: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + out: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + - name: thirty-one-one-letter-words + in: + text: "a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e" + out: "a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e" + - name: sparse-five-words + in: + text: " aa b c d e " + out: "aa b c d e " + - name: dense-five-words + in: + text: "a b c d e" + out: "a b c d e" + - name: two-long-words-leading + in: + text: " aaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbb" + out: "aaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbb" + - name: mixed-word-lengths + in: + text: " a bb cccc ddddddd " + out: "a bb cccc ddddddd " + - name: twenty-spaces-two-words + in: + text: "first second" + out: "first second" + - name: spaces-only-between-three + in: + text: "left middle right" + out: "left middle right" + - name: one-space-between-many + in: + text: "a b c d e f g" + out: "a b c d e f g" + - name: all-space-budget-at-end + in: + text: "a b c " + out: "a b c" + - name: leading-and-trailing-budget + in: + text: " a b c " + out: "a b c" + - name: uneven-seven-words + in: + text: "a bb c d e f g" + out: "a bb c d e f g " + - name: many-leading-one-word + in: + text: " z" + out: "z " + - name: maximum-length-three-words + in: + text: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb cccccccccccccccccccccccccccccccccccccccccccccccccc" + out: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb cccccccccccccccccccccccccccccccccccccccccccccccccc" + - name: generated-letter-stress-20 + in: + text: + gen: "str" + len: 20 + alphabet: "abc" + seed: 20 + - name: generated-letter-stress-50 + in: + text: + gen: "str" + len: 50 + alphabet: "defg" + seed: 50 + - name: generated-letter-stress-80 + in: + text: + gen: "str" + len: 80 + alphabet: "hij" + seed: 80 + - name: generated-letter-stress-99 + in: + text: + gen: "str" + len: 99 + alphabet: "klmn" + seed: 99 + - name: generated-letter-limit + in: + text: + gen: "str" + len: 100 + alphabet: "opqrs" + seed: 100 diff --git a/tests/1501-2000/1592. rearrange-spaces-between-words/sol.cpp b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.cpp new file mode 100644 index 00000000..9af0d7e6 --- /dev/null +++ b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + string reorderSpaces(string text) { + vector words; + stringstream ss(text); + string word; + while (ss >> word) { + words.push_back(word); + } + int total = count(text.begin(), text.end(), ' '); + if (words.size() == 1) { + return words[0] + string(total, ' '); + } + int gap = total / (words.size() - 1); + int extra = total % (words.size() - 1); + string result; + for (int i = 0; i < words.size(); ++i) { + if (i > 0) result += string(gap, ' '); + result += words[i]; + } + result += string(extra, ' '); + return result; + } +}; diff --git a/tests/1501-2000/1592. rearrange-spaces-between-words/sol.cs b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.cs new file mode 100644 index 00000000..7877ba03 --- /dev/null +++ b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.cs @@ -0,0 +1,12 @@ +public class Solution { + public string ReorderSpaces(string text) { + var words = text.Split(' ', StringSplitOptions.RemoveEmptyEntries); + int total = text.Count(c => c == ' '); + if (words.Length == 1) { + return words[0] + new string(' ', total); + } + int gap = total / (words.Length - 1); + int extra = total % (words.Length - 1); + return string.Join(new string(' ', gap), words) + new string(' ', extra); + } +} diff --git a/tests/1501-2000/1592. rearrange-spaces-between-words/sol.dart b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.dart new file mode 100644 index 00000000..b6c89a5b --- /dev/null +++ b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.dart @@ -0,0 +1,12 @@ +class Solution { + String reorderSpaces(String text) { + List words = text.trim().split(RegExp(r'\s+')); + int total = text.split(' ').length - 1; + if (words.length == 1) { + return words[0] + ' ' * total; + } + int gap = total ~/ (words.length - 1); + int extra = total % (words.length - 1); + return words.join(' ' * gap) + ' ' * extra; + } +} diff --git a/tests/1501-2000/1592. rearrange-spaces-between-words/sol.go b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.go new file mode 100644 index 00000000..87a497a7 --- /dev/null +++ b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.go @@ -0,0 +1,10 @@ +func reorderSpaces(text string) string { + words := strings.Fields(text) + total := strings.Count(text, " ") + if len(words) == 1 { + return words[0] + strings.Repeat(" ", total) + } + gap := total / (len(words) - 1) + extra := total % (len(words) - 1) + return strings.Join(words, strings.Repeat(" ", gap)) + strings.Repeat(" ", extra) +} diff --git a/tests/1501-2000/1592. rearrange-spaces-between-words/sol.java b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.java new file mode 100644 index 00000000..b4e8c15c --- /dev/null +++ b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.java @@ -0,0 +1,12 @@ +class Solution { + public String reorderSpaces(String text) { + String[] words = text.trim().split("\\s+"); + int total = text.length() - text.replace(" ", "").length(); + if (words.length == 1) { + return words[0] + " ".repeat(total); + } + int gap = total / (words.length - 1); + int extra = total % (words.length - 1); + return String.join(" ".repeat(gap), words) + " ".repeat(extra); + } +} diff --git a/tests/1501-2000/1592. rearrange-spaces-between-words/sol.kt b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.kt new file mode 100644 index 00000000..ff6f6977 --- /dev/null +++ b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.kt @@ -0,0 +1,12 @@ +class Solution { + fun reorderSpaces(text: String): String { + val words = text.trim().split("\\s+".toRegex()) + val total = text.count { it == ' ' } + if (words.size == 1) { + return words[0] + " ".repeat(total) + } + val gap = total / (words.size - 1) + val extra = total % (words.size - 1) + return words.joinToString(" ".repeat(gap)) + " ".repeat(extra) + } +} diff --git a/tests/1501-2000/1592. rearrange-spaces-between-words/sol.py b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.py new file mode 100644 index 00000000..4c48db98 --- /dev/null +++ b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.py @@ -0,0 +1,14 @@ +class Solution: + def reorderSpaces(self, text: str) -> str: + t = text.split() + _ = text.count(" ") + z = len(t) - 1 + n = 1 + if z > 0: + n = _ // z + s = "" + for i in t: + s += i + " " * n + if z == 0: + return s[:-n] + " " * _ + return s[:-n] + (" " * (_ % z)) diff --git a/tests/1501-2000/1592. rearrange-spaces-between-words/sol.py2 b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.py2 new file mode 100644 index 00000000..c94c1abc --- /dev/null +++ b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.py2 @@ -0,0 +1,13 @@ +class Solution(object): + def reorderSpaces(self, text): + """ + :type text: str + :rtype: str + """ + t = text.split() + total = text.count(" ") + if len(t) == 1: + return t[0] + " " * total + gap = total // (len(t) - 1) + extra = total % (len(t) - 1) + return (" " * gap).join(t) + " " * extra diff --git a/tests/1501-2000/1592. rearrange-spaces-between-words/sol.rb b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.rb new file mode 100644 index 00000000..c24c7e8a --- /dev/null +++ b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.rb @@ -0,0 +1,10 @@ +# @param {String} text +# @return {String} +def reorder_spaces(text) + words = text.split + total = text.count(" ") + return words[0] + " " * total if words.length == 1 + gap = total / (words.length - 1) + extra = total % (words.length - 1) + words.join(" " * gap) + " " * extra +end diff --git a/tests/1501-2000/1592. rearrange-spaces-between-words/sol.rs b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.rs new file mode 100644 index 00000000..3be7fde7 --- /dev/null +++ b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.rs @@ -0,0 +1,14 @@ +impl Solution { + pub fn reorder_spaces(text: String) -> String { + let words: Vec<&str> = text.split_whitespace().collect(); + let total = text.chars().filter(|c| *c == ' ').count(); + if words.len() == 1 { + return format!("{}{}", words[0], " ".repeat(total)); + } + let gap = total / (words.len() - 1); + let extra = total % (words.len() - 1); + let sep = " ".repeat(gap); + let joined = words.join(&sep); + format!("{}{}", joined, " ".repeat(extra)) + } +} diff --git a/tests/1501-2000/1592. rearrange-spaces-between-words/sol.swift b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.swift new file mode 100644 index 00000000..1018f6b2 --- /dev/null +++ b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.swift @@ -0,0 +1,12 @@ +class Solution { + func reorderSpaces(_ text: String) -> String { + let words = text.split(separator: " ").map(String.init) + let total = text.filter { $0 == " " }.count + if words.count == 1 { + return words[0] + String(repeating: " ", count: total) + } + let gap = total / (words.count - 1) + let extra = total % (words.count - 1) + return words.joined(separator: String(repeating: " ", count: gap)) + String(repeating: " ", count: extra) + } +} diff --git a/tests/1501-2000/1592. rearrange-spaces-between-words/sol.ts b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.ts new file mode 100644 index 00000000..2dc507ef --- /dev/null +++ b/tests/1501-2000/1592. rearrange-spaces-between-words/sol.ts @@ -0,0 +1,10 @@ +function reorderSpaces(text: string): string { + const words = text.trim().split(/\s+/); + const total = (text.match(/ /g) || []).length; + if (words.length === 1) { + return words[0] + " ".repeat(total); + } + const gap = Math.floor(total / (words.length - 1)); + const extra = total % (words.length - 1); + return words.join(" ".repeat(gap)) + " ".repeat(extra); +} diff --git a/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/manifest.yaml b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/manifest.yaml new file mode 100644 index 00000000..b12010d4 --- /dev/null +++ b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/manifest.yaml @@ -0,0 +1,298 @@ +entry: + id: 1593 + title: "split-a-string-into-the-max-number-of-unique-substrings" + params: + s: + type: string + call: + cpp: "Solution().maxUniqueSplit({s})" + rust: "Solution::max_unique_split({s})" + python3: "Solution().maxUniqueSplit({s})" + python2: "Solution().maxUniqueSplit({s})" + ruby: "max_unique_split({s})" + java: "new Solution().maxUniqueSplit({s})" + csharp: "new Solution().MaxUniqueSplit({s})" + kotlin: "Solution().maxUniqueSplit({s})" + go: "maxUniqueSplit({s})" + dart: "Solution().maxUniqueSplit({s})" + swift: "Solution().maxUniqueSplit({s})" + typescript: "maxUniqueSplit({s})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxUniqueSplit(s, {result})" + checker: | + class Checker: + def maxUniqueSplit(self, s, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + best = 0 + used = set() + + def dfs(pos): + nonlocal best + if pos == len(s): + best = max(best, len(used)) + return + if len(used) + len(s) - pos <= best: + return + for end in range(pos + 1, len(s) + 1): + part = s[pos:end] + if part not in used: + used.add(part) + dfs(end) + used.remove(part) + + dfs(0) + return result == best + +seed: 1593 + +tests: + - name: example-ababccc + in: + s: "ababccc" + out: 5 + judge: + type: "exact" + - name: example-aba + in: + s: "aba" + out: 2 + judge: + type: "exact" + - name: example-aa + in: + s: "aa" + out: 1 + judge: + type: "exact" + - name: single-letter + in: + s: "z" + out: 1 + judge: + type: "exact" + - name: two-distinct + in: + s: "ab" + out: 2 + judge: + type: "exact" + - name: two-equal + in: + s: "zz" + out: 1 + judge: + type: "exact" + - name: three-distinct + in: + s: "abc" + out: 3 + judge: + type: "exact" + - name: three-repeated + in: + s: "aaa" + out: 2 + judge: + type: "exact" + - name: alternating-four + in: + s: "abab" + out: 3 + judge: + type: "exact" + - name: distinct-four + in: + s: "abcd" + out: 4 + judge: + type: "exact" + - name: repeated-pattern + in: + s: "aabb" + out: 3 + judge: + type: "exact" + - name: palindrome-five + in: + s: "abcba" + out: 4 + judge: + type: "exact" + - name: all-same-five + in: + s: "aaaaa" + out: 2 + judge: + type: "exact" + - name: alternating-six + in: + s: "ababab" + out: 4 + judge: + type: "exact" + - name: repeated-abc + in: + s: "abcabc" + out: 4 + judge: + type: "exact" + - name: unique-six + in: + s: "abcdef" + out: 6 + judge: + type: "exact" + - name: repeated-aab + in: + s: "aabaab" + out: 4 + judge: + type: "exact" + - name: palindrome-seven + in: + s: "abacaba" + out: 4 + judge: + type: "exact" + - name: all-same-seven + in: + s: "aaaaaaa" + out: 3 + judge: + type: "exact" + - name: cyclic-four + in: + s: "abcdabcd" + out: 6 + judge: + type: "exact" + - name: alternating-eight + in: + s: "abababab" + out: 4 + judge: + type: "exact" + - name: unique-eight + in: + s: "abcdefgh" + out: 8 + judge: + type: "exact" + - name: all-same-eight + in: + s: "aaaaaaaa" + out: 3 + judge: + type: "exact" + - name: mixed-nine + in: + s: "aabacadaa" + out: 5 + judge: + type: "exact" + - name: repeated-four-block + in: + s: "abcdabcdabcd" + out: 8 + judge: + type: "exact" + - name: all-same-ten + in: + s: "aaaaaaaaaa" + out: 4 + judge: + type: "exact" + - name: unique-ten + in: + s: "abcdefghij" + out: 10 + judge: + type: "exact" + - name: alternating-ten + in: + s: "ababababab" + out: 5 + judge: + type: "exact" + - name: repeated-abc-twelve + in: + s: "abcabcabcabc" + out: 7 + judge: + type: "exact" + - name: palindrome-twelve + in: + s: "abccbaabccba" + out: 7 + judge: + type: "exact" + - name: unique-twelve + in: + s: "abcdefghijkl" + out: 12 + judge: + type: "exact" + - name: all-same-sixteen + in: + s: "aaaaaaaaaaaaaaaa" + out: 5 + judge: + type: "exact" + - name: alternating-sixteen + in: + s: "abababababababab" + out: 7 + judge: + type: "exact" + - name: unique-sixteen + in: + s: "abcdefghijklmnop" + out: 16 + judge: + type: "exact" + - name: mixed-sixteen + in: + s: "aabbccddeeffgghh" + out: 12 + judge: + type: "exact" + - name: gen-short-binary + in: + s: + gen: "str" + len: 6 + alphabet: "ab" + - name: gen-medium-binary + in: + s: + gen: "str" + len: 10 + alphabet: "ab" + - name: gen-medium-lowercase + in: + s: + gen: "str" + len: 12 + alphabet: "abcd" + - name: gen-near-limit-small-alphabet + in: + s: + gen: "str" + len: 15 + alphabet: "abc" + - name: gen-limit-lowercase + in: + s: + gen: "str" + len: 16 + alphabet: "abcdef" diff --git a/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.cpp b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.cpp new file mode 100644 index 00000000..420daf8a --- /dev/null +++ b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int maxUniqueSplit(string s) { + unordered_set used; + int ans = 0; + backtrack(s, 0, used, ans); + return ans; + } + + void backtrack(const string& s, int index, unordered_set& used, int& ans) { + if (index == s.size()) { + ans = max(ans, (int)used.size()); + return; + } + for (int j = index; j < s.size(); j++) { + string curr = s.substr(index, j - index + 1); + if (used.count(curr)) continue; + used.insert(curr); + backtrack(s, j + 1, used, ans); + used.erase(curr); + } + } +}; diff --git a/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.cs b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.cs new file mode 100644 index 00000000..81d5bf67 --- /dev/null +++ b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public int MaxUniqueSplit(string s) { + var used = new HashSet(); + int ans = 0; + Backtrack(s, 0, used, ref ans); + return ans; + } + + private void Backtrack(string s, int index, HashSet used, ref int ans) { + if (index == s.Length) { + ans = Math.Max(ans, used.Count); + return; + } + for (int j = index; j < s.Length; j++) { + string curr = s.Substring(index, j - index + 1); + if (used.Contains(curr)) continue; + used.Add(curr); + Backtrack(s, j + 1, used, ref ans); + used.Remove(curr); + } + } +} diff --git a/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.dart b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.dart new file mode 100644 index 00000000..70c99fc2 --- /dev/null +++ b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.dart @@ -0,0 +1,25 @@ +class Solution { + int maxUniqueSplit(String s) { + Set used = {}; + int ans = 0; + + void backtrack(int index) { + if (index == s.length) { + if (used.length > ans) { + ans = used.length; + } + return; + } + for (int j = index; j < s.length; j++) { + String curr = s.substring(index, j + 1); + if (used.contains(curr)) continue; + used.add(curr); + backtrack(j + 1); + used.remove(curr); + } + } + + backtrack(0); + return ans; + } +} diff --git a/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.go b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.go new file mode 100644 index 00000000..10cce50c --- /dev/null +++ b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.go @@ -0,0 +1,24 @@ +func maxUniqueSplit(s string) int { + used := make(map[string]bool) + ans := 0 + var backtrack func(int) + backtrack = func(index int) { + if index == len(s) { + if len(used) > ans { + ans = len(used) + } + return + } + for j := index; j < len(s); j++ { + curr := s[index : j+1] + if used[curr] { + continue + } + used[curr] = true + backtrack(j + 1) + delete(used, curr) + } + } + backtrack(0) + return ans +} diff --git a/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.java b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.java new file mode 100644 index 00000000..93c31c79 --- /dev/null +++ b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.java @@ -0,0 +1,22 @@ +class Solution { + public int maxUniqueSplit(String s) { + Set used = new HashSet<>(); + int[] ans = new int[1]; + backtrack(s, 0, used, ans); + return ans[0]; + } + + private void backtrack(String s, int index, Set used, int[] ans) { + if (index == s.length()) { + ans[0] = Math.max(ans[0], used.size()); + return; + } + for (int j = index; j < s.length(); j++) { + String curr = s.substring(index, j + 1); + if (used.contains(curr)) continue; + used.add(curr); + backtrack(s, j + 1, used, ans); + used.remove(curr); + } + } +} diff --git a/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.kt b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.kt new file mode 100644 index 00000000..86afd3e7 --- /dev/null +++ b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.kt @@ -0,0 +1,21 @@ +class Solution { + fun maxUniqueSplit(s: String): Int { + val used = mutableSetOf() + var ans = 0 + fun backtrack(index: Int) { + if (index == s.length) { + ans = maxOf(ans, used.size) + return + } + for (j in index until s.length) { + val curr = s.substring(index, j + 1) + if (curr in used) continue + used.add(curr) + backtrack(j + 1) + used.remove(curr) + } + } + backtrack(0) + return ans + } +} diff --git a/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.py b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.py new file mode 100644 index 00000000..2d840341 --- /dev/null +++ b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.py @@ -0,0 +1,23 @@ +class Solution(object): + def maxUniqueSplit(self, s): + """ + :type s: str + :rtype: int + """ + used = set() + ans = [0] + + def backtrack(index): + if index == len(s): + ans[0] = max(ans[0], len(used)) + return + for j in range(index, len(s)): + curr = s[index : j + 1] + if curr in used: + continue + used.add(curr) + backtrack(j + 1) + used.remove(curr) + + backtrack(0) + return ans[0] diff --git a/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.py2 b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.py2 new file mode 100644 index 00000000..2506a98f --- /dev/null +++ b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def maxUniqueSplit(self, s): + """ + :type s: str + :rtype: int + """ + used=set() + ans=[0] + def backtrack(index): + if index==len(s): + ans[0]=max(ans[0],len(used)) + return + for j in range(index,len(s)): + curr=s[index:j+1] + if curr in used: + continue + used.add(curr) + backtrack(j+1) + used.remove(curr) + backtrack(0) + return ans[0] diff --git a/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.rb b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.rb new file mode 100644 index 00000000..e461b3ff --- /dev/null +++ b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.rb @@ -0,0 +1,23 @@ +# @param {String} s +# @return {Integer} +def max_unique_split(s) + used = {} + ans = [0] + + backtrack = lambda do |index| + if index == s.length + ans[0] = [ans[0], used.length].max + return + end + (index...s.length).each do |j| + curr = s[index..j] + next if used.key?(curr) + used[curr] = true + backtrack.call(j + 1) + used.delete(curr) + end + end + + backtrack.call(0) + ans[0] +end diff --git a/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.rs b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.rs new file mode 100644 index 00000000..bc6a7f7e --- /dev/null +++ b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn max_unique_split(s: String) -> i32 { + let s_chars: Vec = s.chars().collect(); + let mut used = std::collections::HashSet::new(); + let mut ans = 0; + + fn backtrack(chars: &[char], start: usize, used: &mut std::collections::HashSet, ans: &mut i32) { + if start == chars.len() { + *ans = (*ans).max(used.len() as i32); + return; + } + for end in start..chars.len() { + let curr: String = chars[start..=end].iter().collect(); + if used.contains(&curr) { continue; } + used.insert(curr.clone()); + backtrack(chars, end + 1, used, ans); + used.remove(&curr); + } + } + + backtrack(&s_chars, 0, &mut used, &mut ans); + ans + } +} diff --git a/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.swift b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.swift new file mode 100644 index 00000000..2ac1905d --- /dev/null +++ b/tests/1501-2000/1593. split-a-string-into-the-max-number-of-unique-substrings/sol.swift @@ -0,0 +1,24 @@ +class Solution { + func maxUniqueSplit(_ s: String) -> Int { + var used = Set() + var ans = 0 + + func backtrack(_ index: Int) { + if index == s.count { + ans = max(ans, used.count) + return + } + let chars = Array(s) + for j in index..(); + let ans = 0; + + function backtrack(index: number): void { + if (index === s.length) { + ans = Math.max(ans, used.size); + return; + } + for (let j = index; j < s.length; j++) { + const curr = s.substring(index, j + 1); + if (used.has(curr)) continue; + used.add(curr); + backtrack(j + 1); + used.delete(curr); + } + } + + backtrack(0); + return ans; +} diff --git a/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/manifest.yaml b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/manifest.yaml new file mode 100644 index 00000000..6a9579ef --- /dev/null +++ b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/manifest.yaml @@ -0,0 +1,317 @@ +entry: + id: 1594 + title: "maximum-non-negative-product-in-a-matrix" + params: + grid: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().maxProductPath({grid})" + rust: "Solution::max_product_path({grid})" + python3: "Solution().maxProductPath({grid})" + python2: "Solution().maxProductPath({grid})" + ruby: "max_product_path({grid})" + java: "new Solution().maxProductPath({grid})" + csharp: "new Solution().MaxProductPath({grid})" + kotlin: "Solution().maxProductPath({grid})" + go: "maxProductPath({grid})" + dart: "Solution().maxProductPath({grid})" + swift: "Solution().maxProductPath({grid})" + typescript: "maxProductPath({grid})" +judge: + type: "exact" +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().maxProductPath(grid, {result})" + checker: | + class Checker: + def maxProductPath(self, grid, result): + r, c = len(grid), len(grid[0]) + lo = [[0] * c for _ in range(r)] + hi = [[0] * c for _ in range(r)] + lo[0][0] = hi[0][0] = grid[0][0] + for j in range(1, c): + v = hi[0][j - 1] * grid[0][j] + lo[0][j] = hi[0][j] = v + for i in range(1, r): + v = hi[i - 1][0] * grid[i][0] + lo[i][0] = hi[i][0] = v + for i in range(1, r): + for j in range(1, c): + x = grid[i][j] + vals = (lo[i - 1][j] * x, hi[i - 1][j] * x, + lo[i][j - 1] * x, hi[i][j - 1] * x) + lo[i][j], hi[i][j] = min(vals), max(vals) + expected = hi[-1][-1] % (10 ** 9 + 7) if hi[-1][-1] >= 0 else -1 + return result == expected +seed: 1594 +tests: + - name: example-negative + in: + grid: + - [-1, -2, -3] + - [-2, -3, -3] + - [-3, -3, -2] + out: -1 + - name: example-eight + in: + grid: + - [1, -2, 1] + - [1, -2, 1] + - [3, -4, 1] + out: 8 + - name: example-zero + in: + grid: + - [1, 3] + - [0, -4] + out: 0 + - name: one-cell-positive + in: + grid: + - [4] + out: 4 + - name: one-cell-negative + in: + grid: + - [-4] + out: -1 + - name: one-cell-zero + in: + grid: + - [0] + out: 0 + - name: positive-row + in: + grid: + - [1, 2, 3, 4, 2] + out: 48 + - name: negative-row-even + in: + grid: + - [-1, -2, -3, -4] + out: 24 + - name: negative-row-odd + in: + grid: + - [-1, -2, -3] + out: -1 + - name: positive-column + in: + grid: + - [2] + - [3] + - [4] + - [1] + out: 24 + - name: zero-blocked + in: + grid: + - [1, -1, 1] + - [-1, 0, -1] + - [1, -1, 1] + out: 1 + - name: all-zeros + in: + grid: + - [0, 0] + - [0, 0] + out: 0 + - name: all-ones + in: + grid: + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + out: 1 + - name: all-negative-even + in: + grid: + - [-1, -1] + - [-1, -1] + out: -1 + - name: all-negative-odd + in: + grid: + - [-1, -1, -1] + - [-1, -1, -1] + out: 1 + - name: choose-negative-pair + in: + grid: + - [1, -2, -3] + - [2, -3, -4] + - [1, -2, -1] + out: 24 + - name: zero-and-negatives + in: + grid: + - [-2, 0, -2] + - [-3, -4, -3] + out: 72 + - name: mixed-small + in: + grid: + - [-1, 2, -1] + - [3, -4, 2] + - [-2, 1, -3] + out: -1 + - name: max-positive-cells + in: + grid: + - [4, 4, 4] + - [4, 4, 4] + - [4, 4, 4] + out: 1024 + - name: min-negative-cells + in: + grid: + - [-4, -4] + - [-4, -4] + - [-4, -4] + out: 256 + - name: negative-choice + in: + grid: + - [2, -1, -2, 3] + - [-3, -4, 2, -1] + - [2, -2, -3, 4] + out: 576 + - name: narrow-three + in: + grid: + - [-2] + - [3] + - [-4] + out: 24 + - name: wide-mixed + in: + grid: + - [1, -1, 2, -2, 3, -3] + out: -1 + - name: path-zero + in: + grid: + - [-4, -3, -2] + - [-2, 0, -4] + - [-1, -2, -3] + out: 0 + - name: positive-versus-negative + in: + grid: + - [-1, -2] + - [3, -4] + out: 12 + - name: mixed-four + in: + grid: + - [3, -2, 1, -1] + - [-1, -3, -4, 2] + - [2, -2, 3, -4] + - [-1, 1, -2, 4] + out: 3456 + - name: alternating + in: + grid: + - [-1, 1, -1, 1] + - [1, -1, 1, -1] + - [-1, 1, -1, 1] + - [1, -1, 1, -1] + out: 1 + - name: zeros-and-fours + in: + grid: + - [4, 0, 4] + - [4, 4, 4] + - [0, 4, 4] + out: 1024 + - name: asymmetric-five + in: + grid: + - [-2, 3, -1, 2, -4] + - [1, -3, 4, -2, 1] + - [-4, 2, -2, 3, -1] + out: 432 + - name: large-positive + in: + grid: + - [4, 4, 4, 4, 4] + - [4, 4, 4, 4, 4] + - [4, 4, 4, 4, 4] + - [4, 4, 4, 4, 4] + - [4, 4, 4, 4, 4] + out: 262144 + - name: large-negative-mix + in: + grid: + - [-4, -3, -2, -1, 0] + - [1, 2, 3, 4, -4] + - [-1, -2, -3, -4, 0] + - [4, 3, 2, 1, -1] + - [-2, -3, -4, 0, 4] + out: 4608 + - name: six-by-four + in: + grid: + - [2, -2, 2, -2] + - [-2, 2, -2, 2] + - [2, -2, 2, -2] + - [-2, 2, -2, 2] + - [2, -2, 2, -2] + - [-2, 2, -2, 2] + out: 512 + - name: seven-by-three + in: + grid: + - [1, -2, 3] + - [-4, 1, -2] + - [3, -4, 1] + - [-2, 3, -4] + - [1, -2, 3] + - [-4, 1, -2] + - [3, -4, 1] + out: 3456 + - name: fifteen-by-one + in: + grid: + - [4] + - [-4] + - [4] + - [-4] + - [4] + - [-4] + - [4] + - [-4] + - [4] + - [-4] + - [4] + - [-4] + - [4] + - [-4] + - [4] + out: -1 + - name: fifteen-by-fifteen-ones + in: + grid: + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 1 diff --git a/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.cpp b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.cpp new file mode 100644 index 00000000..b75d0cb2 --- /dev/null +++ b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + int maxProductPath(vector>& grid) { + int r = grid.size(), c = grid[0].size(); + const int MOD = 1e9 + 7; + vector>> dp(r, vector>(c, vector(2))); + + long long p = grid[0][0]; + dp[0][0][0] = dp[0][0][1] = p; + for (int j = 1; j < c; j++) { + p *= grid[0][j]; + dp[0][j][0] = dp[0][j][1] = p; + } + + p = grid[0][0]; + for (int i = 1; i < r; i++) { + p *= grid[i][0]; + dp[i][0][0] = dp[i][0][1] = p; + for (int j = 1; j < c; j++) { + long long x = grid[i][j]; + long long vals[4] = {x * dp[i][j-1][0], x * dp[i][j-1][1], x * dp[i-1][j][0], x * dp[i-1][j][1]}; + long long mn = vals[0], mx = vals[0]; + for (int k = 1; k < 4; k++) { + mn = min(mn, vals[k]); + mx = max(mx, vals[k]); + } + dp[i][j][0] = mn; + dp[i][j][1] = mx; + } + } + + long long ans = dp[r-1][c-1][1]; + if (ans < 0) return -1; + return ans % MOD; + } +}; diff --git a/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.cs b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.cs new file mode 100644 index 00000000..73fdadba --- /dev/null +++ b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.cs @@ -0,0 +1,41 @@ +public class Solution { + public int MaxProductPath(int[][] grid) { + int r = grid.Length, c = grid[0].Length; + long MOD = 1_000_000_007L; + long[][][] dp = new long[r][][]; + for (int i = 0; i < r; i++) { + dp[i] = new long[c][]; + for (int j = 0; j < c; j++) { + dp[i][j] = new long[2]; + } + } + + long p = grid[0][0]; + dp[0][0][0] = dp[0][0][1] = p; + for (int j = 1; j < c; j++) { + p *= grid[0][j]; + dp[0][j][0] = dp[0][j][1] = p; + } + + p = grid[0][0]; + for (int i = 1; i < r; i++) { + p *= grid[i][0]; + dp[i][0][0] = dp[i][0][1] = p; + for (int j = 1; j < c; j++) { + long x = grid[i][j]; + long[] vals = {x * dp[i][j-1][0], x * dp[i][j-1][1], x * dp[i-1][j][0], x * dp[i-1][j][1]}; + long mn = vals[0], mx = vals[0]; + for (int k = 1; k < 4; k++) { + mn = Math.Min(mn, vals[k]); + mx = Math.Max(mx, vals[k]); + } + dp[i][j][0] = mn; + dp[i][j][1] = mx; + } + } + + long ans = dp[r-1][c-1][1]; + if (ans < 0) return -1; + return (int)(ans % MOD); + } +} diff --git a/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.dart b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.dart new file mode 100644 index 00000000..8fe110f4 --- /dev/null +++ b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.dart @@ -0,0 +1,34 @@ +class Solution { + int maxProductPath(List> grid) { + int r = grid.length; + int c = grid[0].length; + const int MOD = 1000000007; + List>> dp = List.generate(r, (i) => List.generate(c, (j) => List.filled(2, 0))); + + int p = grid[0][0]; + dp[0][0][0] = p; + dp[0][0][1] = p; + for (int j = 1; j < c; j++) { + p *= grid[0][j]; + dp[0][j][0] = p; + dp[0][j][1] = p; + } + + p = grid[0][0]; + for (int i = 1; i < r; i++) { + p *= grid[i][0]; + dp[i][0][0] = p; + dp[i][0][1] = p; + for (int j = 1; j < c; j++) { + int x = grid[i][j]; + List vals = [x * dp[i][j-1][0], x * dp[i][j-1][1], x * dp[i-1][j][0], x * dp[i-1][j][1]]; + dp[i][j][0] = vals.reduce((a, b) => a < b ? a : b); + dp[i][j][1] = vals.reduce((a, b) => a > b ? a : b); + } + } + + int ans = dp[r-1][c-1][1]; + if (ans < 0) return -1; + return ans % MOD; + } +} diff --git a/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.go b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.go new file mode 100644 index 00000000..c55e19ba --- /dev/null +++ b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.go @@ -0,0 +1,50 @@ +func maxProductPath(grid [][]int) int { + r := len(grid) + c := len(grid[0]) + const MOD = 1000000007 + dp := make([][][]int64, r) + for i := range dp { + dp[i] = make([][]int64, c) + for j := range dp[i] { + dp[i][j] = make([]int64, 2) + } + } + + p := int64(grid[0][0]) + dp[0][0][0] = p + dp[0][0][1] = p + for j := 1; j < c; j++ { + p *= int64(grid[0][j]) + dp[0][j][0] = p + dp[0][j][1] = p + } + + p = int64(grid[0][0]) + for i := 1; i < r; i++ { + p *= int64(grid[i][0]) + dp[i][0][0] = p + dp[i][0][1] = p + for j := 1; j < c; j++ { + x := int64(grid[i][j]) + vals := []int64{x * dp[i][j-1][0], x * dp[i][j-1][1], x * dp[i-1][j][0], x * dp[i-1][j][1]} + mn := vals[0] + mx := vals[0] + for _, v := range vals[1:] { + if v < mn { + mn = v + } + if v > mx { + mx = v + } + } + dp[i][j][0] = mn + dp[i][j][1] = mx + } + } + + ans := dp[r-1][c-1][1] + if ans < 0 { + return -1 + } + return int(ans % MOD) +} diff --git a/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.java b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.java new file mode 100644 index 00000000..93b7cd18 --- /dev/null +++ b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.java @@ -0,0 +1,35 @@ +class Solution { + public int maxProductPath(int[][] grid) { + int r = grid.length, c = grid[0].length; + long MOD = 1_000_000_007L; + long[][][] dp = new long[r][c][2]; + + long p = grid[0][0]; + dp[0][0][0] = dp[0][0][1] = p; + for (int j = 1; j < c; j++) { + p *= grid[0][j]; + dp[0][j][0] = dp[0][j][1] = p; + } + + p = grid[0][0]; + for (int i = 1; i < r; i++) { + p *= grid[i][0]; + dp[i][0][0] = dp[i][0][1] = p; + for (int j = 1; j < c; j++) { + long x = grid[i][j]; + long[] vals = {x * dp[i][j-1][0], x * dp[i][j-1][1], x * dp[i-1][j][0], x * dp[i-1][j][1]}; + long mn = vals[0], mx = vals[0]; + for (int k = 1; k < 4; k++) { + mn = Math.min(mn, vals[k]); + mx = Math.max(mx, vals[k]); + } + dp[i][j][0] = mn; + dp[i][j][1] = mx; + } + } + + long ans = dp[r-1][c-1][1]; + if (ans < 0) return -1; + return (int)(ans % MOD); + } +} diff --git a/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.kt b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.kt new file mode 100644 index 00000000..c8addc2c --- /dev/null +++ b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.kt @@ -0,0 +1,34 @@ +class Solution { + fun maxProductPath(grid: Array): Int { + val r = grid.size + val c = grid[0].size + val MOD = 1_000_000_007L + val dp = Array(r) { Array(c) { LongArray(2) } } + + var p = grid[0][0].toLong() + dp[0][0][0] = p + dp[0][0][1] = p + for (j in 1 until c) { + p *= grid[0][j] + dp[0][j][0] = p + dp[0][j][1] = p + } + + p = grid[0][0].toLong() + for (i in 1 until r) { + p *= grid[i][0] + dp[i][0][0] = p + dp[i][0][1] = p + for (j in 1 until c) { + val x = grid[i][j].toLong() + val vals = longArrayOf(x * dp[i][j-1][0], x * dp[i][j-1][1], x * dp[i-1][j][0], x * dp[i-1][j][1]) + dp[i][j][0] = vals.min()!! + dp[i][j][1] = vals.max()!! + } + } + + val ans = dp[r-1][c-1][1] + if (ans < 0) return -1 + return (ans % MOD).toInt() + } +} diff --git a/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.py b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.py new file mode 100644 index 00000000..e5ad8b26 --- /dev/null +++ b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.py @@ -0,0 +1,25 @@ +class Solution: + def maxProductPath(self, grid: List[List[int]]) -> int: + r, c, MOD = len(grid), len(grid[0]), 10**9 + 7 + dp = [[[0] * 2 for _ in range(c)] for _ in range(r)] + + p = dp[0][0][0] = dp[0][0][1] = grid[0][0] + for j in range(1, c): + p *= grid[0][j] + dp[0][j][0] = dp[0][j][1] = p + + p = grid[0][0] + for i in range(1, r): + p *= grid[i][0] + dp[i][0][0] = dp[i][0][1] = p + for j in range(1, c): + x = grid[i][j] + xx = ( + x * dp[i][j - 1][0], + x * dp[i][j - 1][1], + x * dp[i - 1][j][0], + x * dp[i - 1][j][1], + ) + dp[i][j][0], dp[i][j][1] = min(xx), max(xx) + ans = dp[r - 1][c - 1][1] + return -1 if ans < 0 else ans % MOD diff --git a/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.py2 b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.py2 new file mode 100644 index 00000000..a8a2e5be --- /dev/null +++ b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.py2 @@ -0,0 +1,30 @@ +class Solution(object): + def maxProductPath(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + r, c = len(grid), len(grid[0]) + MOD = 10**9 + 7 + dp = [[[0, 0] for _ in range(c)] for _ in range(r)] + + p = grid[0][0] + dp[0][0][0] = dp[0][0][1] = p + for j in range(1, c): + p *= grid[0][j] + dp[0][j][0] = dp[0][j][1] = p + + p = grid[0][0] + for i in range(1, r): + p *= grid[i][0] + dp[i][0][0] = dp[i][0][1] = p + for j in range(1, c): + x = grid[i][j] + vals = (x * dp[i][j-1][0], x * dp[i][j-1][1], x * dp[i-1][j][0], x * dp[i-1][j][1]) + dp[i][j][0] = min(vals) + dp[i][j][1] = max(vals) + + ans = dp[r-1][c-1][1] + if ans < 0: + return -1 + return ans % MOD diff --git a/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.rb b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.rb new file mode 100644 index 00000000..5f65164e --- /dev/null +++ b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.rb @@ -0,0 +1,29 @@ +# @param {Integer[][]} grid +# @return {Integer} +def max_product_path(grid) + r, c = grid.length, grid[0].length + mod = 10**9 + 7 + dp = Array.new(r) { Array.new(c) { [0, 0] } } + + p = grid[0][0] + dp[0][0][0] = dp[0][0][1] = p + (1...c).each do |j| + p *= grid[0][j] + dp[0][j][0] = dp[0][j][1] = p + end + + p = grid[0][0] + (1...r).each do |i| + p *= grid[i][0] + dp[i][0][0] = dp[i][0][1] = p + (1...c).each do |j| + x = grid[i][j] + vals = [x * dp[i][j-1][0], x * dp[i][j-1][1], x * dp[i-1][j][0], x * dp[i-1][j][1]] + dp[i][j][0] = vals.min + dp[i][j][1] = vals.max + end + end + + ans = dp[r-1][c-1][1] + ans < 0 ? -1 : ans % mod +end diff --git a/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.rs b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.rs new file mode 100644 index 00000000..aee21780 --- /dev/null +++ b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.rs @@ -0,0 +1,36 @@ +impl Solution { + pub fn max_product_path(grid: Vec>) -> i32 { + let r = grid.len(); + let c = grid[0].len(); + let MOD = 1_000_000_007i64; + let mut dp = vec![vec![vec![0i64; 2]; c]; r]; + + let mut p = grid[0][0] as i64; + dp[0][0][0] = p; + dp[0][0][1] = p; + for j in 1..c { + p *= grid[0][j] as i64; + dp[0][j][0] = p; + dp[0][j][1] = p; + } + + p = grid[0][0] as i64; + for i in 1..r { + p *= grid[i][0] as i64; + dp[i][0][0] = p; + dp[i][0][1] = p; + for j in 1..c { + let x = grid[i][j] as i64; + let vals = [x * dp[i][j-1][0], x * dp[i][j-1][1], x * dp[i-1][j][0], x * dp[i-1][j][1]]; + let mn = *vals.iter().min().unwrap(); + let mx = *vals.iter().max().unwrap(); + dp[i][j][0] = mn; + dp[i][j][1] = mx; + } + } + + let ans = dp[r-1][c-1][1]; + if ans < 0 { return -1; } + (ans % MOD) as i32 + } +} diff --git a/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.swift b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.swift new file mode 100644 index 00000000..982b2269 --- /dev/null +++ b/tests/1501-2000/1594. maximum-non-negative-product-in-a-matrix/sol.swift @@ -0,0 +1,34 @@ +class Solution { + func maxProductPath(_ grid: [[Int]]) -> Int { + let r = grid.count + let c = grid[0].count + let MOD = 1_000_000_007 + var dp = Array(repeating: Array(repeating: [0, 0], count: c), count: r) + + var p = grid[0][0] + dp[0][0][0] = p + dp[0][0][1] = p + for j in 1.. + Array.from({ length: c }, () => [0, 0]), + ); + + let p = grid[0][0]; + dp[0][0][0] = p; + dp[0][0][1] = p; + for (let j = 1; j < c; j++) { + p *= grid[0][j]; + dp[0][j][0] = p; + dp[0][j][1] = p; + } + + p = grid[0][0]; + for (let i = 1; i < r; i++) { + p *= grid[i][0]; + dp[i][0][0] = p; + dp[i][0][1] = p; + for (let j = 1; j < c; j++) { + const x = grid[i][j]; + const vals = [ + x * dp[i][j - 1][0], + x * dp[i][j - 1][1], + x * dp[i - 1][j][0], + x * dp[i - 1][j][1], + ]; + dp[i][j][0] = Math.min(...vals); + dp[i][j][1] = Math.max(...vals); + } + } + + const ans = dp[r - 1][c - 1][1]; + if (ans < 0) return -1; + return ans % MOD; +} diff --git a/tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/manifest.yaml b/tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/manifest.yaml new file mode 100644 index 00000000..92188aba --- /dev/null +++ b/tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/manifest.yaml @@ -0,0 +1,499 @@ +entry: + id: 1595 + title: "minimum-cost-to-connect-two-groups-of-points" + params: + cost: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().connectTwoGroups({cost})" + rust: "Solution::connect_two_groups({cost})" + python3: "Solution().connectTwoGroups({cost})" + python2: "Solution().connectTwoGroups({cost})" + ruby: "connect_two_groups({cost})" + java: "new Solution().connectTwoGroups({cost})" + csharp: "new Solution().ConnectTwoGroups({cost})" + kotlin: "Solution().connectTwoGroups({cost})" + go: "connectTwoGroups({cost})" + dart: "Solution().connectTwoGroups({cost})" + swift: "Solution().connectTwoGroups({cost})" + typescript: "connectTwoGroups({cost})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().connectTwoGroups(cost, {result})" + checker: | + class Checker: + def connectTwoGroups(self, cost, result): + if not isinstance(cost, list) or not cost or not isinstance(cost[0], list): + return False + m, n = len(cost), len(cost[0]) + if not (1 <= n <= m <= 12): + return False + if any(not isinstance(row, list) or len(row) != n for row in cost): + return False + if any(any(not isinstance(x, int) or x < 0 or x > 100 for x in row) for row in cost): + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + best_col = [min(cost[i][j] for i in range(m)) for j in range(n)] + inf = 10**18 + dp = [inf] * (1 << n) + dp[0] = 0 + for row in cost: + nxt = [inf] * (1 << n) + for mask, value in enumerate(dp): + if value == inf: + continue + for j, price in enumerate(row): + new_mask = mask | (1 << j) + candidate = value + price + if candidate < nxt[new_mask]: + nxt[new_mask] = candidate + dp = nxt + expected = min(dp[mask] + sum(best_col[j] for j in range(n) if not (mask & (1 << j))) for mask in range(1 << n)) + return result == expected + +seed: 1595 + +tests: + - name: example-one + in: + cost: + - [15, 96] + - [36, 2] + out: 17 + judge: + type: "exact" + - name: example-two + in: + cost: + - [1, 3, 5] + - [4, 1, 1] + - [1, 5, 3] + out: 4 + judge: + type: "exact" + - name: example-three + in: + cost: + - [2, 5, 1] + - [3, 4, 7] + - [8, 1, 2] + - [6, 2, 4] + - [3, 8, 8] + out: 10 + judge: + type: "exact" + - name: one-point-zero + in: + cost: + - [0] + out: 0 + judge: + type: "exact" + - name: one-point-max + in: + cost: + - [100] + out: 100 + judge: + type: "exact" + - name: two-by-one + in: + cost: + - [7] + - [3] + out: 10 + judge: + type: "exact" + - name: three-by-one + in: + cost: + - [9] + - [2] + - [6] + out: 17 + judge: + type: "exact" + - name: two-by-two-diagonal + in: + cost: + - [1, 100] + - [100, 1] + out: 2 + judge: + type: "exact" + - name: two-by-two-shared + in: + cost: + - [1, 2] + - [1, 2] + out: 3 + judge: + type: "exact" + - name: two-by-two-tie + in: + cost: + - [5, 5] + - [5, 5] + out: 10 + judge: + type: "exact" + - name: three-by-two + in: + cost: + - [8, 3] + - [4, 9] + - [2, 7] + out: 9 + judge: + type: "exact" + - name: four-by-two + in: + cost: + - [10, 1] + - [10, 1] + - [1, 10] + - [1, 10] + out: 4 + judge: + type: "exact" + - name: four-by-three + in: + cost: + - [4, 8, 2] + - [6, 1, 9] + - [3, 7, 5] + - [8, 2, 6] + out: 8 + judge: + type: "exact" + - name: five-by-three + in: + cost: + - [9, 9, 1] + - [2, 8, 8] + - [7, 3, 6] + - [4, 5, 2] + - [6, 1, 7] + out: 9 + judge: + type: "exact" + - name: five-by-four + in: + cost: + - [5, 2, 9, 8] + - [7, 6, 1, 4] + - [3, 8, 5, 7] + - [9, 4, 6, 2] + - [1, 7, 3, 9] + out: 9 + judge: + type: "exact" + - name: six-by-two + in: + cost: + - [0, 100] + - [0, 100] + - [0, 100] + - [100, 0] + - [100, 0] + - [100, 0] + out: 0 + judge: + type: "exact" + - name: six-by-three + in: + cost: + - [1, 20, 20] + - [2, 20, 20] + - [20, 1, 20] + - [20, 2, 20] + - [20, 20, 1] + - [20, 20, 2] + out: 9 + judge: + type: "exact" + - name: six-by-six-zero + in: + cost: + - [0, 1, 2, 3, 4, 5] + - [5, 0, 1, 2, 3, 4] + - [4, 5, 0, 1, 2, 3] + - [3, 4, 5, 0, 1, 2] + - [2, 3, 4, 5, 0, 1] + - [1, 2, 3, 4, 5, 0] + out: 0 + judge: + type: "exact" + - name: seven-by-three + in: + cost: + - [14, 2, 8] + - [3, 11, 7] + - [9, 4, 13] + - [6, 8, 1] + - [12, 5, 10] + - [2, 15, 6] + - [7, 3, 9] + out: 20 + judge: + type: "exact" + - name: seven-by-five + in: + cost: + - [4, 9, 2, 8, 7] + - [6, 1, 5, 9, 3] + - [8, 4, 7, 2, 6] + - [3, 8, 1, 5, 9] + - [7, 2, 6, 4, 8] + - [9, 5, 3, 7, 1] + - [2, 6, 8, 3, 5] + out: 11 + judge: + type: "exact" + - name: eight-by-four + in: + cost: + - [10, 20, 30, 40] + - [11, 21, 31, 41] + - [12, 22, 32, 42] + - [13, 23, 33, 43] + - [14, 24, 34, 44] + - [15, 25, 35, 45] + - [16, 26, 36, 46] + - [17, 27, 37, 47] + out: 168 + judge: + type: "exact" + - name: eight-by-eight-max + in: + cost: + - [100, 99, 98, 97, 96, 95, 94, 93] + - [92, 100, 90, 89, 88, 87, 86, 85] + - [84, 83, 100, 81, 80, 79, 78, 77] + - [76, 75, 74, 100, 72, 71, 70, 69] + - [68, 67, 66, 65, 100, 63, 62, 61] + - [60, 59, 58, 57, 56, 100, 54, 53] + - [52, 51, 50, 49, 48, 47, 100, 45] + - [44, 43, 42, 41, 40, 39, 38, 100] + out: 548 + judge: + type: "exact" + - name: nine-by-three + in: + cost: + - [5, 40, 40] + - [6, 40, 40] + - [7, 40, 40] + - [40, 5, 40] + - [40, 6, 40] + - [40, 7, 40] + - [40, 40, 5] + - [40, 40, 6] + - [40, 40, 7] + out: 54 + judge: + type: "exact" + - name: nine-by-six + in: + cost: + - [3, 8, 2, 9, 4, 7] + - [6, 1, 5, 8, 3, 9] + - [7, 4, 9, 2, 8, 5] + - [5, 9, 1, 6, 7, 3] + - [8, 2, 6, 4, 9, 1] + - [4, 7, 3, 8, 2, 6] + - [9, 5, 8, 1, 6, 4] + - [2, 6, 4, 7, 5, 8] + - [1, 3, 7, 5, 4, 9] + out: 13 + judge: + type: "exact" + - name: ten-by-two + in: + cost: + - [1, 100] + - [2, 100] + - [3, 100] + - [4, 100] + - [5, 100] + - [100, 1] + - [100, 2] + - [100, 3] + - [100, 4] + - [100, 5] + out: 30 + judge: + type: "exact" + - name: ten-by-five + in: + cost: + - [1, 50, 50, 50, 50] + - [2, 50, 50, 50, 50] + - [50, 1, 50, 50, 50] + - [50, 2, 50, 50, 50] + - [50, 50, 1, 50, 50] + - [50, 50, 2, 50, 50] + - [50, 50, 50, 1, 50] + - [50, 50, 50, 2, 50] + - [50, 50, 50, 50, 1] + - [50, 50, 50, 50, 2] + out: 15 + judge: + type: "exact" + - name: ten-by-ten-balanced + in: + cost: + - [0, 9, 8, 7, 6, 5, 4, 3, 2, 1] + - [1, 0, 9, 8, 7, 6, 5, 4, 3, 2] + - [2, 1, 0, 9, 8, 7, 6, 5, 4, 3] + - [3, 2, 1, 0, 9, 8, 7, 6, 5, 4] + - [4, 3, 2, 1, 0, 9, 8, 7, 6, 5] + - [5, 4, 3, 2, 1, 0, 9, 8, 7, 6] + - [6, 5, 4, 3, 2, 1, 0, 9, 8, 7] + - [7, 6, 5, 4, 3, 2, 1, 0, 9, 8] + - [8, 7, 6, 5, 4, 3, 2, 1, 0, 9] + - [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] + out: 0 + judge: + type: "exact" + - name: eleven-by-four + in: + cost: + - [17, 3, 12, 9] + - [4, 15, 8, 13] + - [11, 7, 2, 16] + - [9, 14, 6, 1] + - [5, 10, 18, 4] + - [13, 6, 9, 7] + - [8, 12, 5, 11] + - [2, 16, 13, 8] + - [14, 1, 10, 15] + - [6, 9, 4, 12] + - [10, 5, 7, 3] + out: 35 + judge: + type: "exact" + - name: eleven-by-seven + in: + cost: + - [6, 12, 3, 15, 9, 4, 11] + - [8, 2, 14, 7, 13, 5, 10] + - [11, 9, 1, 6, 8, 15, 4] + - [3, 7, 12, 2, 10, 6, 14] + - [15, 4, 8, 11, 1, 9, 7] + - [9, 6, 5, 14, 7, 2, 13] + - [4, 13, 10, 8, 6, 11, 3] + - [12, 1, 7, 9, 14, 5, 8] + - [7, 10, 4, 13, 3, 8, 6] + - [2, 8, 9, 5, 11, 7, 12] + - [10, 5, 13, 4, 9, 3, 15] + out: 23 + judge: + type: "exact" + - name: twelve-by-one + in: + cost: + - [100] + - [99] + - [98] + - [97] + - [96] + - [95] + - [94] + - [93] + - [92] + - [91] + - [90] + - [89] + out: 1134 + judge: + type: "exact" + - name: twelve-by-six + in: + cost: + - [18, 4, 12, 9, 7, 15] + - [6, 14, 3, 11, 8, 10] + - [13, 7, 16, 2, 9, 5] + - [10, 12, 4, 8, 1, 14] + - [5, 9, 11, 6, 13, 3] + - [15, 2, 8, 14, 4, 7] + - [9, 6, 5, 10, 12, 1] + - [3, 11, 14, 7, 6, 9] + - [12, 8, 2, 13, 5, 10] + - [7, 15, 9, 4, 11, 6] + - [4, 10, 7, 1, 14, 8] + - [11, 5, 13, 9, 3, 12] + out: 29 + judge: + type: "exact" + - name: twelve-by-twelve-high + in: + cost: + - [100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100] + - [100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89] + - [88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77] + - [76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65] + - [64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53] + - [52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41] + - [40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29] + - [28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17] + - [16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5] + - [4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7] + - [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] + - [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31] + out: 517 + judge: + type: "exact" + - name: duplicate-columns + in: + cost: + - [4, 4, 4] + - [1, 1, 1] + - [8, 8, 8] + - [2, 2, 2] + out: 15 + judge: + type: "exact" + - name: zero-column-coverage + in: + cost: + - [0, 100, 100, 100] + - [0, 100, 100, 100] + - [100, 0, 100, 100] + - [100, 100, 0, 100] + - [100, 100, 100, 0] + out: 0 + judge: + type: "exact" + - name: all-zero + in: + cost: + - [0, 0, 0] + - [0, 0, 0] + - [0, 0, 0] + - [0, 0, 0] + out: 0 + judge: + type: "exact" + - name: all-hundred + in: + cost: + - [100, 100] + - [100, 100] + - [100, 100] + out: 300 + judge: + type: "exact" diff --git a/tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.cpp b/tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.cpp new file mode 100644 index 00000000..8d7f0ae4 --- /dev/null +++ b/tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int connectTwoGroups(vector>& cost) { + int m = cost.size(); + int n = cost[0].size(); + vector mn(n); + for (int j = 0; j < n; j++) { + mn[j] = cost[0][j]; + for (int i = 1; i < m; i++) { + mn[j] = min(mn[j], cost[i][j]); + } + } + vector> memo(m+1, vector(1< fn = [&](int i, int mask) -> int { + if (memo[i][mask] != -1) return memo[i][mask]; + if (i == m) { + int sum = 0; + for (int j = 0; j < n; j++) { + if ((mask & (1<> cost) { + m = cost.Count; + n = cost[0].Count; + this.cost = new int[m][]; + for (int i = 0; i < m; i++) { + this.cost[i] = new int[n]; + for (int j = 0; j < n; j++) { + this.cost[i][j] = cost[i][j]; + } + } + mn = new int[n]; + for (int j = 0; j < n; j++) { + int minVal = this.cost[0][j]; + for (int i = 1; i < m; i++) { + minVal = Math.Min(minVal, this.cost[i][j]); + } + mn[j] = minVal; + } + memo = new int[m+1, 1<> cost) { + int m = cost.length; + int n = cost[0].length; + List mn = List.generate(n, (j) { + int minVal = cost[0][j]; + for (int i = 1; i < m; i++) { + if (cost[i][j] < minVal) minVal = cost[i][j]; + } + return minVal; + }); + List> memo = List.generate(m+1, (_) => List.filled(1<> 1) + for j := 0; j < n; j++ { + best = min(best, cost[i][j] + fn(i+1, mask | (1<> cost) { + m = cost.size(); + n = cost.get(0).size(); + this.cost = new int[m][n]; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + this.cost[i][j] = cost.get(i).get(j); + } + } + mn = new int[n]; + for (int j = 0; j < n; j++) { + int minVal = Integer.MAX_VALUE; + for (int i = 0; i < m; i++) { + minVal = Math.min(minVal, this.cost[i][j]); + } + mn[j] = minVal; + } + memo = new int[m+1][1<> rows = new java.util.ArrayList<>(); + for (int[] row : cost) { + List values = new java.util.ArrayList<>(); + for (int value : row) values.add(value); + rows.add(values); + } + return connectTwoGroups(rows); + } + private int fn(int i, int mask) { + if (memo[i][mask] != -1) return memo[i][mask]; + if (i == m) { + int sum = 0; + for (int j = 0; j < n; j++) { + if ((mask & (1<): Int { + return connectTwoGroups(cost.map { it.toList() }) + } + + fun connectTwoGroups(cost: List>): Int { + val m = cost.size + val n = cost[0].size + val mn = IntArray(n) { j -> (0 until m).map { cost[it][j] }.min()!! } + val memo = Array(m+1) { IntArray(1 shl n) { -1 } } + fun fn(i: Int, mask: Int): Int { + if (memo[i][mask] != -1) return memo[i][mask] + if (i == m) { + var sum = 0 + for (j in 0 until n) { + if ((mask and (1 shl j)) == 0) sum += mn[j] + } + memo[i][mask] = sum + } else { + var best = Int.MAX_VALUE + for (j in 0 until n) { + best = minOf(best, cost[i][j] + fn(i+1, mask or (1 shl j))) + } + memo[i][mask] = best + } + return memo[i][mask] + } + return fn(0, 0) + } +} diff --git a/tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.py b/tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.py new file mode 100644 index 00000000..f03b5bba --- /dev/null +++ b/tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.py @@ -0,0 +1,17 @@ +from functools import lru_cache +from typing import List + + +class Solution: + def connectTwoGroups(self, cost: List[List[int]]) -> int: + m, n = len(cost), len(cost[0]) + mn = [min(x) for x in zip(*cost)] # min cost of connecting points in 2nd group + + @lru_cache(None) + def fn(i, mask): + """Return min cost of connecting group1[i:] and group2 represented as mask.""" + if i == m: + return sum(mn[j] for j in range(n) if not (mask & (1 << j))) + return min(cost[i][j] + fn(i + 1, mask | 1 << j) for j in range(n)) + + return fn(0, 0) diff --git a/tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.py2 b/tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.py2 new file mode 100644 index 00000000..49e6e303 --- /dev/null +++ b/tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def connectTwoGroups(self, cost): + """ + :type cost: List[List[int]] + :rtype: int + """ + m, n = len(cost), len(cost[0]) + mn = [min(cost[i][j] for i in range(m)) for j in range(n)] + memo = {} + def fn(i, mask): + key = (i, mask) + if key in memo: + return memo[key] + if i == m: + result = sum(mn[j] for j in range(n) if not (mask & (1 << j))) + else: + result = min(cost[i][j] + fn(i+1, mask | (1 << j)) for j in range(n)) + memo[key] = result + return result + return fn(0, 0) diff --git a/tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.rb b/tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.rb new file mode 100644 index 00000000..e01acdc6 --- /dev/null +++ b/tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.rb @@ -0,0 +1,27 @@ +# @param {Integer[][]} cost +# @return {Integer} +def connect_two_groups(cost) + m = cost.length + n = cost[0].length + mn = Array.new(n) { |j| (0...m).map { |i| cost[i][j] }.min } + memo = {} + fn = lambda do |i, mask| + key = [i, mask] + return memo[key] if memo.key?(key) + if i == m + res = 0 + (0...n).each do |j| + res += mn[j] if (mask & (1 << j)) == 0 + end + memo[key] = res + else + res = Float::INFINITY + (0...n).each do |j| + val = cost[i][j] + fn.call(i+1, mask | (1 << j)) + res = [res, val].min + end + memo[key] = res + end + end + fn.call(0, 0) +end diff --git a/tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.rs b/tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.rs new file mode 100644 index 00000000..09f294a8 --- /dev/null +++ b/tests/1501-2000/1595. minimum-cost-to-connect-two-groups-of-points/sol.rs @@ -0,0 +1,35 @@ +impl Solution { + pub fn connect_two_groups(cost: Vec>) -> i32 { + let m = cost.len(); + let n = cost[0].len(); + let mut mn = vec![0; n]; + for j in 0..n { + let mut min_val = cost[0][j]; + for i in 1..m { + min_val = min_val.min(cost[i][j]); + } + mn[j] = min_val; + } + let mut memo = vec![vec![-1; 1<>, mn: &Vec, memo: &mut Vec>, m: usize, n: usize) -> i32 { + if memo[i][mask] != -1 { return memo[i][mask]; } + if i == m { + let mut sum = 0; + for j in 0..n { + if (mask & (1< Int { + let m = cost.count + let n = cost[0].count + var mn = [Int](repeating: 0, count: n) + for j in 0.. Int { + if memo[i][mask] != -1 { return memo[i][mask] } + if i == m { + var sum = 0 + for j in 0.. + new Array(1 << n).fill(-1), + ); + function fn(i: number, mask: number): number { + if (memo[i][mask] !== -1) return memo[i][mask]; + if (i === m) { + let sum = 0; + for (let j = 0; j < n; j++) { + if ((mask & (1 << j)) === 0) sum += mn[j]; + } + memo[i][mask] = sum; + } else { + let best = Infinity; + for (let j = 0; j < n; j++) { + best = Math.min(best, cost[i][j] + fn(i + 1, mask | (1 << j))); + } + memo[i][mask] = best; + } + return memo[i][mask]; + } + return fn(0, 0); +} diff --git a/tests/1501-2000/1598. crawler-log-folder/manifest.yaml b/tests/1501-2000/1598. crawler-log-folder/manifest.yaml new file mode 100644 index 00000000..0f229b5b --- /dev/null +++ b/tests/1501-2000/1598. crawler-log-folder/manifest.yaml @@ -0,0 +1,322 @@ +entry: + id: 1598 + title: "crawler-log-folder" + params: + logs: + type: array + items: + type: string + call: + cpp: "Solution().minOperations({logs})" + rust: "Solution::min_operations({logs})" + python3: "Solution().minOperations({logs})" + python2: "Solution().minOperations({logs})" + ruby: "min_operations({logs})" + java: "new Solution().minOperations({logs})" + csharp: "new Solution().MinOperations({logs})" + kotlin: "Solution().minOperations({logs})" + go: "minOperations({logs})" + dart: "Solution().minOperations({logs})" + swift: "Solution().minOperations({logs})" + typescript: "minOperations({logs})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minOperations(logs, {result})" + checker: | + class Checker: + def minOperations(self, logs, result): + depth = 0 + for operation in logs: + if operation == "../": + depth = max(0, depth - 1) + elif operation == "./": + continue + else: + if not isinstance(operation, str) or not operation.endswith("/"): + return False + name = operation[:-1] + if not name or any(ch not in "abcdefghijklmnopqrstuvwxyz0123456789" for ch in name): + return False + depth += 1 + return isinstance(result, int) and not isinstance(result, bool) and result == depth + +seed: 1598 + +tests: + - name: example-one + in: + logs: ["d1/", "d2/", "../", "d21/", "./"] + out: 2 + judge: + type: "exact" + - name: example-two + in: + logs: ["d1/", "d2/", "./", "d3/", "../", "d31/"] + out: 3 + judge: + type: "exact" + - name: example-three + in: + logs: ["d1/", "../", "../", "../"] + out: 0 + judge: + type: "exact" + - name: one-child + in: + logs: ["a/"] + out: 1 + judge: + type: "exact" + - name: one-parent-at-root + in: + logs: ["../"] + out: 0 + judge: + type: "exact" + - name: one-current + in: + logs: ["./"] + out: 0 + judge: + type: "exact" + - name: nested-three + in: + logs: ["a/", "b/", "c/"] + out: 3 + judge: + type: "exact" + - name: return-one-level + in: + logs: ["a/", "b/", "../"] + out: 1 + judge: + type: "exact" + - name: return-all-levels + in: + logs: ["a/", "b/", "c/", "../", "../", "../"] + out: 0 + judge: + type: "exact" + - name: root-parent-burst + in: + logs: ["../", "../", "../", "../"] + out: 0 + judge: + type: "exact" + - name: current-only-many + in: + logs: ["./", "./", "./", "./", "./"] + out: 0 + judge: + type: "exact" + - name: alternating-child-parent + in: + logs: ["a/", "../", "b/", "../", "c/", "../"] + out: 0 + judge: + type: "exact" + - name: child-after-root-parent + in: + logs: ["../", "x/", "../", "y/"] + out: 1 + judge: + type: "exact" + - name: deep-then-current + in: + logs: ["a/", "b/", "c/", "d/", "./", "./"] + out: 4 + judge: + type: "exact" + - name: deep-then-two-up + in: + logs: ["a/", "b/", "c/", "d/", "../", "../"] + out: 2 + judge: + type: "exact" + - name: repeated-same-name + in: + logs: ["a/", "a/", "a/", "../"] + out: 2 + judge: + type: "exact" + - name: digits-and-letters + in: + logs: ["a1/", "b2/", "../", "c3/"] + out: 2 + judge: + type: "exact" + - name: mixed-all-operations + in: + logs: ["a/", "./", "b/", "../", "../", "./", "c/"] + out: 1 + judge: + type: "exact" + - name: climb-and-descend + in: + logs: ["a/", "b/", "c/", "../", "d/", "../", "../"] + out: 1 + judge: + type: "exact" + - name: many-up-after-short-path + in: + logs: ["a/", "b/", "../", "../", "../", "c/", "d/"] + out: 2 + judge: + type: "exact" + - name: balanced-five + in: + logs: ["a/", "b/", "c/", "../", "../", "d/", "../", "../"] + out: 0 + judge: + type: "exact" + - name: final-parent-dominates + in: + logs: ["a/", "b/", "../", "../", "../", "e/"] + out: 1 + judge: + type: "exact" + - name: long-chain-ten + in: + logs: ["a/", "b/", "c/", "d/", "e/", "f/", "g/", "h/", "i/", "j/"] + out: 10 + judge: + type: "exact" + - name: long-chain-unwind + in: + logs: ["a/", "b/", "c/", "d/", "e/", "../", "../", "../", "../", "../"] + out: 0 + judge: + type: "exact" + - name: long-chain-partial-unwind + in: + logs: ["a/", "b/", "c/", "d/", "e/", "f/", "../", "../", "../"] + out: 3 + judge: + type: "exact" + - name: current-between-levels + in: + logs: ["a/", "./", "b/", "./", "c/", "../", "./"] + out: 2 + judge: + type: "exact" + - name: root-noise + in: + logs: ["./", "../", "./", "../", "x/", "../", "./"] + out: 0 + judge: + type: "exact" + - name: two-branches + in: + logs: ["left/", "leaf/", "../", "right/", "leaf/", "../", "../"] + out: 1 + judge: + type: "exact" + - name: branch-not-unwind + in: + logs: ["left/", "leaf/", "../", "right/", "leaf/"] + out: 3 + judge: + type: "exact" + - name: repeated-root-clamps + in: + logs: ["a/", "../", "../", "b/", "../", "../", "c/"] + out: 1 + judge: + type: "exact" + - name: names-with-digits + in: + logs: ["0/", "1a/", "z9/", "../", "../"] + out: 1 + judge: + type: "exact" + - name: twelve-operations + in: + logs: + [ + "a/", + "b/", + "./", + "../", + "c/", + "d/", + "../", + "../", + "../", + "e/", + "f/", + "../", + ] + out: 1 + judge: + type: "exact" + - name: deep-with-noise + in: + logs: ["a/", "./", "b/", "./", "c/", "../", "d/", "../", "e/", "../"] + out: 2 + judge: + type: "exact" + - name: partial-return-with-noise + in: + logs: ["a/", "b/", "./", "c/", "../", "./", "d/", "../"] + out: 2 + judge: + type: "exact" + - name: fifteen-mixed + in: + logs: + [ + "a/", + "b/", + "../", + "c/", + "d/", + "./", + "../", + "e/", + "../", + "../", + "f/", + "g/", + "../", + "h/", + "../", + ] + out: 2 + judge: + type: "exact" + - name: twenty-mixed + in: + logs: + [ + "a/", + "b/", + "c/", + "../", + "./", + "d/", + "../", + "e/", + "f/", + "../", + "../", + "g/", + "./", + "h/", + "../", + "i/", + "../", + "../", + "j/", + "../", + ] + out: 2 + judge: + type: "exact" diff --git a/tests/1501-2000/1598. crawler-log-folder/sol.cpp b/tests/1501-2000/1598. crawler-log-folder/sol.cpp new file mode 100644 index 00000000..23961c76 --- /dev/null +++ b/tests/1501-2000/1598. crawler-log-folder/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int minOperations(vector& logs) { + int output = 0; + for (string& log : logs) { + if (log == "../") { + output--; + if (output < 0) output = 0; + } else if (log == "./") { + continue; + } else { + output++; + } + } + return output < 0 ? 0 : output; + } +}; diff --git a/tests/1501-2000/1598. crawler-log-folder/sol.cs b/tests/1501-2000/1598. crawler-log-folder/sol.cs new file mode 100644 index 00000000..2486a3dc --- /dev/null +++ b/tests/1501-2000/1598. crawler-log-folder/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public int MinOperations(string[] logs) { + int output = 0; + foreach (string log in logs) { + if (log == "../") { + output--; + if (output < 0) output = 0; + } else if (log == "./") { + continue; + } else { + output++; + } + } + return output < 0 ? 0 : output; + } +} diff --git a/tests/1501-2000/1598. crawler-log-folder/sol.dart b/tests/1501-2000/1598. crawler-log-folder/sol.dart new file mode 100644 index 00000000..16e35d5f --- /dev/null +++ b/tests/1501-2000/1598. crawler-log-folder/sol.dart @@ -0,0 +1,16 @@ +class Solution { + int minOperations(List logs) { + int output = 0; + for (String log in logs) { + if (log == "../") { + output--; + if (output < 0) output = 0; + } else if (log == "./") { + continue; + } else { + output++; + } + } + return output < 0 ? 0 : output; + } +} diff --git a/tests/1501-2000/1598. crawler-log-folder/sol.go b/tests/1501-2000/1598. crawler-log-folder/sol.go new file mode 100644 index 00000000..6cbe1b19 --- /dev/null +++ b/tests/1501-2000/1598. crawler-log-folder/sol.go @@ -0,0 +1,19 @@ +func minOperations(logs []string) int { + output := 0 + for _, log := range logs { + if log == "../" { + output-- + if output < 0 { + output = 0 + } + } else if log == "./" { + continue + } else { + output++ + } + } + if output < 0 { + return 0 + } + return output +} diff --git a/tests/1501-2000/1598. crawler-log-folder/sol.java b/tests/1501-2000/1598. crawler-log-folder/sol.java new file mode 100644 index 00000000..ff0fc77a --- /dev/null +++ b/tests/1501-2000/1598. crawler-log-folder/sol.java @@ -0,0 +1,16 @@ +class Solution { + public int minOperations(String[] logs) { + int output = 0; + for (String log : logs) { + if (log.equals("../")) { + output--; + if (output < 0) output = 0; + } else if (log.equals("./")) { + continue; + } else { + output++; + } + } + return output < 0 ? 0 : output; + } +} diff --git a/tests/1501-2000/1598. crawler-log-folder/sol.kt b/tests/1501-2000/1598. crawler-log-folder/sol.kt new file mode 100644 index 00000000..76b4e473 --- /dev/null +++ b/tests/1501-2000/1598. crawler-log-folder/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun minOperations(logs: Array): Int { + var output = 0 + for (log in logs) { + if (log == "../") { + output-- + if (output < 0) output = 0 + } else if (log == "./") { + continue + } else { + output++ + } + } + return if (output < 0) 0 else output + } +} diff --git a/tests/1501-2000/1598. crawler-log-folder/sol.py b/tests/1501-2000/1598. crawler-log-folder/sol.py new file mode 100644 index 00000000..e92dc647 --- /dev/null +++ b/tests/1501-2000/1598. crawler-log-folder/sol.py @@ -0,0 +1,16 @@ +class Solution: + def minOperations(self, logs: List[str]) -> int: + output = 0 + for i in logs: + if i == "../": + output -= 1 + if output < 0: + output = 0 + elif i == "./": + continue + else: + output += 1 + if output < 0: + return 0 + else: + return output diff --git a/tests/1501-2000/1598. crawler-log-folder/sol.py2 b/tests/1501-2000/1598. crawler-log-folder/sol.py2 new file mode 100644 index 00000000..bad05944 --- /dev/null +++ b/tests/1501-2000/1598. crawler-log-folder/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def minOperations(self, logs): + """ + :type logs: List[str] + :rtype: int + """ + output = 0 + for i in logs : + if i == "../" : + output -= 1 + if output < 0 : + output = 0 + elif i == "./" : + continue + else : + output += 1 + if output < 0 : + return 0 + else : + return output diff --git a/tests/1501-2000/1598. crawler-log-folder/sol.rb b/tests/1501-2000/1598. crawler-log-folder/sol.rb new file mode 100644 index 00000000..970c68e9 --- /dev/null +++ b/tests/1501-2000/1598. crawler-log-folder/sol.rb @@ -0,0 +1,16 @@ +# @param {String[]} logs +# @return {Integer} +def min_operations(logs) + output = 0 + logs.each do |log| + if log == "../" + output -= 1 + output = 0 if output < 0 + elsif log == "./" + next + else + output += 1 + end + end + output < 0 ? 0 : output +end diff --git a/tests/1501-2000/1598. crawler-log-folder/sol.rs b/tests/1501-2000/1598. crawler-log-folder/sol.rs new file mode 100644 index 00000000..ccb14c29 --- /dev/null +++ b/tests/1501-2000/1598. crawler-log-folder/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn min_operations(logs: Vec) -> i32 { + let mut output = 0; + for log in logs { + if log == "../" { + output -= 1; + if output < 0 { output = 0; } + } else if log == "./" { + continue; + } else { + output += 1; + } + } + if output < 0 { 0 } else { output } + } +} diff --git a/tests/1501-2000/1598. crawler-log-folder/sol.swift b/tests/1501-2000/1598. crawler-log-folder/sol.swift new file mode 100644 index 00000000..c365f9ac --- /dev/null +++ b/tests/1501-2000/1598. crawler-log-folder/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func minOperations(_ logs: [String]) -> Int { + var output = 0 + for log in logs { + if log == "../" { + output -= 1 + if output < 0 { output = 0 } + } else if log == "./" { + continue + } else { + output += 1 + } + } + return output < 0 ? 0 : output + } +} diff --git a/tests/1501-2000/1598. crawler-log-folder/sol.ts b/tests/1501-2000/1598. crawler-log-folder/sol.ts new file mode 100644 index 00000000..073c1fef --- /dev/null +++ b/tests/1501-2000/1598. crawler-log-folder/sol.ts @@ -0,0 +1,14 @@ +function minOperations(logs: string[]): number { + let output = 0; + for (let log of logs) { + if (log === "../") { + output--; + if (output < 0) output = 0; + } else if (log === "./") { + continue; + } else { + output++; + } + } + return output < 0 ? 0 : output; +} diff --git a/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/manifest.yaml b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/manifest.yaml new file mode 100644 index 00000000..52783049 --- /dev/null +++ b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/manifest.yaml @@ -0,0 +1,368 @@ +entry: + id: 1599 + title: "maximum-profit-of-operating-a-centennial-wheel" + params: + customers: + type: array + items: + type: int + boardingCost: + type: int + runningCost: + type: int + call: + cpp: "Solution().minOperationsMaxProfit({customers}, {boardingCost}, {runningCost})" + rust: "Solution::min_operations_max_profit({customers}, {boardingCost}, {runningCost})" + python3: "Solution().minOperationsMaxProfit({customers}, {boardingCost}, {runningCost})" + python2: "Solution().minOperationsMaxProfit({customers}, {boardingCost}, {runningCost})" + ruby: "min_operations_max_profit({customers}, {boardingCost}, {runningCost})" + java: "new Solution().minOperationsMaxProfit({customers}, {boardingCost}, {runningCost})" + csharp: "new Solution().MinOperationsMaxProfit({customers}, {boardingCost}, {runningCost})" + kotlin: "Solution().minOperationsMaxProfit({customers}, {boardingCost}, {runningCost})" + go: "minOperationsMaxProfit({customers}, {boardingCost}, {runningCost})" + dart: "Solution().minOperationsMaxProfit({customers}, {boardingCost}, {runningCost})" + swift: "Solution().minOperationsMaxProfit({customers}, {boardingCost}, {runningCost})" + typescript: "minOperationsMaxProfit({customers}, {boardingCost}, {runningCost})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().minOperationsMaxProfit(customers, boardingCost, runningCost, {result})" + checker: | + class Checker: + def minOperationsMaxProfit(self, customers, boardingCost, runningCost, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + waiting = 0 + profit = 0 + best_profit = 0 + expected = -1 + index = 0 + rotations = 0 + while index < len(customers) or waiting > 0: + if index < len(customers): + waiting += customers[index] + boarded = min(4, waiting) + waiting -= boarded + rotations += 1 + profit += boarded * boardingCost - runningCost + if profit > best_profit: + best_profit = profit + expected = rotations + index += 1 + return result == expected + +seed: 1599 + +tests: + - name: example-one + in: + customers: [8, 3] + boardingCost: 5 + runningCost: 6 + out: 3 + - name: example-two + in: + customers: [10, 9, 6] + boardingCost: 6 + runningCost: 4 + out: 7 + - name: example-three-no-profit + in: + customers: [3, 4, 0, 5, 1] + boardingCost: 1 + runningCost: 92 + out: -1 + - name: one-customer-profitable + in: + customers: [1] + boardingCost: 10 + runningCost: 1 + out: 1 + - name: one-empty-arrival + in: + customers: [0] + boardingCost: 10 + runningCost: 1 + out: -1 + - name: one-customer-unprofitable + in: + customers: [4] + boardingCost: 5 + runningCost: 20 + out: -1 + - name: one-full-gondola + in: + customers: [20] + boardingCost: 5 + runningCost: 1 + out: 5 + - name: sparse-small-arrivals + in: + customers: [1, 1, 1, 1] + boardingCost: 2 + runningCost: 1 + out: 4 + - name: repeated-full-gondolas + in: + customers: [4, 4, 4, 4] + boardingCost: 5 + runningCost: 10 + out: 4 + - name: backlog-then-idle + in: + customers: [8, 0, 0] + boardingCost: 5 + runningCost: 6 + out: 2 + - name: idle-before-arrival + in: + customers: [0, 0, 10] + boardingCost: 5 + runningCost: 6 + out: 5 + - name: steady-small-backlog + in: + customers: [2, 2, 2, 2, 2] + boardingCost: 5 + runningCost: 3 + out: 5 + - name: maximum-boarding-minimum-running + in: + customers: [50] + boardingCost: 100 + runningCost: 1 + out: 13 + - name: maximum-running-no-profit + in: + customers: [50] + boardingCost: 1 + runningCost: 100 + out: -1 + - name: increasing-arrivals + in: + customers: [1, 2, 3, 4, 5] + boardingCost: 4 + runningCost: 4 + out: 5 + - name: initial-backlog-with-idle-tail + in: + customers: [5, 0, 0, 0, 0] + boardingCost: 10 + runningCost: 1 + out: 2 + - name: alternating-arrivals + in: + customers: [0, 5, 0, 5, 0] + boardingCost: 10 + runningCost: 2 + out: 5 + - name: profitable-bursts + in: + customers: [7, 1, 7] + boardingCost: 8 + runningCost: 7 + out: 4 + - name: large-second-arrival + in: + customers: [2, 10, 0, 0] + boardingCost: 6 + runningCost: 5 + out: 4 + - name: six-steady-arrivals + in: + customers: [3, 3, 3, 3, 3, 3] + boardingCost: 7 + runningCost: 8 + out: 6 + - name: two-large-arrivals + in: + customers: [9, 9] + boardingCost: 5 + runningCost: 5 + out: 5 + - name: delayed-single-profit + in: + customers: [6, 0, 0, 0, 0, 0] + boardingCost: 5 + runningCost: 5 + out: 2 + - name: profitable-final-arrival + in: + customers: [1, 0, 0, 0, 0, 1] + boardingCost: 5 + runningCost: 4 + out: 1 + - name: three-heavy-arrivals + in: + customers: [10, 10, 10] + boardingCost: 3 + runningCost: 5 + out: 8 + - name: alternating-low-profit + in: + customers: [0, 1, 0, 1, 0, 1] + boardingCost: 20 + runningCost: 10 + out: -1 + - name: small-backlog + in: + customers: [4, 1, 0] + boardingCost: 5 + runningCost: 5 + out: 1 + - name: four-customer-backlog + in: + customers: [12, 0, 0, 0] + boardingCost: 6 + runningCost: 7 + out: 3 + - name: low-fare-steady + in: + customers: [2, 2, 2] + boardingCost: 1 + runningCost: 1 + out: 3 + - name: repeated-overflow + in: + customers: [40, 40, 40, 40] + boardingCost: 9 + runningCost: 20 + out: 40 + - name: burst-with-gaps + in: + customers: [1, 50, 1] + boardingCost: 7 + runningCost: 6 + out: 14 + - name: all-empty + in: + customers: [0, 0, 0, 0, 0] + boardingCost: 100 + runningCost: 1 + out: -1 + - name: descending-arrivals + in: + customers: [5, 4, 3, 2, 1] + boardingCost: 3 + runningCost: 4 + out: 4 + - name: long-initial-backlog + in: + customers: [15, 0, 0, 0, 0] + boardingCost: 4 + runningCost: 3 + out: 4 + - name: five-full-rotations + in: + customers: [6, 6, 6, 6, 6] + boardingCost: 4 + runningCost: 4 + out: 8 + - name: mixed-bursts + in: + customers: [3, 0, 7, 0, 2] + boardingCost: 6 + runningCost: 5 + out: 5 + - name: generated-short + in: + customers: + gen: "array" + len: 17 + of: + gen: "int" + min: 0 + max: 50 + elemType: "int" + boardingCost: + gen: "int" + min: 1 + max: 100 + runningCost: + gen: "int" + min: 1 + max: 100 + seed: 159901 + - name: generated-medium + in: + customers: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 50 + elemType: "int" + boardingCost: + gen: "int" + min: 1 + max: 100 + runningCost: + gen: "int" + min: 1 + max: 100 + seed: 159902 + - name: generated-large-one + in: + customers: + gen: "array" + len: 50000 + of: + gen: "int" + min: 0 + max: 50 + elemType: "int" + boardingCost: + gen: "int" + min: 1 + max: 100 + runningCost: + gen: "int" + min: 1 + max: 100 + seed: 159903 + - name: generated-large-two + in: + customers: + gen: "array" + len: 100000 + of: + gen: "int" + min: 0 + max: 50 + elemType: "int" + boardingCost: + gen: "int" + min: 1 + max: 100 + runningCost: + gen: "int" + min: 1 + max: 100 + seed: 159904 + - name: generated-boundary-values + in: + customers: + gen: "array" + len: 100000 + of: + gen: "int" + min: 0 + max: 50 + elemType: "int" + boardingCost: + gen: "int" + min: 1 + max: 100 + runningCost: + gen: "int" + min: 1 + max: 100 + seed: 159905 diff --git a/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.cpp b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.cpp new file mode 100644 index 00000000..cc2b83b7 --- /dev/null +++ b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int minOperationsMaxProfit(vector& customers, int boardingCost, int runningCost) { + int wait = 0; + int profit = 0; + int maxProfit = 0; + int ans = -1; + int i = 0; + int rotation = 0; + + while (i < customers.size() || wait > 0) { + if (i < customers.size()) { + wait += customers[i]; + } + int boarded = min(4, wait); + wait -= boarded; + + rotation++; + profit += boarded * boardingCost - runningCost; + + if (profit > maxProfit) { + maxProfit = profit; + ans = rotation; + } + + i++; + } + + return ans; + } +}; diff --git a/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.cs b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.cs new file mode 100644 index 00000000..aec37d6d --- /dev/null +++ b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.cs @@ -0,0 +1,30 @@ +public class Solution { + public int MinOperationsMaxProfit(int[] customers, int boardingCost, int runningCost) { + int wait = 0; + int profit = 0; + int maxProfit = 0; + int ans = -1; + int i = 0; + int rotation = 0; + + while (i < customers.Length || wait > 0) { + if (i < customers.Length) { + wait += customers[i]; + } + int boarded = Math.Min(4, wait); + wait -= boarded; + + rotation++; + profit += boarded * boardingCost - runningCost; + + if (profit > maxProfit) { + maxProfit = profit; + ans = rotation; + } + + i++; + } + + return ans; + } +} diff --git a/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.dart b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.dart new file mode 100644 index 00000000..7faa236a --- /dev/null +++ b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.dart @@ -0,0 +1,30 @@ +class Solution { + int minOperationsMaxProfit(List customers, int boardingCost, int runningCost) { + int wait = 0; + int profit = 0; + int maxProfit = 0; + int ans = -1; + int i = 0; + int rotation = 0; + + while (i < customers.length || wait > 0) { + if (i < customers.length) { + wait += customers[i]; + } + int boarded = wait < 4 ? wait : 4; + wait -= boarded; + + rotation++; + profit += boarded * boardingCost - runningCost; + + if (profit > maxProfit) { + maxProfit = profit; + ans = rotation; + } + + i++; + } + + return ans; + } +} diff --git a/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.go b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.go new file mode 100644 index 00000000..c7792568 --- /dev/null +++ b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.go @@ -0,0 +1,31 @@ +func minOperationsMaxProfit(customers []int, boardingCost int, runningCost int) int { + wait := 0 + profit := 0 + maxProfit := 0 + ans := -1 + i := 0 + rotation := 0 + + for i < len(customers) || wait > 0 { + if i < len(customers) { + wait += customers[i] + } + boarded := wait + if boarded > 4 { + boarded = 4 + } + wait -= boarded + + rotation++ + profit += boarded*boardingCost - runningCost + + if profit > maxProfit { + maxProfit = profit + ans = rotation + } + + i++ + } + + return ans +} diff --git a/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.java b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.java new file mode 100644 index 00000000..55eddd9c --- /dev/null +++ b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.java @@ -0,0 +1,30 @@ +class Solution { + public int minOperationsMaxProfit(int[] customers, int boardingCost, int runningCost) { + int wait = 0; + int profit = 0; + int maxProfit = 0; + int ans = -1; + int i = 0; + int rotation = 0; + + while (i < customers.length || wait > 0) { + if (i < customers.length) { + wait += customers[i]; + } + int boarded = Math.min(4, wait); + wait -= boarded; + + rotation++; + profit += boarded * boardingCost - runningCost; + + if (profit > maxProfit) { + maxProfit = profit; + ans = rotation; + } + + i++; + } + + return ans; + } +} diff --git a/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.kt b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.kt new file mode 100644 index 00000000..a5a44386 --- /dev/null +++ b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.kt @@ -0,0 +1,30 @@ +class Solution { + fun minOperationsMaxProfit(customers: IntArray, boardingCost: Int, runningCost: Int): Int { + var wait = 0 + var profit = 0 + var maxProfit = 0 + var ans = -1 + var i = 0 + var rotation = 0 + + while (i < customers.size || wait > 0) { + if (i < customers.size) { + wait += customers[i] + } + val boarded = minOf(4, wait) + wait -= boarded + + rotation++ + profit += boarded * boardingCost - runningCost + + if (profit > maxProfit) { + maxProfit = profit + ans = rotation + } + + i++ + } + + return ans + } +} diff --git a/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.py b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.py new file mode 100644 index 00000000..5af9dc68 --- /dev/null +++ b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.py @@ -0,0 +1,31 @@ +class Solution(object): + def minOperationsMaxProfit(self, customers, boardingCost, runningCost): + """ + :type customers: List[int] + :type boardingCost: int + :type runningCost: int + :rtype: int + """ + wait = 0 + profit = 0 + max_profit = 0 + ans = -1 + i = 0 + rotation = 0 + + while i < len(customers) or wait > 0: + if i < len(customers): + wait += customers[i] + boarded = min(4, wait) + wait -= boarded + + rotation += 1 + profit += boarded * boardingCost - runningCost + + if profit > max_profit: + max_profit = profit + ans = rotation + + i += 1 + + return ans diff --git a/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.py2 b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.py2 new file mode 100644 index 00000000..5af9dc68 --- /dev/null +++ b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.py2 @@ -0,0 +1,31 @@ +class Solution(object): + def minOperationsMaxProfit(self, customers, boardingCost, runningCost): + """ + :type customers: List[int] + :type boardingCost: int + :type runningCost: int + :rtype: int + """ + wait = 0 + profit = 0 + max_profit = 0 + ans = -1 + i = 0 + rotation = 0 + + while i < len(customers) or wait > 0: + if i < len(customers): + wait += customers[i] + boarded = min(4, wait) + wait -= boarded + + rotation += 1 + profit += boarded * boardingCost - runningCost + + if profit > max_profit: + max_profit = profit + ans = rotation + + i += 1 + + return ans diff --git a/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.rb b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.rb new file mode 100644 index 00000000..80b33021 --- /dev/null +++ b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.rb @@ -0,0 +1,30 @@ +# @param {Integer[]} customers +# @param {Integer} boarding_cost +# @param {Integer} running_cost +# @return {Integer} +def min_operations_max_profit(customers, boarding_cost, running_cost) + wait = 0 + profit = 0 + max_profit = 0 + ans = -1 + i = 0 + rotation = 0 + + while i < customers.length || wait > 0 + wait += customers[i] if i < customers.length + boarded = [4, wait].min + wait -= boarded + + rotation += 1 + profit += boarded * boarding_cost - running_cost + + if profit > max_profit + max_profit = profit + ans = rotation + end + + i += 1 + end + + ans +end diff --git a/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.rs b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.rs new file mode 100644 index 00000000..79da42b9 --- /dev/null +++ b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.rs @@ -0,0 +1,30 @@ +impl Solution { + pub fn min_operations_max_profit(customers: Vec, boarding_cost: i32, running_cost: i32) -> i32 { + let mut wait = 0; + let mut profit = 0; + let mut max_profit = 0; + let mut ans = -1; + let mut i = 0; + let mut rotation = 0; + + while i < customers.len() || wait > 0 { + if i < customers.len() { + wait += customers[i]; + } + let boarded = wait.min(4); + wait -= boarded; + + rotation += 1; + profit += boarded * boarding_cost - running_cost; + + if profit > max_profit { + max_profit = profit; + ans = rotation; + } + + i += 1; + } + + ans + } +} diff --git a/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.swift b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.swift new file mode 100644 index 00000000..ebee64f6 --- /dev/null +++ b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.swift @@ -0,0 +1,30 @@ +class Solution { + func minOperationsMaxProfit(_ customers: [Int], _ boardingCost: Int, _ runningCost: Int) -> Int { + var wait = 0 + var profit = 0 + var maxProfit = 0 + var ans = -1 + var i = 0 + var rotation = 0 + + while i < customers.count || wait > 0 { + if i < customers.count { + wait += customers[i] + } + let boarded = min(4, wait) + wait -= boarded + + rotation += 1 + profit += boarded * boardingCost - runningCost + + if profit > maxProfit { + maxProfit = profit + ans = rotation + } + + i += 1 + } + + return ans + } +} diff --git a/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.ts b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.ts new file mode 100644 index 00000000..131f9897 --- /dev/null +++ b/tests/1501-2000/1599. maximum-profit-of-operating-a-centennial-wheel/sol.ts @@ -0,0 +1,32 @@ +function minOperationsMaxProfit( + customers: number[], + boardingCost: number, + runningCost: number, +): number { + let wait = 0; + let profit = 0; + let maxProfit = 0; + let ans = -1; + let i = 0; + let rotation = 0; + + while (i < customers.length || wait > 0) { + if (i < customers.length) { + wait += customers[i]; + } + let boarded = Math.min(4, wait); + wait -= boarded; + + rotation += 1; + profit += boarded * boardingCost - runningCost; + + if (profit > maxProfit) { + maxProfit = profit; + ans = rotation; + } + + i += 1; + } + + return ans; +} diff --git a/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/manifest.yaml b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/manifest.yaml new file mode 100644 index 00000000..2b1682ad --- /dev/null +++ b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/manifest.yaml @@ -0,0 +1,600 @@ +entry: + id: 1601 + title: "maximum-number-of-achievable-transfer-requests" + params: + n: + type: int + requests: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().maximumRequests({n}, {requests})" + rust: "Solution::maximum_requests({n}, {requests})" + python3: "Solution().maximumRequests({n}, {requests})" + python2: "Solution().maximumRequests({n}, {requests})" + ruby: "maximum_requests({n}, {requests})" + java: "new Solution().maximumRequests({n}, {requests})" + csharp: "new Solution().MaximumRequests({n}, {requests})" + kotlin: "Solution().maximumRequests({n}, {requests})" + go: "maximumRequests({n}, {requests})" + dart: "Solution().maximumRequests({n}, {requests})" + swift: "Solution().maximumRequests({n}, {requests})" + typescript: "maximumRequests({n}, {requests})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().maximumRequests(n, requests, {result})" + checker: | + class Checker: + def maximumRequests(self, n, requests, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not (1 <= n <= 20) or not (1 <= len(requests) <= 16): + return False + best = 0 + for mask in range(1 << len(requests)): + balance = [0] * n + count = 0 + for i, pair in enumerate(requests): + if (mask >> i) & 1: + a, b = pair + balance[a] -= 1 + balance[b] += 1 + count += 1 + if all(value == 0 for value in balance): + best = max(best, count) + return result == best + +seed: 1601 + +tests: + - name: "example_one" + in: + n: 5 + requests: + elemType: "int" + value: + - [0, 1] + - [1, 0] + - [0, 1] + - [1, 2] + - [2, 0] + - [3, 4] + out: 5 + - name: "example_two" + in: + n: 3 + requests: + elemType: "int" + value: + - [0, 0] + - [1, 2] + - [2, 1] + out: 3 + - name: "example_three" + in: + n: 4 + requests: + elemType: "int" + value: + - [0, 3] + - [3, 1] + - [1, 2] + - [2, 0] + out: 4 + - name: "single_unbalanced" + in: + n: 2 + requests: + elemType: "int" + value: + - [0, 1] + out: 0 + - name: "single_swap" + in: + n: 2 + requests: + elemType: "int" + value: + - [0, 1] + - [1, 0] + out: 2 + - name: "single_self_request" + in: + n: 4 + requests: + elemType: "int" + value: + - [0, 0] + out: 1 + - name: "open_chain" + in: + n: 4 + requests: + elemType: "int" + value: + - [0, 1] + - [1, 2] + - [2, 3] + out: 0 + - name: "three_cycle" + in: + n: 4 + requests: + elemType: "int" + value: + - [0, 1] + - [1, 2] + - [2, 0] + out: 3 + - name: "two_disjoint_swaps" + in: + n: 5 + requests: + elemType: "int" + value: + - [0, 1] + - [1, 0] + - [2, 3] + - [3, 2] + out: 4 + - name: "six_cycle" + in: + n: 6 + requests: + elemType: "int" + value: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 0] + out: 6 + - name: "duplicate_direction" + in: + n: 3 + requests: + elemType: "int" + value: + - [0, 1] + - [0, 1] + - [1, 0] + - [2, 2] + out: 3 + - name: "cycle_with_self" + in: + n: 4 + requests: + elemType: "int" + value: + - [0, 1] + - [0, 1] + - [1, 2] + - [2, 0] + - [3, 3] + out: 4 + - name: "two_cycles_and_self" + in: + n: 5 + requests: + elemType: "int" + value: + - [0, 2] + - [2, 0] + - [1, 3] + - [3, 1] + - [4, 4] + out: 5 + - name: "cycle_and_self_pair" + in: + n: 6 + requests: + elemType: "int" + value: + - [0, 1] + - [1, 0] + - [2, 3] + - [3, 4] + - [4, 2] + - [5, 5] + out: 6 + - name: "many_swaps" + in: + n: 7 + requests: + elemType: "int" + value: + - [0, 1] + - [1, 0] + - [1, 2] + - [2, 1] + - [3, 4] + - [4, 3] + - [5, 6] + - [6, 5] + out: 8 + - name: "two_cycles_and_open_edge" + in: + n: 8 + requests: + elemType: "int" + value: + - [0, 1] + - [1, 2] + - [2, 0] + - [3, 4] + - [4, 5] + - [5, 3] + - [6, 7] + out: 6 + - name: "four_requests_each_way" + in: + n: 4 + requests: + elemType: "int" + value: + - [0, 1] + - [1, 0] + - [0, 1] + - [1, 0] + - [2, 3] + - [3, 2] + out: 6 + - name: "cycle_with_extra_pair" + in: + n: 5 + requests: + elemType: "int" + value: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 0] + - [0, 2] + - [2, 0] + out: 7 + - name: "self_requests_and_swap" + in: + n: 3 + requests: + elemType: "int" + value: + - [0, 0] + - [1, 1] + - [2, 2] + - [0, 1] + - [1, 0] + out: 5 + - name: "ten_cycle" + in: + n: 10 + requests: + elemType: "int" + value: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 0] + out: 10 + - name: "swaps_and_self_requests" + in: + n: 6 + requests: + elemType: "int" + value: + - [0, 1] + - [1, 0] + - [2, 2] + - [3, 4] + - [4, 3] + - [5, 5] + out: 6 + - name: "mixed_cycles" + in: + n: 5 + requests: + elemType: "int" + value: + - [0, 4] + - [4, 0] + - [1, 3] + - [3, 1] + - [2, 2] + - [0, 2] + - [2, 0] + out: 7 + - name: "overlapping_cycles" + in: + n: 4 + requests: + elemType: "int" + value: + - [0, 2] + - [2, 1] + - [1, 0] + - [0, 3] + - [3, 0] + out: 5 + - name: "reverse_cycle" + in: + n: 6 + requests: + elemType: "int" + value: + - [0, 5] + - [5, 4] + - [4, 3] + - [3, 2] + - [2, 1] + - [1, 0] + out: 6 + - name: "self_requests_with_swap" + in: + n: 7 + requests: + elemType: "int" + value: + - [0, 0] + - [1, 1] + - [2, 2] + - [3, 3] + - [4, 5] + - [5, 4] + - [6, 6] + out: 7 + - name: "three_swaps_and_self" + in: + n: 8 + requests: + elemType: "int" + value: + - [0, 1] + - [1, 0] + - [2, 3] + - [3, 2] + - [4, 5] + - [5, 6] + - [6, 4] + - [7, 7] + out: 8 + - name: "three_disjoint_cycles" + in: + n: 9 + requests: + elemType: "int" + value: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 0] + - [4, 5] + - [5, 4] + - [6, 7] + - [7, 8] + - [8, 6] + out: 9 + - name: "reverse_ten_cycle" + in: + n: 10 + requests: + elemType: "int" + value: + - [0, 9] + - [9, 8] + - [8, 7] + - [7, 6] + - [6, 5] + - [5, 4] + - [4, 3] + - [3, 2] + - [2, 1] + - [1, 0] + out: 10 + - name: "cycle_with_chord" + in: + n: 3 + requests: + elemType: "int" + value: + - [0, 1] + - [1, 2] + - [2, 0] + - [0, 2] + out: 3 + - name: "cycle_and_extra_edge" + in: + n: 5 + requests: + elemType: "int" + value: + - [0, 1] + - [1, 0] + - [2, 3] + - [3, 4] + - [4, 2] + - [0, 4] + out: 5 + - name: "two_cycles_with_cross_swap" + in: + n: 6 + requests: + elemType: "int" + value: + - [0, 2] + - [2, 4] + - [4, 0] + - [1, 3] + - [3, 5] + - [5, 1] + - [0, 1] + - [1, 0] + out: 8 + - name: "self_requests_and_partial_swap" + in: + n: 4 + requests: + elemType: "int" + value: + - [0, 0] + - [1, 1] + - [2, 2] + - [3, 3] + - [0, 1] + - [1, 0] + - [2, 3] + out: 6 + - name: "two_four_cycles" + in: + n: 8 + requests: + elemType: "int" + value: + - [0, 2] + - [2, 4] + - [4, 6] + - [6, 0] + - [1, 3] + - [3, 5] + - [5, 7] + - [7, 1] + out: 8 + - name: "four_swaps_and_open_request" + in: + n: 10 + requests: + elemType: "int" + value: + - [0, 1] + - [1, 0] + - [2, 3] + - [3, 2] + - [4, 5] + - [5, 4] + - [6, 7] + - [7, 6] + - [8, 9] + out: 8 + - name: "maximum_n_open_chain" + in: + n: 20 + requests: + elemType: "int" + value: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [11, 12] + - [12, 13] + - [13, 14] + - [14, 15] + - [15, 16] + out: 0 + - name: "maximum_n_self_and_swaps" + in: + n: 20 + requests: + elemType: "int" + value: + - [0, 0] + - [1, 1] + - [2, 2] + - [3, 3] + - [4, 4] + - [5, 5] + - [6, 6] + - [7, 7] + - [8, 8] + - [9, 9] + - [10, 11] + - [11, 10] + - [12, 13] + - [13, 12] + - [14, 15] + - [15, 14] + out: 16 + - name: "generated_small" + seed: 16011 + in: + n: 20 + requests: + gen: "array" + len: 16 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 19 + elemType: "int" + - name: "generated_medium" + seed: 16012 + in: + n: 20 + requests: + gen: "array" + len: 16 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 19 + elemType: "int" + - name: "generated_duplicates" + seed: 16013 + in: + n: 20 + requests: + gen: "array" + len: 16 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 19 + elemType: "int" + - name: "generated_boundary_buildings" + seed: 16014 + in: + n: 20 + requests: + gen: "array" + len: 16 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 19 + elemType: "int" diff --git a/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.cpp b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.cpp new file mode 100644 index 00000000..79ee0685 --- /dev/null +++ b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int maximumRequests(int n, vector>& requests) { + ans = 0; + vector indegree(n, 0); + helper(0, requests, indegree, n, 0); + return ans; + } + +private: + int ans; + + void helper(int start, vector>& requests, vector& indegree, int n, int count) { + if (start == requests.size()) { + for (int i = 0; i < n; i++) { + if (indegree[i] != 0) return; + } + ans = max(ans, count); + return; + } + + // Take + indegree[requests[start][0]]--; + indegree[requests[start][1]]++; + helper(start + 1, requests, indegree, n, count + 1); + + // Not-take + indegree[requests[start][0]]++; + indegree[requests[start][1]]--; + helper(start + 1, requests, indegree, n, count); + } +}; diff --git a/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.cs b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.cs new file mode 100644 index 00000000..47b03807 --- /dev/null +++ b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.cs @@ -0,0 +1,29 @@ +public class Solution { + private int ans = 0; + + public int MaximumRequests(int n, int[][] requests) { + int[] indegree = new int[n]; + Helper(0, requests, indegree, n, 0); + return ans; + } + + private void Helper(int start, int[][] requests, int[] indegree, int n, int count) { + if (start == requests.Length) { + for (int i = 0; i < n; i++) { + if (indegree[i] != 0) return; + } + ans = Math.Max(ans, count); + return; + } + + // Take + indegree[requests[start][0]]--; + indegree[requests[start][1]]++; + Helper(start + 1, requests, indegree, n, count + 1); + + // Not-take + indegree[requests[start][0]]++; + indegree[requests[start][1]]--; + Helper(start + 1, requests, indegree, n, count); + } +} diff --git a/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.dart b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.dart new file mode 100644 index 00000000..f4781f73 --- /dev/null +++ b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.dart @@ -0,0 +1,33 @@ +class Solution { + int ans = 0; + + int maximumRequests(int n, List> requests) { + List indegree = List.filled(n, 0); + helper(0, requests, indegree, n, 0); + return ans; + } + + void helper(int start, List> requests, List indegree, int n, int count) { + if (start == requests.length) { + bool ok = true; + for (int i = 0; i < n; i++) { + if (indegree[i] != 0) { + ok = false; + break; + } + } + if (ok && count > ans) ans = count; + return; + } + + // Take + indegree[requests[start][0]]--; + indegree[requests[start][1]]++; + helper(start + 1, requests, indegree, n, count + 1); + + // Not-take + indegree[requests[start][0]]++; + indegree[requests[start][1]]--; + helper(start + 1, requests, indegree, n, count); + } +} diff --git a/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.go b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.go new file mode 100644 index 00000000..1253cae2 --- /dev/null +++ b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.go @@ -0,0 +1,32 @@ +func maximumRequests(n int, requests [][]int) int { + ans := 0 + indegree := make([]int, n) + var helper func(start int, count int) + helper = func(start int, count int) { + if start == len(requests) { + ok := true + for _, v := range indegree { + if v != 0 { + ok = false + break + } + } + if ok && count > ans { + ans = count + } + return + } + + // Take + indegree[requests[start][0]]-- + indegree[requests[start][1]]++ + helper(start+1, count+1) + + // Not-take + indegree[requests[start][0]]++ + indegree[requests[start][1]]-- + helper(start+1, count) + } + helper(0, 0) + return ans +} diff --git a/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.java b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.java new file mode 100644 index 00000000..36cf0858 --- /dev/null +++ b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.java @@ -0,0 +1,29 @@ +class Solution { + private int ans = 0; + + public int maximumRequests(int n, int[][] requests) { + int[] indegree = new int[n]; + helper(0, requests, indegree, n, 0); + return ans; + } + + private void helper(int start, int[][] requests, int[] indegree, int n, int count) { + if (start == requests.length) { + for (int i = 0; i < n; i++) { + if (indegree[i] != 0) return; + } + ans = Math.max(ans, count); + return; + } + + // Take + indegree[requests[start][0]]--; + indegree[requests[start][1]]++; + helper(start + 1, requests, indegree, n, count + 1); + + // Not-take + indegree[requests[start][0]]++; + indegree[requests[start][1]]--; + helper(start + 1, requests, indegree, n, count); + } +} diff --git a/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.kt b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.kt new file mode 100644 index 00000000..5e1b6894 --- /dev/null +++ b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.kt @@ -0,0 +1,29 @@ +class Solution { + private var ans = 0 + + fun maximumRequests(n: Int, requests: Array): Int { + val indegree = IntArray(n) + helper(0, requests, indegree, n, 0) + return ans + } + + private fun helper(start: Int, requests: Array, indegree: IntArray, n: Int, count: Int) { + if (start == requests.size) { + for (i in 0 until n) { + if (indegree[i] != 0) return + } + ans = maxOf(ans, count) + return + } + + // Take + indegree[requests[start][0]]-- + indegree[requests[start][1]]++ + helper(start + 1, requests, indegree, n, count + 1) + + // Not-take + indegree[requests[start][0]]++ + indegree[requests[start][1]]-- + helper(start + 1, requests, indegree, n, count) + } +} diff --git a/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.py b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.py new file mode 100644 index 00000000..b4454177 --- /dev/null +++ b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.py @@ -0,0 +1,26 @@ +class Solution: + def __init__(self): + self.ans = 0 + + def helper(self, start, requests, indegree, n, count): + if start == len(requests): + for i in range(n): + if indegree[i] != 0: + return + self.ans = max(self.ans, count) + return + + # Take + indegree[requests[start][0]] -= 1 + indegree[requests[start][1]] += 1 + self.helper(start + 1, requests, indegree, n, count + 1) + + # Not-take + indegree[requests[start][0]] += 1 + indegree[requests[start][1]] -= 1 + self.helper(start + 1, requests, indegree, n, count) + + def maximumRequests(self, n, requests): + indegree = [0] * n + self.helper(0, requests, indegree, n, 0) + return self.ans diff --git a/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.py2 b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.py2 new file mode 100644 index 00000000..104e3d5d --- /dev/null +++ b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.py2 @@ -0,0 +1,29 @@ +class Solution(object): + def maximumRequests(self, n, requests): + """ + :type n: int + :type requests: List[List[int]] + :rtype: int + """ + self.ans = 0 + indegree = [0] * n + self.helper(0, requests, indegree, n, 0) + return self.ans + + def helper(self, start, requests, indegree, n, count): + if start == len(requests): + for i in range(n): + if indegree[i] != 0: + return + self.ans = max(self.ans, count) + return + + # Take + indegree[requests[start][0]] -= 1 + indegree[requests[start][1]] += 1 + self.helper(start + 1, requests, indegree, n, count + 1) + + # Not-take + indegree[requests[start][0]] += 1 + indegree[requests[start][1]] -= 1 + self.helper(start + 1, requests, indegree, n, count) diff --git a/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.rb b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.rb new file mode 100644 index 00000000..0a4416d8 --- /dev/null +++ b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.rb @@ -0,0 +1,29 @@ +# @param {Integer} n +# @param {Integer[][]} requests +# @return {Integer} +def maximum_requests(n, requests) + @ans = 0 + indegree = Array.new(n, 0) + helper(0, requests, indegree, n, 0) + @ans +end + +def helper(start, requests, indegree, n, count) + if start == requests.length + (0...n).each do |i| + return if indegree[i] != 0 + end + @ans = [@ans, count].max + return + end + + # Take + indegree[requests[start][0]] -= 1 + indegree[requests[start][1]] += 1 + helper(start + 1, requests, indegree, n, count + 1) + + # Not-take + indegree[requests[start][0]] += 1 + indegree[requests[start][1]] -= 1 + helper(start + 1, requests, indegree, n, count) +end diff --git a/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.rs b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.rs new file mode 100644 index 00000000..2a2944fc --- /dev/null +++ b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.rs @@ -0,0 +1,32 @@ +impl Solution { + pub fn maximum_requests(n: i32, requests: Vec>) -> i32 { + let mut ans = 0; + let mut indegree = vec![0; n as usize]; + Self::helper(0, &requests, &mut indegree, n as usize, 0, &mut ans); + ans + } + + fn helper(start: usize, requests: &Vec>, indegree: &mut Vec, n: usize, count: i32, ans: &mut i32) { + if start == requests.len() { + for i in 0..n { + if indegree[i] != 0 { + return; + } + } + if count > *ans { + *ans = count; + } + return; + } + + // Take + indegree[requests[start][0] as usize] -= 1; + indegree[requests[start][1] as usize] += 1; + Self::helper(start + 1, requests, indegree, n, count + 1, ans); + + // Not-take + indegree[requests[start][0] as usize] += 1; + indegree[requests[start][1] as usize] -= 1; + Self::helper(start + 1, requests, indegree, n, count, ans); + } +} diff --git a/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.swift b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.swift new file mode 100644 index 00000000..0989320d --- /dev/null +++ b/tests/1501-2000/1601. maximum-number-of-achievable-transfer-requests/sol.swift @@ -0,0 +1,29 @@ +class Solution { + var ans = 0 + + func maximumRequests(_ n: Int, _ requests: [[Int]]) -> Int { + var indegree = [Int](repeating: 0, count: n) + helper(0, requests, &indegree, n, 0) + return ans + } + + private func helper(_ start: Int, _ requests: [[Int]], _ indegree: inout [Int], _ n: Int, _ count: Int) { + if start == requests.count { + for i in 0.. { + if (start === requests.length) { + let ok = true; + for (let i = 0; i < n; i++) { + if (indegree[i] !== 0) { + ok = false; + break; + } + } + if (ok && count > ans) ans = count; + return; + } + + // Take + indegree[requests[start][0]]--; + indegree[requests[start][1]]++; + helper(start + 1, count + 1); + + // Not-take + indegree[requests[start][0]]++; + indegree[requests[start][1]]--; + helper(start + 1, count); + }; + + helper(0, 0); + return ans; +} diff --git a/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/manifest.yaml b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/manifest.yaml new file mode 100644 index 00000000..5160d775 --- /dev/null +++ b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/manifest.yaml @@ -0,0 +1,279 @@ +entry: + id: 1604 + title: "Alert Using Same Key-Card Three or More Times in a One Hour Period" + params: + keyName: + type: array + items: + type: string + keyTime: + type: array + items: + type: string + call: + cpp: "Solution().alertNames({keyName}, {keyTime})" + rust: "Solution::alert_names({keyName}, {keyTime})" + python3: "Solution().alertNames({keyName}, {keyTime})" + python2: "Solution().alertNames({keyName}, {keyTime})" + ruby: "alert_names({keyName}, {keyTime})" + java: "new Solution().alertNames({keyName}, {keyTime})" + csharp: "new Solution().AlertNames({keyName}, {keyTime})" + kotlin: "Solution().alertNames({keyName}, {keyTime})" + go: "alertNames({keyName}, {keyTime})" + dart: "Solution().alertNames({keyName}, {keyTime})" + swift: "Solution().alertNames({keyName}, {keyTime})" + typescript: "alertNames({keyName}, {keyTime})" + +judge: + type: exact + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().alertNames(keyName, keyTime, {result})" + checker: | + class Checker: + def alertNames(self, keyName, keyTime, result): + expected = [] + grouped = {} + for name, stamp in zip(keyName, keyTime): + h, m = map(int, stamp.split(':')) + grouped.setdefault(name, []).append(h * 60 + m) + for name, times in grouped.items(): + times.sort() + if any(times[i + 2] - times[i] <= 60 for i in range(len(times) - 2)): + expected.append(name) + return result == sorted(expected) + +seed: 1604 + +tests: + - name: empty + in: + keyName: [a] + keyTime: ["00:00"] + out: [] + - name: two-uses-not-alert + in: + keyName: [alice, alice] + keyTime: ["09:00", "09:30"] + out: [] + - name: exact-sixty-minutes + in: + keyName: [alice, alice, alice] + keyTime: ["09:00", "09:30", "10:00"] + out: [alice] + - name: just-over-hour + in: + keyName: [alice, alice, alice] + keyTime: ["09:00", "09:30", "10:01"] + out: [] + - name: unsorted-input + in: + keyName: [alice, alice, alice] + keyTime: ["10:00", "09:00", "09:30"] + out: [alice] + - name: duplicate-time + in: + keyName: [bob, bob, bob] + keyTime: ["12:00", "12:01", "13:01"] + out: [] + - name: midnight-window + in: + keyName: [carol, carol, carol] + keyTime: ["00:00", "00:01", "01:00"] + out: [carol] + - name: end-of-day + in: + keyName: [dave, dave, dave] + keyTime: ["22:59", "23:00", "23:59"] + out: [dave] + - name: multiple-names-sorted + in: + keyName: [zoe, amy, zoe, amy, zoe, amy] + keyTime: ["08:00", "09:00", "08:20", "09:20", "08:40", "09:40"] + out: [amy, zoe] + - name: one-alert-one-safe + in: + keyName: [alice, bob, alice, bob, alice, bob] + keyTime: ["08:00", "08:00", "08:20", "09:01", "08:40", "10:00"] + out: [alice] + - name: sliding-window-late + in: + keyName: [alice, alice, alice, alice] + keyTime: ["08:00", "09:02", "09:30", "09:45"] + out: [alice] + - name: three-spread-four-safe + in: + keyName: [alice, alice, alice, alice] + keyTime: ["08:00", "08:30", "09:01", "10:30"] + out: [] + - name: four-over-hour + in: + keyName: [alice, alice, alice, alice] + keyTime: ["08:00", "08:30", "09:01", "09:31"] + out: [] + - name: names-with-spaces + in: + keyName: [johndoe, johndoe, johndoe, annlee, annlee, annlee] + keyTime: ["10:00", "10:20", "10:40", "10:00", "11:01", "11:30"] + out: [johndoe] + - name: lexicographic-order + in: + keyName: [z, a, m, z, a, m, z, a, m] + keyTime: + [ + "01:00", + "02:00", + "03:00", + "01:10", + "02:10", + "03:10", + "01:20", + "02:20", + "03:20", + ] + out: [a, m, z] + - name: isolated-names + in: + keyName: [a, b, c, d, e] + keyTime: ["00:00", "01:00", "02:00", "03:00", "04:00"] + out: [] + - name: boundary-100 + in: + keyName: [a, a, a, b, b, b] + keyTime: ["01:00", "01:59", "02:40", "01:00", "02:00", "03:01"] + out: [] + - name: early-hours + in: + keyName: [a, a, a, b, b, b] + keyTime: ["00:01", "00:02", "00:03", "04:57", "04:58", "05:59"] + out: [a] + - name: late-hours-safe + in: + keyName: [a, a, a] + keyTime: ["21:00", "22:01", "23:02"] + out: [] + - name: repeated-alert-candidates + in: + keyName: [a, a, a, a, b, b, b, c, c, c] + keyTime: + [ + "10:00", + "10:10", + "10:20", + "10:30", + "11:00", + "11:30", + "12:00", + "12:00", + "12:30", + "13:01", + ] + out: [a, b] + - name: same-minute-three + in: + keyName: [a, a, a] + keyTime: ["14:15", "14:15", "14:15"] + out: [a] + - name: interleaved-safe + in: + keyName: [a, b, a, b, a, b] + keyTime: ["08:00", "08:00", "09:01", "09:01", "10:02", "10:02"] + out: [] + - name: interleaved-alert + in: + keyName: [a, b, a, b, a, b] + keyTime: ["08:00", "08:00", "09:00", "09:00", "09:59", "09:59"] + out: [] + - name: unsorted-mixed + in: + keyName: [b, a, b, a, b, a] + keyTime: ["18:00", "17:30", "17:00", "18:00", "17:30", "18:30"] + out: [a, b] + - name: one-name-many-safe + in: + keyName: [a, a, a, a, a, a] + keyTime: ["06:00", "07:01", "08:02", "09:03", "10:04", "11:05"] + out: [] + - name: one-name-many-alert + in: + keyName: [a, a, a, a, a, a] + keyTime: ["06:00", "06:59", "07:00", "08:02", "08:03", "09:03"] + out: [a] + - name: exact-hour-later-window + in: + keyName: [a, a, a, a] + keyTime: ["02:00", "02:59", "03:00", "04:30"] + out: [a] + - name: no-cross-midnight + in: + keyName: [a, a, a] + keyTime: ["23:30", "23:50", "00:10"] + out: [] + - name: alphabetic-long-names + in: + keyName: [alexander, beatrice, alexander, beatrice, alexander, beatrice] + keyTime: ["15:00", "15:00", "15:30", "16:01", "16:00", "17:02"] + out: [alexander] + - name: four-users + in: + keyName: [a, b, c, d, a, b, c, d, a, b, c, d] + keyTime: + [ + "07:00", + "07:00", + "07:00", + "07:00", + "07:20", + "07:20", + "07:20", + "07:20", + "07:40", + "07:40", + "08:01", + "08:01", + ] + out: [a, b] + - name: four-users-safe + in: + keyName: [a, b, c, d, a, b, c, d, a, b, c, d] + keyTime: + [ + "07:00", + "07:00", + "07:00", + "07:00", + "08:01", + "08:01", + "08:01", + "08:01", + "09:02", + "09:02", + "09:02", + "09:02", + ] + out: [] + - name: dense-and-sparse + in: + keyName: [dense, sparse, dense, sparse, dense, sparse, dense] + keyTime: ["12:00", "00:00", "12:01", "01:01", "12:02", "02:02", "12:03"] + out: [dense] + - name: late-alert + in: + keyName: [a, a, a, b, b, b] + keyTime: ["22:00", "22:30", "23:00", "22:00", "22:30", "23:01"] + out: [a] + - name: exact-hour-with-duplicates + in: + keyName: [a, a, a, a] + keyTime: ["05:00", "05:00", "06:00", "08:00"] + out: [a] + - name: long-window-safe + in: + keyName: [a, a, a, a, a] + keyTime: ["00:00", "01:01", "02:02", "03:03", "04:04"] + out: [] diff --git a/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.cpp b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.cpp new file mode 100644 index 00000000..a4f41a34 --- /dev/null +++ b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + vector alertNames(vector& keyName, vector& keyTime) { + unordered_map> mp; + + for (int i = 0; i < keyName.size(); i++) { + int h = stoi(keyTime[i].substr(0, 2)); + int m = stoi(keyTime[i].substr(3)); + int minutes = h * 60 + m; + mp[keyName[i]].push_back(minutes); + } + + vector result; + + for (auto& [name, times] : mp) { + sort(times.begin(), times.end()); + for (int i = 0; i + 2 < times.size(); i++) { + if (times[i+2] - times[i] <= 60) { + result.push_back(name); + break; + } + } + } + + sort(result.begin(), result.end()); + return result; + } +}; diff --git a/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.cs b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.cs new file mode 100644 index 00000000..aebf0645 --- /dev/null +++ b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.cs @@ -0,0 +1,30 @@ +public class Solution { + public IList AlertNames(string[] keyName, string[] keyTime) { + var map = new Dictionary>(); + + for (int i = 0; i < keyName.Length; i++) { + var parts = keyTime[i].Split(':'); + int minutes = int.Parse(parts[0]) * 60 + int.Parse(parts[1]); + if (!map.ContainsKey(keyName[i])) { + map[keyName[i]] = new List(); + } + map[keyName[i]].Add(minutes); + } + + var result = new List(); + + foreach (var kvp in map) { + var times = kvp.Value; + times.Sort(); + for (int i = 0; i < times.Count - 2; i++) { + if (times[i+2] - times[i] <= 60) { + result.Add(kvp.Key); + break; + } + } + } + + result.Sort(); + return result; + } +} diff --git a/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.dart b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.dart new file mode 100644 index 00000000..a689b1ac --- /dev/null +++ b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.dart @@ -0,0 +1,26 @@ +class Solution { + List alertNames(List keyName, List keyTime) { + Map> map = {}; + + for (int i = 0; i < keyName.length; i++) { + List parts = keyTime[i].split(':'); + int minutes = int.parse(parts[0]) * 60 + int.parse(parts[1]); + map.putIfAbsent(keyName[i], () => []).add(minutes); + } + + List result = []; + + map.forEach((name, times) { + times.sort(); + for (int i = 0; i < times.length - 2; i++) { + if (times[i+2] - times[i] <= 60) { + result.add(name); + return; + } + } + }); + + result.sort(); + return result; + } +} diff --git a/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.go b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.go new file mode 100644 index 00000000..2049115e --- /dev/null +++ b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.go @@ -0,0 +1,26 @@ +func alertNames(keyName []string, keyTime []string) []string { + m := make(map[string][]int) + + for i, name := range keyName { + parts := strings.Split(keyTime[i], ":") + h, _ := strconv.Atoi(parts[0]) + min, _ := strconv.Atoi(parts[1]) + minutes := h*60 + min + m[name] = append(m[name], minutes) + } + + result := []string{} + + for name, times := range m { + sort.Ints(times) + for i := 0; i < len(times)-2; i++ { + if times[i+2] - times[i] <= 60 { + result = append(result, name) + break + } + } + } + + sort.Strings(result) + return result +} diff --git a/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.java b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.java new file mode 100644 index 00000000..e9cd1187 --- /dev/null +++ b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.java @@ -0,0 +1,27 @@ +class Solution { + public List alertNames(String[] keyName, String[] keyTime) { + Map> map = new HashMap<>(); + + for (int i = 0; i < keyName.length; i++) { + String[] parts = keyTime[i].split(":"); + int minutes = Integer.parseInt(parts[0]) * 60 + Integer.parseInt(parts[1]); + map.computeIfAbsent(keyName[i], k -> new ArrayList<>()).add(minutes); + } + + List result = new ArrayList<>(); + + for (Map.Entry> entry : map.entrySet()) { + List times = entry.getValue(); + Collections.sort(times); + for (int i = 0; i < times.size() - 2; i++) { + if (times.get(i+2) - times.get(i) <= 60) { + result.add(entry.getKey()); + break; + } + } + } + + Collections.sort(result); + return result; + } +} diff --git a/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.kt b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.kt new file mode 100644 index 00000000..2b2be935 --- /dev/null +++ b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun alertNames(keyName: Array, keyTime: Array): List { + val map = mutableMapOf>() + + for (i in keyName.indices) { + val parts = keyTime[i].split(":") + val minutes = parts[0].toInt() * 60 + parts[1].toInt() + map.getOrPut(keyName[i]) { mutableListOf() }.add(minutes) + } + + val result = mutableListOf() + + for ((name, times) in map) { + times.sort() + for (i in 0 until times.size - 2) { + if (times[i+2] - times[i] <= 60) { + result.add(name) + break + } + } + } + + return result.sorted() + } +} diff --git a/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.py b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.py new file mode 100644 index 00000000..04521311 --- /dev/null +++ b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.py @@ -0,0 +1,27 @@ +class Solution(object): + def alertNames(self, keyName, keyTime): + """ + :type keyName: List[str] + :type keyTime: List[str] + :rtype: List[str] + """ + + def timeToMinutes(t): + h, m = map(int, t.split(":")) + return h * 60 + m + + name_to_times = defaultdict(list) + + for name, time in zip(keyName, keyTime): + name_to_times[name].append(timeToMinutes(time)) + + alerted = [] + + for name, times in name_to_times.items(): + times.sort() + for i in range(len(times) - 2): + if times[i + 2] - times[i] <= 60: + alerted.append(name) + break + + return sorted(alerted) diff --git a/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.py2 b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.py2 new file mode 100644 index 00000000..f70c671e --- /dev/null +++ b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.py2 @@ -0,0 +1,27 @@ +class Solution(object): + def alertNames(self, keyName, keyTime): + """ + :type keyName: List[str] + :type keyTime: List[str] + :rtype: List[str] + """ + def timeToMinutes(t): + h, m = map(int, t.split(':')) + return h * 60 + m + + from collections import defaultdict + name_to_times = defaultdict(list) + + for name, time in zip(keyName, keyTime): + name_to_times[name].append(timeToMinutes(time)) + + alerted = [] + + for name, times in name_to_times.items(): + times.sort() + for i in range(len(times) - 2): + if times[i+2] - times[i] <= 60: + alerted.append(name) + break + + return sorted(alerted) diff --git a/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.rb b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.rb new file mode 100644 index 00000000..dc37ce83 --- /dev/null +++ b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.rb @@ -0,0 +1,26 @@ +# @param {String[]} key_name +# @param {String[]} key_time +# @return {String[]} +def alert_names(key_name, key_time) + time_to_min = ->(t) { h, m = t.split(':').map(&:to_i); h * 60 + m } + + name_to_times = Hash.new { |h, k| h[k] = [] } + + key_name.each_with_index do |name, i| + name_to_times[name] << time_to_min.call(key_time[i]) + end + + alerted = [] + + name_to_times.each do |name, times| + times.sort! + (0...(times.length - 2)).each do |i| + if times[i+2] - times[i] <= 60 + alerted << name + break + end + end + end + + alerted.sort +end diff --git a/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.rs b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.rs new file mode 100644 index 00000000..6a15c569 --- /dev/null +++ b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.rs @@ -0,0 +1,28 @@ +impl Solution { + pub fn alert_names(key_name: Vec, key_time: Vec) -> Vec { + use std::collections::HashMap; + + let mut map: HashMap> = HashMap::new(); + + for (name, time) in key_name.iter().zip(key_time.iter()) { + let parts: Vec<&str> = time.split(':').collect(); + let minutes = parts[0].parse::().unwrap() * 60 + parts[1].parse::().unwrap(); + map.entry(name.clone()).or_insert(Vec::new()).push(minutes); + } + + let mut result = Vec::new(); + + for (name, mut times) in map { + times.sort(); + for i in 0..times.len().saturating_sub(2) { + if times[i+2] - times[i] <= 60 { + result.push(name.clone()); + break; + } + } + } + + result.sort(); + result + } +} diff --git a/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.swift b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.swift new file mode 100644 index 00000000..52537806 --- /dev/null +++ b/tests/1501-2000/1604. alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/sol.swift @@ -0,0 +1,26 @@ +class Solution { + func alertNames(_ keyName: [String], _ keyTime: [String]) -> [String] { + var map = [String: [Int]]() + + for i in 0..(); + + for (let i = 0; i < keyName.length; i++) { + const parts = keyTime[i].split(":"); + const minutes = parseInt(parts[0]) * 60 + parseInt(parts[1]); + if (!map.has(keyName[i])) { + map.set(keyName[i], []); + } + map.get(keyName[i])!.push(minutes); + } + + const result: string[] = []; + + for (const [name, times] of map) { + times.sort((a, b) => a - b); + for (let i = 0; i < times.length - 2; i++) { + if (times[i + 2] - times[i] <= 60) { + result.push(name); + break; + } + } + } + + return result.sort(); +} diff --git a/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/manifest.yaml b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/manifest.yaml new file mode 100644 index 00000000..e4d489b8 --- /dev/null +++ b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/manifest.yaml @@ -0,0 +1,203 @@ +entry: + id: 1605 + title: "find-valid-matrix-given-row-and-column-sums" + params: + rowSum: + type: array + items: + type: int + colSum: + type: array + items: + type: int + call: + cpp: "Solution().restoreMatrix({rowSum}, {colSum})" + rust: "Solution::restore_matrix({rowSum}, {colSum})" + python3: "Solution().restoreMatrix({rowSum}, {colSum})" + python2: "Solution().restoreMatrix({rowSum}, {colSum})" + ruby: "restore_matrix({rowSum}, {colSum})" + java: "new Solution().restoreMatrix({rowSum}, {colSum})" + csharp: "new Solution().RestoreMatrix({rowSum}, {colSum})" + kotlin: "Solution().restoreMatrix({rowSum}, {colSum})" + go: "restoreMatrix({rowSum}, {colSum})" + dart: "Solution().restoreMatrix({rowSum}, {colSum})" + swift: "Solution().restoreMatrix({rowSum}, {colSum})" + typescript: "restoreMatrix({rowSum}, {colSum})" + +judge: + type: exact + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().restoreMatrix(rowSum, colSum, {result})" + checker: | + class Checker: + def restoreMatrix(self, rowSum, colSum, result): + if not isinstance(result, list) or len(result) != len(rowSum): + return False + n = len(colSum) + col_totals = [0] * n + for i, row in enumerate(result): + if not isinstance(row, list) or len(row) != n: + return False + total = 0 + for j, value in enumerate(row): + if not isinstance(value, int) or isinstance(value, bool) or value < 0: + return False + total += value + col_totals[j] += value + if total != rowSum[i]: + return False + return col_totals == colSum + +seed: 1605 + +tests: + - name: example-one + in: + rowSum: [3, 8] + colSum: [4, 7] + - name: example-two + in: + rowSum: [5, 7, 10] + colSum: [8, 6, 8] + - name: single-cell-zero + in: + rowSum: [0] + colSum: [0] + - name: single-cell-large + in: + rowSum: [100000000] + colSum: [100000000] + - name: one-row + in: + rowSum: [15] + colSum: [0, 1, 4, 10] + - name: one-column + in: + rowSum: [0, 3, 7, 0] + colSum: [10] + - name: all-zero-rectangle + in: + rowSum: [0, 0, 0] + colSum: [0, 0] + - name: equal-two-by-two + in: + rowSum: [5, 5] + colSum: [5, 5] + - name: skew-two-by-three + in: + rowSum: [1, 19] + colSum: [10, 5, 5] + - name: zeros-leading + in: + rowSum: [0, 0, 9, 1] + colSum: [0, 4, 6] + - name: zeros-trailing + in: + rowSum: [8, 0, 0] + colSum: [3, 5, 0, 0] + - name: alternating-zeros + in: + rowSum: [4, 0, 6, 0, 5] + colSum: [0, 7, 0, 8] + - name: many-columns + in: + rowSum: [21, 13] + colSum: [1, 2, 3, 4, 5, 6, 7, 6] + - name: many-rows + in: + rowSum: [1, 2, 3, 4, 5, 6, 7, 8] + colSum: [12, 14, 10] + - name: exact-prefix-fills + in: + rowSum: [2, 3, 4] + colSum: [2, 3, 4] + - name: descending + in: + rowSum: [15, 10, 6, 3] + colSum: [9, 8, 7, 6, 4] + - name: ascending + in: + rowSum: [1, 2, 3, 4, 5] + colSum: [5, 4, 3, 2, 1] + - name: one-heavy-row + in: + rowSum: [100, 1, 1, 1] + colSum: [25, 25, 25, 28] + - name: one-heavy-column + in: + rowSum: [25, 25, 25, 28] + colSum: [100, 1, 1, 1] + - name: large-values + in: + rowSum: [100000000, 99999999] + colSum: [1, 99999998, 100000000] + - name: balanced-three + in: + rowSum: [12, 12, 12] + colSum: [12, 12, 12] + - name: balanced-four + in: + rowSum: [20, 20, 20, 20] + colSum: [20, 20, 20, 20] + - name: sparse-four + in: + rowSum: [0, 50, 0, 50] + colSum: [25, 25, 25, 25] + - name: uneven-five + in: + rowSum: [2, 17, 3, 28] + colSum: [10, 20, 20] + - name: powers-of-two + in: + rowSum: [1, 2, 4, 8, 16] + colSum: [16, 8, 4, 2, 1] + - name: repeated-small + in: + rowSum: [6, 6, 6, 6, 6] + colSum: [10, 10, 5, 5] + - name: two-by-five + in: + rowSum: [37, 8] + colSum: [5, 7, 9, 11, 13] + - name: five-by-two + in: + rowSum: [3, 14, 2, 17, 4] + colSum: [20, 20] + - name: nine-by-one + in: + rowSum: [1, 0, 3, 0, 5, 0, 7, 0, 9] + colSum: [25] + - name: one-by-nine + in: + rowSum: [45] + colSum: [1, 2, 3, 4, 5, 6, 7, 8, 9] + - name: dense-six + in: + rowSum: [31, 27, 23, 19, 15, 11] + colSum: [20, 25, 30, 20, 20, 11] + - name: zero-middle + in: + rowSum: [10, 0, 20, 0, 30] + colSum: [15, 15, 15, 15] + - name: max-two-by-two + in: + rowSum: [100000000, 100000000] + colSum: [100000000, 100000000] + - name: mixed-seven + in: + rowSum: [7, 0, 14, 3, 21, 5] + colSum: [10, 15, 25] + - name: rectangular-eight + in: + rowSum: [8, 16, 24, 32] + colSum: [20, 20, 20, 20] + - name: final-irregular + in: + rowSum: [11, 1, 18, 7, 23] + colSum: [6, 12, 9, 15, 18] diff --git a/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.cpp b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.cpp new file mode 100644 index 00000000..ee60cde3 --- /dev/null +++ b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector> restoreMatrix(vector& rowSum, vector& colSum) { + int m = rowSum.size(), n = colSum.size(); + vector> matrix(m, vector(n, 0)); + int i = 0, j = 0; + while (i < m && j < n) { + int val = min(rowSum[i], colSum[j]); + matrix[i][j] = val; + rowSum[i] -= val; + colSum[j] -= val; + if (rowSum[i] == 0) i++; + if (colSum[j] == 0) j++; + } + return matrix; + } +}; diff --git a/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.cs b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.cs new file mode 100644 index 00000000..f744329c --- /dev/null +++ b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.cs @@ -0,0 +1,17 @@ +public class Solution { + public int[][] RestoreMatrix(int[] rowSum, int[] colSum) { + int m = rowSum.Length, n = colSum.Length; + int[][] matrix = new int[m][]; + for (int i = 0; i < m; i++) matrix[i] = new int[n]; + int row = 0, col = 0; + while (row < m && col < n) { + int val = Math.Min(rowSum[row], colSum[col]); + matrix[row][col] = val; + rowSum[row] -= val; + colSum[col] -= val; + if (rowSum[row] == 0) row++; + if (colSum[col] == 0) col++; + } + return matrix; + } +} diff --git a/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.dart b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.dart new file mode 100644 index 00000000..a9602b81 --- /dev/null +++ b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.dart @@ -0,0 +1,16 @@ +class Solution { + List> restoreMatrix(List rowSum, List colSum) { + int m = rowSum.length, n = colSum.length; + List> matrix = List.generate(m, (_) => List.filled(n, 0)); + int i = 0, j = 0; + while (i < m && j < n) { + int val = rowSum[i] < colSum[j] ? rowSum[i] : colSum[j]; + matrix[i][j] = val; + rowSum[i] -= val; + colSum[j] -= val; + if (rowSum[i] == 0) i++; + if (colSum[j] == 0) j++; + } + return matrix; + } +} diff --git a/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.go b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.go new file mode 100644 index 00000000..87677d2c --- /dev/null +++ b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.go @@ -0,0 +1,21 @@ +func restoreMatrix(rowSum []int, colSum []int) [][]int { + m, n := len(rowSum), len(colSum) + matrix := make([][]int, m) + for i := range matrix { + matrix[i] = make([]int, n) + } + i, j := 0, 0 + for i < m && j < n { + val := min(rowSum[i], colSum[j]) + matrix[i][j] = val + rowSum[i] -= val + colSum[j] -= val + if rowSum[i] == 0 { + i++ + } + if colSum[j] == 0 { + j++ + } + } + return matrix +} diff --git a/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.java b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.java new file mode 100644 index 00000000..c4972bd6 --- /dev/null +++ b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.java @@ -0,0 +1,16 @@ +class Solution { + public int[][] restoreMatrix(int[] rowSum, int[] colSum) { + int m = rowSum.length, n = colSum.length; + int[][] matrix = new int[m][n]; + int i = 0, j = 0; + while (i < m && j < n) { + int val = Math.min(rowSum[i], colSum[j]); + matrix[i][j] = val; + rowSum[i] -= val; + colSum[j] -= val; + if (rowSum[i] == 0) i++; + if (colSum[j] == 0) j++; + } + return matrix; + } +} diff --git a/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.kt b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.kt new file mode 100644 index 00000000..9925e5e9 --- /dev/null +++ b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.kt @@ -0,0 +1,18 @@ +class Solution { + fun restoreMatrix(rowSum: IntArray, colSum: IntArray): Array { + val m = rowSum.size + val n = colSum.size + val matrix = Array(m) { IntArray(n) } + var i = 0 + var j = 0 + while (i < m && j < n) { + val value = minOf(rowSum[i], colSum[j]) + matrix[i][j] = value + rowSum[i] -= value + colSum[j] -= value + if (rowSum[i] == 0) i++ + if (colSum[j] == 0) j++ + } + return matrix + } +} diff --git a/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.py b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.py new file mode 100644 index 00000000..dbffc73a --- /dev/null +++ b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.py @@ -0,0 +1,20 @@ +class Solution: + def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]: + m, n = len(rowSum), len(colSum) + + matrix = [[0] * n for _ in range(m)] + i, j = 0, 0 + + while i < m and j < n: + val = min(rowSum[i], colSum[j]) + matrix[i][j] = val + + rowSum[i] -= val + colSum[j] -= val + + if rowSum[i] == 0: + i += 1 + if colSum[j] == 0: + j += 1 + + return matrix diff --git a/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.py2 b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.py2 new file mode 100644 index 00000000..ba0afa61 --- /dev/null +++ b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def restoreMatrix(self, rowSum, colSum): + """ + :type rowSum: List[int] + :type colSum: List[int] + :rtype: List[List[int]] + """ + m, n = len(rowSum), len(colSum) + matrix = [[0] * n for _ in range(m)] + i, j = 0, 0 + while i < m and j < n: + val = min(rowSum[i], colSum[j]) + matrix[i][j] = val + rowSum[i] -= val + colSum[j] -= val + if rowSum[i] == 0: + i += 1 + if colSum[j] == 0: + j += 1 + return matrix diff --git a/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.rb b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.rb new file mode 100644 index 00000000..20412aca --- /dev/null +++ b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.rb @@ -0,0 +1,17 @@ +# @param {Integer[]} row_sum +# @param {Integer[]} col_sum +# @return {Integer[][]} +def restore_matrix(row_sum, col_sum) + m, n = row_sum.length, col_sum.length + matrix = Array.new(m) { Array.new(n, 0) } + i, j = 0, 0 + while i < m && j < n + val = [row_sum[i], col_sum[j]].min + matrix[i][j] = val + row_sum[i] -= val + col_sum[j] -= val + i += 1 if row_sum[i] == 0 + j += 1 if col_sum[j] == 0 + end + matrix +end diff --git a/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.rs b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.rs new file mode 100644 index 00000000..a4cf65a2 --- /dev/null +++ b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn restore_matrix(row_sum: Vec, col_sum: Vec) -> Vec> { + let mut row_sum = row_sum; + let mut col_sum = col_sum; + let (m, n) = (row_sum.len(), col_sum.len()); + let mut matrix = vec![vec![0; n]; m]; + let (mut i, mut j) = (0, 0); + while i < m && j < n { + let val = row_sum[i].min(col_sum[j]); + matrix[i][j] = val; + row_sum[i] -= val; + col_sum[j] -= val; + if row_sum[i] == 0 { i += 1; } + if col_sum[j] == 0 { j += 1; } + } + matrix + } +} diff --git a/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.swift b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.swift new file mode 100644 index 00000000..1453ffa1 --- /dev/null +++ b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.swift @@ -0,0 +1,18 @@ +class Solution { + func restoreMatrix(_ rowSum: [Int], _ colSum: [Int]) -> [[Int]] { + var rowSum = rowSum + var colSum = colSum + let m = rowSum.count, n = colSum.count + var matrix = [[Int]](repeating: [Int](repeating: 0, count: n), count: m) + var i = 0, j = 0 + while i < m && j < n { + let val = min(rowSum[i], colSum[j]) + matrix[i][j] = val + rowSum[i] -= val + colSum[j] -= val + if rowSum[i] == 0 { i += 1 } + if colSum[j] == 0 { j += 1 } + } + return matrix + } +} diff --git a/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.ts b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.ts new file mode 100644 index 00000000..b55a5d68 --- /dev/null +++ b/tests/1501-2000/1605. find-valid-matrix-given-row-and-column-sums/sol.ts @@ -0,0 +1,18 @@ +function restoreMatrix(rowSum: number[], colSum: number[]): number[][] { + const m = rowSum.length, + n = colSum.length; + const matrix: number[][] = Array.from({ length: m }, () => + new Array(n).fill(0), + ); + let i = 0, + j = 0; + while (i < m && j < n) { + const val = Math.min(rowSum[i], colSum[j]); + matrix[i][j] = val; + rowSum[i] -= val; + colSum[j] -= val; + if (rowSum[i] === 0) i++; + if (colSum[j] === 0) j++; + } + return matrix; +} diff --git a/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/manifest.yaml b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/manifest.yaml new file mode 100644 index 00000000..dfe34e59 --- /dev/null +++ b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/manifest.yaml @@ -0,0 +1,438 @@ +entry: + id: 1606 + title: "find-servers-that-handled-most-number-of-requests" + params: + k: + type: int + arrival: + type: array + items: + type: int + load: + type: array + items: + type: int + call: + cpp: "Solution().busiestServers({k}, {arrival}, {load})" + rust: "Solution::busiest_servers({k}, {arrival}, {load})" + python3: "Solution().busiestServers({k}, {arrival}, {load})" + python2: "Solution().busiestServers({k}, {arrival}, {load})" + ruby: "busiest_servers({k}, {arrival}, {load})" + java: "new Solution().busiestServers({k}, {arrival}, {load})" + csharp: "new Solution().BusiestServers({k}, {arrival}, {load})" + kotlin: "Solution().busiestServers({k}, {arrival}, {load})" + go: "busiestServers({k}, {arrival}, {load})" + dart: "Solution().busiestServers({k}, {arrival}, {load})" + swift: "Solution().busiestServers({k}, {arrival}, {load})" + typescript: "busiestServers({k}, {arrival}, {load})" + +judge: + type: ignore_order + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().busiestServers(k, arrival, load, {result})" + checker: | + import heapq + + class Checker: + def busiestServers(self, k, arrival, load, result): + if not isinstance(result, list): + return False + available = list(range(k)) + heapq.heapify(available) + busy = [] + counts = [0] * k + for i, start in enumerate(arrival): + while busy and busy[0][0] <= start: + finish, server = heapq.heappop(busy) + heapq.heappush(available, i + (server - i) % k) + if available: + encoded = heapq.heappop(available) + server = encoded % k + counts[server] += 1 + heapq.heappush(busy, (start + load[i], server)) + best = max(counts) + expected = {i for i, count in enumerate(counts) if count == best} + try: + actual = [int(x) for x in result] + except (TypeError, ValueError): + return False + return len(actual) == len(set(actual)) and set(actual) == expected + +seed: 1606001 + +tests: + - name: example-one + in: + k: 3 + arrival: [1, 2, 3, 4, 5] + load: [5, 2, 3, 3, 3] + - name: example-two + in: + k: 3 + arrival: [1, 2, 3, 4] + load: [1, 2, 1, 2] + - name: example-three + in: + k: 3 + arrival: [1, 2, 3] + load: [10, 12, 11] + - name: single-server-repeated + in: + k: 2 + arrival: [1, 2, 3, 4, 5, 6] + load: [1, 1, 1, 1, 1, 1] + - name: all-busy-drops + in: + k: 2 + arrival: [1, 2, 3, 4, 5] + load: [100, 100, 100, 100, 100] + - name: immediate-reuse + in: + k: 4 + arrival: [1, 2, 3, 4, 5, 6, 7, 8] + load: [1, 1, 1, 1, 1, 1, 1, 1] + - name: wraparound + in: + k: 3 + arrival: [1, 2, 3, 4, 5, 6, 7] + load: [4, 1, 1, 4, 1, 1, 4] + - name: one-request + in: + k: 100 + arrival: [17] + load: [23] + - name: k-two-alternating + in: + k: 2 + arrival: [2, 5, 8, 11, 14, 17, 20] + load: [4, 1, 5, 2, 6, 1, 3] + - name: sparse-arrivals + in: + k: 5 + arrival: [1, 100, 200, 300, 400, 500] + load: [99, 99, 99, 99, 99, 99] + - name: equal-finish-boundary + in: + k: 3 + arrival: [1, 4, 7, 10, 13, 16] + load: [3, 3, 3, 3, 3, 3] + - name: heavy-server-zero + in: + k: 4 + arrival: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + load: [100, 1, 1, 1, 100, 1, 1, 1, 100, 1] + - name: varied-gaps + in: + k: 6 + arrival: [3, 4, 10, 11, 25, 26, 40, 41, 70] + load: [5, 20, 1, 30, 2, 40, 3, 50, 4] + - name: dense-six + in: + k: 6 + arrival: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + load: [6, 6, 6, 6, 1, 1, 1, 1, 6, 6, 6, 6] + - name: large-k-few-requests + in: + k: 100000 + arrival: [1, 2, 3, 1000000000] + load: [1000000000, 1, 1, 1] + - name: large-times + in: + k: 7 + arrival: [1, 100000000, 200000000, 300000000, 400000000] + load: [1000000000, 999999999, 500000000, 1, 1000000000] + - name: repeated-collisions + in: + k: 3 + arrival: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + load: [3, 4, 5, 1, 2, 6, 1, 4, 2, 5, 1] + - name: five-servers + in: + k: 5 + arrival: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] + load: [2, 9, 1, 8, 3, 7, 4, 6, 5, 2, 9, 1, 8] + - name: long-busy-periods + in: + k: 8 + arrival: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + load: [20, 1, 20, 1, 20, 1, 20, 1, 20, 1, 20, 1, 20, 1, 20] + - name: alternating-long-short + in: + k: 4 + arrival: [1, 2, 3, 10, 11, 12, 20, 21, 22] + load: [9, 1, 9, 1, 9, 1, 9, 1, 9] + - name: ten-servers + in: + k: 10 + arrival: + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] + load: [11, 3, 7, 2, 13, 5, 1, 9, 4, 8, 6, 2, 12, 1, 10, 3, 7, 5, 9, 2] + - name: mostly-dropped + in: + k: 3 + arrival: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] + load: [100, 100, 100, 1, 1, 1, 100, 100, 1, 1] + - name: staggered-release + in: + k: 5 + arrival: [1, 2, 6, 7, 12, 13, 20, 21, 30, 31] + load: [5, 5, 5, 5, 5, 5, 5, 5, 5, 5] + - name: prime-gaps + in: + k: 7 + arrival: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37] + load: [4, 8, 1, 9, 2, 7, 3, 6, 5, 1, 10, 2] + - name: server-index-wrap + in: + k: 4 + arrival: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + load: [2, 2, 2, 10, 1, 1, 1, 10, 3, 3, 3, 10] + - name: all-release-before-next + in: + k: 9 + arrival: [1, 100, 200, 300, 400, 500, 600, 700, 800, 900] + load: [50, 50, 50, 50, 50, 50, 50, 50, 50, 50] + - name: mixed-extremes + in: + k: 6 + arrival: [1, 2, 100, 101, 1000, 1001, 10000, 10001] + load: [1000000000, 1, 999999999, 2, 1000000000, 3, 999999998, 4] + - name: dense-ten + in: + k: 10 + arrival: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + ] + load: + [ + 4, + 3, + 2, + 1, + 20, + 19, + 18, + 17, + 16, + 15, + 14, + 13, + 12, + 11, + 10, + 9, + 8, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + 20, + ] + - name: twenty-requests-three-servers + in: + k: 3 + arrival: + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] + load: [1, 7, 2, 6, 3, 5, 4, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14] + - name: one-server-like-load + in: + k: 2 + arrival: [1, 3, 5, 7, 9, 11, 13, 15, 17] + load: [10, 1, 10, 1, 10, 1, 10, 1, 10] + - name: thirty-requests-seven-servers + in: + k: 7 + arrival: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + ] + load: + [ + 8, + 1, + 6, + 2, + 9, + 3, + 7, + 4, + 5, + 10, + 1, + 8, + 2, + 6, + 3, + 9, + 4, + 7, + 5, + 11, + 1, + 8, + 2, + 6, + 3, + 9, + 4, + 7, + 5, + 12, + ] + - name: near-max-k + in: + k: 99999 + arrival: [1, 2, 3, 4, 5, 6, 7, 8] + load: [1000000000, 999999999, 999999998, 999999997, 1, 2, 3, 4] + - name: near-max-values + in: + k: 2 + arrival: [999999990, 999999991, 999999992, 999999993, 999999994] + load: [1000000000, 1, 1000000000, 1, 1000000000] + - name: thirty-five-requests + in: + k: 11 + arrival: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + ] + load: + [ + 3, + 8, + 1, + 9, + 2, + 7, + 4, + 6, + 5, + 10, + 1, + 3, + 8, + 1, + 9, + 2, + 7, + 4, + 6, + 5, + 10, + 1, + 3, + 8, + 1, + 9, + 2, + 7, + 4, + 6, + 5, + 10, + 1, + 3, + 8, + ] + - name: exact-completion-release + in: + k: 3 + arrival: [1, 2, 3, 6, 7, 8, 9] + load: [5, 5, 5, 1, 1, 1, 1] diff --git a/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.cpp b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.cpp new file mode 100644 index 00000000..86c2e9f3 --- /dev/null +++ b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector busiestServers(int k, vector& arrival, vector& load) { + priority_queue, greater> available; + for (int i = 0; i < k; i++) available.push(i); + priority_queue, vector>, greater>> busy; + vector res(k, 0); + for (int i = 0; i < (int)arrival.size(); i++) { + int a = arrival[i]; + while (!busy.empty() && busy.top().first <= a) { + int x = busy.top().second; + busy.pop(); + available.push(i + ((x - i) % k + k) % k); + } + if (!available.empty()) { + int j = available.top() % k; + available.pop(); + busy.push({a + load[i], j}); + res[j]++; + } + } + int mx = *max_element(res.begin(), res.end()); + vector ans; + for (int i = 0; i < k; i++) if (res[i] == mx) ans.push_back(i); + return ans; + } +}; diff --git a/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.cs b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.cs new file mode 100644 index 00000000..66369930 --- /dev/null +++ b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.cs @@ -0,0 +1,29 @@ +public class Solution { + public IList BusiestServers(int k, int[] arrival, int[] load) { + var available = new SortedSet(); + for (int i = 0; i < k; i++) available.Add(i); + var busy = new SortedSet<(int end, int server)>(); + var res = new int[k]; + for (int i = 0; i < arrival.Length; i++) { + int a = arrival[i]; + while (busy.Count > 0 && busy.Min.end <= a) { + var item = busy.Min; + busy.Remove(item); + int x = item.server; + int encoded = i + ((x - i) % k + k) % k; + available.Add(encoded); + } + if (available.Count > 0) { + int encoded = available.Min; + available.Remove(encoded); + int j = encoded % k; + busy.Add((a + load[i], j)); + res[j]++; + } + } + int mx = res.Max(); + var ans = new List(); + for (int i = 0; i < k; i++) if (res[i] == mx) ans.Add(i); + return ans; + } +} diff --git a/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.dart b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.dart new file mode 100644 index 00000000..16c8f5e9 --- /dev/null +++ b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.dart @@ -0,0 +1,28 @@ +import 'dart:collection'; + +class Solution { + List busiestServers(int k, List arrival, List load) { + var available = PriorityQueue((a, b) => a - b); + for (var i = 0; i < k; i++) available.add(i); + var busy = PriorityQueue>((a, b) => a[0] - b[0]); + var res = List.filled(k, 0); + for (var i = 0; i < arrival.length; i++) { + var a = arrival[i]; + while (busy.isNotEmpty && busy.first[0] <= a) { + var x = busy.removeFirst()[1]; + available.add(i + (x - i) % k); + } + if (available.isNotEmpty) { + var j = available.removeFirst() % k; + busy.add([a + load[i], j]); + res[j]++; + } + } + var max = res.reduce((a, b) => a > b ? a : b); + var ans = []; + for (var i = 0; i < k; i++) { + if (res[i] == max) ans.add(i); + } + return ans; + } +} diff --git a/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.go b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.go new file mode 100644 index 00000000..58f28eca --- /dev/null +++ b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.go @@ -0,0 +1,38 @@ +func busiestServers(k int, arrival []int, load []int) []int { + available := make([]int, 0, k) + for i := 0; i < k; i++ { + available = append(available, i) + } + sort.Ints(available) + busy := make([][2]int, 0) + res := make([]int, k) + for i, a := range arrival { + // remove finished + for len(busy) > 0 && busy[0][0] <= a { + x := busy[0][1] + busy = busy[1:] + available = append(available, i+((x-i)%k+k)%k) + sort.Ints(available) + } + if len(available) > 0 { + j := available[0] % k + available = available[1:] + busy = append(busy, [2]int{a + load[i], j}) + sort.Slice(busy, func(a, b int) bool { return busy[a][0] < busy[b][0] }) + res[j]++ + } + } + max := 0 + for _, r := range res { + if r > max { + max = r + } + } + ans := []int{} + for i, r := range res { + if r == max { + ans = append(ans, i) + } + } + return ans +} diff --git a/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.java b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.java new file mode 100644 index 00000000..a9bebd99 --- /dev/null +++ b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.java @@ -0,0 +1,27 @@ +import java.util.*; + +class Solution { + public List busiestServers(int k, int[] arrival, int[] load) { + PriorityQueue available = new PriorityQueue<>(); + for (int i = 0; i < k; i++) available.add(i); + PriorityQueue busy = new PriorityQueue<>((a, b) -> a[0] - b[0]); + int[] res = new int[k]; + for (int i = 0; i < arrival.length; i++) { + int a = arrival[i]; + while (!busy.isEmpty() && busy.peek()[0] <= a) { + int x = busy.poll()[1]; + available.add(i + ((x - i) % k + k) % k); + } + if (!available.isEmpty()) { + int j = available.poll() % k; + busy.add(new int[]{a + load[i], j}); + res[j]++; + } + } + int max = 0; + for (int r : res) max = Math.max(max, r); + List ans = new ArrayList<>(); + for (int i = 0; i < k; i++) if (res[i] == max) ans.add(i); + return ans; + } +} diff --git a/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.kt b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.kt new file mode 100644 index 00000000..e346bce0 --- /dev/null +++ b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.kt @@ -0,0 +1,22 @@ +class Solution { + fun busiestServers(k: Int, arrival: IntArray, load: IntArray): List { + val available = java.util.PriorityQueue() + for (i in 0 until k) available.add(i) + val busy = java.util.PriorityQueue>(compareBy { it.first }) + val res = IntArray(k) + for (i in arrival.indices) { + val a = arrival[i] + while (busy.isNotEmpty() && busy.peek().first <= a) { + val x = busy.poll().second + available.add(i + ((x - i) % k + k) % k) + } + if (available.isNotEmpty()) { + val j = available.poll() % k + busy.add(Pair(a + load[i], j)) + res[j]++ + } + } + val max = res.max() ?: 0 + return (0 until k).filter { res[it] == max } + } +} diff --git a/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.py b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.py new file mode 100644 index 00000000..a929abcb --- /dev/null +++ b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.py @@ -0,0 +1,19 @@ +class Solution: + def busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]: + available = list(range(k)) # already a min-heap + busy = [] + res = [0] * k + for i, a in enumerate(arrival): + while ( + busy and busy[0][0] <= a + ): # these are done, put them back as available + _, x = heapq.heappop(busy) + heapq.heappush( + available, i + (x - i) % k + ) # invariant: min(available) is at least i, at most i+k-1 + if available: + j = heapq.heappop(available) % k + heapq.heappush(busy, (a + load[i], j)) + res[j] += 1 + a = max(res) + return [i for i in range(k) if res[i] == a] diff --git a/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.py2 b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.py2 new file mode 100644 index 00000000..28733e2a --- /dev/null +++ b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def busiestServers(self, k, arrival, load): + """ + :type k: int + :type arrival: List[int] + :type load: List[int] + :rtype: List[int] + """ + import heapq + available = list(range(k)) # already a min-heap + busy = [] + res = [0] * k + for i, a in enumerate(arrival): + while busy and busy[0][0] <= a: + _, x = heapq.heappop(busy) + heapq.heappush(available, i + (x - i) % k) + if available: + j = heapq.heappop(available) % k + heapq.heappush(busy, (a + load[i], j)) + res[j] += 1 + max_count = max(res) + return [i for i in range(k) if res[i] == max_count] diff --git a/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.rb b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.rb new file mode 100644 index 00000000..4f061da2 --- /dev/null +++ b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.rb @@ -0,0 +1,24 @@ +# @param {Integer} k +# @param {Integer[]} arrival +# @param {Integer[]} load +# @return {Integer[]} +def busiest_servers(k, arrival, load) + available = (0...k).to_a + busy = [] + res = [0] * k + arrival.each_with_index do |a, i| + while !busy.empty? && busy[0][0] <= a + _, x = busy.shift + available << i + (x - i) % k + available.sort! + end + unless available.empty? + j = available.shift % k + busy << [a + load[i], j] + busy.sort_by! { |b| b[0] } + res[j] += 1 + end + end + max_count = res.max + res.each_index.select { |i| res[i] == max_count } +end diff --git a/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.rs b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.rs new file mode 100644 index 00000000..2136f5e5 --- /dev/null +++ b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.rs @@ -0,0 +1,30 @@ +use std::collections::BinaryHeap; +use std::cmp::Reverse; + +impl Solution { + pub fn busiest_servers(k: i32, arrival: Vec, load: Vec) -> Vec { + let k = k as usize; + let mut available: BinaryHeap> = (0..k as i32).map(Reverse).collect(); + let mut busy: BinaryHeap<(Reverse, i32)> = BinaryHeap::new(); + let mut res = vec![0; k]; + for i in 0..arrival.len() { + let a = arrival[i]; + while let Some(&(Reverse(end), x)) = busy.peek() { + if end <= a { + busy.pop(); + let offset = ((x - i as i32) % k as i32 + k as i32) % k as i32; + available.push(Reverse(i as i32 + offset)); + } else { + break; + } + } + if let Some(Reverse(j)) = available.pop() { + let j = j as usize % k; + busy.push((Reverse(a + load[i]), j as i32)); + res[j] += 1; + } + } + let max = *res.iter().max().unwrap(); + (0..k).filter(|&i| res[i] == max).map(|i| i as i32).collect() + } +} diff --git a/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.swift b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.swift new file mode 100644 index 00000000..2b42d2ca --- /dev/null +++ b/tests/1501-2000/1606. find-servers-that-handled-most-number-of-requests/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func busiestServers(_ k: Int, _ arrival: [Int], _ load: [Int]) -> [Int] { + var available = Set(0.. a - b); + const busy: [number, number][] = []; + const res: number[] = new Array(k).fill(0); + for (let i = 0; i < arrival.length; i++) { + const a = arrival[i]; + while (busy.length > 0 && busy[0][0] <= a) { + const x = busy.shift()![1]; + available.push(i + ((((x - i) % k) + k) % k)); + available.sort((a, b) => a - b); + } + if (available.length > 0) { + const j = available.shift()! % k; + busy.push([a + load[i], j]); + busy.sort((a, b) => a[0] - b[0]); + res[j]++; + } + } + const max = Math.max(...res); + const ans: number[] = []; + for (let i = 0; i < k; i++) { + if (res[i] === max) ans.push(i); + } + return ans; +} diff --git a/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/manifest.yaml b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/manifest.yaml new file mode 100644 index 00000000..6f636566 --- /dev/null +++ b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/manifest.yaml @@ -0,0 +1,453 @@ +entry: + id: 1608 + title: "special-array-with-x-elements-greater-than-or-equal-x" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().specialArray({nums})" + rust: "Solution::special_array({nums})" + python3: "Solution().specialArray({nums})" + python2: "Solution().specialArray({nums})" + ruby: "special_array({nums})" + java: "new Solution().specialArray({nums})" + csharp: "new Solution().SpecialArray({nums})" + kotlin: "Solution().specialArray({nums})" + go: "specialArray({nums})" + dart: "Solution().specialArray({nums})" + swift: "Solution().specialArray({nums})" + typescript: "specialArray({nums})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().specialArray(nums, {result})" + checker: | + class Checker: + def specialArray(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + valid = [x for x in range(len(nums) + 1) if sum(v >= x for v in nums) == x] + expected = valid[0] if valid else -1 + return result == expected + +seed: 1608 + +tests: + - name: example-one + in: + nums: [3, 5] + out: 2 + - name: example-two + in: + nums: [0, 0] + out: -1 + - name: example-three + in: + nums: [0, 4, 3, 0, 4] + out: 3 + - name: single-zero + in: + nums: [0] + out: -1 + - name: single-positive + in: + nums: [1] + out: 1 + - name: all-zero-five + in: + nums: [0, 0, 0, 0, 0] + out: -1 + - name: all-one-four + in: + nums: [1, 1, 1, 1] + out: -1 + - name: all-two-four + in: + nums: [2, 2, 2, 2] + out: -1 + - name: all-three-six + in: + nums: [3, 3, 3, 3, 3, 3] + out: -1 + - name: strictly-small + in: + nums: [0, 1, 2, 3] + out: 2 + - name: strictly-large + in: + nums: [4, 5, 6, 7] + out: 4 + - name: no-x-too-few + in: + nums: [0, 1, 1, 1] + out: -1 + - name: exact-one + in: + nums: [0, 0, 0, 9] + out: 1 + - name: exact-two + in: + nums: [0, 2, 2, 0] + out: 2 + - name: exact-three + in: + nums: [0, 3, 3, 3, 0] + out: 3 + - name: exact-four + in: + nums: [4, 4, 4, 4, 0, 0] + out: 4 + - name: boundary-values + in: + nums: [0, 1, 2, 99, 100] + out: -1 + - name: duplicate-threshold + in: + nums: [2, 2, 2, 3, 4] + out: -1 + - name: threshold-not-element + in: + nums: [0, 0, 4, 4, 4] + out: 3 + - name: negative-impossible-input-replaced + in: + nums: [0, 2, 5, 5, 8, 9] + out: 4 + - name: six-with-two-high + in: + nums: [0, 0, 0, 0, 10, 10] + out: 2 + - name: six-with-five-high + in: + nums: [0, 1, 2, 3, 4, 10] + out: 3 + - name: eight-balanced + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8] + out: -1 + - name: eight-high-tail + in: + nums: [0, 0, 0, 0, 0, 20, 20, 20] + out: 3 + - name: ten-all-high + in: + nums: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10] + out: 10 + - name: ten-below-threshold + in: + nums: [0, 1, 1, 2, 2, 3, 3, 4, 4, 4] + out: -1 + - name: twelve-mixed + in: + nums: [0, 0, 1, 2, 2, 3, 5, 5, 6, 8, 9, 12] + out: -1 + - name: fifteen-threshold-six + in: + nums: [0, 1, 2, 3, 4, 6, 6, 6, 7, 8, 9, 10, 11, 12, 13] + out: 7 + - name: fifteen-no-solution + in: + nums: [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4] + out: -1 + - name: twenty-threshold-ten + in: + nums: + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 18] + out: 10 + - name: twenty-all-max + in: + nums: + [ + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + 1000, + ] + out: 20 + - name: twenty-one-threshold-one + in: + nums: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1000] + out: 1 + - name: thirty-two-threshold-sixteen + in: + nums: + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + ] + out: 16 + - name: fifty-threshold-twenty-five + in: + nums: + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + ] + out: -1 + - name: hundred-threshold-fifty + in: + nums: + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + 63, + 64, + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + 99, + ] + out: -1 + - name: generated-small + in: + nums: + gen: "array" + len: 1 + of: + gen: "int" + min: 0 + max: 20 + elemType: "int" + seed: 16081 + - name: generated-medium + in: + nums: + gen: "array" + len: 10 + of: + gen: "int" + min: 0 + max: 100 + elemType: "int" + seed: 16082 + - name: generated-duplicates + in: + nums: + gen: "array" + len: 50 + of: + gen: "int" + min: 0 + max: 5 + elemType: "int" + seed: 16083 + - name: generated-large + in: + nums: + gen: "array" + len: 99 + of: + gen: "int" + min: 0 + max: 1000 + elemType: "int" + seed: 16084 + - name: generated-near-limit + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 1000 + elemType: "int" + seed: 16085 diff --git a/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.cpp b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.cpp new file mode 100644 index 00000000..30037376 --- /dev/null +++ b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int specialArray(vector& nums) { + vector ans(nums.size() + 1, 0); + for (int i = 0; i <= nums.size(); i++) { + int count = 0; + for (int ele : nums) { + if (i <= ele) count++; + } + ans[i] = count; + if (ans[i] == i) return i; + } + return -1; + } +}; diff --git a/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.cs b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.cs new file mode 100644 index 00000000..d510cf42 --- /dev/null +++ b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.cs @@ -0,0 +1,14 @@ +public class Solution { + public int SpecialArray(int[] nums) { + int[] ans = new int[nums.Length + 1]; + for (int i = 0; i <= nums.Length; i++) { + int count = 0; + foreach (int ele in nums) { + if (i <= ele) count++; + } + ans[i] = count; + if (ans[i] == i) return i; + } + return -1; + } +} diff --git a/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.dart b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.dart new file mode 100644 index 00000000..9283f670 --- /dev/null +++ b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.dart @@ -0,0 +1,14 @@ +class Solution { + int specialArray(List nums) { + List ans = List.filled(nums.length + 1, 0); + for (int i = 0; i <= nums.length; i++) { + int count = 0; + for (int ele in nums) { + if (i <= ele) count++; + } + ans[i] = count; + if (ans[i] == i) return i; + } + return -1; + } +} diff --git a/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.go b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.go new file mode 100644 index 00000000..4fba744a --- /dev/null +++ b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.go @@ -0,0 +1,16 @@ +func specialArray(nums []int) int { + ans := make([]int, len(nums)+1) + for i := 0; i <= len(nums); i++ { + count := 0 + for _, ele := range nums { + if i <= ele { + count++ + } + } + ans[i] = count + if ans[i] == i { + return i + } + } + return -1 +} diff --git a/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.java b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.java new file mode 100644 index 00000000..40d3b1ce --- /dev/null +++ b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.java @@ -0,0 +1,14 @@ +class Solution { + public int specialArray(int[] nums) { + int[] ans = new int[nums.length + 1]; + for (int i = 0; i <= nums.length; i++) { + int count = 0; + for (int ele : nums) { + if (i <= ele) count++; + } + ans[i] = count; + if (ans[i] == i) return i; + } + return -1; + } +} diff --git a/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.kt b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.kt new file mode 100644 index 00000000..3f9f7e70 --- /dev/null +++ b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun specialArray(nums: IntArray): Int { + val ans = IntArray(nums.size + 1) + for (i in 0..nums.size) { + var count = 0 + for (ele in nums) { + if (i <= ele) count++ + } + ans[i] = count + if (ans[i] == i) return i + } + return -1 + } +} diff --git a/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.py b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.py new file mode 100644 index 00000000..8042af98 --- /dev/null +++ b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.py @@ -0,0 +1,12 @@ +class Solution: + def specialArray(self, nums: List[int]) -> int: + ans = [] + for i in range(0, len(nums) + 1): + count = 0 + for ele in nums: + if i <= ele: + count += 1 + ans.append(count) + if ans[i] == i: + return i + return -1 diff --git a/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.py2 b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.py2 new file mode 100644 index 00000000..2cbc16bc --- /dev/null +++ b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def specialArray(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + ans=[] + for i in range(0,len(nums)+1): + count=0 + for ele in nums: + if i <=ele: + count+=1 + ans.append(count) + if ans[i] ==i: + return i + return -1 diff --git a/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.rb b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.rb new file mode 100644 index 00000000..41ae4e03 --- /dev/null +++ b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[]} nums +# @return {Integer} +def special_array(nums) + ans = [] + (0..nums.length).each do |i| + count = 0 + nums.each do |ele| + count += 1 if i <= ele + end + ans << count + return i if ans[i] == i + end + -1 +end diff --git a/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.rs b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.rs new file mode 100644 index 00000000..1d3d2342 --- /dev/null +++ b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn special_array(nums: Vec) -> i32 { + let mut ans = vec![0; nums.len() + 1]; + for i in 0..=nums.len() { + let mut count = 0; + for &ele in &nums { + if (i as i32) <= ele { + count += 1; + } + } + ans[i] = count; + if ans[i] == i as i32 { + return i as i32; + } + } + -1 + } +} diff --git a/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.swift b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.swift new file mode 100644 index 00000000..957bb660 --- /dev/null +++ b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.swift @@ -0,0 +1,14 @@ +class Solution { + func specialArray(_ nums: [Int]) -> Int { + var ans = [Int](repeating: 0, count: nums.count + 1) + for i in 0...nums.count { + var count = 0 + for ele in nums { + if i <= ele { count += 1 } + } + ans[i] = count + if ans[i] == i { return i } + } + return -1 + } +} diff --git a/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.ts b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.ts new file mode 100644 index 00000000..26e8d92e --- /dev/null +++ b/tests/1501-2000/1608. special-array-with-x-elements-greater-than-or-equal-x/sol.ts @@ -0,0 +1,12 @@ +function specialArray(nums: number[]): number { + const ans: number[] = new Array(nums.length + 1).fill(0); + for (let i = 0; i <= nums.length; i++) { + let count = 0; + for (const ele of nums) { + if (i <= ele) count++; + } + ans[i] = count; + if (ans[i] === i) return i; + } + return -1; +} diff --git a/tests/1501-2000/1609. even-odd-tree/manifest.yaml b/tests/1501-2000/1609. even-odd-tree/manifest.yaml new file mode 100644 index 00000000..ab720b6f --- /dev/null +++ b/tests/1501-2000/1609. even-odd-tree/manifest.yaml @@ -0,0 +1,230 @@ +entry: + id: 1609 + title: "even-odd-tree" + params: + root: + type: tree_node + call: + cpp: "Solution().isEvenOddTree({root})" + rust: "Solution::is_even_odd_tree({root})" + python3: "Solution().isEvenOddTree({root})" + python2: "Solution().isEvenOddTree({root})" + ruby: "is_even_odd_tree({root})" + java: "new Solution().isEvenOddTree({root})" + csharp: "new Solution().IsEvenOddTree({root})" + kotlin: "Solution().isEvenOddTree({root})" + go: "isEvenOddTree({root})" + dart: "Solution().isEvenOddTree({root})" + swift: "Solution().isEvenOddTree({root})" + typescript: "isEvenOddTree({root})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().isEvenOddTree(root, {result})" + checker: | + class Checker: + def isEvenOddTree(self, root, result): + if not isinstance(result, bool): + return False + if root is None: + return result is False + level = [root] + parity = 0 + while level: + values = [node.val for node in level] + if parity == 0: + if any(value % 2 == 0 for value in values): + expected = False + return result == expected + if any(left >= right for left, right in zip(values, values[1:])): + expected = False + return result == expected + else: + if any(value % 2 != 0 for value in values): + expected = False + return result == expected + if any(left <= right for left, right in zip(values, values[1:])): + expected = False + return result == expected + next_level = [] + for node in level: + if node.left is not None: + next_level.append(node.left) + if node.right is not None: + next_level.append(node.right) + level = next_level + parity ^= 1 + return result is True + +seed: 1609 + +tests: + - name: single-odd + in: + root: [1] + out: true + - name: single-even + in: + root: [2] + out: false + - name: two-level-decreasing + in: + root: [1, 10, 4] + out: true + - name: two-level-increasing-invalid + in: + root: [1, 4, 10] + out: false + - name: child-odd-invalid + in: + root: [1, 9, 4] + out: false + - name: root-even-invalid + in: + root: [2, 10, 4] + out: false + - name: perfect-three-valid-with-even-level + in: + root: [1, 4, 2, 3, 5, 7, 9] + out: true + - name: example-one + in: + root: [1, 10, 4, 3, null, 7, 9, 12, 8, 6, null, null, 2] + out: true + - name: example-two + in: + root: [5, 4, 2, 3, 3, 7] + out: false + - name: example-three + in: + root: [5, 9, 1, 3, 5, 7] + out: false + - name: perfect-three-valid + in: + root: [1, 10, 4, 3, 5, 7, 9] + out: true + - name: perfect-three-left-order-invalid + in: + root: [1, 10, 4, 5, 3, 7, 9] + out: false + - name: perfect-three-right-order-invalid + in: + root: [1, 10, 4, 3, 5, 9, 7] + out: false + - name: perfect-seven-valid + in: + root: [1, 10, 8, 3, 5, 7, 9, 20, 18, 16, 14, 12, 10, 8, 6] + out: true + - name: perfect-seven-level-one-parity + in: + root: [1, 10, 8, 3, 5, 7, 9, 11, 13, 15, 17, 19, 22, 23, 25] + out: false + - name: sparse-left-valid + in: + root: [1, 10, null, 3, null, null, null, 11] + out: true + - name: sparse-left-invalid-order + in: + root: [1, 10, null, 4] + out: false + - name: sparse-right-valid + in: + root: [1, null, 8] + out: true + - name: sparse-right-invalid-parity + in: + root: [1, null, 8, null, 4] + out: false + - name: alternating-chain-valid + in: + root: + [ + 1, + 10, + null, + 3, + null, + null, + null, + 12, + null, + null, + null, + null, + null, + null, + null, + 5, + ] + out: true + - name: alternating-chain-invalid-level-two + in: + root: [1, 10, null, 4] + out: false + - name: deep-level-order-invalid + in: + root: [1, 10, 8, 3, 9, 7, 9] + out: false + - name: boundary-values-valid + in: + root: [999999, 1000000, 999998] + out: true + - name: boundary-root-even + in: + root: [1000000] + out: false + - name: deep-complete-valid + in: + root: [1, 10, 8, 3, 5, 7, 9, 16, 14, 12, 10, 8, 6, 4, 2] + out: true + - name: deep-complete-invalid-level-three + in: + root: [1, 10, 8, 3, 5, 7, 9, 16, 14, 12, 10, 8, 6, 8, 2] + out: false + - name: deep-complete-even-boundary-invalid + in: + root: [1, 10, 8, 3, 5, 7, 9, 14, 12, 10, 8, 6, 4, 2, 2] + out: false + - name: four-level-valid-corrected + in: + root: [1, 10, 8, 3, 5, 7, 9, 20, 18, 16, 14, 12, 10, 8, 6] + out: true + - name: four-level-descending-invalid + in: + root: [1, 10, 8, 3, 5, 7, 9, 18, 20, 16, 14, 12, 10, 8, 6] + out: false + - name: missing-middle-child + in: + root: [1, 10, 8, 3, null, 7, 9] + out: true + - name: missing-middle-child-invalid + in: + root: [1, 10, 8, 3, null, 7, 9, 11, null, null, null, 12] + out: false + - name: duplicate-odd-level + in: + root: [1, 10, 8, 3, 5, 7, 7] + out: false + - name: duplicate-even-level + in: + root: [1, 10, 8, 3, 5, 8, 9] + out: false + - name: wide-valid-levels + in: + root: [1, 100, 98, 3, 5, 7, 9, 20, 18, 16, 14, 12, 10, 8, 6] + out: true + - name: wide-valid-root-level + in: + root: [1, 100, 98, 3, 5, 7, 11, 20, 18, 16, 14, 12, 10, 8, 6] + out: true + - name: parity-failure-deep + in: + root: [1, 10, 8, 3, 5, 7, 9, 20, 18, 16, 14, 12, 11, 8, 6] + out: false diff --git a/tests/1501-2000/1609. even-odd-tree/sol.cpp b/tests/1501-2000/1609. even-odd-tree/sol.cpp new file mode 100644 index 00000000..781e56f3 --- /dev/null +++ b/tests/1501-2000/1609. even-odd-tree/sol.cpp @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isEvenOddTree(TreeNode* root) { + vector> elements = {{}}; + function collect = [&](TreeNode* temp, int pos) { + if (temp == nullptr) return true; + if (elements.size() == pos) elements.push_back({}); + int posCheck = pos % 2; + int valCheck = temp->val % 2; + if (posCheck == 0 && valCheck != 0) { + if (!elements[pos].empty() && !(elements[pos].back() < temp->val)) return false; + elements[pos].push_back(temp->val); + } else if (posCheck != 0 && valCheck == 0) { + if (!elements[pos].empty() && !(elements[pos].back() > temp->val)) return false; + elements[pos].push_back(temp->val); + } else { + return false; + } + return collect(temp->left, pos + 1) && collect(temp->right, pos + 1); + }; + return collect(root, 0); + } +}; diff --git a/tests/1501-2000/1609. even-odd-tree/sol.cs b/tests/1501-2000/1609. even-odd-tree/sol.cs new file mode 100644 index 00000000..53884705 --- /dev/null +++ b/tests/1501-2000/1609. even-odd-tree/sol.cs @@ -0,0 +1,35 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + public bool IsEvenOddTree(TreeNode root) { + var elements = new List> { new List() }; + bool Collect(TreeNode temp, int pos) { + if (temp == null) return true; + if (elements.Count == pos) elements.Add(new List()); + int posCheck = pos % 2; + int valCheck = temp.val % 2; + if (posCheck == 0 && valCheck != 0) { + if (elements[pos].Count > 0 && !(elements[pos][elements[pos].Count - 1] < temp.val)) return false; + elements[pos].Add(temp.val); + } else if (posCheck != 0 && valCheck == 0) { + if (elements[pos].Count > 0 && !(elements[pos][elements[pos].Count - 1] > temp.val)) return false; + elements[pos].Add(temp.val); + } else { + return false; + } + return Collect(temp.left, pos + 1) && Collect(temp.right, pos + 1); + } + return Collect(root, 0); + } +} diff --git a/tests/1501-2000/1609. even-odd-tree/sol.dart b/tests/1501-2000/1609. even-odd-tree/sol.dart new file mode 100644 index 00000000..b95cd984 --- /dev/null +++ b/tests/1501-2000/1609. even-odd-tree/sol.dart @@ -0,0 +1,31 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * int val; + * TreeNode? left; + * TreeNode? right; + * TreeNode([this.val = 0, this.left, this.right]); + * } + */ +class Solution { + bool isEvenOddTree(TreeNode? root) { + List> elements = [[]]; + bool collect(TreeNode? temp, int pos) { + if (temp == null) return true; + if (elements.length == pos) elements.add([]); + int posCheck = pos % 2; + int valCheck = temp.val % 2; + if (posCheck == 0 && valCheck != 0) { + if (elements[pos].isNotEmpty && !(elements[pos].last < temp.val)) return false; + elements[pos].add(temp.val); + } else if (posCheck != 0 && valCheck == 0) { + if (elements[pos].isNotEmpty && !(elements[pos].last > temp.val)) return false; + elements[pos].add(temp.val); + } else { + return false; + } + return collect(temp.left, pos + 1) && collect(temp.right, pos + 1); + } + return collect(root, 0); + } +} diff --git a/tests/1501-2000/1609. even-odd-tree/sol.go b/tests/1501-2000/1609. even-odd-tree/sol.go new file mode 100644 index 00000000..0d5ad2ee --- /dev/null +++ b/tests/1501-2000/1609. even-odd-tree/sol.go @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func isEvenOddTree(root *TreeNode) bool { + elements := [][]int{{}} + var collect func(*TreeNode, int) bool + collect = func(temp *TreeNode, pos int) bool { + if temp == nil { + return true + } + if len(elements) == pos { + elements = append(elements, []int{}) + } + posCheck := pos % 2 + valCheck := temp.Val % 2 + if posCheck == 0 && valCheck != 0 { + if len(elements[pos]) > 0 && !(elements[pos][len(elements[pos])-1] < temp.Val) { + return false + } + elements[pos] = append(elements[pos], temp.Val) + } else if posCheck != 0 && valCheck == 0 { + if len(elements[pos]) > 0 && !(elements[pos][len(elements[pos])-1] > temp.Val) { + return false + } + elements[pos] = append(elements[pos], temp.Val) + } else { + return false + } + return collect(temp.Left, pos+1) && collect(temp.Right, pos+1) + } + return collect(root, 0) +} diff --git a/tests/1501-2000/1609. even-odd-tree/sol.java b/tests/1501-2000/1609. even-odd-tree/sol.java new file mode 100644 index 00000000..b0c3060e --- /dev/null +++ b/tests/1501-2000/1609. even-odd-tree/sol.java @@ -0,0 +1,39 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean isEvenOddTree(TreeNode root) { + List> elements = new ArrayList<>(); + elements.add(new ArrayList<>()); + return collect(root, 0, elements); + } + + private boolean collect(TreeNode temp, int pos, List> elements) { + if (temp == null) return true; + if (elements.size() == pos) elements.add(new ArrayList<>()); + int posCheck = pos % 2; + int valCheck = temp.val % 2; + if (posCheck == 0 && valCheck != 0) { + if (!elements.get(pos).isEmpty() && !(elements.get(pos).get(elements.get(pos).size() - 1) < temp.val)) return false; + elements.get(pos).add(temp.val); + } else if (posCheck != 0 && valCheck == 0) { + if (!elements.get(pos).isEmpty() && !(elements.get(pos).get(elements.get(pos).size() - 1) > temp.val)) return false; + elements.get(pos).add(temp.val); + } else { + return false; + } + return collect(temp.left, pos + 1, elements) && collect(temp.right, pos + 1, elements); + } +} diff --git a/tests/1501-2000/1609. even-odd-tree/sol.kt b/tests/1501-2000/1609. even-odd-tree/sol.kt new file mode 100644 index 00000000..d593c6e1 --- /dev/null +++ b/tests/1501-2000/1609. even-odd-tree/sol.kt @@ -0,0 +1,32 @@ +/** + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + fun isEvenOddTree(root: TreeNode?): Boolean { + val elements = mutableListOf>(mutableListOf()) + fun collect(temp: TreeNode?, pos: Int): Boolean { + if (temp == null) return true + if (elements.size == pos) elements.add(mutableListOf()) + val posCheck = pos % 2 + val valCheck = temp.`val` % 2 + if (posCheck == 0 && valCheck != 0) { + if (elements[pos].isNotEmpty() && !(elements[pos].last() < temp.`val`)) return false + elements[pos].add(temp.`val`) + } else if (posCheck != 0 && valCheck == 0) { + if (elements[pos].isNotEmpty() && !(elements[pos].last() > temp.`val`)) return false + elements[pos].add(temp.`val`) + } else { + return false + } + return collect(temp.left, pos + 1) && collect(temp.right, pos + 1) + } + return collect(root, 0) + } +} diff --git a/tests/1501-2000/1609. even-odd-tree/sol.py b/tests/1501-2000/1609. even-odd-tree/sol.py new file mode 100644 index 00000000..21e297b9 --- /dev/null +++ b/tests/1501-2000/1609. even-odd-tree/sol.py @@ -0,0 +1,30 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isEvenOddTree(self, root: Optional[TreeNode]) -> bool: + elements = [[]] + + def collect(temp, pos): + if not temp: + return True + if len(elements) == pos: + elements.append([]) + posCheck = pos % 2 + valCheck = temp.val % 2 + if posCheck == 0 and valCheck != 0: + if elements[pos] and not elements[pos][-1] < temp.val: + return False + elements[pos].append(temp.val) + elif posCheck != 0 and valCheck == 0: + if elements[pos] and not elements[pos][-1] > temp.val: + return False + elements[pos].append(temp.val) + else: + return False + return collect(temp.left, pos + 1) and collect(temp.right, pos + 1) + + return collect(root, 0) diff --git a/tests/1501-2000/1609. even-odd-tree/sol.py2 b/tests/1501-2000/1609. even-odd-tree/sol.py2 new file mode 100644 index 00000000..ea72277b --- /dev/null +++ b/tests/1501-2000/1609. even-odd-tree/sol.py2 @@ -0,0 +1,32 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution(object): + def isEvenOddTree(self, root): + """ + :type root: Optional[TreeNode] + :rtype: bool + """ + elements = [[]] + def collect(temp, pos): + if not temp: + return True + if len(elements) == pos: + elements.append([]) + posCheck = pos % 2 + valCheck = temp.val % 2 + if posCheck == 0 and valCheck != 0: + if elements[pos] and not elements[pos][-1] < temp.val: + return False + elements[pos].append(temp.val) + elif posCheck != 0 and valCheck == 0: + if elements[pos] and not elements[pos][-1] > temp.val: + return False + elements[pos].append(temp.val) + else: + return False + return collect(temp.left, pos + 1) and collect(temp.right, pos + 1) + return collect(root, 0) diff --git a/tests/1501-2000/1609. even-odd-tree/sol.rb b/tests/1501-2000/1609. even-odd-tree/sol.rb new file mode 100644 index 00000000..74a5b968 --- /dev/null +++ b/tests/1501-2000/1609. even-odd-tree/sol.rb @@ -0,0 +1,31 @@ +# Definition for a binary tree node. +# class TreeNode +# attr_accessor :val, :left, :right +# def initialize(val = 0, left = nil, right = nil) +# @val = val +# @left = left +# @right = right +# end +# end +# @param {TreeNode} root +# @return {Boolean} +def is_even_odd_tree(root) + elements = [[]] + collect = lambda do |temp, pos| + return true if temp.nil? + elements << [] if elements.length == pos + pos_check = pos % 2 + val_check = temp.val % 2 + if pos_check == 0 && val_check != 0 + return false if !elements[pos].empty? && !(elements[pos][-1] < temp.val) + elements[pos] << temp.val + elsif pos_check != 0 && val_check == 0 + return false if !elements[pos].empty? && !(elements[pos][-1] > temp.val) + elements[pos] << temp.val + else + return false + end + collect.call(temp.left, pos + 1) && collect.call(temp.right, pos + 1) + end + collect.call(root, 0) +end diff --git a/tests/1501-2000/1609. even-odd-tree/sol.rs b/tests/1501-2000/1609. even-odd-tree/sol.rs new file mode 100644 index 00000000..55217809 --- /dev/null +++ b/tests/1501-2000/1609. even-odd-tree/sol.rs @@ -0,0 +1,55 @@ +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +impl Solution { + pub fn is_even_odd_tree(root: Option>>) -> bool { + fn collect(temp: Option>>, pos: usize, elements: &mut Vec>) -> bool { + if let Some(node) = temp { + if elements.len() == pos { elements.push(vec![]); } + let node = node.borrow(); + let pos_check = pos % 2; + let val_check = node.val % 2; + if pos_check == 0 && val_check != 0 { + if let Some(&last) = elements[pos].last() { + if !(last < node.val) { return false; } + } + elements[pos].push(node.val); + } else if pos_check != 0 && val_check == 0 { + if let Some(&last) = elements[pos].last() { + if !(last > node.val) { return false; } + } + elements[pos].push(node.val); + } else { + return false; + } + let left = match &node.left { + Some(l) => Some(l.clone()), + None => None, + }; + let right = match &node.right { + Some(r) => Some(r.clone()), + None => None, + }; + return collect(left, pos + 1, elements) && collect(right, pos + 1, elements); + } + true + } + let mut elements = vec![vec![]]; + collect(root, 0, &mut elements) + } +} diff --git a/tests/1501-2000/1609. even-odd-tree/sol.swift b/tests/1501-2000/1609. even-odd-tree/sol.swift new file mode 100644 index 00000000..861fcd29 --- /dev/null +++ b/tests/1501-2000/1609. even-odd-tree/sol.swift @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public var val: Int + * public var left: TreeNode? + * public var right: TreeNode? + * public init() { self.val = 0; self.left = nil; self.right = nil; } + * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } + * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { + * self.val = val + * self.left = left + * self.right = right + * } + * } + */ +class Solution { + func isEvenOddTree(_ root: TreeNode?) -> Bool { + var elements: [[Int]] = [[]] + func collect(_ temp: TreeNode?, _ pos: Int) -> Bool { + guard let temp = temp else { return true } + if elements.count == pos { elements.append([]) } + let posCheck = pos % 2 + let valCheck = temp.val % 2 + if posCheck == 0 && valCheck != 0 { + if !elements[pos].isEmpty && !(elements[pos].last! < temp.val) { return false } + elements[pos].append(temp.val) + } else if posCheck != 0 && valCheck == 0 { + if !elements[pos].isEmpty && !(elements[pos].last! > temp.val) { return false } + elements[pos].append(temp.val) + } else { + return false + } + return collect(temp.left, pos + 1) && collect(temp.right, pos + 1) + } + return collect(root, 0) + } +} diff --git a/tests/1501-2000/1609. even-odd-tree/sol.ts b/tests/1501-2000/1609. even-odd-tree/sol.ts new file mode 100644 index 00000000..eb53ccc4 --- /dev/null +++ b/tests/1501-2000/1609. even-odd-tree/sol.ts @@ -0,0 +1,42 @@ +/** + * Definition for a binary tree node. + * 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 isEvenOddTree(root: TreeNode | null): boolean { + const elements: number[][] = [[]]; + function collect(temp: TreeNode | null, pos: number): boolean { + if (temp === null) return true; + if (elements.length === pos) elements.push([]); + const posCheck = pos % 2; + const valCheck = temp.val % 2; + if (posCheck === 0 && valCheck !== 0) { + if ( + elements[pos].length > 0 && + !(elements[pos][elements[pos].length - 1] < temp.val) + ) + return false; + elements[pos].push(temp.val); + } else if (posCheck !== 0 && valCheck === 0) { + if ( + elements[pos].length > 0 && + !(elements[pos][elements[pos].length - 1] > temp.val) + ) + return false; + elements[pos].push(temp.val); + } else { + return false; + } + return collect(temp.left, pos + 1) && collect(temp.right, pos + 1); + } + return collect(root, 0); +} diff --git a/tests/1501-2000/1610. maximum-number-of-visible-points/manifest.yaml b/tests/1501-2000/1610. maximum-number-of-visible-points/manifest.yaml new file mode 100644 index 00000000..53b10614 --- /dev/null +++ b/tests/1501-2000/1610. maximum-number-of-visible-points/manifest.yaml @@ -0,0 +1,542 @@ +entry: + id: 1610 + title: "maximum-number-of-visible-points" + params: + points: + type: array + items: + type: array + items: + type: int + angle: + type: int + location: + type: array + items: + type: int + call: + cpp: "Solution().visiblePoints({points}, {angle}, {location})" + rust: "Solution::visible_points({points}, {angle}, {location})" + python3: "Solution().visiblePoints({points}, {angle}, {location})" + python2: "Solution().visiblePoints({points}, {angle}, {location})" + ruby: "visible_points({points}, {angle}, {location})" + java: "new Solution().visiblePoints({points}, {angle}, {location})" + csharp: "new Solution().VisiblePoints({points}, {angle}, {location})" + kotlin: "Solution().visiblePoints({points}, {angle}, {location})" + go: "visiblePoints({points}, {angle}, {location})" + dart: "Solution().visiblePoints({points}, {angle}, {location})" + swift: "Solution().visiblePoints({points}, {angle}, {location})" + typescript: "visiblePoints({points}, {angle}, {location})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().visiblePoints(points, angle, location, {result})" + checker: | + import math + + class Checker: + def visiblePoints(self, points, angle, location, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + lx, ly = location + same = 0 + values = [] + for x, y in points: + dx, dy = x - lx, y - ly + if dx == 0 and dy == 0: + same += 1 + else: + values.append(math.degrees(math.atan2(dy, dx))) + if not values: + return result == same + values.sort() + doubled = values + [x + 360.0 for x in values] + best = 0 + left = 0 + eps = 1e-10 + for right in range(len(doubled)): + while doubled[right] - doubled[left] > angle + eps: + left += 1 + if right - left + 1 > best: + best = right - left + 1 + return result == same + min(best, len(values)) + +seed: 16101610 + +tests: + - name: example-one + in: + points: + - [2, 1] + - [2, 2] + - [3, 3] + angle: 90 + location: [1, 1] + out: 3 + - name: example-two-with-location-point + in: + points: + - [2, 1] + - [2, 2] + - [3, 4] + - [1, 1] + angle: 90 + location: [1, 1] + out: 4 + - name: example-three + in: + points: + - [1, 0] + - [2, 1] + angle: 13 + location: [1, 1] + out: 1 + - name: all-at-location + in: + points: + - [5, 5] + - [5, 5] + - [5, 5] + angle: 0 + location: [5, 5] + out: 3 + - name: one-point-zero-angle + in: + points: + - [1, 0] + angle: 0 + location: [0, 0] + out: 1 + - name: opposite-points-zero-angle + in: + points: + - [51, 50] + - [49, 50] + angle: 0 + location: [50, 50] + out: 1 + - name: full-circle-excluded + in: + points: + - [51, 50] + - [50, 51] + - [49, 50] + - [50, 49] + angle: 359 + location: [50, 50] + out: 4 + - name: cardinal-quarter + in: + points: + - [51, 50] + - [50, 51] + - [49, 50] + - [50, 49] + angle: 90 + location: [50, 50] + out: 2 + - name: wrap-around-east + in: + points: + - [60, 49] + - [60, 50] + - [60, 51] + - [50, 60] + angle: 20 + location: [50, 50] + out: 3 + - name: duplicate-rays + in: + points: + - [2, 2] + - [4, 4] + - [6, 6] + - [3, 0] + angle: 1 + location: [0, 0] + out: 3 + - name: negative-relative-coordinates + in: + points: + - [0, 0] + - [0, 1] + - [1, 0] + - [1, 1] + angle: 45 + location: [1, 1] + out: 3 + - name: boundary-inclusive + in: + points: + - [1, 0] + - [1, 1] + - [0, 1] + angle: 45 + location: [0, 0] + out: 2 + - name: vertical-line + in: + points: + - [2, 5] + - [2, 6] + - [2, 7] + - [1, 5] + angle: 0 + location: [2, 5] + out: 3 + - name: angle-one + in: + points: + - [100, 1] + - [100, 2] + - [99, 0] + - [98, 0] + angle: 1 + location: [0, 0] + out: 3 + - name: angle-180 + in: + points: + - [51, 50] + - [50, 51] + - [49, 50] + - [50, 49] + angle: 180 + location: [50, 50] + out: 3 + - name: clustered-diagonal + in: + points: + - [10, 1] + - [10, 2] + - [10, 3] + - [1, 10] + - [0, 10] + angle: 15 + location: [0, 0] + out: 3 + - name: location-on-boundary + in: + points: + - [1, 1] + - [2, 1] + - [1, 2] + - [0, 1] + angle: 90 + location: [1, 1] + out: 3 + - name: same-ray-plus-opposite + in: + points: + - [51, 51] + - [52, 52] + - [53, 53] + - [49, 49] + angle: 10 + location: [50, 50] + out: 3 + - name: sparse-square + in: + points: + - [0, 0] + - [100, 0] + - [0, 100] + - [100, 100] + angle: 1 + location: [50, 50] + out: 1 + - name: repeated-location-and-ray + in: + points: + - [5, 5] + - [5, 5] + - [6, 5] + - [7, 5] + - [5, 6] + angle: 0 + location: [5, 5] + out: 4 + - name: obtuse-cluster + in: + points: + - [51, 50] + - [50, 51] + - [49, 50] + - [50, 49] + - [51, 51] + angle: 135 + location: [50, 50] + out: 3 + - name: near-limit-coordinates + in: + points: + - [100, 100] + - [100, 0] + - [0, 100] + - [0, 0] + - [50, 50] + angle: 90 + location: [50, 50] + out: 3 + - name: horizontal-cluster + in: + points: + - [0, 50] + - [1, 50] + - [2, 50] + - [100, 50] + - [50, 0] + angle: 1 + location: [50, 50] + out: 3 + - name: narrow-negative-side + in: + points: + - [0, 1] + - [0, 2] + - [1, 0] + - [2, 0] + angle: 10 + location: [1, 1] + out: 1 + - name: broad-view + in: + points: + - [0, 0] + - [100, 0] + - [0, 100] + - [100, 100] + - [50, 50] + angle: 270 + location: [50, 50] + out: 5 + - name: diagonal-boundary + in: + points: + - [2, 1] + - [3, 2] + - [4, 3] + - [3, 1] + angle: 0 + location: [1, 0] + out: 3 + - name: points-at-extremes + in: + points: + - [0, 0] + - [0, 100] + - [100, 0] + - [100, 100] + angle: 45 + location: [0, 0] + out: 3 + - name: many-collinear + in: + points: + - [1, 0] + - [2, 0] + - [3, 0] + - [4, 0] + - [5, 0] + - [0, 1] + angle: 0 + location: [0, 0] + out: 5 + - name: angle-359-with-location + in: + points: + - [50, 50] + - [51, 50] + - [50, 51] + - [49, 50] + - [50, 49] + angle: 359 + location: [50, 50] + out: 5 + - name: diagonal-location + in: + points: + - [10, 10] + - [11, 10] + - [10, 11] + - [9, 10] + - [10, 9] + angle: 90 + location: [10, 10] + out: 3 + - name: small-grid + in: + points: + - [0, 0] + - [0, 1] + - [1, 0] + - [1, 1] + - [2, 0] + - [0, 2] + angle: 90 + location: [0, 0] + out: 6 + - name: duplicate-all-directions + in: + points: + - [51, 50] + - [51, 50] + - [50, 51] + - [50, 51] + - [49, 50] + - [49, 50] + angle: 90 + location: [50, 50] + out: 4 + - name: zero-angle-location + in: + points: + - [1, 1] + - [2, 1] + - [1, 1] + - [0, 1] + angle: 0 + location: [1, 1] + out: 3 + - name: all-visible-270 + in: + points: + - [51, 50] + - [50, 51] + - [49, 50] + - [50, 49] + angle: 270 + location: [50, 50] + out: 4 + - name: gen-random-small + in: + points: + gen: "array" + len: 20 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 100 + elemType: "int" + angle: + gen: "int" + min: 0 + max: 359 + location: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 100 + elemType: "int" + - name: gen-random-medium + in: + points: + gen: "array" + len: 1000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 100 + elemType: "int" + angle: + gen: "int" + min: 0 + max: 359 + location: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 100 + elemType: "int" + - name: gen-random-large + in: + points: + gen: "array" + len: 50000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 100 + elemType: "int" + angle: + gen: "int" + min: 0 + max: 359 + location: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 100 + elemType: "int" + - name: gen-random-near-limit + in: + points: + gen: "array" + len: 100000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 100 + elemType: "int" + angle: + gen: "int" + min: 0 + max: 359 + location: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 100 + elemType: "int" + - name: gen-dense-boundary + in: + points: + gen: "array" + len: 100000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 100 + elemType: "int" + angle: + gen: "int" + min: 1 + max: 10 + location: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 100 + elemType: "int" diff --git a/tests/1501-2000/1610. maximum-number-of-visible-points/sol.cpp b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.cpp new file mode 100644 index 00000000..51f81974 --- /dev/null +++ b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.cpp @@ -0,0 +1,41 @@ +#include +#include +#include + +class Solution { +public: + int visiblePoints(vector>& points, int angle, vector& location) { + vector angles; + int same = 0; + int x0 = location[0], y0 = location[1]; + + for (auto& p : points) { + int dx = p[0] - x0; + int dy = p[1] - y0; + if (dx == 0 && dy == 0) { + same++; + continue; + } + double ang = atan2(dy, dx) * 180.0 / M_PI; + angles.push_back(ang); + } + + if (angles.empty()) return same; + + sort(angles.begin(), angles.end()); + int n = angles.size(); + vector full = angles; + for (double a : angles) full.push_back(a + 360); + + int maxVis = 0; + int j = 0; + for (int i = 0; i < n; i++) { + while (j < full.size() && full[j] - full[i] <= angle) { + j++; + } + maxVis = max(maxVis, j - i); + } + + return maxVis + same; + } +}; diff --git a/tests/1501-2000/1610. maximum-number-of-visible-points/sol.cs b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.cs new file mode 100644 index 00000000..ac198fb8 --- /dev/null +++ b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +public class Solution { + public int VisiblePoints(IList> points, int angle, IList location) { + List angles = new List(); + int same = 0; + int x0 = location[0], y0 = location[1]; + + foreach (var p in points) { + int dx = p[0] - x0; + int dy = p[1] - y0; + if (dx == 0 && dy == 0) { + same++; + continue; + } + double ang = Math.Atan2(dy, dx) * 180.0 / Math.PI; + angles.Add(ang); + } + + if (angles.Count == 0) return same; + + angles.Sort(); + int n = angles.Count; + List full = new List(angles); + foreach (double a in angles) full.Add(a + 360); + + int maxVis = 0; + int j = 0; + for (int i = 0; i < n; i++) { + while (j < full.Count && full[j] - full[i] <= angle) { + j++; + } + maxVis = Math.Max(maxVis, j - i); + } + + return maxVis + same; + } +} diff --git a/tests/1501-2000/1610. maximum-number-of-visible-points/sol.dart b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.dart new file mode 100644 index 00000000..2feefac7 --- /dev/null +++ b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.dart @@ -0,0 +1,40 @@ +import 'dart:math'; + +class Solution { + int visiblePoints(List> points, int angle, List location) { + List angles = []; + int same = 0; + int x0 = location[0], y0 = location[1]; + + for (var p in points) { + int dx = p[0] - x0; + int dy = p[1] - y0; + if (dx == 0 && dy == 0) { + same++; + continue; + } + double ang = atan2(dy.toDouble(), dx.toDouble()) * 180 / pi; + angles.add(ang); + } + + if (angles.isEmpty) return same; + + angles.sort(); + int n = angles.length; + List full = List.from(angles); + for (var a in angles) { + full.add(a + 360); + } + + int maxVis = 0; + int j = 0; + for (int i = 0; i < n; i++) { + while (j < full.length && full[j] - full[i] <= angle.toDouble()) { + j++; + } + if (j - i > maxVis) maxVis = j - i; + } + + return maxVis + same; + } +} diff --git a/tests/1501-2000/1610. maximum-number-of-visible-points/sol.go b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.go new file mode 100644 index 00000000..d8b4faf8 --- /dev/null +++ b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.go @@ -0,0 +1,41 @@ +func visiblePoints(points [][]int, angle int, location []int) int { + angles := []float64{} + same := 0 + x0, y0 := location[0], location[1] + + for _, p := range points { + dx := p[0] - x0 + dy := p[1] - y0 + if dx == 0 && dy == 0 { + same++ + continue + } + ang := math.Atan2(float64(dy), float64(dx)) * 180.0 / math.Pi + angles = append(angles, ang) + } + + if len(angles) == 0 { + return same + } + + sort.Float64s(angles) + n := len(angles) + full := make([]float64, 0, 2*n) + full = append(full, angles...) + for _, a := range angles { + full = append(full, a+360) + } + + maxVis := 0 + j := 0 + for i := 0; i < n; i++ { + for j < len(full) && full[j]-full[i] <= float64(angle) { + j++ + } + if j-i > maxVis { + maxVis = j - i + } + } + + return maxVis + same +} diff --git a/tests/1501-2000/1610. maximum-number-of-visible-points/sol.java b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.java new file mode 100644 index 00000000..3ee73468 --- /dev/null +++ b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.java @@ -0,0 +1,47 @@ +import java.util.*; + +class Solution { + public int visiblePoints(List> points, int angle, List location) { + int[][] pointArray = new int[points.size()][2]; + for (int i = 0; i < points.size(); i++) { + pointArray[i][0] = points.get(i).get(0); + pointArray[i][1] = points.get(i).get(1); + } + return visiblePoints(pointArray, angle, new int[] {location.get(0), location.get(1)}); + } + + public int visiblePoints(int[][] points, int angle, int[] location) { + List angles = new ArrayList<>(); + int same = 0; + int x0 = location[0], y0 = location[1]; + + for (int[] p : points) { + int dx = p[0] - x0; + int dy = p[1] - y0; + if (dx == 0 && dy == 0) { + same++; + continue; + } + double ang = Math.toDegrees(Math.atan2(dy, dx)); + angles.add(ang); + } + + if (angles.isEmpty()) return same; + + Collections.sort(angles); + int n = angles.size(); + List full = new ArrayList<>(angles); + for (double a : angles) full.add(a + 360); + + int maxVis = 0; + int j = 0; + for (int i = 0; i < n; i++) { + while (j < full.size() && full.get(j) - full.get(i) <= angle) { + j++; + } + maxVis = Math.max(maxVis, j - i); + } + + return maxVis + same; + } +} diff --git a/tests/1501-2000/1610. maximum-number-of-visible-points/sol.kt b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.kt new file mode 100644 index 00000000..1b9d1c72 --- /dev/null +++ b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.kt @@ -0,0 +1,40 @@ +class Solution { + fun visiblePoints(points: List>, angle: Int, location: List): Int { + return visiblePoints(points.map { it.toIntArray() }.toTypedArray(), angle, location.toIntArray()) + } + + fun visiblePoints(points: Array, angle: Int, location: IntArray): Int { + val angles = mutableListOf() + var same = 0 + val x0 = location[0] + val y0 = location[1] + + for (p in points) { + val dx = p[0] - x0 + val dy = p[1] - y0 + if (dx == 0 && dy == 0) { + same++ + continue + } + val ang = Math.toDegrees(Math.atan2(dy.toDouble(), dx.toDouble())) + angles.add(ang) + } + + if (angles.isEmpty()) return same + + angles.sort() + val n = angles.size + val full = angles + angles.map { it + 360 } + + var maxVis = 0 + var j = 0 + for (i in 0 until n) { + while (j < full.size && full[j] - full[i] <= angle) { + j++ + } + maxVis = maxOf(maxVis, j - i) + } + + return maxVis + same + } +} diff --git a/tests/1501-2000/1610. maximum-number-of-visible-points/sol.py b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.py new file mode 100644 index 00000000..57368047 --- /dev/null +++ b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.py @@ -0,0 +1,44 @@ +import numpy as np + + +class Solution: + def visiblePoints( + self, points: List[List[int]], angle: int, location: List[int] + ) -> int: + pts = np.array(points) + loc = np.array(location) + + # 1. Vectorized Radial Projection + # Translate points to origin (observer location) + diff = pts - loc + + # Identify points at the same location (Singularities) + is_same = np.all(diff == 0, axis=1) + same_pos_count = np.sum(is_same) + + # Filter out singularities for angular calculation + valid_diff = diff[~is_same] + if valid_diff.size == 0: + return int(same_pos_count) + + # 2. Coordinate Transformation (Atan2 SIMD) + # Calculate degrees for all points in a single vectorized call + angles = np.degrees(np.arctan2(valid_diff[:, 1], valid_diff[:, 0])) + angles.sort() + + # 3. Manifold Linearization (Circular Wrap) + # Duplicate the manifold to handle the 360° boundary + full_manifold = np.concatenate([angles, angles + 360]) + + # 4. Vectorized Sliding Window (The Search Partition) + # For every starting angle, find the furthest 'right' index + # where angle_right <= angle_start + field_of_view + n = len(angles) + # searchsorted performs a vectorized binary search for every element + right_indices = np.searchsorted(full_manifold, angles + angle, side="right") + + # Visibility counts = right_index - current_index + left_indices = np.arange(n) + max_visible = np.max(right_indices - left_indices) + + return int(max_visible + same_pos_count) diff --git a/tests/1501-2000/1610. maximum-number-of-visible-points/sol.py2 b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.py2 new file mode 100644 index 00000000..b6deb2ee --- /dev/null +++ b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.py2 @@ -0,0 +1,38 @@ +class Solution(object): + def visiblePoints(self, points, angle, location): + """ + :type points: List[List[int]] + :type angle: int + :type location: List[int] + :rtype: int + """ + import math + + same = 0 + angles = [] + x0, y0 = location + + for x, y in points: + dx = x - x0 + dy = y - y0 + if dx == 0 and dy == 0: + same += 1 + continue + ang = math.degrees(math.atan2(dy, dx)) + angles.append(ang) + + if not angles: + return same + + angles.sort() + full = angles + [a + 360 for a in angles] + n = len(angles) + + max_vis = 0 + j = 0 + for i in range(n): + while j < len(full) and full[j] - full[i] <= angle: + j += 1 + max_vis = max(max_vis, j - i) + + return max_vis + same diff --git a/tests/1501-2000/1610. maximum-number-of-visible-points/sol.rb b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.rb new file mode 100644 index 00000000..e3ec9fb4 --- /dev/null +++ b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.rb @@ -0,0 +1,37 @@ +# @param {Integer[][]} points +# @param {Integer} angle +# @param {Integer[]} location +# @return {Integer} +def visible_points(points, angle, location) + same = 0 + angles = [] + x0, y0 = location + + points.each do |p| + dx = p[0] - x0 + dy = p[1] - y0 + if dx == 0 && dy == 0 + same += 1 + next + end + ang = Math.atan2(dy, dx) * 180.0 / Math::PI + angles << ang + end + + return same if angles.empty? + + angles.sort! + n = angles.length + full = angles + angles.map { |a| a + 360 } + + max_vis = 0 + j = 0 + (0...n).each do |i| + while j < full.length && full[j] - full[i] <= angle + j += 1 + end + max_vis = [max_vis, j - i].max + end + + max_vis + same +end diff --git a/tests/1501-2000/1610. maximum-number-of-visible-points/sol.rs b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.rs new file mode 100644 index 00000000..9fc33c19 --- /dev/null +++ b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.rs @@ -0,0 +1,43 @@ +impl Solution { + pub fn visible_points(points: Vec>, angle: i32, location: Vec) -> i32 { + use std::f64::consts::PI; + + let mut angles: Vec = Vec::new(); + let mut same = 0; + let x0 = location[0]; + let y0 = location[1]; + + for p in &points { + let dx = p[0] - x0; + let dy = p[1] - y0; + if dx == 0 && dy == 0 { + same += 1; + continue; + } + let ang = (dy as f64).atan2(dx as f64) * 180.0 / PI; + angles.push(ang); + } + + if angles.is_empty() { + return same; + } + + angles.sort_by(|a, b| a.partial_cmp(b).unwrap()); + let n = angles.len(); + let mut full: Vec = angles.clone(); + for &a in &angles { + full.push(a + 360.0); + } + + let mut max_vis = 0; + let mut j = 0; + for i in 0..n { + while j < full.len() && full[j] - full[i] <= angle as f64 { + j += 1; + } + max_vis = max_vis.max(j - i); + } + + (max_vis as i32) + same + } +} diff --git a/tests/1501-2000/1610. maximum-number-of-visible-points/sol.swift b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.swift new file mode 100644 index 00000000..19c1b1b0 --- /dev/null +++ b/tests/1501-2000/1610. maximum-number-of-visible-points/sol.swift @@ -0,0 +1,36 @@ +class Solution { + func visiblePoints(_ points: [[Int]], _ angle: Int, _ location: [Int]) -> Int { + var angles: [Double] = [] + var same = 0 + let x0 = location[0], y0 = location[1] + + for p in points { + let dx = p[0] - x0 + let dy = p[1] - y0 + if dx == 0 && dy == 0 { + same += 1 + continue + } + let ang = atan2(Double(dy), Double(dx)) * 180.0 / Double.pi + angles.append(ang) + } + + if angles.isEmpty { return same } + + angles.sort() + let n = angles.count + var full = angles + full += angles.map { $0 + 360 } + + var maxVis = 0 + var j = 0 + for i in 0.. a - b); + const n = angles.length; + const full = [...angles, ...angles.map((a) => a + 360)]; + + let maxVis = 0; + let j = 0; + for (let i = 0; i < n; i++) { + while (j < full.length && full[j] - full[i] <= angle) { + j++; + } + maxVis = Math.max(maxVis, j - i); + } + + return maxVis + same; +} diff --git a/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/manifest.yaml b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/manifest.yaml new file mode 100644 index 00000000..2fd66a34 --- /dev/null +++ b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/manifest.yaml @@ -0,0 +1,218 @@ +entry: + id: 1611 + title: "minimum-one-bit-operations-to-make-integers-zero" + params: + n: + type: int + call: + cpp: "Solution().minimumOneBitOperations({n})" + rust: "Solution::minimum_one_bit_operations({n})" + python3: "Solution().minimumOneBitOperations({n})" + python2: "Solution().minimumOneBitOperations({n})" + ruby: "minimum_one_bit_operations({n})" + java: "new Solution().minimumOneBitOperations({n})" + csharp: "new Solution().MinimumOneBitOperations({n})" + kotlin: "Solution().minimumOneBitOperations({n})" + go: "minimumOneBitOperations({n})" + dart: "Solution().minimumOneBitOperations({n})" + swift: "Solution().minimumOneBitOperations({n})" + typescript: "minimumOneBitOperations({n})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minimumOneBitOperations(n, {result})" + checker: | + class Checker: + def minimumOneBitOperations(self, n, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + expected = 0 + add = True + highest = n.bit_length() - 1 + for i in range(highest, -1, -1): + if n & (1 << i): + value = (1 << (i + 1)) - 1 + expected = expected + value if add else expected - value + add = not add + return result == expected + +seed: 1611 + +tests: + - name: zero + in: + n: 0 + out: 0 + - name: one + in: + n: 1 + out: 1 + - name: two + in: + n: 2 + out: 3 + - name: three + in: + n: 3 + out: 2 + - name: four + in: + n: 4 + out: 7 + - name: five + in: + n: 5 + out: 6 + - name: six + in: + n: 6 + out: 4 + - name: seven + in: + n: 7 + out: 5 + - name: eight + in: + n: 8 + out: 15 + - name: nine + in: + n: 9 + out: 14 + - name: ten + in: + n: 10 + out: 12 + - name: eleven + in: + n: 11 + out: 13 + - name: twelve + in: + n: 12 + out: 8 + - name: thirteen + in: + n: 13 + out: 9 + - name: fourteen + in: + n: 14 + out: 11 + - name: fifteen + in: + n: 15 + out: 10 + - name: sixteen + in: + n: 16 + out: 31 + - name: seventeen + in: + n: 17 + out: 30 + - name: eighteen + in: + n: 18 + out: 28 + - name: nineteen + in: + n: 19 + out: 29 + - name: twenty + in: + n: 20 + out: 24 + - name: twenty-one + in: + n: 21 + out: 25 + - name: twenty-two + in: + n: 22 + out: 27 + - name: twenty-three + in: + n: 23 + out: 26 + - name: twenty-four + in: + n: 24 + out: 16 + - name: twenty-five + in: + n: 25 + out: 17 + - name: twenty-six + in: + n: 26 + out: 19 + - name: twenty-seven + in: + n: 27 + out: 18 + - name: twenty-eight + in: + n: 28 + out: 23 + - name: twenty-nine + in: + n: 29 + out: 22 + - name: thirty + in: + n: 30 + out: 20 + - name: thirty-one + in: + n: 31 + out: 21 + - name: thirty-two + in: + n: 32 + out: 63 + - name: sixty-three + in: + n: 63 + out: 42 + - name: sixty-four + in: + n: 64 + out: 127 + - name: generated-small + in: + n: + gen: "int" + min: 0 + max: 1000 + - name: generated-medium + in: + n: + gen: "int" + min: 1001 + max: 100000 + - name: generated-large + in: + n: + gen: "int" + min: 100001 + max: 10000000 + - name: generated-near-limit + in: + n: + gen: "int" + min: 900000000 + max: 1000000000 + - name: generated-full-range + in: + n: + gen: "int" + min: 0 + max: 1000000000 diff --git a/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.cpp b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.cpp new file mode 100644 index 00000000..ba8b3553 --- /dev/null +++ b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int minimumOneBitOperations(int n) { + int highest = 0; + for (int i = 0; i < 32; i++) { + if (n & (1 << i)) { + highest = i; + } + } + + int ans = 0; + bool add = true; + for (int i = highest; i >= 0; i--) { + if (n & (1 << i)) { + int val = (1 << (i + 1)) - 1; + if (add) { + ans += val; + } else { + ans -= val; + } + add = !add; + } + } + + return ans; + } +}; diff --git a/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.cs b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.cs new file mode 100644 index 00000000..65f90c20 --- /dev/null +++ b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.cs @@ -0,0 +1,26 @@ +public class Solution { + public int MinimumOneBitOperations(int n) { + int highest = 0; + for (int i = 0; i < 32; i++) { + if ((n & (1 << i)) != 0) { + highest = i; + } + } + + int ans = 0; + bool add = true; + for (int i = highest; i >= 0; i--) { + if ((n & (1 << i)) != 0) { + int val = (1 << (i + 1)) - 1; + if (add) { + ans += val; + } else { + ans -= val; + } + add = !add; + } + } + + return ans; + } +} diff --git a/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.dart b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.dart new file mode 100644 index 00000000..1a4a814f --- /dev/null +++ b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.dart @@ -0,0 +1,26 @@ +class Solution { + int minimumOneBitOperations(int n) { + int highest = 0; + for (int i = 0; i < 32; i++) { + if ((n & (1 << i)) != 0) { + highest = i; + } + } + + int ans = 0; + bool add = true; + for (int i = highest; i >= 0; i--) { + if ((n & (1 << i)) != 0) { + int val = (1 << (i + 1)) - 1; + if (add) { + ans += val; + } else { + ans -= val; + } + add = !add; + } + } + + return ans; + } +} diff --git a/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.go b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.go new file mode 100644 index 00000000..d95235cf --- /dev/null +++ b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.go @@ -0,0 +1,24 @@ +func minimumOneBitOperations(n int) int { + highest := 0 + for i := 0; i < 32; i++ { + if n & (1 << i) != 0 { + highest = i + } + } + + ans := 0 + add := true + for i := highest; i >= 0; i-- { + if n & (1 << i) != 0 { + val := (1 << (i + 1)) - 1 + if add { + ans += val + } else { + ans -= val + } + add = !add + } + } + + return ans +} diff --git a/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.java b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.java new file mode 100644 index 00000000..3a6361d7 --- /dev/null +++ b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.java @@ -0,0 +1,26 @@ +class Solution { + public int minimumOneBitOperations(int n) { + int highest = 0; + for (int i = 0; i < 32; i++) { + if ((n & (1 << i)) != 0) { + highest = i; + } + } + + int ans = 0; + boolean add = true; + for (int i = highest; i >= 0; i--) { + if ((n & (1 << i)) != 0) { + int val = (1 << (i + 1)) - 1; + if (add) { + ans += val; + } else { + ans -= val; + } + add = !add; + } + } + + return ans; + } +} diff --git a/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.kt b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.kt new file mode 100644 index 00000000..378b739c --- /dev/null +++ b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.kt @@ -0,0 +1,26 @@ +class Solution { + fun minimumOneBitOperations(n: Int): Int { + var highest = 0 + for (i in 0 until 32) { + if ((n and (1 shl i)) != 0) { + highest = i + } + } + + var ans = 0 + var add = true + for (i in highest downTo 0) { + if ((n and (1 shl i)) != 0) { + val value = (1 shl (i + 1)) - 1 + if (add) { + ans += value + } else { + ans -= value + } + add = !add + } + } + + return ans + } +} diff --git a/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.py b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.py new file mode 100644 index 00000000..d4233528 --- /dev/null +++ b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.py @@ -0,0 +1,19 @@ +class Solution: + def minimumOneBitOperations(self, n: int) -> int: + highest = 0 + for i in range(32): + if n & (1 << i): + highest = i + + ans = 0 + add = True + for i in range(highest, -1, -1): + if n & (1 << i): + val = (1 << (i + 1)) - 1 + if add: + ans += val + else: + ans -= val + add = not add + + return ans diff --git a/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.py2 b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.py2 new file mode 100644 index 00000000..84e8fec3 --- /dev/null +++ b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def minimumOneBitOperations(self, n): + """ + :type n: int + :rtype: int + """ + highest = 0 + for i in range(32): + if n & (1 << i): + highest = i + + ans = 0 + add = True + for i in range(highest, -1, -1): + if n & (1 << i): + val = (1 << (i + 1)) - 1 + if add: + ans += val + else: + ans -= val + add = not add + + return ans diff --git a/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.rb b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.rb new file mode 100644 index 00000000..0ce58c4d --- /dev/null +++ b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.rb @@ -0,0 +1,26 @@ +# @param {Integer} n +# @return {Integer} +def minimum_one_bit_operations(n) + highest = 0 + (0...32).each do |i| + if n & (1 << i) != 0 + highest = i + end + end + + ans = 0 + add = true + highest.downto(0) do |i| + if n & (1 << i) != 0 + val = (1 << (i + 1)) - 1 + if add + ans += val + else + ans -= val + end + add = !add + end + end + + ans +end diff --git a/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.rs b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.rs new file mode 100644 index 00000000..03bba783 --- /dev/null +++ b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn minimum_one_bit_operations(n: i32) -> i32 { + let mut highest = 0; + for i in 0..32 { + if (n & (1 << i)) != 0 { + highest = i; + } + } + + let mut ans = 0; + let mut add = true; + for i in (0..=highest).rev() { + if (n & (1 << i)) != 0 { + let val = (1 << (i + 1)) - 1; + if add { + ans += val; + } else { + ans -= val; + } + add = !add; + } + } + + ans + } +} diff --git a/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.swift b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.swift new file mode 100644 index 00000000..8db53c2b --- /dev/null +++ b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.swift @@ -0,0 +1,28 @@ +class Solution { + func minimumOneBitOperations(_ n: Int) -> Int { + var highest = 0 + for i in 0..<32 { + if (n & (1 << i)) != 0 { + highest = i + } + } + + var ans = 0 + var add = true + var i = highest + while i >= 0 { + if (n & (1 << i)) != 0 { + let val = (1 << (i + 1)) - 1 + if add { + ans += val + } else { + ans -= val + } + add = !add + } + i -= 1 + } + + return ans + } +} diff --git a/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.ts b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.ts new file mode 100644 index 00000000..2c3308f2 --- /dev/null +++ b/tests/1501-2000/1611. minimum-one-bit-operations-to-make-integers-zero/sol.ts @@ -0,0 +1,24 @@ +function minimumOneBitOperations(n: number): number { + let highest = 0; + for (let i = 0; i < 32; i++) { + if ((n & (1 << i)) !== 0) { + highest = i; + } + } + + let ans = 0; + let add = true; + for (let i = highest; i >= 0; i--) { + if ((n & (1 << i)) !== 0) { + const val = (1 << (i + 1)) - 1; + if (add) { + ans += val; + } else { + ans -= val; + } + add = !add; + } + } + + return ans; +} diff --git a/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/manifest.yaml b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/manifest.yaml new file mode 100644 index 00000000..60f7c661 --- /dev/null +++ b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/manifest.yaml @@ -0,0 +1,194 @@ +entry: + id: 1614 + title: "maximum-nesting-depth-of-the-parentheses" + params: + s: + type: string + call: + cpp: "Solution().maxDepth({s})" + rust: "Solution::max_depth({s})" + python3: "Solution().maxDepth({s})" + python2: "Solution().maxDepth({s})" + ruby: "max_depth({s})" + java: "new Solution().maxDepth({s})" + csharp: "new Solution().MaxDepth({s})" + kotlin: "Solution().maxDepth({s})" + go: "maxDepth({s})" + dart: "Solution().maxDepth({s})" + swift: "Solution().maxDepth({s})" + typescript: "maxDepth({s})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxDepth(s, {result})" + checker: | + class Checker: + def maxDepth(self, s, result): + depth = 0 + expected = 0 + for ch in s: + if ch == '(': + depth += 1 + expected = max(expected, depth) + elif ch == ')': + depth -= 1 + return result == expected + +seed: 1614 + +tests: + - name: single-pair + in: + s: "()" + out: 1 + - name: empty-nesting-by-adjacency + in: + s: "()()()()" + out: 1 + - name: nested-three + in: + s: "((()))" + out: 3 + - name: nested-four + in: + s: "(((())))" + out: 4 + - name: nested-five + in: + s: "((((()))))" + out: 5 + - name: example-one + in: + s: "(1+(2*3)+((8)/4))+1" + out: 3 + - name: example-two + in: + s: "(1)+((2))+(((3)))" + out: 3 + - name: example-three + in: + s: "()(())((()()))" + out: 3 + - name: operators-flat + in: + s: "1+2-3*4/5" + out: 0 + - name: one-pair-with-operators + in: + s: "(1+2-3*4/5)" + out: 1 + - name: two-level-expression + in: + s: "((1+2)*(3-4))" + out: 2 + - name: asymmetric-left + in: + s: "(((1)+2)+3)" + out: 3 + - name: asymmetric-right + in: + s: "(1+(2+(3)))" + out: 3 + - name: siblings + in: + s: "((1)+(2)+(3))" + out: 2 + - name: repeated-siblings + in: + s: "(1)(2)((3))(4)" + out: 2 + - name: digits-and-all-operators + in: + s: "((9/8)+(7*6)-(5+4))" + out: 2 + - name: alternating-depth + in: + s: "(1+(2*(3/(4))))" + out: 4 + - name: deep-with-empty-pairs + in: + s: "(()(()))" + out: 3 + - name: deep-right-branch + in: + s: "(((()))+((())))" + out: 4 + - name: max-small-expression + in: + s: "((((((((((1))))))))))" + out: 10 + - name: depth-six-mixed + in: + s: "((1+(2*(3-(4/(5+6))))))" + out: 6 + - name: depth-seven-mixed + in: + s: "(((1)+((2)+(((3))))))" + out: 6 + - name: depth-eight-mixed + in: + s: "((((1+2)-3)*4)/(((5))))" + out: 4 + - name: balanced-depth-three + in: + s: "((1+2)*(3+(4*5)))" + out: 3 + - name: balanced-depth-four + in: + s: "(((1+2)*(3+(4*5))))" + out: 4 + - name: many-flat-pairs + in: + s: "(1)(2)(3)(4)(5)(6)(7)(8)(9)(0)" + out: 1 + - name: many-pairs-depth-two + in: + s: "((1))((2))((3))((4))((5))" + out: 2 + - name: nested-operators + in: + s: "(1+((2*3)/(4-(5+6))))" + out: 4 + - name: left-heavy + in: + s: "((((1)+2)+3)+4)" + out: 4 + - name: right-heavy + in: + s: "(1+(2+(3+(4))))" + out: 4 + - name: depth-nine + in: + s: "(((((((((1)))))))))" + out: 9 + - name: depth-twelve + in: + s: "((((((((((((1))))))))))))" + out: 12 + - name: nested-zeroes + in: + s: "((0+(0))*(0-(0)))" + out: 3 + - name: long-flat-expression + in: + s: "1+2-3*4/5+6-7*8/9+0-1*2/3+4-5*6/7+8-9*0/1+2-3*4/5" + out: 0 + - name: long-depth-five + in: + s: "(((((1+2))))+((((3+4))))+(((5))))" + out: 5 + - name: long-depth-twenty + in: + s: "((((((((((((((((((((1))))))))))))))))))))" + out: 20 + - name: maximum-depth-forty-nine + in: + s: "(((((((((((((((((((((((((((((((((((((((((((((((((1)))))))))))))))))))))))))))))))))))))))))))))))))" + out: 49 diff --git a/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.cpp b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.cpp new file mode 100644 index 00000000..29779454 --- /dev/null +++ b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int maxDepth(string s) { + int ctr = 0; + int ans = 0; + for (char ch : s) { + if (ch == '(') { + ctr++; + ans = max(ans, ctr); + } else if (ch == ')') { + ctr--; + } + } + return ans; + } +}; diff --git a/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.cs b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.cs new file mode 100644 index 00000000..1c9a3a59 --- /dev/null +++ b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int MaxDepth(string s) { + int ctr = 0; + int ans = 0; + foreach (char ch in s) { + if (ch == '(') { + ctr++; + ans = Math.Max(ans, ctr); + } else if (ch == ')') { + ctr--; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.dart b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.dart new file mode 100644 index 00000000..3dbb8980 --- /dev/null +++ b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.dart @@ -0,0 +1,15 @@ +class Solution { + int maxDepth(String s) { + int ctr = 0; + int ans = 0; + for (int i = 0; i < s.length; i++) { + if (s[i] == '(') { + ctr++; + if (ctr > ans) ans = ctr; + } else if (s[i] == ')') { + ctr--; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.go b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.go new file mode 100644 index 00000000..7d455c1d --- /dev/null +++ b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.go @@ -0,0 +1,15 @@ +func maxDepth(s string) int { + ctr := 0 + ans := 0 + for _, ch := range s { + if ch == '(' { + ctr++ + if ctr > ans { + ans = ctr + } + } else if ch == ')' { + ctr-- + } + } + return ans +} diff --git a/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.java b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.java new file mode 100644 index 00000000..6f28f096 --- /dev/null +++ b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.java @@ -0,0 +1,15 @@ +class Solution { + public int maxDepth(String s) { + int ctr = 0; + int ans = 0; + for (char ch : s.toCharArray()) { + if (ch == '(') { + ctr++; + ans = Math.max(ans, ctr); + } else if (ch == ')') { + ctr--; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.kt b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.kt new file mode 100644 index 00000000..8e5e4745 --- /dev/null +++ b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun maxDepth(s: String): Int { + var ctr = 0 + var ans = 0 + for (ch in s) { + if (ch == '(') { + ctr++ + ans = maxOf(ans, ctr) + } else if (ch == ')') { + ctr-- + } + } + return ans + } +} diff --git a/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.py b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.py new file mode 100644 index 00000000..0d40cee6 --- /dev/null +++ b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.py @@ -0,0 +1,11 @@ +class Solution: + def maxDepth(self, s: str) -> int: + ctr = 0 + ans = 0 + for i in s: + if i == "(": + ctr += 1 + ans = max(ans, ctr) + elif i == ")": + ctr -= 1 + return ans diff --git a/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.py2 b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.py2 new file mode 100644 index 00000000..3024e696 --- /dev/null +++ b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def maxDepth(self, s): + """ + :type s: str + :rtype: int + """ + ctr = 0 + ans = 0 + for ch in s: + if ch == '(': + ctr += 1 + ans = max(ans, ctr) + elif ch == ')': + ctr -= 1 + return ans diff --git a/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.rb b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.rb new file mode 100644 index 00000000..27b544df --- /dev/null +++ b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.rb @@ -0,0 +1,15 @@ +# @param {String} s +# @return {Integer} +def max_depth(s) + ctr = 0 + ans = 0 + s.each_char do |ch| + if ch == '(' + ctr += 1 + ans = [ans, ctr].max + elsif ch == ')' + ctr -= 1 + end + end + ans +end diff --git a/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.rs b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.rs new file mode 100644 index 00000000..690a5752 --- /dev/null +++ b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn max_depth(s: String) -> i32 { + let mut ctr = 0i32; + let mut ans = 0i32; + for ch in s.chars() { + if ch == '(' { + ctr += 1; + ans = ans.max(ctr); + } else if ch == ')' { + ctr -= 1; + } + } + ans + } +} diff --git a/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.swift b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.swift new file mode 100644 index 00000000..a3fe8858 --- /dev/null +++ b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func maxDepth(_ s: String) -> Int { + var ctr = 0 + var ans = 0 + for ch in s { + if ch == "(" { + ctr += 1 + ans = max(ans, ctr) + } else if ch == ")" { + ctr -= 1 + } + } + return ans + } +} diff --git a/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.ts b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.ts new file mode 100644 index 00000000..9694da45 --- /dev/null +++ b/tests/1501-2000/1614. maximum-nesting-depth-of-the-parentheses/sol.ts @@ -0,0 +1,13 @@ +function maxDepth(s: string): number { + let ctr = 0; + let ans = 0; + for (const ch of s) { + if (ch === "(") { + ctr++; + ans = Math.max(ans, ctr); + } else if (ch === ")") { + ctr--; + } + } + return ans; +} diff --git a/tests/1501-2000/1615. maximal-network-rank/manifest.yaml b/tests/1501-2000/1615. maximal-network-rank/manifest.yaml new file mode 100644 index 00000000..950ac511 --- /dev/null +++ b/tests/1501-2000/1615. maximal-network-rank/manifest.yaml @@ -0,0 +1,629 @@ +entry: + id: 1615 + title: maximal-network-rank + params: + n: + type: int + roads: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().maximalNetworkRank({n}, {roads})" + rust: "Solution::maximal_network_rank({n}, {roads})" + python3: "Solution().maximalNetworkRank({n}, {roads})" + python2: "Solution().maximalNetworkRank({n}, {roads})" + ruby: "maximal_network_rank({n}, {roads})" + java: "new Solution().maximalNetworkRank({n}, {roads})" + csharp: "new Solution().MaximalNetworkRank({n}, {roads})" + kotlin: "Solution().maximalNetworkRank({n}, {roads})" + go: "maximalNetworkRank({n}, {roads})" + dart: "Solution().maximalNetworkRank({n}, {roads})" + swift: "Solution().maximalNetworkRank({n}, {roads})" + typescript: "maximalNetworkRank({n}, {roads})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maximalNetworkRank(n, roads, {result})" + checker: | + class Checker: + def maximalNetworkRank(self, n, roads, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + degree = [0] * n + edges = set() + for a, b in roads: + degree[a] += 1 + degree[b] += 1 + edges.add((min(a, b), max(a, b))) + expected = max(degree[i] + degree[j] - ((min(i, j), max(i, j)) in edges) + for i in range(n) for j in range(i + 1, n)) + return result == expected + +seed: 1615 + +tests: + - name: empty-four + in: + n: 4 + roads: [] + out: 0 + judge: + type: "exact" + - name: single-road + in: + n: 4 + roads: + - [0, 1] + out: 1 + judge: + type: "exact" + - name: example-one + in: + n: 4 + roads: + - [0, 1] + - [0, 3] + - [1, 2] + - [1, 3] + out: 4 + judge: + type: "exact" + - name: example-two + in: + n: 5 + roads: + - [0, 1] + - [0, 3] + - [1, 2] + - [1, 3] + - [2, 3] + - [2, 4] + out: 5 + judge: + type: "exact" + - name: example-three + in: + n: 8 + roads: + - [0, 1] + - [1, 2] + - [2, 3] + - [2, 4] + - [5, 6] + - [5, 7] + out: 5 + judge: + type: "exact" + - name: path-four + in: + n: 4 + roads: + - [0, 1] + - [1, 2] + - [2, 3] + out: 3 + judge: + type: "exact" + - name: path-five + in: + n: 5 + roads: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + out: 4 + judge: + type: "exact" + - name: star-five + in: + n: 5 + roads: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + out: 4 + judge: + type: "exact" + - name: star-six + in: + n: 6 + roads: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + out: 5 + judge: + type: "exact" + - name: triangle + in: + n: 3 + roads: + - [0, 1] + - [1, 2] + - [0, 2] + out: 3 + judge: + type: "exact" + - name: complete-four + in: + n: 4 + roads: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 2] + - [1, 3] + - [2, 3] + out: 5 + judge: + type: "exact" + - name: complete-five + in: + n: 5 + roads: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 3] + - [2, 4] + - [3, 4] + out: 7 + judge: + type: "exact" + - name: two-disjoint-edges + in: + n: 6 + roads: + - [0, 1] + - [2, 3] + out: 2 + judge: + type: "exact" + - name: two-triangles + in: + n: 6 + roads: + - [0, 1] + - [1, 2] + - [0, 2] + - [3, 4] + - [4, 5] + - [3, 5] + out: 4 + judge: + type: "exact" + - name: hub-and-edge + in: + n: 7 + roads: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [1, 6] + out: 6 + judge: + type: "exact" + - name: cycle-six + in: + n: 6 + roads: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 0] + out: 4 + judge: + type: "exact" + - name: cycle-with-chord + in: + n: 6 + roads: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 0] + - [0, 3] + out: 5 + judge: + type: "exact" + - name: bipartite-three-three + in: + n: 6 + roads: + - [0, 3] + - [0, 4] + - [0, 5] + - [1, 3] + - [1, 4] + - [1, 5] + - [2, 3] + - [2, 4] + - [2, 5] + out: 6 + judge: + type: "exact" + - name: dense-five-missing-one + in: + n: 5 + roads: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 3] + - [3, 4] + out: 7 + judge: + type: "exact" + - name: isolated-last + in: + n: 6 + roads: + - [0, 1] + - [0, 2] + - [1, 2] + - [2, 3] + - [3, 4] + out: 4 + judge: + type: "exact" + - name: isolated-many + in: + n: 10 + roads: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 2] + out: 4 + judge: + type: "exact" + - name: complete-three-plus-isolated + in: + n: 7 + roads: + - [0, 1] + - [0, 2] + - [1, 2] + out: 3 + judge: + type: "exact" + - name: complete-six + in: + n: 6 + roads: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [2, 3] + - [2, 4] + - [2, 5] + - [3, 4] + - [3, 5] + - [4, 5] + out: 9 + judge: + type: "exact" + - name: ladder-six + in: + n: 6 + roads: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [0, 2] + - [1, 3] + - [2, 4] + - [3, 5] + out: 7 + judge: + type: "exact" + - name: paired-hubs + in: + n: 8 + roads: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [2, 3] + out: 7 + judge: + type: "exact" + - name: four-regular-ish + in: + n: 8 + roads: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [1, 2] + - [1, 5] + - [1, 6] + - [2, 3] + - [2, 6] + - [2, 7] + - [3, 4] + - [3, 7] + out: 8 + judge: + type: "exact" + - name: long-chain-eight + in: + n: 8 + roads: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + out: 4 + judge: + type: "exact" + - name: two-stars + in: + n: 8 + roads: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 4] + - [1, 5] + - [1, 6] + out: 6 + judge: + type: "exact" + - name: complete-seven + in: + n: 7 + roads: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [2, 3] + - [2, 4] + - [2, 5] + - [2, 6] + - [3, 4] + - [3, 5] + - [3, 6] + - [4, 5] + - [4, 6] + - [5, 6] + out: 11 + judge: + type: "exact" + - name: sparse-ten + in: + n: 10 + roads: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 0] + - [5, 6] + - [6, 7] + - [7, 8] + out: 4 + judge: + type: "exact" + - name: dense-eight + in: + n: 8 + roads: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [1, 2] + - [1, 3] + - [1, 5] + - [2, 3] + - [2, 4] + - [2, 5] + - [3, 4] + - [3, 6] + - [4, 5] + - [4, 6] + - [5, 6] + - [5, 7] + - [6, 7] + out: 10 + judge: + type: "exact" + - name: one-hub-nine + in: + n: 10 + roads: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + - [0, 7] + - [0, 8] + - [0, 9] + out: 9 + judge: + type: "exact" + - name: matching-five + in: + n: 10 + roads: + - [0, 1] + - [2, 3] + - [4, 5] + - [6, 7] + - [8, 9] + out: 2 + judge: + type: "exact" + - name: hub-triangle + in: + n: 9 + roads: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 3] + - [2, 4] + - [3, 4] + out: 7 + judge: + type: "exact" + - name: complete-eight + in: + n: 8 + roads: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + - [0, 7] + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [2, 3] + - [2, 4] + - [2, 5] + - [2, 6] + - [2, 7] + - [3, 4] + - [3, 5] + - [3, 6] + - [3, 7] + - [4, 5] + - [4, 6] + - [4, 7] + - [5, 6] + - [5, 7] + - [6, 7] + out: 13 + judge: + type: "exact" + - name: max-n-empty + in: + n: 100 + roads: [] + out: 0 + judge: + type: "exact" + - name: max-n-single + in: + n: 100 + roads: + - [0, 99] + out: 1 + judge: + type: "exact" + - name: max-n-star + in: + n: 100 + roads: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + - [0, 7] + - [0, 8] + - [0, 9] + - [0, 10] + out: 10 + judge: + type: "exact" + - name: max-n-two-hubs + in: + n: 100 + roads: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [1, 6] + - [1, 7] + - [1, 8] + - [1, 9] + - [1, 10] + out: 10 + judge: + type: "exact" + - name: max-n-dense-core + in: + n: 100 + roads: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 3] + - [2, 4] + - [3, 4] + out: 7 + judge: + type: "exact" diff --git a/tests/1501-2000/1615. maximal-network-rank/sol.cpp b/tests/1501-2000/1615. maximal-network-rank/sol.cpp new file mode 100644 index 00000000..366d0d04 --- /dev/null +++ b/tests/1501-2000/1615. maximal-network-rank/sol.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int maximalNetworkRank(int n, vector>& roads) { + vector> a(n, vector(n, 0)); + for (auto& road : roads) { + a[road[0]][road[1]] = 1; + a[road[1]][road[0]] = 1; + } + + vector d(n, 0); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + d[i] += a[i][j]; + } + } + + vector> rank(n, vector(n, -1)); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (i != j) { + rank[i][j] = d[i] + d[j] - a[i][j]; + } + } + } + + int max = -1; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (rank[i][j] > max) max = rank[i][j]; + } + } + return max; + } +}; diff --git a/tests/1501-2000/1615. maximal-network-rank/sol.cs b/tests/1501-2000/1615. maximal-network-rank/sol.cs new file mode 100644 index 00000000..20838aab --- /dev/null +++ b/tests/1501-2000/1615. maximal-network-rank/sol.cs @@ -0,0 +1,35 @@ +public class Solution { + public int MaximalNetworkRank(int n, int[][] roads) { + int[,] a = new int[n, n]; + foreach (var road in roads) { + a[road[0], road[1]] = 1; + a[road[1], road[0]] = 1; + } + + int[] d = new int[n]; + for (int i = 0; i < n; i++) { + int sum = 0; + for (int j = 0; j < n; j++) sum += a[i, j]; + d[i] = sum; + } + + int[,] rank = new int[n, n]; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (i != j) { + rank[i, j] = d[i] + d[j] - a[i, j]; + } else { + rank[i, j] = -1; + } + } + } + + int max = -1; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (rank[i, j] > max) max = rank[i, j]; + } + } + return max; + } +} diff --git a/tests/1501-2000/1615. maximal-network-rank/sol.dart b/tests/1501-2000/1615. maximal-network-rank/sol.dart new file mode 100644 index 00000000..e424d241 --- /dev/null +++ b/tests/1501-2000/1615. maximal-network-rank/sol.dart @@ -0,0 +1,28 @@ +class Solution { + int maximalNetworkRank(int n, List> roads) { + List> a = List.generate(n, (_) => List.filled(n, 0)); + for (final road in roads) { + a[road[0]][road[1]] = 1; + a[road[1]][road[0]] = 1; + } + + List d = List.generate(n, (i) => a[i].reduce((x, y) => x + y)); + + List> rank = List.generate(n, (_) => List.filled(n, -1)); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (i != j) { + rank[i][j] = d[i] + d[j] - a[i][j]; + } + } + } + + int max = -1; + for (final row in rank) { + for (final val in row) { + if (val > max) max = val; + } + } + return max; + } +} diff --git a/tests/1501-2000/1615. maximal-network-rank/sol.go b/tests/1501-2000/1615. maximal-network-rank/sol.go new file mode 100644 index 00000000..39983aa5 --- /dev/null +++ b/tests/1501-2000/1615. maximal-network-rank/sol.go @@ -0,0 +1,41 @@ +func maximalNetworkRank(n int, roads [][]int) int { + a := make([][]int, n) + for i := range a { + a[i] = make([]int, n) + } + for _, road := range roads { + a[road[0]][road[1]] = 1 + a[road[1]][road[0]] = 1 + } + + d := make([]int, n) + for i := 0; i < n; i++ { + sum := 0 + for j := 0; j < n; j++ { + sum += a[i][j] + } + d[i] = sum + } + + rank := make([][]int, n) + for i := range rank { + rank[i] = make([]int, n) + for j := range rank[i] { + if i == j { + rank[i][j] = -1 + } else { + rank[i][j] = d[i] + d[j] - a[i][j] + } + } + } + + max := -1 + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + if rank[i][j] > max { + max = rank[i][j] + } + } + } + return max +} diff --git a/tests/1501-2000/1615. maximal-network-rank/sol.java b/tests/1501-2000/1615. maximal-network-rank/sol.java new file mode 100644 index 00000000..4b2a747c --- /dev/null +++ b/tests/1501-2000/1615. maximal-network-rank/sol.java @@ -0,0 +1,35 @@ +class Solution { + public int maximalNetworkRank(int n, int[][] roads) { + int[][] a = new int[n][n]; + for (int[] road : roads) { + a[road[0]][road[1]] = 1; + a[road[1]][road[0]] = 1; + } + + int[] d = new int[n]; + for (int i = 0; i < n; i++) { + int sum = 0; + for (int j = 0; j < n; j++) sum += a[i][j]; + d[i] = sum; + } + + int[][] rank = new int[n][n]; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (i != j) { + rank[i][j] = d[i] + d[j] - a[i][j]; + } else { + rank[i][j] = -1; + } + } + } + + int max = -1; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + max = Math.max(max, rank[i][j]); + } + } + return max; + } +} diff --git a/tests/1501-2000/1615. maximal-network-rank/sol.kt b/tests/1501-2000/1615. maximal-network-rank/sol.kt new file mode 100644 index 00000000..db60bf31 --- /dev/null +++ b/tests/1501-2000/1615. maximal-network-rank/sol.kt @@ -0,0 +1,28 @@ +class Solution { + fun maximalNetworkRank(n: Int, roads: Array): Int { + val a = Array(n) { IntArray(n) } + for (road in roads) { + a[road[0]][road[1]] = 1 + a[road[1]][road[0]] = 1 + } + + val d = IntArray(n) { i -> a[i].sum() } + + val rank = Array(n) { IntArray(n) { -1 } } + for (i in 0 until n) { + for (j in 0 until n) { + if (i != j) { + rank[i][j] = d[i] + d[j] - a[i][j] + } + } + } + + var answer = -1 + for (row in rank) { + for (value in row) { + if (value > answer) answer = value + } + } + return answer + } +} diff --git a/tests/1501-2000/1615. maximal-network-rank/sol.py b/tests/1501-2000/1615. maximal-network-rank/sol.py new file mode 100644 index 00000000..15f2d73a --- /dev/null +++ b/tests/1501-2000/1615. maximal-network-rank/sol.py @@ -0,0 +1,25 @@ +import numpy as np + + +class Solution: + def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: + # 1. Construct the Adjacency Matrix (A) + A = np.zeros((n, n), dtype=int) + if roads: + # Vectorized edge ingestion using advanced indexing + edges = np.array(roads) + A[edges[:, 0], edges[:, 1]] = 1 + A[edges[:, 1], edges[:, 0]] = 1 + + # 2. Compute the Degree Vector (d) + d = A.sum(axis=1) + + # 3. Compute the Rank Matrix for all pairs via broadcasting: R_ij = d_i + d_j - A_ij + # d[:, None] creates a column vector, d[None, :] creates a row vector + Rank = d[:, None] + d[None, :] - A + + # 4. Enforce i != j by masking out the main diagonal + np.fill_diagonal(Rank, -1) + + # 5. Extract the maximum rank across the entire structure + return int(Rank.max()) diff --git a/tests/1501-2000/1615. maximal-network-rank/sol.py2 b/tests/1501-2000/1615. maximal-network-rank/sol.py2 new file mode 100644 index 00000000..eb4455f9 --- /dev/null +++ b/tests/1501-2000/1615. maximal-network-rank/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def maximalNetworkRank(self, n, roads): + """ + :type n: int + :type roads: List[List[int]] + :rtype: int + """ + A = [[0] * n for _ in range(n)] + for u, v in roads: + A[u][v] = 1 + A[v][u] = 1 + + d = [sum(row) for row in A] + + Rank = [[-1] * n for _ in range(n)] + for i in range(n): + for j in range(n): + if i != j: + Rank[i][j] = d[i] + d[j] - A[i][j] + + return max(max(row) for row in Rank) diff --git a/tests/1501-2000/1615. maximal-network-rank/sol.rb b/tests/1501-2000/1615. maximal-network-rank/sol.rb new file mode 100644 index 00000000..b28509bb --- /dev/null +++ b/tests/1501-2000/1615. maximal-network-rank/sol.rb @@ -0,0 +1,23 @@ +# @param {Integer} n +# @param {Integer[][]} roads +# @return {Integer} +def maximal_network_rank(n, roads) + a = Array.new(n) { Array.new(n, 0) } + roads.each do |u, v| + a[u][v] = 1 + a[v][u] = 1 + end + + d = a.map { |row| row.sum } + + rank = Array.new(n) { Array.new(n, -1) } + (0...n).each do |i| + (0...n).each do |j| + if i != j + rank[i][j] = d[i] + d[j] - a[i][j] + end + end + end + + rank.flatten.max +end diff --git a/tests/1501-2000/1615. maximal-network-rank/sol.rs b/tests/1501-2000/1615. maximal-network-rank/sol.rs new file mode 100644 index 00000000..94008aa3 --- /dev/null +++ b/tests/1501-2000/1615. maximal-network-rank/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn maximal_network_rank(n: i32, roads: Vec>) -> i32 { + let n = n as usize; + let mut a = vec![vec![0; n]; n]; + for road in &roads { + let u = road[0] as usize; + let v = road[1] as usize; + a[u][v] = 1; + a[v][u] = 1; + } + + let d: Vec = a.iter().map(|row| row.iter().sum()).collect(); + + let mut rank = vec![vec![-1; n]; n]; + for i in 0..n { + for j in 0..n { + if i != j { + rank[i][j] = d[i] + d[j] - a[i][j]; + } + } + } + + rank.iter().flat_map(|row| row.iter()).max().copied().unwrap_or(-1) + } +} diff --git a/tests/1501-2000/1615. maximal-network-rank/sol.swift b/tests/1501-2000/1615. maximal-network-rank/sol.swift new file mode 100644 index 00000000..db803987 --- /dev/null +++ b/tests/1501-2000/1615. maximal-network-rank/sol.swift @@ -0,0 +1,22 @@ +class Solution { + func maximalNetworkRank(_ n: Int, _ roads: [[Int]]) -> Int { + var a = Array(repeating: Array(repeating: 0, count: n), count: n) + for road in roads { + a[road[0]][road[1]] = 1 + a[road[1]][road[0]] = 1 + } + + let d = a.map { row in row.reduce(0, +) } + + var rank = Array(repeating: Array(repeating: -1, count: n), count: n) + for i in 0.. Array(n).fill(0)); + for (const [u, v] of roads) { + a[u][v] = 1; + a[v][u] = 1; + } + + const d: number[] = a.map((row) => row.reduce((x, y) => x + y, 0)); + + const rank: number[][] = Array.from({ length: n }, () => Array(n).fill(-1)); + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + if (i !== j) { + rank[i][j] = d[i] + d[j] - a[i][j]; + } + } + } + + return Math.max(...rank.flat()); +} diff --git a/tests/1501-2000/1616. split-two-strings-to-make-palindrome/manifest.yaml b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/manifest.yaml new file mode 100644 index 00000000..d6cb4c10 --- /dev/null +++ b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/manifest.yaml @@ -0,0 +1,347 @@ +entry: + id: 1616 + title: "split-two-strings-to-make-palindrome" + params: + a: + type: string + b: + type: string + call: + cpp: "Solution().checkPalindromeFormation({a}, {b})" + rust: "Solution::check_palindrome_formation({a}, {b})" + python3: "Solution().checkPalindromeFormation({a}, {b})" + python2: "Solution().checkPalindromeFormation({a}, {b})" + ruby: "check_palindrome_formation({a}, {b})" + java: "new Solution().checkPalindromeFormation({a}, {b})" + csharp: "new Solution().CheckPalindromeFormation({a}, {b})" + kotlin: "Solution().checkPalindromeFormation({a}, {b})" + go: "checkPalindromeFormation({a}, {b})" + dart: "Solution().checkPalindromeFormation({a}, {b})" + swift: "Solution().checkPalindromeFormation({a}, {b})" + typescript: "checkPalindromeFormation({a}, {b})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().checkPalindromeFormation(a, b, {result})" + checker: | + class Checker: + def checkPalindromeFormation(self, a, b, result): + if not isinstance(result, bool) or len(a) != len(b): + return False + def palindrome(s, i, j): + while i < j: + if s[i] != s[j]: + return False + i += 1 + j -= 1 + return True + def check(left, right): + i, j = 0, len(left) - 1 + while i < j and left[i] == right[j]: + i += 1 + j -= 1 + return palindrome(left, i, j) or palindrome(right, i, j) + expected = check(a, b) or check(b, a) + return result == expected +seed: 1616 +tests: + - name: single-different + in: + a: "x" + b: "y" + out: true + judge: + type: "exact" + - name: example-false + in: + a: "xbdef" + b: "xecab" + out: false + judge: + type: "exact" + - name: example-true + in: + a: "ulacfd" + b: "jizalu" + out: true + judge: + type: "exact" + - name: equal-letters + in: + a: "aaaa" + b: "aaaa" + out: true + judge: + type: "exact" + - name: both-palindromes + in: + a: "racecar" + b: "levelxy" + out: true + judge: + type: "exact" + - name: reverse-pair + in: + a: "abc" + b: "cba" + out: true + judge: + type: "exact" + - name: two-false + in: + a: "ab" + b: "cd" + out: false + judge: + type: "exact" + - name: matching-cross + in: + a: "abca" + b: "caba" + out: true + judge: + type: "exact" + - name: even-center + in: + a: "abcdba" + b: "efghfe" + out: false + judge: + type: "exact" + - name: odd-center + in: + a: "abcxy" + b: "zyxba" + out: true + judge: + type: "exact" + - name: one-mismatch-palindrome + in: + a: "abcc" + b: "zzba" + out: true + judge: + type: "exact" + - name: disjoint-pattern + in: + a: "abcde" + b: "fghij" + out: false + judge: + type: "exact" + - name: cut-at-start + in: + a: "abc" + b: "aba" + out: true + judge: + type: "exact" + - name: cut-at-end + in: + a: "aba" + b: "abc" + out: true + judge: + type: "exact" + - name: repeated-blocks + in: + a: "aabbaa" + b: "bbabba" + out: true + judge: + type: "exact" + - name: alternating-true + in: + a: "ababab" + b: "bababa" + out: true + judge: + type: "exact" + - name: alternating-false + in: + a: "abab" + b: "bcbc" + out: false + judge: + type: "exact" + - name: center-match + in: + a: "mnopon" + b: "xyzzyx" + out: true + judge: + type: "exact" + - name: palindrome-a + in: + a: "abccba" + b: "qwerty" + out: true + judge: + type: "exact" + - name: palindrome-b + in: + a: "qwerty" + b: "abccba" + out: true + judge: + type: "exact" + - name: same-length-three + in: + a: "abc" + b: "def" + out: false + judge: + type: "exact" + - name: mirrored-prefix + in: + a: "abxyz" + b: "zyxba" + out: true + judge: + type: "exact" + - name: late-mismatch + in: + a: "aaaaab" + b: "cbaaaa" + out: true + judge: + type: "exact" + - name: no-crossing + in: + a: "aabbcc" + b: "ddeeff" + out: false + judge: + type: "exact" + - name: repeated-single + in: + a: "bbbbbb" + b: "bbbbbc" + out: true + judge: + type: "exact" + - name: mixed-case-lowercase + in: + a: "azbycxdw" + b: "wxcbyzad" + out: false + judge: + type: "exact" + - name: long-false-pattern + in: + a: "abcdefghij" + b: "klmnopqrst" + out: false + judge: + type: "exact" + - name: long-true-pattern + in: + a: "abcdefghijk" + b: "kjihgfedcba" + out: true + judge: + type: "exact" + - name: near-palindrome-left + in: + a: "abccbx" + b: "xbyyza" + out: true + judge: + type: "exact" + - name: near-palindrome-false + in: + a: "aabbccdd" + b: "eeffgghh" + out: false + judge: + type: "exact" + - name: all-alphabet + in: + a: "abcdefghijklmnopqrstuvwx" + b: "xwvutsrqponmlkjihgfedcba" + out: true + judge: + type: "exact" + - name: asymmetric-true + in: + a: "lmnopqr" + b: "srqponl" + out: false + judge: + type: "exact" + - name: asymmetric-false + in: + a: "abcdefgh" + b: "zzzzzzzz" + out: true + judge: + type: "exact" + - name: long-repeated + in: + a: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + b: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + out: true + judge: + type: "exact" + - name: long-repeated-true + in: + a: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" + b: "cbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: true + judge: + type: "exact" + - name: boundary-letters + in: + a: "azazazazaz" + b: "zazazazaza" + out: true + judge: + type: "exact" + - name: generated-uniform-a + in: + a: + gen: "str" + len: 100000 + alphabet: "a" + b: + gen: "str" + len: 100000 + alphabet: "b" + seed: 161601 + - name: generated-binary-random + in: + a: + gen: "str" + len: 100000 + alphabet: "ab" + b: + gen: "str" + len: 100000 + alphabet: "ab" + seed: 161602 + - name: generated-alphabet-random + in: + a: + gen: "str" + len: 99999 + alphabet: "abcxyz" + b: + gen: "str" + len: 99999 + alphabet: "abcxyz" + seed: 161603 + - name: generated-uniform-z + in: + a: + gen: "str" + len: 100000 + alphabet: "z" + b: + gen: "str" + len: 100000 + alphabet: "z" + seed: 161604 diff --git a/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.cpp b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.cpp new file mode 100644 index 00000000..7d1854c3 --- /dev/null +++ b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + bool checkPalindromeFormation(string a, string b) { + return check(a, b) || check(b, a); + } + +private: + bool check(const string& a, const string& b) { + int i = 0, j = a.length() - 1; + while (i < j && a[i] == b[j]) { + i++; + j--; + } + return isPalindrome(a.substr(i, j - i + 1)) || isPalindrome(b.substr(i, j - i + 1)); + } + + bool isPalindrome(const string& s) { + int left = 0, right = s.length() - 1; + while (left < right) { + if (s[left] != s[right]) return false; + left++; + right--; + } + return true; + } +}; diff --git a/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.cs b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.cs new file mode 100644 index 00000000..55c24b69 --- /dev/null +++ b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.cs @@ -0,0 +1,24 @@ +public class Solution { + public bool CheckPalindromeFormation(string a, string b) { + return Check(a, b) || Check(b, a); + } + + private bool Check(string a, string b) { + int i = 0, j = a.Length - 1; + while (i < j && a[i] == b[j]) { + i++; + j--; + } + return IsPalindrome(a.Substring(i, j - i + 1)) || IsPalindrome(b.Substring(i, j - i + 1)); + } + + private bool IsPalindrome(string s) { + int left = 0, right = s.Length - 1; + while (left < right) { + if (s[left] != s[right]) return false; + left++; + right--; + } + return true; + } +} diff --git a/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.dart b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.dart new file mode 100644 index 00000000..98fa076b --- /dev/null +++ b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.dart @@ -0,0 +1,16 @@ +class Solution { + bool checkPalindromeFormation(String a, String b) { + return check(a, b) || check(b, a); + } + + bool check(String a, String b) { + int i = 0, j = a.length - 1; + while (i < j && a[i] == b[j]) { + i++; + j--; + } + return isPalindrome(a.substring(i, j + 1)) || isPalindrome(b.substring(i, j + 1)); + } + + bool isPalindrome(String s) => s == s.split('').reversed.join(); +} diff --git a/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.go b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.go new file mode 100644 index 00000000..ea492066 --- /dev/null +++ b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.go @@ -0,0 +1,21 @@ +func checkPalindromeFormation(a string, b string) bool { + return check(a, b) || check(b, a) +} + +func check(a, b string) bool { + i, j := 0, len(a)-1 + for i < j && a[i] == b[j] { + i++ + j-- + } + return isPalindrome(a[i:j+1]) || isPalindrome(b[i:j+1]) +} + +func isPalindrome(s string) bool { + for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { + if s[i] != s[j] { + return false + } + } + return true +} diff --git a/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.java b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.java new file mode 100644 index 00000000..a8b48191 --- /dev/null +++ b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.java @@ -0,0 +1,18 @@ +class Solution { + public boolean checkPalindromeFormation(String a, String b) { + return check(a, b) || check(b, a); + } + + private boolean check(String a, String b) { + int i = 0, j = a.length() - 1; + while (i < j && a.charAt(i) == b.charAt(j)) { + i++; + j--; + } + return isPalindrome(a.substring(i, j + 1)) || isPalindrome(b.substring(i, j + 1)); + } + + private boolean isPalindrome(String s) { + return new StringBuilder(s).reverse().toString().equals(s); + } +} diff --git a/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.kt b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.kt new file mode 100644 index 00000000..5a1336b4 --- /dev/null +++ b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.kt @@ -0,0 +1,17 @@ +class Solution { + fun checkPalindromeFormation(a: String, b: String): Boolean { + return check(a, b) || check(b, a) + } + + private fun check(a: String, b: String): Boolean { + var i = 0 + var j = a.length - 1 + while (i < j && a[i] == b[j]) { + i++ + j-- + } + return isPalindrome(a.substring(i, j + 1)) || isPalindrome(b.substring(i, j + 1)) + } + + private fun isPalindrome(s: String): Boolean = s == s.reversed() +} diff --git a/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.py b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.py new file mode 100644 index 00000000..562bd412 --- /dev/null +++ b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.py @@ -0,0 +1,19 @@ +class Solution(object): + def checkPalindromeFormation(self, a, b): + """ + :type a: str + :type b: str + :rtype: bool + """ + + def is_palindrome(s): + return s == s[::-1] + + def check(a, b): + i, j = 0, len(a) - 1 + while i < j and a[i] == b[j]: + i += 1 + j -= 1 + return is_palindrome(a[i : j + 1]) or is_palindrome(b[i : j + 1]) + + return check(a, b) or check(b, a) diff --git a/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.py2 b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.py2 new file mode 100644 index 00000000..48fa1c92 --- /dev/null +++ b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def checkPalindromeFormation(self, a, b): + """ + :type a: str + :type b: str + :rtype: bool + """ + def is_palindrome(s): + return s == s[::-1] + + def check(a, b): + i, j = 0, len(a) - 1 + while i < j and a[i] == b[j]: + i += 1 + j -= 1 + return is_palindrome(a[i:j+1]) or is_palindrome(b[i:j+1]) + + return check(a, b) or check(b, a) diff --git a/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.rb b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.rb new file mode 100644 index 00000000..a159c24b --- /dev/null +++ b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.rb @@ -0,0 +1,16 @@ +def check_palindrome_formation(a, b) + def is_palindrome(s) + s == s.reverse + end + + def check(a, b) + i, j = 0, a.length - 1 + while i < j && a[i] == b[j] + i += 1 + j -= 1 + end + is_palindrome(a[i..j]) || is_palindrome(b[i..j]) + end + + check(a, b) || check(b, a) +end diff --git a/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.rs b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.rs new file mode 100644 index 00000000..1cd5cd03 --- /dev/null +++ b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.rs @@ -0,0 +1,30 @@ +impl Solution { + pub fn check_palindrome_formation(a: String, b: String) -> bool { + let check = |a: &str, b: &str| -> bool { + let a_chars: Vec = a.chars().collect(); + let b_chars: Vec = b.chars().collect(); + let mut i = 0; + let mut j = a.len() - 1; + while i < j && a_chars[i] == b_chars[j] { + i += 1; + j -= 1; + } + let sub_a: String = a_chars[i..=j].iter().collect(); + let sub_b: String = b_chars[i..=j].iter().collect(); + is_palindrome(&sub_a) || is_palindrome(&sub_b) + }; + + fn is_palindrome(s: &str) -> bool { + let chars: Vec = s.chars().collect(); + let len = chars.len(); + for i in 0..len / 2 { + if chars[i] != chars[len - 1 - i] { + return false; + } + } + true + } + + check(&a, &b) || check(&b, &a) + } +} diff --git a/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.swift b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.swift new file mode 100644 index 00000000..d40b2630 --- /dev/null +++ b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.swift @@ -0,0 +1,24 @@ +class Solution { + func checkPalindromeFormation(_ a: String, _ b: String) -> Bool { + return check(a, b) || check(b, a) + } + + private func check(_ a: String, _ b: String) -> Bool { + let arrA = Array(a) + let arrB = Array(b) + var i = 0 + var j = arrA.count - 1 + while i < j && arrA[i] == arrB[j] { + i += 1 + j -= 1 + } + if i >= j { + return true + } + return isPalindrome(String(arrA[i...j])) || isPalindrome(String(arrB[i...j])) + } + + private func isPalindrome(_ s: String) -> Bool { + return s == String(s.reversed()) + } +} diff --git a/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.ts b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.ts new file mode 100644 index 00000000..34ca203e --- /dev/null +++ b/tests/1501-2000/1616. split-two-strings-to-make-palindrome/sol.ts @@ -0,0 +1,19 @@ +function checkPalindromeFormation(a: string, b: string): boolean { + const check = (a: string, b: string): boolean => { + let i = 0, + j = a.length - 1; + while (i < j && a[i] === b[j]) { + i++; + j--; + } + const subA = a.substring(i, j + 1); + const subB = b.substring(i, j + 1); + return isPalindrome(subA) || isPalindrome(subB); + }; + + const isPalindrome = (s: string): boolean => { + return s === s.split("").reverse().join(""); + }; + + return check(a, b) || check(b, a); +} diff --git a/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/manifest.yaml b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/manifest.yaml new file mode 100644 index 00000000..13f27ba6 --- /dev/null +++ b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/manifest.yaml @@ -0,0 +1,517 @@ +entry: + id: 1617 + title: count-subtrees-with-max-distance-between-cities + params: + n: + type: int + edges: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().countSubgraphsForEachDiameter({n}, {edges})" + rust: "Solution::count_subgraphs_for_each_diameter({n}, {edges})" + python3: "Solution().countSubgraphsForEachDiameter({n}, {edges})" + python2: "Solution().countSubgraphsForEachDiameter({n}, {edges})" + ruby: "count_subgraphs_for_each_diameter({n}, {edges})" + java: "new Solution().countSubgraphsForEachDiameter({n}, {edges})" + csharp: "new Solution().CountSubgraphsForEachDiameter({n}, {edges})" + kotlin: "Solution().countSubgraphsForEachDiameter({n}, {edges})" + go: "countSubgraphsForEachDiameter({n}, {edges})" + dart: "Solution().countSubgraphsForEachDiameter({n}, {edges})" + swift: "Solution().countSubgraphsForEachDiameter({n}, {edges})" + typescript: "countSubgraphsForEachDiameter({n}, {edges})" +judge: + type: exact +limits: + time_ms: 5000 + memory_mb: 512 +oracle: + python3: + call: "Checker().check(n, edges, {result})" + checker: | + class Checker: + def check(self, n, edges, result): + if not isinstance(result, list) or len(result) != n - 1: + return False + graph = [[] for _ in range(n)] + for edge in edges: + if len(edge) != 2: + return False + u, v = edge[0] - 1, edge[1] - 1 + graph[u].append(v) + graph[v].append(u) + expected = [0] * (n - 1) + for mask in range(1, 1 << n): + if mask & (mask - 1) == 0: + continue + start = (mask & -mask).bit_length() - 1 + seen = {start} + queue = [start] + for u in queue: + for v in graph[u]: + if (mask >> v) & 1 and v not in seen: + seen.add(v) + queue.append(v) + if len(seen) != mask.bit_count(): + continue + diameter = 0 + for source in seen: + distance = {source: 0} + queue = [source] + for u in queue: + for v in graph[u]: + if (mask >> v) & 1 and v not in distance: + distance[v] = distance[u] + 1 + queue.append(v) + diameter = max(diameter, max(distance.values())) + expected[diameter - 1] += 1 + return result == expected +seed: 1617 +tests: + - name: path-2 + in: + n: 2 + edges: + - [1, 2] + out: [1] + - name: path-3 + in: + n: 3 + edges: + - [1, 2] + - [2, 3] + out: [2, 1] + - name: path-4 + in: + n: 4 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + out: [3, 2, 1] + - name: path-5 + in: + n: 5 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + out: [4, 3, 2, 1] + - name: path-6 + in: + n: 6 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + out: [5, 4, 3, 2, 1] + - name: path-7 + in: + n: 7 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + out: [6, 5, 4, 3, 2, 1] + - name: path-8 + in: + n: 8 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + out: [7, 6, 5, 4, 3, 2, 1] + - name: path-9 + in: + n: 9 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + out: [8, 7, 6, 5, 4, 3, 2, 1] + - name: path-10 + in: + n: 10 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + out: [9, 8, 7, 6, 5, 4, 3, 2, 1] + - name: path-11 + in: + n: 11 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + out: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + - name: path-12 + in: + n: 12 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [11, 12] + out: [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + - name: path-13 + in: + n: 13 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [11, 12] + - [12, 13] + out: [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + - name: path-14 + in: + n: 14 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [11, 12] + - [12, 13] + - [13, 14] + out: [13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + - name: path-15 + in: + n: 15 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [11, 12] + - [12, 13] + - [13, 14] + - [14, 15] + out: [14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + - name: star-3 + in: + n: 3 + edges: + - [1, 2] + - [1, 3] + out: [2, 1] + - name: star-4 + in: + n: 4 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + out: [3, 4, 0] + - name: star-5 + in: + n: 5 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + out: [4, 11, 0, 0] + - name: star-6 + in: + n: 6 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + out: [5, 26, 0, 0, 0] + - name: star-7 + in: + n: 7 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + out: [6, 57, 0, 0, 0, 0] + - name: star-8 + in: + n: 8 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [1, 8] + out: [7, 120, 0, 0, 0, 0, 0] + - name: star-9 + in: + n: 9 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [1, 8] + - [1, 9] + out: [8, 247, 0, 0, 0, 0, 0, 0] + - name: star-10 + in: + n: 10 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [1, 8] + - [1, 9] + - [1, 10] + out: [9, 502, 0, 0, 0, 0, 0, 0, 0] + - name: star-11 + in: + n: 11 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [1, 8] + - [1, 9] + - [1, 10] + - [1, 11] + out: [10, 1013, 0, 0, 0, 0, 0, 0, 0, 0] + - name: star-12 + in: + n: 12 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [1, 8] + - [1, 9] + - [1, 10] + - [1, 11] + - [1, 12] + out: [11, 2036, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: star-13 + in: + n: 13 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [1, 8] + - [1, 9] + - [1, 10] + - [1, 11] + - [1, 12] + - [1, 13] + out: [12, 4083, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: star-14 + in: + n: 14 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [1, 8] + - [1, 9] + - [1, 10] + - [1, 11] + - [1, 12] + - [1, 13] + - [1, 14] + out: [13, 8178, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: star-15 + in: + n: 15 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [1, 8] + - [1, 9] + - [1, 10] + - [1, 11] + - [1, 12] + - [1, 13] + - [1, 14] + - [1, 15] + out: [14, 16369, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: branched-5 + in: + n: 5 + edges: + - [1, 2] + - [2, 3] + - [2, 4] + - [4, 5] + out: [4, 5, 3, 0] + - name: branched-6 + in: + n: 6 + edges: + - [1, 2] + - [1, 3] + - [3, 4] + - [3, 5] + - [5, 6] + out: [5, 6, 6, 2, 0] + - name: branched-7 + in: + n: 7 + edges: + - [1, 2] + - [2, 3] + - [2, 4] + - [4, 5] + - [4, 6] + - [6, 7] + out: [6, 9, 12, 6, 0, 0] + - name: branched-8 + in: + n: 8 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [3, 5] + - [5, 6] + - [6, 7] + - [6, 8] + out: [7, 10, 9, 11, 6, 0, 0] + - name: balanced-9 + in: + n: 9 + edges: + - [1, 2] + - [1, 3] + - [2, 4] + - [2, 5] + - [3, 6] + - [3, 7] + - [7, 8] + - [7, 9] + out: [8, 13, 15, 15, 18, 0, 0, 0] + - name: long-branch-10 + in: + n: 10 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [3, 6] + - [6, 7] + - [6, 8] + - [8, 9] + - [8, 10] + out: [9, 14, 24, 35, 30, 0, 0, 0, 0] + - name: deep-11 + in: + n: 11 + edges: + - [1, 2] + - [2, 3] + - [2, 4] + - [4, 5] + - [4, 6] + - [6, 7] + - [6, 8] + - [8, 9] + - [9, 10] + - [9, 11] + out: [10, 17, 24, 33, 30, 36, 0, 0, 0, 0] + - name: complete-binary-12 + in: + n: 12 + edges: + - [1, 2] + - [1, 3] + - [2, 4] + - [2, 5] + - [3, 6] + - [3, 7] + - [4, 8] + - [5, 9] + - [6, 10] + - [7, 11] + - [7, 12] + out: [11, 16, 24, 33, 48, 55, 0, 0, 0, 0, 0] diff --git a/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.cpp b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.cpp new file mode 100644 index 00000000..7c5bab18 --- /dev/null +++ b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.cpp @@ -0,0 +1,57 @@ +class Solution { +public: + vector countSubgraphsForEachDiameter(int n, vector>& edges) { + vector> graph(n); + for (auto& e : edges) { + int u = e[0] - 1, v = e[1] - 1; + graph[u].push_back(v); + graph[v].push_back(u); + } + vector answer(n - 1, 0); + for (int mask = 1; mask < (1 << n); ++mask) { + if (__builtin_popcount(mask) <= 1) continue; + int b = mask & -mask; + int s = __builtin_ctz(b); + vector seen(n, false); + seen[s] = true; + int cnt = 1; + queue q; + q.push(s); + while (!q.empty()) { + int u = q.front(); + q.pop(); + for (int v : graph[u]) { + if ((mask >> v) & 1 && !seen[v]) { + seen[v] = true; + cnt++; + q.push(v); + } + } + } + if (cnt != __builtin_popcount(mask)) continue; + auto bfs = [&](int start) -> pair { + vector dist(n, -1); + dist[start] = 0; + queue q; + q.push(start); + int last = start; + while (!q.empty()) { + int u = q.front(); + q.pop(); + last = u; + for (int v : graph[u]) { + if ((mask >> v) & 1 && dist[v] == -1) { + dist[v] = dist[u] + 1; + q.push(v); + } + } + } + return {last, dist[last]}; + }; + auto [a, _] = bfs(s); + auto [b2, d] = bfs(a); + if (d >= 1) answer[d - 1]++; + } + return answer; + } +}; diff --git a/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.cs b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.cs new file mode 100644 index 00000000..194f3193 --- /dev/null +++ b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; + +public class Solution { + public int[] CountSubgraphsForEachDiameter(int n, int[][] edges) { + var graph = new List[n]; + for (int i = 0; i < n; i++) graph[i] = new List(); + foreach (var e in edges) { + int u = e[0] - 1, v = e[1] - 1; + graph[u].Add(v); + graph[v].Add(u); + } + int[] answer = new int[n - 1]; + for (int mask = 1; mask < (1 << n); mask++) { + if (BitCount(mask) <= 1) continue; + int b = mask & -mask; + int s = 0; + while ((b >> s) > 1) s++; + bool[] seen = new bool[n]; + seen[s] = true; + int cnt = 1; + Queue q = new Queue(); + q.Enqueue(s); + while (q.Count > 0) { + int u = q.Dequeue(); + foreach (int v in graph[u]) { + if (((mask >> v) & 1) == 1 && !seen[v]) { + seen[v] = true; + cnt++; + q.Enqueue(v); + } + } + } + if (cnt != BitCount(mask)) continue; + var bfs = new Func(start => { + int[] dist = new int[n]; + for (int i = 0; i < n; i++) dist[i] = -1; + dist[start] = 0; + Queue q = new Queue(); + q.Enqueue(start); + int last = start; + while (q.Count > 0) { + int u = q.Dequeue(); + last = u; + foreach (int v in graph[u]) { + if (((mask >> v) & 1) == 1 && dist[v] == -1) { + dist[v] = dist[u] + 1; + q.Enqueue(v); + } + } + } + return (last, dist[last]); + }); + var (a, _) = bfs(s); + var (_, d) = bfs(a); + if (d >= 1) answer[d - 1]++; + } + return answer; + } + + private int BitCount(int x) { + int count = 0; + while (x > 0) { + count += x & 1; + x >>= 1; + } + return count; + } +} diff --git a/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.dart b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.dart new file mode 100644 index 00000000..9c20319d --- /dev/null +++ b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.dart @@ -0,0 +1,76 @@ +import 'dart:collection'; + +class _BfsResult { + final int last; + final int distance; + _BfsResult(this.last, this.distance); +} + +class Solution { + List countSubgraphsForEachDiameter(int n, List> edges) { + final graph = List.generate(n, (_) => []); + for (final e in edges) { + final u = e[0] - 1; + final v = e[1] - 1; + graph[u].add(v); + graph[v].add(u); + } + final answer = List.filled(n - 1, 0); + for (var mask = 1; mask < (1 << n); mask++) { + if ((mask & (mask - 1)) == 0) continue; + final start = _lowestBit(mask); + final seen = List.filled(n, false); + final queue = Queue()..add(start); + seen[start] = true; + var count = 1; + while (queue.isNotEmpty) { + final u = queue.removeFirst(); + for (final v in graph[u]) { + if (((mask >> v) & 1) != 0 && !seen[v]) { + seen[v] = true; + count++; + queue.add(v); + } + } + } + if (count != mask.bitLength - 1 + _popcount(mask) - (mask.bitLength - 1)) continue; + final first = _bfs(start, mask, graph, n); + final diameter = _bfs(first.last, mask, graph, n).distance; + if (diameter > 0) answer[diameter - 1]++; + } + return answer; + } + + int _lowestBit(int mask) { + var i = 0; + while (((mask >> i) & 1) == 0) i++; + return i; + } + + int _popcount(int mask) { + var count = 0; + while (mask != 0) { + count += mask & 1; + mask >>= 1; + } + return count; + } + + _BfsResult _bfs(int start, int mask, List> graph, int n) { + final dist = List.filled(n, -1); + final queue = Queue()..add(start); + dist[start] = 0; + var last = start; + while (queue.isNotEmpty) { + final u = queue.removeFirst(); + last = u; + for (final v in graph[u]) { + if (((mask >> v) & 1) != 0 && dist[v] == -1) { + dist[v] = dist[u] + 1; + queue.add(v); + } + } + } + return _BfsResult(last, dist[last]); + } +} diff --git a/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.go b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.go new file mode 100644 index 00000000..0df2aa40 --- /dev/null +++ b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.go @@ -0,0 +1,62 @@ +func countSubgraphsForEachDiameter(n int, edges [][]int) []int { + graph := make([][]int, n) + for _, e := range edges { + u := e[0] - 1 + v := e[1] - 1 + graph[u] = append(graph[u], v) + graph[v] = append(graph[v], u) + } + answer := make([]int, n-1) + for mask := 1; mask < (1 << n); mask++ { + if bits.OnesCount(uint(mask)) <= 1 { + continue + } + b := mask & -mask + s := bits.TrailingZeros(uint(b)) + seen := make([]bool, n) + seen[s] = true + cnt := 1 + q := []int{s} + for len(q) > 0 { + u := q[0] + q = q[1:] + for _, v := range graph[u] { + if ((mask >> v) & 1) == 1 && !seen[v] { + seen[v] = true + cnt++ + q = append(q, v) + } + } + } + if cnt != bits.OnesCount(uint(mask)) { + continue + } + bfs := func(start int) (int, int) { + dist := make([]int, n) + for i := range dist { + dist[i] = -1 + } + dist[start] = 0 + q := []int{start} + last := start + for len(q) > 0 { + u := q[0] + q = q[1:] + last = u + for _, v := range graph[u] { + if ((mask >> v) & 1) == 1 && dist[v] == -1 { + dist[v] = dist[u] + 1 + q = append(q, v) + } + } + } + return last, dist[last] + } + a, _ := bfs(s) + _, d := bfs(a) + if d >= 1 { + answer[d-1]++ + } + } + return answer +} diff --git a/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.java b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.java new file mode 100644 index 00000000..84d0a2f6 --- /dev/null +++ b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.java @@ -0,0 +1,59 @@ +import java.util.*; + +class Solution { + public int[] countSubgraphsForEachDiameter(int n, int[][] edges) { + List> graph = new ArrayList<>(); + for (int i = 0; i < n; i++) graph.add(new ArrayList<>()); + for (int[] e : edges) { + int u = e[0] - 1, v = e[1] - 1; + graph.get(u).add(v); + graph.get(v).add(u); + } + int[] answer = new int[n - 1]; + for (int mask = 1; mask < (1 << n); mask++) { + if (Integer.bitCount(mask) <= 1) continue; + int b = mask & -mask; + int s = Integer.numberOfTrailingZeros(b); + boolean[] seen = new boolean[n]; + seen[s] = true; + int cnt = 1; + Queue q = new LinkedList<>(); + q.add(s); + while (!q.isEmpty()) { + int u = q.poll(); + for (int v : graph.get(u)) { + if (((mask >> v) & 1) == 1 && !seen[v]) { + seen[v] = true; + cnt++; + q.add(v); + } + } + } + if (cnt != Integer.bitCount(mask)) continue; + int[] bfsRes = bfs(mask, s, graph, n); + int[] bfsRes2 = bfs(mask, bfsRes[0], graph, n); + if (bfsRes2[1] >= 1) answer[bfsRes2[1] - 1]++; + } + return answer; + } + + private int[] bfs(int mask, int start, List> graph, int n) { + int[] dist = new int[n]; + Arrays.fill(dist, -1); + dist[start] = 0; + Queue q = new LinkedList<>(); + q.add(start); + int last = start; + while (!q.isEmpty()) { + int u = q.poll(); + last = u; + for (int v : graph.get(u)) { + if (((mask >> v) & 1) == 1 && dist[v] == -1) { + dist[v] = dist[u] + 1; + q.add(v); + } + } + } + return new int[]{last, dist[last]}; + } +} diff --git a/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.kt b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.kt new file mode 100644 index 00000000..c17fedab --- /dev/null +++ b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.kt @@ -0,0 +1,57 @@ +class Solution { + fun countSubgraphsForEachDiameter(n: Int, edges: Array): IntArray { + val graph = Array(n) { mutableListOf() } + for (e in edges) { + val u = e[0] - 1 + val v = e[1] - 1 + graph[u].add(v) + graph[v].add(u) + } + val answer = IntArray(n - 1) + for (mask in 1 until (1 shl n)) { + if (Integer.bitCount(mask) <= 1) continue + val b = mask and -mask + val s = Integer.numberOfTrailingZeros(b) + val seen = BooleanArray(n) + seen[s] = true + var cnt = 1 + val q = ArrayDeque() + q.add(s) + while (q.isNotEmpty()) { + val u = q.removeFirst() + for (v in graph[u]) { + if ((mask shr v) and 1 == 1 && !seen[v]) { + seen[v] = true + cnt++ + q.add(v) + } + } + } + if (cnt != Integer.bitCount(mask)) continue + val (a, _) = bfs(mask, s, graph) + val (_, d) = bfs(mask, a, graph) + if (d >= 1) answer[d - 1]++ + } + return answer + } + + private fun bfs(mask: Int, start: Int, graph: Array>): Pair { + val n = graph.size + val dist = IntArray(n) { -1 } + dist[start] = 0 + val q = ArrayDeque() + q.add(start) + var last = start + while (q.isNotEmpty()) { + val u = q.removeFirst() + last = u + for (v in graph[u]) { + if ((mask shr v) and 1 == 1 && dist[v] == -1) { + dist[v] = dist[u] + 1 + q.add(v) + } + } + } + return last to dist[last] + } +} diff --git a/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.py b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.py new file mode 100644 index 00000000..c20c5de9 --- /dev/null +++ b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.py @@ -0,0 +1,53 @@ +from collections import deque + + +class Solution: + def countSubgraphsForEachDiameter( + self, n: int, edges: list[list[int]] + ) -> list[int]: + def bfs(start): + d = [-1] * n + d[start] = 0 + q = deque([start]) + last = start + while q: + u = q.popleft() + last = u + for v in graph[u]: + if ((mask >> v) & 1) and d[v] == -1: + d[v] = d[u] + 1 + q.append(v) + return last, d[last] + + graph = [[] for _ in range(n)] + for u, v in edges: + u -= 1 + v -= 1 + graph[u].append(v) + graph[v].append(u) + answer = [0] * (n - 1) + for mask in range(1, 1 << n): + if mask & (mask - 1) == 0: + continue + b = mask & -mask + s = b.bit_length() - 1 + vis = 0 + q = deque([s]) + seen = [False] * n + seen[s] = True + cnt = 1 + while q: + u = q.popleft() + for v in graph[u]: + if ((mask >> v) & 1) and not seen[v]: + seen[v] = True + cnt += 1 + q.append(v) + if cnt != mask.bit_count(): + continue + a, _ = bfs(s) + _, diam = bfs(a) + if diam >= 1: + answer[diam - 1] += 1 + + return answer diff --git a/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.py2 b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.py2 new file mode 100644 index 00000000..6d63c0a8 --- /dev/null +++ b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.py2 @@ -0,0 +1,52 @@ +class Solution(object): + def countSubgraphsForEachDiameter(self, n, edges): + """ + :type n: int + :type edges: List[List[int]] + :rtype: List[int] + """ + from collections import deque + + graph = [[] for _ in range(n)] + for u, v in edges: + u -= 1 + v -= 1 + graph[u].append(v) + graph[v].append(u) + answer = [0] * (n - 1) + for mask in range(1, 1 << n): + if mask & (mask - 1) == 0: + continue + b = mask & -mask + s = (b.bit_length() - 1) + seen = [False] * n + seen[s] = True + cnt = 1 + q = deque([s]) + while q: + u = q.popleft() + for v in graph[u]: + if (mask >> v) & 1 and not seen[v]: + seen[v] = True + cnt += 1 + q.append(v) + if cnt != bin(mask).count('1'): + continue + def bfs(start): + d = [-1] * n + d[start] = 0 + q = deque([start]) + last = start + while q: + u = q.popleft() + last = u + for v in graph[u]: + if (mask >> v) & 1 and d[v] == -1: + d[v] = d[u] + 1 + q.append(v) + return last, d[last] + a, _ = bfs(s) + _, diam = bfs(a) + if diam >= 1: + answer[diam - 1] += 1 + return answer diff --git a/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.rb b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.rb new file mode 100644 index 00000000..f5125ca6 --- /dev/null +++ b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.rb @@ -0,0 +1,51 @@ +def count_subgraphs_for_each_diameter(n, edges) + graph = Array.new(n) { [] } + edges.each do |u, v| + u -= 1 + v -= 1 + graph[u] << v + graph[v] << u + end + answer = Array.new(n - 1, 0) + (1...(1 << n)).each do |mask| + next if mask & (mask - 1) == 0 + b = mask & -mask + s = (b.bit_length - 1) + seen = Array.new(n, false) + seen[s] = true + cnt = 1 + q = [s] + until q.empty? + u = q.shift + graph[u].each do |v| + if (mask >> v) & 1 == 1 && !seen[v] + seen[v] = true + cnt += 1 + q << v + end + end + end + next if cnt != mask.to_s(2).count('1') + bfs = ->(start) { + d = Array.new(n, -1) + d[start] = 0 + q = [start] + last = start + until q.empty? + u = q.shift + last = u + graph[u].each do |v| + if (mask >> v) & 1 == 1 && d[v] == -1 + d[v] = d[u] + 1 + q << v + end + end + end + [last, d[last]] + } + a, _ = bfs.call(s) + _, diam = bfs.call(a) + answer[diam - 1] += 1 if diam >= 1 + end + answer +end diff --git a/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.rs b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.rs new file mode 100644 index 00000000..b5053cdb --- /dev/null +++ b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.rs @@ -0,0 +1,60 @@ +impl Solution { + pub fn count_subgraphs_for_each_diameter(n: i32, edges: Vec>) -> Vec { + let n = n as usize; + let mut graph = vec![vec![]; n]; + for e in &edges { + let u = (e[0] - 1) as usize; + let v = (e[1] - 1) as usize; + graph[u].push(v); + graph[v].push(u); + } + let mut answer = vec![0; n - 1]; + for mask in 1..(1usize << n) { + if mask.count_ones() <= 1 { + continue; + } + let b = mask & mask.wrapping_neg(); + let s = b.trailing_zeros() as usize; + let mut seen = vec![false; n]; + seen[s] = true; + let mut cnt = 1; + let mut q = std::collections::VecDeque::new(); + q.push_back(s); + while let Some(u) = q.pop_front() { + for &v in &graph[u] { + if (mask >> v) & 1 == 1 && !seen[v] { + seen[v] = true; + cnt += 1; + q.push_back(v); + } + } + } + if cnt != mask.count_ones() as usize { + continue; + } + let bfs = |start: usize| -> (usize, i32) { + let mut dist = vec![-1; n]; + dist[start] = 0; + let mut q = std::collections::VecDeque::new(); + q.push_back(start); + let mut last = start; + while let Some(u) = q.pop_front() { + last = u; + for &v in &graph[u] { + if (mask >> v) & 1 == 1 && dist[v] == -1 { + dist[v] = dist[u] + 1; + q.push_back(v); + } + } + } + (last, dist[last]) + }; + let (a, _) = bfs(s); + let (_, d) = bfs(a); + if d >= 1 { + answer[(d - 1) as usize] += 1; + } + } + answer + } +} diff --git a/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.swift b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.swift new file mode 100644 index 00000000..5e687baf --- /dev/null +++ b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.swift @@ -0,0 +1,58 @@ +class Solution { + func countSubgraphsForEachDiameter(_ n: Int, _ edges: [[Int]]) -> [Int] { + var graph = [[Int]](repeating: [], count: n) + for e in edges { + let u = e[0] - 1, v = e[1] - 1 + graph[u].append(v) + graph[v].append(u) + } + var answer = [Int](repeating: 0, count: n - 1) + for mask in 1..<(1 << n) { + if mask.nonzeroBitCount <= 1 { continue } + let b = mask & -mask + let s = b.trailingZeroBitCount + var seen = [Bool](repeating: false, count: n) + seen[s] = true + var cnt = 1 + var q = [s] + var idx = 0 + while idx < q.count { + let u = q[idx] + idx += 1 + for v in graph[u] { + if ((mask >> v) & 1) == 1 && !seen[v] { + seen[v] = true + cnt += 1 + q.append(v) + } + } + } + if cnt != mask.nonzeroBitCount { continue } + func bfs(_ start: Int) -> (Int, Int) { + var dist = [Int](repeating: -1, count: n) + dist[start] = 0 + var q = [start] + var idx = 0 + var last = start + while idx < q.count { + let u = q[idx] + idx += 1 + last = u + for v in graph[u] { + if ((mask >> v) & 1) == 1 && dist[v] == -1 { + dist[v] = dist[u] + 1 + q.append(v) + } + } + } + return (last, dist[last]) + } + let (a, _) = bfs(s) + let (_, d) = bfs(a) + if d >= 1 { + answer[d - 1] += 1 + } + } + return answer + } +} diff --git a/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.ts b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.ts new file mode 100644 index 00000000..65aff22c --- /dev/null +++ b/tests/1501-2000/1617. count-subtrees-with-max-distance-between-cities/sol.ts @@ -0,0 +1,63 @@ +function countSubgraphsForEachDiameter(n: number, edges: number[][]): number[] { + const graph: number[][] = Array.from({ length: n }, () => []); + for (const [u0, v0] of edges) { + const u = u0 - 1, + v = v0 - 1; + graph[u].push(v); + graph[v].push(u); + } + const answer: number[] = new Array(n - 1).fill(0); + for (let mask = 1; mask < 1 << n; mask++) { + if (popcount(mask) <= 1) continue; + const b = mask & -mask; + const s = + Math.clz32(b) === 31 ? 31 - Math.floor(Math.log2(b)) : 31 - Math.clz32(b); + // better: use Math.log2 + const start = Math.log2(b); + const seen = new Array(n).fill(false); + seen[start] = true; + let cnt = 1; + const q: number[] = [start]; + while (q.length) { + const u = q.shift()!; + for (const v of graph[u]) { + if (((mask >> v) & 1) === 1 && !seen[v]) { + seen[v] = true; + cnt++; + q.push(v); + } + } + } + if (cnt !== popcount(mask)) continue; + const bfs = (s: number): [number, number] => { + const dist = new Array(n).fill(-1); + dist[s] = 0; + const q: number[] = [s]; + let last = s; + while (q.length) { + const u = q.shift()!; + last = u; + for (const v of graph[u]) { + if (((mask >> v) & 1) === 1 && dist[v] === -1) { + dist[v] = dist[u] + 1; + q.push(v); + } + } + } + return [last, dist[last]]; + }; + const [a, _] = bfs(start); + const [, d] = bfs(a); + if (d >= 1) answer[d - 1]++; + } + return answer; +} + +function popcount(x: number): number { + let count = 0; + while (x) { + count += x & 1; + x >>= 1; + } + return count; +} diff --git a/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/manifest.yaml b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/manifest.yaml new file mode 100644 index 00000000..f8a06645 --- /dev/null +++ b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/manifest.yaml @@ -0,0 +1,1182 @@ +entry: + id: 1619 + title: "mean-of-array-after-removing-some-elements" + params: + arr: + type: array + items: + type: int + call: + cpp: "Solution().trimMean({arr})" + rust: "Solution::trim_mean({arr})" + python3: "Solution().trimMean({arr})" + python2: "Solution().trimMean({arr})" + ruby: "trim_mean({arr})" + java: "new Solution().trimMean({arr})" + csharp: "new Solution().TrimMean({arr})" + kotlin: "Solution().trimMean({arr})" + go: "trimMean({arr})" + dart: "Solution().trimMean({arr})" + swift: "Solution().trimMean({arr})" + typescript: "trimMean({arr})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().trimMean(arr, {result})" + checker: | + class Checker: + def trimMean(self, arr, result): + if not isinstance(result, (int, float)) or isinstance(result, bool): + return False + n = len(arr) + k = n // 20 + expected = sum(sorted(arr)[k:n-k]) / float(n - 2 * k) + return abs(float(result) - expected) <= 1e-5 +seed: 1619 +tests: + - name: example-one + in: + arr: [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3] + - name: example-two + in: + arr: [6, 2, 7, 5, 1, 2, 0, 3, 10, 2, 5, 0, 5, 5, 0, 8, 7, 6, 8, 0] + - name: example-three + in: + arr: + [ + 6, + 0, + 7, + 0, + 7, + 5, + 7, + 8, + 3, + 4, + 0, + 7, + 8, + 1, + 6, + 8, + 1, + 1, + 2, + 4, + 8, + 1, + 9, + 5, + 4, + 3, + 8, + 5, + 10, + 8, + 6, + 6, + 1, + 0, + 6, + 10, + 8, + 2, + 3, + 4, + ] + - name: zeros + in: + arr: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: maximums + in: + arr: + [ + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + 100000, + ] + - name: ascending + in: + arr: + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] + - name: descending + in: + arr: + [19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] + - name: binary + in: + arr: + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + ] + - name: repeated-one + in: + arr: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100000] + - name: repeated-high + in: + arr: + [ + 0, + 99999, + 99999, + 99999, + 99999, + 99999, + 99999, + 99999, + 99999, + 99999, + 99999, + 99999, + 99999, + 99999, + 99999, + 99999, + 99999, + 99999, + 99999, + 100000, + ] + - name: alternating + in: + arr: + [ + 0, + 100000, + 1, + 99999, + 2, + 99998, + 3, + 99997, + 4, + 99996, + 5, + 99995, + 6, + 99994, + 7, + 99993, + 8, + 99992, + 9, + 99991, + ] + - name: constant-seven + in: + arr: [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7] + - name: multiples-five + in: + arr: + [ + 0, + 5, + 10, + 15, + 20, + 25, + 30, + 35, + 40, + 45, + 50, + 55, + 60, + 65, + 70, + 75, + 80, + 85, + 90, + 95, + ] + - name: duplicate-blocks + in: + arr: [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5] + - name: zeros-tens + in: + arr: + [0, 10, 0, 10, 0, 10, 0, 10, 0, 10, 0, 10, 0, 10, 0, 10, 0, 10, 0, 10] + - name: forty-ascending + in: + arr: + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + ] + - name: forty-constant + in: + arr: + [ + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + 1234, + ] + - name: forty-paired + in: + arr: + [ + 0, + 100, + 1, + 99, + 2, + 98, + 3, + 97, + 4, + 96, + 5, + 95, + 6, + 94, + 7, + 93, + 8, + 92, + 9, + 91, + 10, + 90, + 11, + 89, + 12, + 88, + 13, + 87, + 14, + 86, + 15, + 85, + 16, + 84, + 17, + 83, + 18, + 82, + 19, + 81, + 20, + 80, + ] + - name: sixty-ascending + in: + arr: + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + ] + - name: sixty-constant + in: + arr: + [ + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + ] + - name: eighty-ascending + in: + arr: + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + 63, + 64, + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + ] + - name: eighty-constant + in: + arr: + [ + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + 8080, + ] + - name: hundred-ascending + in: + arr: + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + 63, + 64, + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + 99, + ] + - name: hundred-constant + in: + arr: + [ + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + 555, + ] + - name: hundred-extreme-pairs + in: + arr: + [ + 0, + 100000, + 1, + 99999, + 2, + 99998, + 3, + 99997, + 4, + 99996, + 5, + 99995, + 6, + 99994, + 7, + 99993, + 8, + 99992, + 9, + 99991, + 10, + 99990, + 11, + 99989, + 12, + 99988, + 13, + 99987, + 14, + 99986, + 15, + 99985, + 16, + 99984, + 17, + 99983, + 18, + 99982, + 19, + 99981, + 20, + 99980, + 21, + 99979, + 22, + 99978, + 23, + 99977, + 24, + 99976, + 25, + 99975, + 26, + 99974, + 27, + 99973, + 28, + 99972, + 29, + 99971, + 30, + 99970, + 31, + 99969, + 32, + 99968, + 33, + 99967, + 34, + 99966, + 35, + 99965, + 36, + 99964, + 37, + 99963, + 38, + 99962, + 39, + 99961, + 40, + 99960, + 41, + 99959, + 42, + 99958, + 43, + 99957, + 44, + 99956, + 45, + 99955, + 46, + 99954, + 47, + 99953, + 48, + 99952, + 49, + 99951, + ] + - name: mixed-small + in: + arr: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4] + - name: mixed-large + in: + arr: + [ + 99999, + 1, + 50000, + 2, + 99998, + 3, + 49999, + 4, + 99997, + 5, + 49998, + 6, + 99996, + 7, + 49997, + 8, + 99995, + 9, + 49996, + 10, + ] + - name: twenty-one-not-allowed-use-forty + in: + arr: + [ + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 20, + 21, + 21, + 21, + 21, + 21, + 21, + 21, + 21, + 21, + 21, + 21, + 21, + 21, + 21, + 21, + 21, + 21, + 21, + 21, + 21, + ] + - name: values-near-limit + in: + arr: + [ + 99990, + 99991, + 99992, + 99993, + 99994, + 99995, + 99996, + 99997, + 99998, + 99999, + 100000, + 99990, + 99991, + 99992, + 99993, + 99994, + 99995, + 99996, + 99997, + 99998, + ] + - name: forty-random-pattern + in: + arr: + [ + 17, + 3, + 88, + 42, + 9, + 71, + 26, + 54, + 11, + 63, + 95, + 4, + 38, + 77, + 20, + 59, + 1, + 84, + 33, + 68, + 14, + 6, + 91, + 47, + 29, + 73, + 12, + 56, + 99, + 35, + 8, + 62, + 24, + 80, + 5, + 44, + 18, + 70, + 31, + 86, + ] + - name: gen-uniform-small + in: + arr: + gen: "array" + len: 20 + of: + gen: "int" + min: 0 + max: 100 + elemType: "int" + - name: gen-uniform-medium + in: + arr: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 100000 + elemType: "int" + - name: gen-uniform-large + in: + arr: + gen: "array" + len: 500 + of: + gen: "int" + min: 0 + max: 100000 + elemType: "int" + - name: gen-maximum-size + in: + arr: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 100000 + elemType: "int" + - name: gen-small-range + in: + arr: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 10 + elemType: "int" diff --git a/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.cpp b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.cpp new file mode 100644 index 00000000..447c2776 --- /dev/null +++ b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + double trimMean(vector& arr) { + int n = arr.size(); + int per5 = (int)(0.05 * n); + sort(arr.begin(), arr.end()); + double sum = 0; + for (int i = per5; i < n - per5; i++) { + sum += arr[i]; + } + return sum / (n - per5 - per5); + } +}; diff --git a/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.cs b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.cs new file mode 100644 index 00000000..f19674cf --- /dev/null +++ b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.cs @@ -0,0 +1,12 @@ +public class Solution { + public double TrimMean(int[] arr) { + int n = arr.Length; + int per5 = (int)(0.05 * n); + Array.Sort(arr); + double sum = 0; + for (int i = per5; i < n - per5; i++) { + sum += arr[i]; + } + return sum / (n - per5 - per5); + } +} diff --git a/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.dart b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.dart new file mode 100644 index 00000000..8d284571 --- /dev/null +++ b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.dart @@ -0,0 +1,12 @@ +class Solution { + double trimMean(List arr) { + int n = arr.length; + int per5 = (0.05 * n).toInt(); + arr.sort(); + double sum = 0; + for (int i = per5; i < n - per5; i++) { + sum += arr[i]; + } + return sum / (n - per5 - per5); + } +} diff --git a/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.go b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.go new file mode 100644 index 00000000..fb65f2d4 --- /dev/null +++ b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.go @@ -0,0 +1,10 @@ +func trimMean(arr []int) float64 { + n := len(arr) + per5 := int(0.05 * float64(n)) + sort.Ints(arr) + sum := 0 + for i := per5; i < n-per5; i++ { + sum += arr[i] + } + return float64(sum) / float64(n-per5-per5) +} diff --git a/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.java b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.java new file mode 100644 index 00000000..6a0ad61d --- /dev/null +++ b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.java @@ -0,0 +1,12 @@ +class Solution { + public double trimMean(int[] arr) { + int n = arr.length; + int per5 = (int)(0.05 * n); + Arrays.sort(arr); + double sum = 0; + for (int i = per5; i < n - per5; i++) { + sum += arr[i]; + } + return sum / (n - per5 - per5); + } +} diff --git a/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.kt b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.kt new file mode 100644 index 00000000..9eb05519 --- /dev/null +++ b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.kt @@ -0,0 +1,12 @@ +class Solution { + fun trimMean(arr: IntArray): Double { + val n = arr.size + val per5 = (0.05 * n).toInt() + arr.sort() + var sum = 0.0 + for (i in per5 until n - per5) { + sum += arr[i] + } + return sum / (n - per5 - per5) + } +} diff --git a/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.py b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.py new file mode 100644 index 00000000..085c12dd --- /dev/null +++ b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.py @@ -0,0 +1,7 @@ +class Solution: + def trimMean(self, arr: List[int]) -> float: + n = len(arr) + per5 = int(0.05 * n) + arr.sort() + arr = arr[per5 : n - per5] + return sum(arr) / (n - per5 - per5) diff --git a/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.py2 b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.py2 new file mode 100644 index 00000000..bcc18928 --- /dev/null +++ b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def trimMean(self, arr): + """ + :type arr: List[int] + :rtype: float + """ + n = len(arr) + per5 = int(0.05*n) + arr.sort() + arr = arr[per5:n-per5] + return float(sum(arr))/(n-per5-per5) diff --git a/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.rb b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.rb new file mode 100644 index 00000000..660db2b4 --- /dev/null +++ b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.rb @@ -0,0 +1,9 @@ +# @param {Integer[]} arr +# @return {Float} +def trim_mean(arr) + n = arr.length + per5 = (0.05 * n).to_i + arr.sort! + arr = arr[per5...n-per5] + arr.sum.to_f / (n - per5 - per5) +end diff --git a/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.rs b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.rs new file mode 100644 index 00000000..ff5091bd --- /dev/null +++ b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.rs @@ -0,0 +1,10 @@ +impl Solution { + pub fn trim_mean(arr: Vec) -> f64 { + let n = arr.len(); + let per5 = (0.05 * n as f64) as usize; + let mut arr = arr; + arr.sort(); + let sum: i32 = arr[per5..n-per5].iter().sum(); + sum as f64 / (n - per5 - per5) as f64 + } +} diff --git a/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.swift b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.swift new file mode 100644 index 00000000..f3b48498 --- /dev/null +++ b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.swift @@ -0,0 +1,9 @@ +class Solution { + func trimMean(_ arr: [Int]) -> Double { + let n = arr.count + let per5 = Int(0.05 * Double(n)) + let sorted = arr.sorted() + let sum = sorted[per5..<(n-per5)].reduce(0, +) + return Double(sum) / Double(n - per5 - per5) + } +} diff --git a/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.ts b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.ts new file mode 100644 index 00000000..a802f98b --- /dev/null +++ b/tests/1501-2000/1619. mean-of-array-after-removing-some-elements/sol.ts @@ -0,0 +1,10 @@ +function trimMean(arr: number[]): number { + const n = arr.length; + const per5 = Math.floor(0.05 * n); + arr.sort((a, b) => a - b); + let sum = 0; + for (let i = per5; i < n - per5; i++) { + sum += arr[i]; + } + return sum / (n - per5 - per5); +} diff --git a/tests/1501-2000/1620. coordinate-with-maximum-network-quality/manifest.yaml b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/manifest.yaml new file mode 100644 index 00000000..50210a3e --- /dev/null +++ b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/manifest.yaml @@ -0,0 +1,479 @@ +entry: + id: 1620 + title: "coordinate-with-maximum-network-quality" + params: + towers: + type: array + items: + type: array + items: + type: int + radius: + type: int + call: + cpp: "Solution().bestCoordinate({towers}, {radius})" + rust: "Solution::best_coordinate({towers}, {radius})" + python3: "Solution().bestCoordinate({towers}, {radius})" + python2: "Solution().bestCoordinate({towers}, {radius})" + ruby: "best_coordinate({towers}, {radius})" + java: "new Solution().bestCoordinate({towers}, {radius})" + csharp: "new Solution().BestCoordinate({towers}, {radius})" + kotlin: "Solution().bestCoordinate({towers}, {radius})" + go: "bestCoordinate({towers}, {radius})" + dart: "Solution().bestCoordinate({towers}, {radius})" + swift: "Solution().bestCoordinate({towers}, {radius})" + typescript: "bestCoordinate({towers}, {radius})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().bestCoordinate(towers, radius, {result})" + checker: | + import math + + class Checker: + def bestCoordinate(self, towers, radius, result): + if not isinstance(result, list) or len(result) != 2: + return False + if not all(isinstance(v, int) and not isinstance(v, bool) for v in result): + return False + max_x = max(t[0] for t in towers) + max_y = max(t[1] for t in towers) + expected = [0, 0] + best = 0 + for x in range(max_x + 1): + for y in range(max_y + 1): + quality = 0 + for tx, ty, q in towers: + distance = math.sqrt((tx - x) ** 2 + (ty - y) ** 2) + if distance <= radius: + quality += int(q / (1 + distance)) + candidate = [x, y] + if quality > best or (quality == best and candidate < expected): + best = quality + expected = candidate + return result == expected + +seed: 1620 + +tests: + - name: "example_1" + in: + towers: + elemType: "int" + value: + - [1, 2, 5] + - [2, 1, 7] + - [3, 1, 9] + radius: 2 + out: [2, 1] + + - name: "example_2" + in: + towers: + elemType: "int" + value: + - [23, 11, 21] + radius: 9 + out: [23, 11] + + - name: "example_3" + in: + towers: + elemType: "int" + value: + - [1, 2, 13] + - [2, 1, 7] + - [0, 1, 9] + radius: 2 + out: [1, 2] + + - name: "zero_quality_tower" + in: + towers: + elemType: "int" + value: + - [50, 50, 0] + radius: 1 + + - name: "origin_tower" + in: + towers: + elemType: "int" + value: + - [0, 0, 50] + radius: 50 + out: [0, 0] + + - name: "lexicographic_tie" + in: + towers: + elemType: "int" + value: + - [1, 0, 1] + - [0, 1, 1] + radius: 1 + + - name: "same_location" + in: + towers: + elemType: "int" + value: + - [4, 4, 10] + - [4, 4, 20] + radius: 1 + + - name: "radius_one" + in: + towers: + elemType: "int" + value: + - [2, 2, 30] + - [0, 0, 30] + - [1, 1, 30] + radius: 1 + + - name: "radius_max" + in: + towers: + elemType: "int" + value: + - [0, 50, 50] + - [50, 0, 49] + radius: 50 + + - name: "diagonal_distance" + in: + towers: + elemType: "int" + value: + - [0, 0, 40] + - [3, 4, 40] + radius: 5 + + - name: "boundary_coordinates" + in: + towers: + elemType: "int" + value: + - [0, 50, 1] + - [50, 50, 50] + - [50, 0, 1] + radius: 2 + + - name: "clustered_towers" + in: + towers: + elemType: "int" + value: + - [10, 10, 5] + - [10, 11, 6] + - [11, 10, 7] + - [11, 11, 8] + - [12, 12, 9] + radius: 3 + + - name: "sparse_towers" + in: + towers: + elemType: "int" + value: + - [0, 0, 50] + - [25, 25, 49] + - [50, 50, 48] + radius: 2 + + - name: "many_zero_quality" + in: + towers: + elemType: "int" + value: + - [1, 1, 0] + - [2, 2, 0] + - [3, 3, 0] + - [4, 4, 50] + radius: 4 + + - name: "small_square" + in: + towers: + elemType: "int" + value: + - [0, 0, 10] + - [0, 2, 10] + - [2, 0, 10] + - [2, 2, 10] + radius: 2 + + - name: "overlapping_reach" + in: + towers: + elemType: "int" + value: + - [5, 5, 20] + - [6, 5, 20] + - [5, 6, 20] + - [4, 5, 20] + - [5, 4, 20] + radius: 2 + + - name: "quality_gradient" + in: + towers: + elemType: "int" + value: + - [0, 0, 1] + - [1, 0, 2] + - [2, 0, 3] + - [3, 0, 4] + - [4, 0, 5] + radius: 4 + + - name: "far_high_quality" + in: + towers: + elemType: "int" + value: + - [0, 0, 1] + - [50, 50, 50] + radius: 10 + + - name: "integer_boundary_distance" + in: + towers: + elemType: "int" + value: + - [0, 0, 25] + - [3, 4, 26] + - [6, 8, 27] + radius: 5 + + - name: "rectangle_corners" + in: + towers: + elemType: "int" + value: + - [1, 1, 11] + - [1, 9, 12] + - [9, 1, 13] + - [9, 9, 14] + radius: 6 + + - name: "duplicate_coordinates_different_quality" + in: + towers: + elemType: "int" + value: + - [7, 8, 1] + - [7, 8, 2] + - [7, 8, 3] + - [6, 8, 50] + radius: 3 + + - name: "low_radius_cluster" + in: + towers: + elemType: "int" + value: + - [20, 20, 50] + - [20, 21, 49] + - [21, 20, 48] + - [21, 21, 47] + - [22, 22, 46] + radius: 1 + + - name: "large_radius_cluster" + in: + towers: + elemType: "int" + value: + - [15, 15, 15] + - [16, 16, 16] + - [17, 17, 17] + - [18, 18, 18] + - [19, 19, 19] + radius: 20 + + - name: "axes_mix" + in: + towers: + elemType: "int" + value: + - [0, 7, 30] + - [7, 0, 29] + - [0, 0, 28] + - [7, 7, 27] + radius: 7 + + - name: "all_maximum_values" + in: + towers: + elemType: "int" + value: + - [50, 50, 50] + - [50, 49, 50] + - [49, 50, 50] + - [49, 49, 50] + radius: 50 + + - name: "quality_zero_origin_tie" + in: + towers: + elemType: "int" + value: + - [50, 50, 0] + - [50, 49, 0] + radius: 1 + + - name: "long_horizontal_line" + in: + towers: + elemType: "int" + value: + - [0, 25, 5] + - [10, 25, 10] + - [20, 25, 15] + - [30, 25, 20] + - [40, 25, 25] + - [50, 25, 30] + radius: 10 + + - name: "long_vertical_line" + in: + towers: + elemType: "int" + value: + - [25, 0, 5] + - [25, 10, 10] + - [25, 20, 15] + - [25, 30, 20] + - [25, 40, 25] + - [25, 50, 30] + radius: 15 + + - name: "mixed_extremes" + in: + towers: + elemType: "int" + value: + - [0, 0, 50] + - [0, 50, 1] + - [50, 0, 1] + - [50, 50, 50] + - [25, 25, 25] + radius: 25 + + - name: "single_low_quality_corner" + in: + towers: + elemType: "int" + value: + - [50, 0, 1] + radius: 50 + + - name: "generated_small" + seed: 162001 + in: + towers: + gen: "array" + len: + gen: "int" + min: 1 + max: 8 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 0 + max: 10 + elemType: "int" + radius: + gen: "int" + min: 1 + max: 10 + + - name: "generated_medium" + seed: 162002 + in: + towers: + gen: "array" + len: + gen: "int" + min: 10 + max: 20 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 0 + max: 50 + elemType: "int" + radius: + gen: "int" + min: 1 + max: 25 + + - name: "generated_dense" + seed: 162003 + in: + towers: + gen: "array" + len: 50 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 0 + max: 50 + elemType: "int" + radius: 50 + + - name: "generated_sparse" + seed: 162004 + in: + towers: + gen: "array" + len: + gen: "int" + min: 1 + max: 5 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 0 + max: 50 + elemType: "int" + radius: 1 + + - name: "generated_near_limit" + seed: 162005 + in: + towers: + gen: "array" + len: + gen: "int" + min: 40 + max: 50 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 0 + max: 50 + elemType: "int" + radius: + gen: "int" + min: 40 + max: 50 diff --git a/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.cpp b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.cpp new file mode 100644 index 00000000..2a96ca19 --- /dev/null +++ b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + vector bestCoordinate(vector>& towers, int radius) { + int max_x = 0; + int max_y = 0; + for (const auto& t : towers) { + max_x = max(max_x, t[0]); + max_y = max(max_y, t[1]); + } + + int best_quality = 0; + vector best_coord = {0, 0}; + + for (int x = 0; x <= max_x; x++) { + for (int y = 0; y <= max_y; y++) { + int quality = 0; + for (const auto& t : towers) { + double dist = sqrt(pow(t[0] - x, 2) + pow(t[1] - y, 2)); + if (dist <= radius) { + quality += (int)(t[2] / (1 + dist)); + } + } + if (quality > best_quality || (quality == best_quality && (x < best_coord[0] || (x == best_coord[0] && y < best_coord[1])))) { + best_quality = quality; + best_coord[0] = x; + best_coord[1] = y; + } + } + } + + return best_coord; + } +}; diff --git a/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.cs b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.cs new file mode 100644 index 00000000..342cb46d --- /dev/null +++ b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.cs @@ -0,0 +1,32 @@ +public class Solution { + public int[] BestCoordinate(int[][] towers, int radius) { + int maxX = 0; + int maxY = 0; + foreach (var t in towers) { + maxX = Math.Max(maxX, t[0]); + maxY = Math.Max(maxY, t[1]); + } + + int bestQuality = 0; + int[] bestCoord = new int[] {0, 0}; + + for (int x = 0; x <= maxX; x++) { + for (int y = 0; y <= maxY; y++) { + int quality = 0; + foreach (var t in towers) { + double dist = Math.Sqrt(Math.Pow(t[0] - x, 2) + Math.Pow(t[1] - y, 2)); + if (dist <= radius) { + quality += (int)(t[2] / (1 + dist)); + } + } + if (quality > bestQuality || (quality == bestQuality && (x < bestCoord[0] || (x == bestCoord[0] && y < bestCoord[1])))) { + bestQuality = quality; + bestCoord[0] = x; + bestCoord[1] = y; + } + } + } + + return bestCoord; + } +} diff --git a/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.dart b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.dart new file mode 100644 index 00000000..aaf4b640 --- /dev/null +++ b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.dart @@ -0,0 +1,32 @@ +class Solution { + List bestCoordinate(List> towers, int radius) { + int maxX = 0; + int maxY = 0; + for (var t in towers) { + if (t[0] > maxX) maxX = t[0]; + if (t[1] > maxY) maxY = t[1]; + } + + int bestQuality = 0; + List bestCoord = [0, 0]; + + for (int x = 0; x <= maxX; x++) { + for (int y = 0; y <= maxY; y++) { + int quality = 0; + for (var t in towers) { + double dist = sqrt(pow(t[0] - x, 2) + pow(t[1] - y, 2)); + if (dist <= radius) { + quality += (t[2] / (1 + dist)).toInt(); + } + } + if (quality > bestQuality || (quality == bestQuality && (x < bestCoord[0] || (x == bestCoord[0] && y < bestCoord[1])))) { + bestQuality = quality; + bestCoord[0] = x; + bestCoord[1] = y; + } + } + } + + return bestCoord; + } +} diff --git a/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.go b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.go new file mode 100644 index 00000000..12bb38cd --- /dev/null +++ b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.go @@ -0,0 +1,32 @@ +func bestCoordinate(towers [][]int, radius int) []int { + maxX := 0 + maxY := 0 + for _, t := range towers { + if t[0] > maxX { maxX = t[0] } + if t[1] > maxY { maxY = t[1] } + } + + bestQuality := 0 + bestCoord := []int{0, 0} + + for x := 0; x <= maxX; x++ { + for y := 0; y <= maxY; y++ { + quality := 0 + for _, t := range towers { + dx := float64(t[0] - x) + dy := float64(t[1] - y) + dist := math.Sqrt(dx*dx + dy*dy) + if dist <= float64(radius) { + quality += int(float64(t[2]) / (1 + dist)) + } + } + if quality > bestQuality || (quality == bestQuality && (x < bestCoord[0] || (x == bestCoord[0] && y < bestCoord[1]))) { + bestQuality = quality + bestCoord[0] = x + bestCoord[1] = y + } + } + } + + return bestCoord +} diff --git a/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.java b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.java new file mode 100644 index 00000000..aee112ce --- /dev/null +++ b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.java @@ -0,0 +1,32 @@ +class Solution { + public int[] bestCoordinate(int[][] towers, int radius) { + int maxX = 0; + int maxY = 0; + for (int[] t : towers) { + maxX = Math.max(maxX, t[0]); + maxY = Math.max(maxY, t[1]); + } + + int bestQuality = 0; + int[] bestCoord = new int[]{0, 0}; + + for (int x = 0; x <= maxX; x++) { + for (int y = 0; y <= maxY; y++) { + int quality = 0; + for (int[] t : towers) { + double dist = Math.sqrt(Math.pow(t[0] - x, 2) + Math.pow(t[1] - y, 2)); + if (dist <= radius) { + quality += (int)(t[2] / (1 + dist)); + } + } + if (quality > bestQuality || (quality == bestQuality && (x < bestCoord[0] || (x == bestCoord[0] && y < bestCoord[1])))) { + bestQuality = quality; + bestCoord[0] = x; + bestCoord[1] = y; + } + } + } + + return bestCoord; + } +} diff --git a/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.kt b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.kt new file mode 100644 index 00000000..5e9c3da1 --- /dev/null +++ b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.kt @@ -0,0 +1,32 @@ +class Solution { + fun bestCoordinate(towers: Array, radius: Int): IntArray { + var maxX = 0 + var maxY = 0 + for (t in towers) { + maxX = maxOf(maxX, t[0]) + maxY = maxOf(maxY, t[1]) + } + + var bestQuality = 0 + var bestCoord = intArrayOf(0, 0) + + for (x in 0..maxX) { + for (y in 0..maxY) { + var quality = 0 + for (t in towers) { + val dist = Math.sqrt(((t[0] - x) * (t[0] - x) + (t[1] - y) * (t[1] - y)).toDouble()) + if (dist <= radius) { + quality += (t[2] / (1 + dist)).toInt() + } + } + if (quality > bestQuality || (quality == bestQuality && (x < bestCoord[0] || (x == bestCoord[0] && y < bestCoord[1])))) { + bestQuality = quality + bestCoord[0] = x + bestCoord[1] = y + } + } + } + + return bestCoord + } +} diff --git a/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.py b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.py new file mode 100644 index 00000000..4e3a732e --- /dev/null +++ b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.py @@ -0,0 +1,27 @@ +class Solution(object): + def bestCoordinate(self, towers, radius): + """ + :type towers: List[List[int]] + :type radius: int + :rtype: List[int] + """ + max_x = max(t[0] for t in towers) + max_y = max(t[1] for t in towers) + + best_quality = 0 + best_coord = [0, 0] + + for x in range(max_x + 1): + for y in range(max_y + 1): + quality = 0 + for tx, ty, q in towers: + dist = math.sqrt((tx - x) ** 2 + (ty - y) ** 2) + if dist <= radius: + quality += int(q / (1 + dist)) + if quality > best_quality or ( + quality == best_quality and [x, y] < best_coord + ): + best_quality = quality + best_coord = [x, y] + + return best_coord diff --git a/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.py2 b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.py2 new file mode 100644 index 00000000..bf6ae16f --- /dev/null +++ b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.py2 @@ -0,0 +1,26 @@ +class Solution(object): + def bestCoordinate(self, towers, radius): + """ + :type towers: List[List[int]] + :type radius: int + :rtype: List[int] + """ + import math + max_x = max(t[0] for t in towers) + max_y = max(t[1] for t in towers) + + best_quality = 0 + best_coord = [0, 0] + + for x in range(max_x + 1): + for y in range(max_y + 1): + quality = 0 + for tx, ty, q in towers: + dist = math.sqrt((tx - x) ** 2 + (ty - y) ** 2) + if dist <= radius: + quality += int(q / (1 + dist)) + if quality > best_quality or (quality == best_quality and [x, y] < best_coord): + best_quality = quality + best_coord = [x, y] + + return best_coord diff --git a/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.rb b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.rb new file mode 100644 index 00000000..279a60ae --- /dev/null +++ b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.rb @@ -0,0 +1,28 @@ +# @param {Integer[][]} towers +# @param {Integer} radius +# @return {Integer[]} +def best_coordinate(towers, radius) + max_x = towers.map { |t| t[0] }.max + max_y = towers.map { |t| t[1] }.max + + best_quality = 0 + best_coord = [0, 0] + + (0..max_x).each do |x| + (0..max_y).each do |y| + quality = 0 + towers.each do |tx, ty, q| + dist = Math.sqrt((tx - x) ** 2 + (ty - y) ** 2) + if dist <= radius + quality += (q / (1 + dist)).to_i + end + end + if quality > best_quality || (quality == best_quality && (x < best_coord[0] || (x == best_coord[0] && y < best_coord[1]))) + best_quality = quality + best_coord = [x, y] + end + end + end + + best_coord +end diff --git a/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.rs b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.rs new file mode 100644 index 00000000..535fa65c --- /dev/null +++ b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.rs @@ -0,0 +1,34 @@ +impl Solution { + pub fn best_coordinate(towers: Vec>, radius: i32) -> Vec { + let mut max_x = 0; + let mut max_y = 0; + for t in &towers { + max_x = max_x.max(t[0]); + max_y = max_y.max(t[1]); + } + + let mut best_quality = 0; + let mut best_coord = vec![0, 0]; + + for x in 0..=max_x { + for y in 0..=max_y { + let mut quality = 0; + for t in &towers { + let dx = (t[0] - x) as f64; + let dy = (t[1] - y) as f64; + let dist = (dx * dx + dy * dy).sqrt(); + if dist <= radius as f64 { + quality += (t[2] as f64 / (1.0 + dist)) as i32; + } + } + if quality > best_quality || (quality == best_quality && (x < best_coord[0] || (x == best_coord[0] && y < best_coord[1]))) { + best_quality = quality; + best_coord[0] = x; + best_coord[1] = y; + } + } + } + + best_coord + } +} diff --git a/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.swift b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.swift new file mode 100644 index 00000000..7201445b --- /dev/null +++ b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.swift @@ -0,0 +1,32 @@ +class Solution { + func bestCoordinate(_ towers: [[Int]], _ radius: Int) -> [Int] { + var maxX = 0 + var maxY = 0 + for t in towers { + maxX = max(maxX, t[0]) + maxY = max(maxY, t[1]) + } + + var bestQuality = 0 + var bestCoord = [0, 0] + + for x in 0...maxX { + for y in 0...maxY { + var quality = 0 + for t in towers { + let dist = sqrt(Double((t[0] - x) * (t[0] - x) + (t[1] - y) * (t[1] - y))) + if dist <= Double(radius) { + quality += Int(Double(t[2]) / (1 + dist)) + } + } + if quality > bestQuality || (quality == bestQuality && (x < bestCoord[0] || (x == bestCoord[0] && y < bestCoord[1]))) { + bestQuality = quality + bestCoord[0] = x + bestCoord[1] = y + } + } + } + + return bestCoord + } +} diff --git a/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.ts b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.ts new file mode 100644 index 00000000..cf8155c7 --- /dev/null +++ b/tests/1501-2000/1620. coordinate-with-maximum-network-quality/sol.ts @@ -0,0 +1,34 @@ +function bestCoordinate(towers: number[][], radius: number): number[] { + let maxX = 0; + let maxY = 0; + for (const t of towers) { + maxX = Math.max(maxX, t[0]); + maxY = Math.max(maxY, t[1]); + } + + let bestQuality = 0; + let bestCoord = [0, 0]; + + for (let x = 0; x <= maxX; x++) { + for (let y = 0; y <= maxY; y++) { + let quality = 0; + for (const t of towers) { + const dist = Math.sqrt(Math.pow(t[0] - x, 2) + Math.pow(t[1] - y, 2)); + if (dist <= radius) { + quality += Math.floor(t[2] / (1 + dist)); + } + } + if ( + quality > bestQuality || + (quality === bestQuality && + (x < bestCoord[0] || (x === bestCoord[0] && y < bestCoord[1]))) + ) { + bestQuality = quality; + bestCoord[0] = x; + bestCoord[1] = y; + } + } + } + + return bestCoord; +} diff --git a/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/manifest.yaml b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/manifest.yaml new file mode 100644 index 00000000..88d9e63c --- /dev/null +++ b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/manifest.yaml @@ -0,0 +1,255 @@ +entry: + id: 1621 + title: number-of-sets-of-k-non-overlapping-line-segments + params: + n: + type: int + k: + type: int + call: + cpp: "Solution().numberOfSets({n}, {k})" + rust: "Solution::number_of_sets({n}, {k})" + python3: "Solution().numberOfSets({n}, {k})" + python2: "Solution().numberOfSets({n}, {k})" + ruby: "number_of_sets({n}, {k})" + java: "new Solution().numberOfSets({n}, {k})" + csharp: "new Solution().NumberOfSets({n}, {k})" + kotlin: "Solution().numberOfSets({n}, {k})" + go: "numberOfSets({n}, {k})" + dart: "Solution().numberOfSets({n}, {k})" + swift: "Solution().numberOfSets({n}, {k})" + typescript: "numberOfSets({n}, {k})" + +judge: + type: exact + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().numberOfSets(n, k, {result})" + checker: | + import math + + class Checker: + def numberOfSets(self, n, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + expected = math.comb(n + k - 1, 2 * k) % (10 ** 9 + 7) + return result == expected + +seed: 1621 + +tests: + - name: minimum-valid + in: + n: 3 + k: 1 + out: 3 + - name: example-one-segment + in: + n: 4 + k: 1 + out: 6 + - name: example-two-segments + in: + n: 4 + k: 2 + out: 5 + - name: small-one + in: + n: 5 + k: 1 + out: 10 + - name: small-two + in: + n: 5 + k: 2 + out: 15 + - name: maximum-k-five + in: + n: 5 + k: 4 + out: 1 + - name: six-one + in: + n: 6 + k: 1 + out: 15 + - name: six-three + in: + n: 6 + k: 3 + out: 28 + - name: seven-two + in: + n: 7 + k: 2 + out: 70 + - name: maximum-k-seven + in: + n: 7 + k: 6 + out: 1 + - name: balanced-eight + in: + n: 8 + k: 4 + out: 165 + - name: nine-two + in: + n: 9 + k: 2 + out: 210 + - name: ten-one + in: + n: 10 + k: 1 + out: 45 + - name: ten-half + in: + n: 10 + k: 5 + out: 1001 + - name: maximum-k-ten + in: + n: 10 + k: 9 + out: 1 + - name: eleven-three + in: + n: 11 + k: 3 + out: 1716 + - name: twelve-half + in: + n: 12 + k: 6 + out: 6188 + - name: fifteen-two + in: + n: 15 + k: 2 + out: 1820 + - name: fifteen-seven + in: + n: 15 + k: 7 + out: 116280 + - name: maximum-k-fifteen + in: + n: 15 + k: 14 + out: 1 + - name: twenty-one + in: + n: 20 + k: 1 + out: 190 + - name: twenty-half + in: + n: 20 + k: 10 + out: 10015005 + - name: maximum-k-twenty + in: + n: 20 + k: 19 + out: 1 + - name: twenty-five-five + in: + n: 25 + k: 5 + out: 20030010 + - name: twenty-five-twelve + in: + n: 25 + k: 12 + out: 251677693 + - name: example-three + in: + n: 30 + k: 7 + out: 796297179 + - name: thirty-half + in: + n: 30 + k: 15 + out: 955807730 + - name: fifty-two + in: + n: 50 + k: 2 + out: 249900 + - name: fifty-half + in: + n: 50 + k: 25 + out: 9688739 + - name: hundred-one + in: + n: 100 + k: 1 + out: 4950 + - name: hundred-half + in: + n: 100 + k: 50 + out: 237930091 + - name: maximum-k-hundred + in: + n: 100 + k: 99 + out: 1 + - name: five-hundred-two + in: + n: 500 + k: 2 + out: 593739611 + - name: five-hundred-half + in: + n: 500 + k: 250 + out: 540818587 + - name: maximum-k-thousand + in: + n: 1000 + k: 999 + out: 1 + - name: generated-small-k + in: + n: 1000 + k: + gen: int + min: 1 + max: 20 + - name: generated-medium-k + in: + n: 1000 + k: + gen: int + min: 21 + max: 200 + - name: generated-large-k + in: + n: 1000 + k: + gen: int + min: 201 + max: 700 + - name: generated-near-limit-k + in: + n: 1000 + k: + gen: int + min: 701 + max: 998 + - name: generated-maximum-k + in: + n: 1000 + k: + gen: int + min: 999 + max: 999 diff --git a/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.cpp b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.cpp new file mode 100644 index 00000000..e73f75ba --- /dev/null +++ b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int numberOfSets(int n, int k) { + const long long MOD = 1000000007LL; + vector dp_prev(n, 1); + + vector prefix_prev(n, 0); + prefix_prev[0] = dp_prev[0]; + for (int i = 1; i < n; ++i) { + prefix_prev[i] = (prefix_prev[i-1] + dp_prev[i]) % MOD; + } + + for (int iter = 0; iter < k; ++iter) { + vector dp_cur(n, 0); + for (int i = 1; i < n; ++i) { + dp_cur[i] = (dp_cur[i-1] + prefix_prev[i-1]) % MOD; + } + dp_prev = dp_cur; + prefix_prev[0] = dp_prev[0]; + for (int i = 1; i < n; ++i) { + prefix_prev[i] = (prefix_prev[i-1] + dp_prev[i]) % MOD; + } + } + + return (int)dp_prev[n-1]; + } +}; diff --git a/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.cs b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.cs new file mode 100644 index 00000000..c177d9a1 --- /dev/null +++ b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.cs @@ -0,0 +1,27 @@ +public class Solution { + public int NumberOfSets(int n, int k) { + const long MOD = 1000000007L; + long[] dpPrev = new long[n]; + for (int i = 0; i < n; i++) dpPrev[i] = 1; + + long[] prefixPrev = new long[n]; + prefixPrev[0] = dpPrev[0]; + for (int i = 1; i < n; i++) { + prefixPrev[i] = (prefixPrev[i-1] + dpPrev[i]) % MOD; + } + + for (int iter = 0; iter < k; iter++) { + long[] dpCur = new long[n]; + for (int i = 1; i < n; i++) { + dpCur[i] = (dpCur[i-1] + prefixPrev[i-1]) % MOD; + } + dpPrev = dpCur; + prefixPrev[0] = dpPrev[0]; + for (int i = 1; i < n; i++) { + prefixPrev[i] = (prefixPrev[i-1] + dpPrev[i]) % MOD; + } + } + + return (int)dpPrev[n-1]; + } +} diff --git a/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.dart b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.dart new file mode 100644 index 00000000..69075937 --- /dev/null +++ b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.dart @@ -0,0 +1,26 @@ +class Solution { + int numberOfSets(int n, int k) { + const MOD = 1000000007; + List dpPrev = List.filled(n, 1); + + List prefixPrev = List.filled(n, 0); + prefixPrev[0] = dpPrev[0]; + for (int i = 1; i < n; i++) { + prefixPrev[i] = (prefixPrev[i-1] + dpPrev[i]) % MOD; + } + + for (int iter = 0; iter < k; iter++) { + List dpCur = List.filled(n, 0); + for (int i = 1; i < n; i++) { + dpCur[i] = (dpCur[i-1] + prefixPrev[i-1]) % MOD; + } + dpPrev = dpCur; + prefixPrev[0] = dpPrev[0]; + for (int i = 1; i < n; i++) { + prefixPrev[i] = (prefixPrev[i-1] + dpPrev[i]) % MOD; + } + } + + return dpPrev[n-1]; + } +} diff --git a/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.go b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.go new file mode 100644 index 00000000..e08b3c73 --- /dev/null +++ b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.go @@ -0,0 +1,27 @@ +func numberOfSets(n int, k int) int { + const MOD = 1000000007 + dpPrev := make([]int64, n) + for i := 0; i < n; i++ { + dpPrev[i] = 1 + } + + prefixPrev := make([]int64, n) + prefixPrev[0] = dpPrev[0] + for i := 1; i < n; i++ { + prefixPrev[i] = (prefixPrev[i-1] + dpPrev[i]) % MOD + } + + for iter := 0; iter < k; iter++ { + dpCur := make([]int64, n) + for i := 1; i < n; i++ { + dpCur[i] = (dpCur[i-1] + prefixPrev[i-1]) % MOD + } + dpPrev = dpCur + prefixPrev[0] = dpPrev[0] + for i := 1; i < n; i++ { + prefixPrev[i] = (prefixPrev[i-1] + dpPrev[i]) % MOD + } + } + + return int(dpPrev[n-1]) +} diff --git a/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.java b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.java new file mode 100644 index 00000000..f10a87a5 --- /dev/null +++ b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.java @@ -0,0 +1,27 @@ +class Solution { + public int numberOfSets(int n, int k) { + long MOD = 1_000_000_007L; + long[] dp_prev = new long[n]; + for (int i = 0; i < n; i++) dp_prev[i] = 1; + + long[] prefix_prev = new long[n]; + prefix_prev[0] = dp_prev[0]; + for (int i = 1; i < n; i++) { + prefix_prev[i] = (prefix_prev[i-1] + dp_prev[i]) % MOD; + } + + for (int iter = 0; iter < k; iter++) { + long[] dp_cur = new long[n]; + for (int i = 1; i < n; i++) { + dp_cur[i] = (dp_cur[i-1] + prefix_prev[i-1]) % MOD; + } + dp_prev = dp_cur; + prefix_prev[0] = dp_prev[0]; + for (int i = 1; i < n; i++) { + prefix_prev[i] = (prefix_prev[i-1] + dp_prev[i]) % MOD; + } + } + + return (int) dp_prev[n-1]; + } +} diff --git a/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.kt b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.kt new file mode 100644 index 00000000..61f67a2d --- /dev/null +++ b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.kt @@ -0,0 +1,26 @@ +class Solution { + fun numberOfSets(n: Int, k: Int): Int { + val MOD = 1_000_000_007L + var dpPrev = LongArray(n) { 1L } + + var prefixPrev = LongArray(n) + prefixPrev[0] = dpPrev[0] + for (i in 1 until n) { + prefixPrev[i] = (prefixPrev[i-1] + dpPrev[i]) % MOD + } + + repeat(k) { + val dpCur = LongArray(n) + for (i in 1 until n) { + dpCur[i] = (dpCur[i-1] + prefixPrev[i-1]) % MOD + } + dpPrev = dpCur + prefixPrev[0] = dpPrev[0] + for (i in 1 until n) { + prefixPrev[i] = (prefixPrev[i-1] + dpPrev[i]) % MOD + } + } + + return dpPrev[n-1].toInt() + } +} diff --git a/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.py b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.py new file mode 100644 index 00000000..4b2887a2 --- /dev/null +++ b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.py @@ -0,0 +1,28 @@ +class Solution(object): + def numberOfSets(self, n, k): + """ + :type n: int + :type k: int + :rtype: int + """ + MOD = 10**9 + 7 + dp_prev = [1] * n + + prefix_prev = [0] * n + prefix_prev[0] = dp_prev[0] + for i in range(1, n): + prefix_prev[i] = (prefix_prev[i - 1] + dp_prev[i]) % MOD + + for _ in range(1, k + 1): + dp_cur = [0] * n + for i in range(1, n): + dp_cur[i] = dp_cur[i - 1] + prefix_prev[i - 1] + if dp_cur[i] >= MOD: + dp_cur[i] %= MOD + + dp_prev = dp_cur + prefix_prev[0] = dp_prev[0] + for i in range(1, n): + prefix_prev[i] = (prefix_prev[i - 1] + dp_prev[i]) % MOD + + return dp_prev[n - 1] diff --git a/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.py2 b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.py2 new file mode 100644 index 00000000..a27cede9 --- /dev/null +++ b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.py2 @@ -0,0 +1,28 @@ +class Solution(object): + def numberOfSets(self, n, k): + """ + :type n: int + :type k: int + :rtype: int + """ + MOD = 10**9 + 7 + dp_prev = [1] * n + + prefix_prev = [0] * n + prefix_prev[0] = dp_prev[0] + for i in range(1, n): + prefix_prev[i] = (prefix_prev[i-1] + dp_prev[i]) % MOD + + for _ in range(1, k+1): + dp_cur = [0] * n + for i in range(1, n): + dp_cur[i] = dp_cur[i-1] + prefix_prev[i-1] + if dp_cur[i] >= MOD: + dp_cur[i] %= MOD + + dp_prev = dp_cur + prefix_prev[0] = dp_prev[0] + for i in range(1, n): + prefix_prev[i] = (prefix_prev[i-1] + dp_prev[i]) % MOD + + return dp_prev[n-1] diff --git a/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.rb b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.rb new file mode 100644 index 00000000..75ee6e1b --- /dev/null +++ b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.rb @@ -0,0 +1,29 @@ +# @param {Integer} n +# @param {Integer} k +# @return {Integer} +def number_of_sets(n, k) + mod = 10**9 + 7 + dp_prev = Array.new(n, 1) + + prefix_prev = Array.new(n, 0) + prefix_prev[0] = dp_prev[0] + (1...n).each do |i| + prefix_prev[i] = (prefix_prev[i-1] + dp_prev[i]) % mod + end + + (1..k).each do + dp_cur = Array.new(n, 0) + (1...n).each do |i| + dp_cur[i] = dp_cur[i-1] + prefix_prev[i-1] + dp_cur[i] %= mod if dp_cur[i] >= mod + end + + dp_prev = dp_cur + prefix_prev[0] = dp_prev[0] + (1...n).each do |i| + prefix_prev[i] = (prefix_prev[i-1] + dp_prev[i]) % mod + end + end + + dp_prev[n-1] +end diff --git a/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.rs b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.rs new file mode 100644 index 00000000..1347c8c6 --- /dev/null +++ b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.rs @@ -0,0 +1,28 @@ +impl Solution { + pub fn number_of_sets(n: i32, k: i32) -> i32 { + const MOD: i64 = 1_000_000_007; + let n = n as usize; + let k = k as usize; + let mut dp_prev = vec![1i64; n]; + + let mut prefix_prev = vec![0i64; n]; + prefix_prev[0] = dp_prev[0]; + for i in 1..n { + prefix_prev[i] = (prefix_prev[i-1] + dp_prev[i]) % MOD; + } + + for _ in 0..k { + let mut dp_cur = vec![0i64; n]; + for i in 1..n { + dp_cur[i] = (dp_cur[i-1] + prefix_prev[i-1]) % MOD; + } + dp_prev = dp_cur; + prefix_prev[0] = dp_prev[0]; + for i in 1..n { + prefix_prev[i] = (prefix_prev[i-1] + dp_prev[i]) % MOD; + } + } + + dp_prev[n-1] as i32 + } +} diff --git a/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.swift b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.swift new file mode 100644 index 00000000..3ad69add --- /dev/null +++ b/tests/1501-2000/1621. number-of-sets-of-k-non-overlapping-line-segments/sol.swift @@ -0,0 +1,26 @@ +class Solution { + func numberOfSets(_ n: Int, _ k: Int) -> Int { + let MOD = 1_000_000_007 + var dpPrev = [Int](repeating: 1, count: n) + + var prefixPrev = [Int](repeating: 0, count: n) + prefixPrev[0] = dpPrev[0] + for i in 1.. firstPos(26, -1); + vector lastPos(26, -1); + int n = s.size(); + for (int i = 0; i < n; i++) { + int idx = s[i] - 'a'; + if (firstPos[idx] == -1) firstPos[idx] = i; + } + for (int i = n - 1; i >= 0; i--) { + int idx = s[i] - 'a'; + if (lastPos[idx] == -1) lastPos[idx] = i; + } + int maxLen = -1; + for (int i = 0; i < 26; i++) { + if (firstPos[i] != -1 && lastPos[i] != -1) { + maxLen = max(maxLen, lastPos[i] - firstPos[i] - 1); + } + } + return maxLen; + } +}; diff --git a/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.cs b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.cs new file mode 100644 index 00000000..3e6401cf --- /dev/null +++ b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.cs @@ -0,0 +1,26 @@ +public class Solution { + public int MaxLengthBetweenEqualCharacters(string s) { + int[] firstPos = new int[26]; + int[] lastPos = new int[26]; + for (int i = 0; i < 26; i++) { + firstPos[i] = -1; + lastPos[i] = -1; + } + int n = s.Length; + for (int i = 0; i < n; i++) { + int idx = s[i] - 'a'; + if (firstPos[idx] == -1) firstPos[idx] = i; + } + for (int i = n - 1; i >= 0; i--) { + int idx = s[i] - 'a'; + if (lastPos[idx] == -1) lastPos[idx] = i; + } + int maxLen = -1; + for (int i = 0; i < 26; i++) { + if (firstPos[i] != -1 && lastPos[i] != -1) { + maxLen = Math.Max(maxLen, lastPos[i] - firstPos[i] - 1); + } + } + return maxLen; + } +} diff --git a/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.dart b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.dart new file mode 100644 index 00000000..3ad40238 --- /dev/null +++ b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.dart @@ -0,0 +1,23 @@ +class Solution { + int maxLengthBetweenEqualCharacters(String s) { + List firstPos = List.filled(26, -1); + List lastPos = List.filled(26, -1); + int n = s.length; + for (int i = 0; i < n; i++) { + int idx = s.codeUnitAt(i) - 'a'.codeUnitAt(0); + if (firstPos[idx] == -1) firstPos[idx] = i; + } + for (int i = n - 1; i >= 0; i--) { + int idx = s.codeUnitAt(i) - 'a'.codeUnitAt(0); + if (lastPos[idx] == -1) lastPos[idx] = i; + } + int maxLen = -1; + for (int i = 0; i < 26; i++) { + if (firstPos[i] != -1 && lastPos[i] != -1) { + int diff = lastPos[i] - firstPos[i] - 1; + if (diff > maxLen) maxLen = diff; + } + } + return maxLen; + } +} diff --git a/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.go b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.go new file mode 100644 index 00000000..d9266f0e --- /dev/null +++ b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.go @@ -0,0 +1,31 @@ +func maxLengthBetweenEqualCharacters(s string) int { + firstPos := make([]int, 26) + lastPos := make([]int, 26) + for i := range firstPos { + firstPos[i] = -1 + lastPos[i] = -1 + } + n := len(s) + for i := 0; i < n; i++ { + idx := int(s[i] - 'a') + if firstPos[idx] == -1 { + firstPos[idx] = i + } + } + for i := n - 1; i >= 0; i-- { + idx := int(s[i] - 'a') + if lastPos[idx] == -1 { + lastPos[idx] = i + } + } + maxLen := -1 + for i := 0; i < 26; i++ { + if firstPos[i] != -1 && lastPos[i] != -1 { + diff := lastPos[i] - firstPos[i] - 1 + if diff > maxLen { + maxLen = diff + } + } + } + return maxLen +} diff --git a/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.java b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.java new file mode 100644 index 00000000..b35bc442 --- /dev/null +++ b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.java @@ -0,0 +1,24 @@ +class Solution { + public int maxLengthBetweenEqualCharacters(String s) { + int[] firstPos = new int[26]; + int[] lastPos = new int[26]; + java.util.Arrays.fill(firstPos, -1); + java.util.Arrays.fill(lastPos, -1); + int n = s.length(); + for (int i = 0; i < n; i++) { + int idx = s.charAt(i) - 'a'; + if (firstPos[idx] == -1) firstPos[idx] = i; + } + for (int i = n - 1; i >= 0; i--) { + int idx = s.charAt(i) - 'a'; + if (lastPos[idx] == -1) lastPos[idx] = i; + } + int maxLen = -1; + for (int i = 0; i < 26; i++) { + if (firstPos[i] != -1 && lastPos[i] != -1) { + maxLen = Math.max(maxLen, lastPos[i] - firstPos[i] - 1); + } + } + return maxLen; + } +} diff --git a/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.kt b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.kt new file mode 100644 index 00000000..80c1f364 --- /dev/null +++ b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.kt @@ -0,0 +1,22 @@ +class Solution { + fun maxLengthBetweenEqualCharacters(s: String): Int { + val firstPos = IntArray(26) { -1 } + val lastPos = IntArray(26) { -1 } + val n = s.length + for (i in 0 until n) { + val idx = s[i] - 'a' + if (firstPos[idx] == -1) firstPos[idx] = i + } + for (i in n - 1 downTo 0) { + val idx = s[i] - 'a' + if (lastPos[idx] == -1) lastPos[idx] = i + } + var maxLen = -1 + for (i in 0 until 26) { + if (firstPos[i] != -1 && lastPos[i] != -1) { + maxLen = maxOf(maxLen, lastPos[i] - firstPos[i] - 1) + } + } + return maxLen + } +} diff --git a/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.py b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.py new file mode 100644 index 00000000..704f3a80 --- /dev/null +++ b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.py @@ -0,0 +1,22 @@ +class Solution: + def maxLengthBetweenEqualCharacters(self, s): + firstPos = [-1] * 26 + lastPos = [-1] * 26 + n = len(s) + for i in range(n): + idx = ord(s[i]) - ord("a") + if firstPos[idx] == -1: + firstPos[idx] = i + for i in range(n - 1, -1, -1): + idx = ord(s[i]) - ord("a") + if lastPos[idx] == -1: + lastPos[idx] = i + maxLenSubStr = -1 + for i in range(26): + if firstPos[i] != -1 and lastPos[i] != -1: + maxLenSubStr = max(maxLenSubStr, lastPos[i] - firstPos[i] - 1) + return maxLenSubStr + + +# Example +print(Solution().maxLengthBetweenEqualCharacters("abca")) # Output: 2 diff --git a/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.py2 b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.py2 new file mode 100644 index 00000000..44039c57 --- /dev/null +++ b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def maxLengthBetweenEqualCharacters(self, s): + """ + :type s: str + :rtype: int + """ + firstPos = [-1] * 26 + lastPos = [-1] * 26 + n = len(s) + for i in range(n): + idx = ord(s[i]) - ord('a') + if firstPos[idx] == -1: + firstPos[idx] = i + for i in range(n - 1, -1, -1): + idx = ord(s[i]) - ord('a') + if lastPos[idx] == -1: + lastPos[idx] = i + maxLenSubStr = -1 + for i in range(26): + if firstPos[i] != -1 and lastPos[i] != -1: + maxLenSubStr = max(maxLenSubStr, lastPos[i] - firstPos[i] - 1) + return maxLenSubStr diff --git a/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.rb b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.rb new file mode 100644 index 00000000..7799b2bd --- /dev/null +++ b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.rb @@ -0,0 +1,20 @@ +def max_length_between_equal_characters(s) + first_pos = Array.new(26, -1) + last_pos = Array.new(26, -1) + n = s.length + (0...n).each do |i| + idx = s[i].ord - 'a'.ord + first_pos[idx] = i if first_pos[idx] == -1 + end + (n-1).downto(0) do |i| + idx = s[i].ord - 'a'.ord + last_pos[idx] = i if last_pos[idx] == -1 + end + max_len = -1 + (0...26).each do |i| + if first_pos[i] != -1 && last_pos[i] != -1 + max_len = [max_len, last_pos[i] - first_pos[i] - 1].max + end + end + max_len +end diff --git a/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.rs b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.rs new file mode 100644 index 00000000..558556d6 --- /dev/null +++ b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.rs @@ -0,0 +1,27 @@ +impl Solution { + pub fn max_length_between_equal_characters(s: String) -> i32 { + let mut first_pos = vec![-1; 26]; + let mut last_pos = vec![-1; 26]; + let bytes = s.as_bytes(); + let base = b'a'; + for (i, &b) in bytes.iter().enumerate() { + let idx = (b - base) as usize; + if first_pos[idx] == -1 { + first_pos[idx] = i as i32; + } + } + for i in (0..bytes.len()).rev() { + let idx = (bytes[i] - base) as usize; + if last_pos[idx] == -1 { + last_pos[idx] = i as i32; + } + } + let mut max_len = -1; + for i in 0..26 { + if first_pos[i] != -1 && last_pos[i] != -1 { + max_len = max_len.max(last_pos[i] - first_pos[i] - 1); + } + } + max_len + } +} diff --git a/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.swift b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.swift new file mode 100644 index 00000000..02aee798 --- /dev/null +++ b/tests/1501-2000/1624. largest-substring-between-two-equal-characters/sol.swift @@ -0,0 +1,24 @@ +class Solution { + func maxLengthBetweenEqualCharacters(_ s: String) -> Int { + var firstPos = [Int](repeating: -1, count: 26) + var lastPos = [Int](repeating: -1, count: 26) + let arr = Array(s) + let n = arr.count + let a = Int(Character("a").asciiValue!) + for i in 0..= 0; i--) { + const idx = s.charCodeAt(i) - base; + if (lastPos[idx] === -1) lastPos[idx] = i; + } + let maxLen = -1; + for (let i = 0; i < 26; i++) { + if (firstPos[i] !== -1 && lastPos[i] !== -1) { + maxLen = Math.max(maxLen, lastPos[i] - firstPos[i] - 1); + } + } + return maxLen; +} diff --git a/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/manifest.yaml b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/manifest.yaml new file mode 100644 index 00000000..b0c0e29d --- /dev/null +++ b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/manifest.yaml @@ -0,0 +1,309 @@ +entry: + id: 1625 + title: "lexicographically-smallest-string-after-applying-operations" + params: + s: + type: string + a: + type: int + b: + type: int + call: + cpp: "Solution().findLexSmallestString({s}, {a}, {b})" + rust: "Solution::find_lex_smallest_string({s}, {a}, {b})" + python3: "Solution().findLexSmallestString({s}, {a}, {b})" + python2: "Solution().findLexSmallestString({s}, {a}, {b})" + ruby: "find_lex_smallest_string({s}, {a}, {b})" + java: "new Solution().findLexSmallestString({s}, {a}, {b})" + csharp: "new Solution().FindLexSmallestString({s}, {a}, {b})" + kotlin: "Solution().findLexSmallestString({s}, {a}, {b})" + go: "findLexSmallestString({s}, {a}, {b})" + dart: "Solution().findLexSmallestString({s}, {a}, {b})" + swift: "Solution().findLexSmallestString({s}, {a}, {b})" + typescript: "findLexSmallestString({s}, {a}, {b})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().findLexSmallestString(s, a, b, {result})" + checker: | + from collections import deque + + class Checker: + def findLexSmallestString(self, s, a, b, result): + if not isinstance(result, str) or len(result) != len(s): + return False + if any(ch < '0' or ch > '9' for ch in result): + return False + n = len(s) + seen = {s} + queue = deque([s]) + while queue: + cur = queue.popleft() + chars = list(cur) + for i in range(1, n, 2): + chars[i] = str((ord(chars[i]) - 48 + a) % 10) + nxt = ''.join(chars) + if nxt not in seen: + seen.add(nxt) + queue.append(nxt) + nxt = cur[n - b:] + cur[:n - b] + if nxt not in seen: + seen.add(nxt) + queue.append(nxt) + return result == min(seen) + +seed: 1625 + +tests: + - name: example-1 + in: + s: "5525" + a: 9 + b: 2 + - name: example-2 + in: + s: "74" + a: 5 + b: 1 + - name: example-3 + in: + s: "0011" + a: 4 + b: 2 + - name: two-digits-no-change + in: + s: "98" + a: 9 + b: 1 + - name: two-digits-zero + in: + s: "00" + a: 1 + b: 1 + - name: two-digits-max + in: + s: "99" + a: 9 + b: 1 + - name: four-rotate-one + in: + s: "1234" + a: 1 + b: 1 + - name: four-rotate-three + in: + s: "9876" + a: 8 + b: 3 + - name: four-even-rotation + in: + s: "0009" + a: 1 + b: 2 + - name: four-add-cycle + in: + s: "0909" + a: 5 + b: 2 + - name: six-small + in: + s: "123456" + a: 2 + b: 1 + - name: six-large-add + in: + s: "987654" + a: 9 + b: 5 + - name: six-rotation-gcd + in: + s: "314159" + a: 3 + b: 3 + - name: six-odd-rotation + in: + s: "271828" + a: 7 + b: 5 + - name: eight-repeated + in: + s: "55555555" + a: 5 + b: 4 + - name: eight-alternating + in: + s: "01010101" + a: 9 + b: 3 + - name: eight-distinct + in: + s: "01234567" + a: 4 + b: 7 + - name: eight-high-digits + in: + s: "99887766" + a: 6 + b: 2 + - name: ten-palindrome + in: + s: "1234543210" + a: 1 + b: 5 + - name: ten-random + in: + s: "9081726354" + a: 8 + b: 3 + - name: ten-zero-heavy + in: + s: "1000000000" + a: 5 + b: 9 + - name: twelve-cycle + in: + s: "314159265358" + a: 2 + b: 6 + - name: twelve-rotation-one + in: + s: "987654321098" + a: 7 + b: 1 + - name: twelve-rotation-eleven + in: + s: "246813579135" + a: 9 + b: 11 + - name: fourteen-alternating + in: + s: "90909090909090" + a: 3 + b: 7 + - name: fourteen-random + in: + s: "27182818284590" + a: 4 + b: 5 + - name: sixteen-distinct + in: + s: "0123456789012345" + a: 5 + b: 8 + - name: sixteen-repeated-block + in: + s: "3141314131413141" + a: 6 + b: 15 + - name: eighteen-high + in: + s: "999999999999999999" + a: 1 + b: 9 + - name: twenty-mixed + in: + s: "90817263549081726354" + a: 8 + b: 7 + - name: twenty-two-periodic + in: + s: "1231231231231231231231" + a: 3 + b: 10 + - name: twenty-four-random + in: + s: "864209753186420975318642" + a: 7 + b: 11 + - name: thirty-two-long + in: + s: "98765432100123456789876543210012" + a: 9 + b: 13 + - name: forty-eight-long + in: + s: "31415926535897932384626433832795028841971693993751" + a: 2 + b: 17 + - name: hundred-boundary + in: + s: "0123456789" + a: 1 + b: 1 + - name: generated-medium + in: + s: + gen: "str" + len: 100 + alphabet: "0123456789" + a: + gen: "int" + min: 1 + max: 9 + b: + gen: "int" + min: 1 + max: 99 + - name: generated-medium-2 + in: + s: + gen: "str" + len: 100 + alphabet: "0123456789" + a: + gen: "int" + min: 1 + max: 9 + b: + gen: "int" + min: 1 + max: 99 + - name: generated-medium-3 + in: + s: + gen: "str" + len: 100 + alphabet: "0123456789" + a: + gen: "int" + min: 1 + max: 9 + b: + gen: "int" + min: 1 + max: 99 + - name: generated-medium-4 + in: + s: + gen: "str" + len: 100 + alphabet: "0123456789" + a: + gen: "int" + min: 1 + max: 9 + b: + gen: "int" + min: 1 + max: 99 + - name: generated-medium-5 + in: + s: + gen: "str" + len: 100 + alphabet: "0123456789" + a: + gen: "int" + min: 1 + max: 9 + b: + gen: "int" + min: 1 + max: 99 diff --git a/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.cpp b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.cpp new file mode 100644 index 00000000..00d9d1be --- /dev/null +++ b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + string findLexSmallestString(string s, int a, int b) { + int n = s.size(); + unordered_set seen; + function dfs = [&](string cur){ + if(seen.count(cur)) return; + seen.insert(cur); + string add = cur; + for(int i=1;i(); + void Dfs(string cur) { + if (seen.Contains(cur)) return; + seen.Add(cur); + char[] arr = cur.ToCharArray(); + for (int i = 1; i < n; i += 2) { + arr[i] = (char)('0' + (arr[i] - '0' + a) % 10); + } + Dfs(new string(arr)); + Dfs(cur.Substring(n - b) + cur.Substring(0, n - b)); + } + Dfs(s); + return seen.Min(); + } +} diff --git a/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.dart b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.dart new file mode 100644 index 00000000..cd20c427 --- /dev/null +++ b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.dart @@ -0,0 +1,18 @@ +class Solution { + String findLexSmallestString(String s, int a, int b) { + int n = s.length; + Set seen = {}; + void dfs(String cur) { + if (seen.contains(cur)) return; + seen.add(cur); + List add = cur.split(''); + for (int i = 1; i < n; i += 2) { + add[i] = ((int.parse(add[i]) + a) % 10).toString(); + } + dfs(add.join()); + dfs(cur.substring(n - b) + cur.substring(0, n - b)); + } + dfs(s); + return seen.reduce((a, b) => a.compareTo(b) <= 0 ? a : b); + } +} diff --git a/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.go b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.go new file mode 100644 index 00000000..6a1ba5be --- /dev/null +++ b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.go @@ -0,0 +1,23 @@ +func findLexSmallestString(s string, a int, b int) string { + n := len(s) + seen := make(map[string]bool) + var dfs func(string) + dfs = func(cur string) { + if seen[cur] { return } + seen[cur] = true + add := []byte(cur) + for i := 1; i < n; i += 2 { + add[i] = byte('0' + (int(add[i]-'0')+a)%10) + } + dfs(string(add)) + dfs(cur[n-b:] + cur[:n-b]) + } + dfs(s) + minStr := s + for str := range seen { + if str < minStr { + minStr = str + } + } + return minStr +} diff --git a/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.java b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.java new file mode 100644 index 00000000..a365c0fc --- /dev/null +++ b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.java @@ -0,0 +1,34 @@ +import java.util.*; + +class Solution { + public String findLexSmallestString(String s, int a, int b) { + int n = s.length(); + Set seen = new HashSet<>(); + ArrayDeque queue = new ArrayDeque<>(); + queue.add(s); + while (!queue.isEmpty()) { + String cur = queue.remove(); + if (seen.contains(cur)) continue; + seen.add(cur); + char[] arr = cur.toCharArray(); + for (int i = 1; i < arr.length; i += 2) { + arr[i] = (char)('0' + (arr[i] - '0' + a) % 10); + } + int len = cur.length(); + queue.add(new String(arr)); + queue.add(cur.substring(len-b) + cur.substring(0, len-b)); + } + return Collections.min(seen); + } + private void dfs(String s, int a, int b, Set seen) { + if (seen.contains(s)) return; + seen.add(s); + char[] arr = s.toCharArray(); + for (int i = 1; i < arr.length; i += 2) { + arr[i] = (char)('0' + (arr[i] - '0' + a) % 10); + } + dfs(new String(arr), a, b, seen); + int n = s.length(); + dfs(s.substring(n-b) + s.substring(0, n-b), a, b, seen); + } +} diff --git a/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.kt b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.kt new file mode 100644 index 00000000..6e32e961 --- /dev/null +++ b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.kt @@ -0,0 +1,19 @@ +class Solution { + fun findLexSmallestString(s: String, a: Int, b: Int): String { + val n = s.length + val seen = mutableSetOf() + val queue = java.util.ArrayDeque() + queue.add(s) + while (queue.isNotEmpty()) { + val cur = queue.removeFirst() + if (!seen.add(cur)) continue + val add = cur.toCharArray() + for (i in 1 until n step 2) { + add[i] = '0' + (add[i] - '0' + a) % 10 + } + queue.add(String(add)) + queue.add(cur.substring(n - b) + cur.substring(0, n - b)) + } + return seen.min()!! + } +} diff --git a/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.py b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.py new file mode 100644 index 00000000..5d62038b --- /dev/null +++ b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.py @@ -0,0 +1,29 @@ +class Solution: + def findLexSmallestString(self, s: str, a: int, b: int) -> str: + n = len(s) + # this map holds the new value of every digit after addition by a % 10 + incremented = {str(n): str((n + a) % 10) for n in range(10)} + + # function applying the addition operation + def addOp(s): + res = "" + for i in range(n): + res += s[i] if i % 2 == 0 else incremented[s[i]] + return res + + # function applying the rotation operation + def rotOp(s): + return s[n - b :] + s[: n - b] + + seen = set() + + def dfs(s): + if s in seen: + return + seen.add(s) + dfs(addOp(s)) + dfs(rotOp(s)) + return + + dfs(s) + return min(seen) diff --git a/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.py2 b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.py2 new file mode 100644 index 00000000..657bd8e1 --- /dev/null +++ b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def findLexSmallestString(self, s, a, b): + """ + :type s: str + :type a: int + :type b: int + :rtype: str + """ + n = len(s) + seen = set() + def dfs(cur): + if cur in seen: + return + seen.add(cur) + add = list(cur) + for i in range(1, n, 2): + add[i] = str((int(add[i]) + a) % 10) + dfs(''.join(add)) + dfs(cur[n-b:] + cur[:n-b]) + dfs(s) + return min(seen) diff --git a/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.rb b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.rb new file mode 100644 index 00000000..666d77c1 --- /dev/null +++ b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.rb @@ -0,0 +1,16 @@ +def find_lex_smallest_string(s, a, b) + n = s.length + seen = Set.new + dfs = lambda do |cur| + return if seen.include?(cur) + seen.add(cur) + add = cur.dup + (1...n).step(2) do |i| + add[i] = ((add[i].to_i + a) % 10).to_s + end + dfs.call(add) + dfs.call(cur[n-b..] + cur[0...n-b]) + end + dfs.call(s) + seen.min +end diff --git a/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.rs b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.rs new file mode 100644 index 00000000..f17ee356 --- /dev/null +++ b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.rs @@ -0,0 +1,28 @@ +use std::collections::HashSet; + +impl Solution { + pub fn find_lex_smallest_string(s: String, a: i32, b: i32) -> String { + let n = s.len(); + let mut seen = HashSet::new(); + let mut s = s; + fn dfs(s: &mut String, a: i32, b: i32, seen: &mut HashSet) { + if seen.contains(s) { return; } + seen.insert(s.clone()); + let mut add = s.clone(); + let bytes = unsafe { add.as_bytes_mut() }; + for i in (1..bytes.len()).step_by(2) { + bytes[i] = ((bytes[i] - b'0' + a as u8) % 10 + b'0') as u8; + } + dfs(&mut add, a, b, seen); + let len = s.len(); + let rot = format!("{}{}", &s[len-b as usize..], &s[..len-b as usize]); + dfs(&mut rot.clone(), a, b, seen); + } + dfs(&mut s, a, b, &mut seen); + let mut min_str = s.clone(); + for st in &seen { + if st < &min_str { min_str = st.clone(); } + } + min_str + } +} diff --git a/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.swift b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.swift new file mode 100644 index 00000000..031c3136 --- /dev/null +++ b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.swift @@ -0,0 +1,22 @@ +class Solution { + func findLexSmallestString(_ s: String, _ a: Int, _ b: Int) -> String { + let n = s.count + var seen = Set() + var queue = [s] + while !queue.isEmpty { + let cur = queue.removeFirst() + if seen.contains(cur) { continue } + seen.insert(cur) + var arr = Array(cur) + var i = 1 + while i < arr.count { + arr[i] = Character(String((Int(String(arr[i]))! + a) % 10)) + i += 2 + } + queue.append(String(arr)) + let rot = String(cur.suffix(n - b)) + String(cur.prefix(b)) + queue.append(rot) + } + return seen.min()! + } +} diff --git a/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.ts b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.ts new file mode 100644 index 00000000..77526b22 --- /dev/null +++ b/tests/1501-2000/1625. lexicographically-smallest-string-after-applying-operations/sol.ts @@ -0,0 +1,16 @@ +function findLexSmallestString(s: string, a: number, b: number): string { + const n = s.length; + const seen = new Set(); + const dfs = (cur: string) => { + if (seen.has(cur)) return; + seen.add(cur); + const add = cur.split(""); + for (let i = 1; i < n; i += 2) { + add[i] = String((Number(add[i]) + a) % 10); + } + dfs(add.join("")); + dfs(cur.slice(n - b) + cur.slice(0, n - b)); + }; + dfs(s); + return Array.from(seen).sort()[0]; +} diff --git a/tests/1501-2000/1626. best-team-with-no-conflicts/manifest.yaml b/tests/1501-2000/1626. best-team-with-no-conflicts/manifest.yaml new file mode 100644 index 00000000..8933a6ab --- /dev/null +++ b/tests/1501-2000/1626. best-team-with-no-conflicts/manifest.yaml @@ -0,0 +1,331 @@ +entry: + id: 1626 + title: best-team-with-no-conflicts + params: + scores: + type: array + items: + type: int + ages: + type: array + items: + type: int + call: + cpp: "Solution().bestTeamScore({scores}, {ages})" + rust: "Solution::best_team_score({scores}, {ages})" + python3: "Solution().bestTeamScore({scores}, {ages})" + python2: "Solution().bestTeamScore({scores}, {ages})" + ruby: "best_team_score({scores}, {ages})" + java: "new Solution().bestTeamScore({scores}, {ages})" + csharp: "new Solution().BestTeamScore({scores}, {ages})" + kotlin: "Solution().bestTeamScore({scores}, {ages})" + go: "bestTeamScore({scores}, {ages})" + dart: "Solution().bestTeamScore({scores}, {ages})" + swift: "Solution().bestTeamScore({scores}, {ages})" + typescript: "bestTeamScore({scores}, {ages})" + +judge: + type: "exact" + +limits: + time_ms: 5000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().bestTeamScore(scores, ages, {result})" + checker: | + class Checker: + def bestTeamScore(self, scores, ages, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if len(scores) != len(ages) or not scores: + return False + order = sorted(zip(ages, scores)) + dp = [] + for _, score in order: + dp.append(score) + for i in range(len(order)): + for j in range(i): + if order[j][1] <= order[i][1]: + dp[i] = max(dp[i], dp[j] + order[i][1]) + return result == max(dp) + +seed: 1626 + +tests: + - name: example-increasing + in: + scores: [1, 3, 5, 10, 15] + ages: [1, 2, 3, 4, 5] + out: 34 + - name: example-same-age + in: + scores: [4, 5, 6, 5] + ages: [2, 1, 2, 1] + out: 16 + - name: example-conflict + in: + scores: [1, 2, 3, 5] + ages: [8, 9, 10, 1] + out: 6 + - name: one-player + in: + scores: [7] + ages: [3] + out: 7 + - name: all-equal + in: + scores: [5, 5, 5, 5] + ages: [1, 2, 3, 4] + out: 20 + - name: equal-ages + in: + scores: [2, 9, 4, 7] + ages: [6, 6, 6, 6] + out: 22 + - name: descending-scores-ascending-ages + in: + scores: [10, 9, 8, 7] + ages: [1, 2, 3, 4] + out: 10 + - name: ascending-scores-descending-ages + in: + scores: [2, 4, 6, 8] + ages: [4, 3, 2, 1] + out: 8 + - name: duplicate-ages-and-scores + in: + scores: [1, 2, 2, 3, 3] + ages: [2, 1, 2, 1, 2] + out: 8 + - name: alternating + in: + scores: [5, 1, 6, 2, 7, 3] + ages: [1, 2, 3, 4, 5, 6] + out: 18 + - name: older-high-score + in: + scores: [100, 1, 2, 3] + ages: [10, 1, 2, 3] + out: 106 + - name: tie-score-chain + in: + scores: [8, 8, 8, 1] + ages: [3, 1, 2, 4] + out: 24 + - name: two-conflicting + in: + scores: [5, 6] + ages: [2, 1] + out: 6 + - name: two-compatible + in: + scores: [5, 6] + ages: [1, 2] + out: 11 + - name: middle-best-chain + in: + scores: [4, 10, 5, 6] + ages: [1, 2, 3, 4] + out: 15 + - name: low-score-blocker + in: + scores: [9, 1, 8, 7, 6] + ages: [1, 2, 3, 4, 5] + out: 9 + - name: repeated-age-groups + in: + scores: [4, 6, 5, 7, 3, 8] + ages: [1, 1, 2, 2, 3, 3] + out: 25 + - name: large-score-values + in: + scores: [1000000, 999999, 1000000] + ages: [1, 2, 3] + out: 2000000 + - name: all-max-values + in: + scores: [1000000, 1000000, 1000000, 1000000] + ages: [1000, 1, 500, 1000] + out: 4000000 + - name: age-boundaries + in: + scores: [3, 4, 5, 6] + ages: [1, 1000, 1, 1000] + out: 14 + - name: many-equal-ages + in: + scores: [3, 9, 1, 8, 2, 7, 4] + ages: [5, 5, 5, 5, 5, 5, 5] + out: 34 + - name: zigzag-ages + in: + scores: [3, 8, 4, 9, 5, 10] + ages: [1, 6, 2, 5, 3, 4] + out: 22 + - name: zigzag-scores + in: + scores: [9, 2, 8, 3, 7, 4] + ages: [1, 2, 3, 4, 5, 6] + out: 12 + - name: nested-optimum + in: + scores: [5, 100, 6, 7, 8, 9] + ages: [1, 2, 3, 4, 5, 6] + out: 105 + - name: choose-two-after-conflict + in: + scores: [20, 1, 19, 18, 17] + ages: [1, 2, 3, 4, 5] + out: 20 + - name: repeated-pattern + in: + scores: [2, 5, 2, 5, 2, 5, 2, 5] + ages: [1, 2, 3, 4, 5, 6, 7, 8] + out: 22 + - name: broad-age-ties + in: + scores: [12, 3, 9, 4, 10, 5] + ages: [2, 2, 4, 4, 6, 6] + out: 26 + - name: minimum-scores + in: + scores: [1, 1, 1, 1, 1] + ages: [1, 1000, 500, 2, 999] + out: 5 + - name: high-low-high + in: + scores: [50, 2, 49, 3, 48] + ages: [1, 2, 3, 4, 5] + out: 53 + - name: compatible-blocks + in: + scores: [4, 4, 6, 6, 8, 8] + ages: [1, 1, 2, 2, 3, 3] + out: 36 + - name: age-sort-reorders + in: + scores: [10, 20, 30, 40] + ages: [4, 1, 3, 2] + out: 60 + - name: mixed-plateaus + in: + scores: [6, 6, 2, 9, 9, 4, 10] + ages: [1, 2, 3, 4, 5, 6, 7] + out: 40 + - name: nontrivial-subsequence + in: + scores: [4, 9, 5, 6, 10, 7, 8] + ages: [3, 1, 4, 2, 5, 6, 7] + out: 24 + - name: seven-player-ties + in: + scores: [3, 8, 8, 2, 9, 9, 4] + ages: [1, 2, 2, 3, 3, 4, 4] + out: 37 + - name: near-limit-static + in: + scores: [1000000, 1, 999998, 2, 999997, 3, 999996, 4] + ages: [1, 2, 3, 4, 5, 6, 7, 8] + out: 1000002 + - name: generated-small + in: + scores: + gen: "array" + len: 20 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + elemType: "int" + ages: + gen: "array" + len: 20 + of: + gen: "int" + min: 1 + max: 20 + distinct: false + elemType: "int" + - name: generated-medium + in: + scores: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + elemType: "int" + ages: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + elemType: "int" + - name: generated-large + in: + scores: + gen: "array" + len: 500 + of: + gen: "int" + min: 1 + max: 1000000 + distinct: false + elemType: "int" + ages: + gen: "array" + len: 500 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + elemType: "int" + - name: generated-near-limit + in: + scores: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000000 + distinct: false + elemType: "int" + ages: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + elemType: "int" + - name: generated-small-values + in: + scores: + gen: "array" + len: 250 + of: + gen: "int" + min: 1 + max: 10 + distinct: false + elemType: "int" + ages: + gen: "array" + len: 250 + of: + gen: "int" + min: 1 + max: 10 + distinct: false + elemType: "int" diff --git a/tests/1501-2000/1626. best-team-with-no-conflicts/sol.cpp b/tests/1501-2000/1626. best-team-with-no-conflicts/sol.cpp new file mode 100644 index 00000000..0db0f15f --- /dev/null +++ b/tests/1501-2000/1626. best-team-with-no-conflicts/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int bestTeamScore(vector& scores, vector& ages) { + vector> players; + for(int i=0; i dp(scores.size()); + for(int i=0; i a.age != b.age ? a.age.CompareTo(b.age) : a.score.CompareTo(b.score)); + int[] dp = new int[n]; + for (int i=0; i scores, List ages) { + int n = scores.length; + List> players = List.generate(n, (i) => [ages[i], scores[i]]); + players.sort((a,b) => a[0] != b[0] ? a[0].compareTo(b[0]) : a[1].compareTo(b[1])); + List dp = List.generate(n, (i) => players[i][1]); + for (int i=0; i dp[j]+players[i][1] ? dp[i] : dp[j]+players[i][1]; + } + } + } + return dp.reduce((a,b) => a>b ? a : b); + } +} diff --git a/tests/1501-2000/1626. best-team-with-no-conflicts/sol.go b/tests/1501-2000/1626. best-team-with-no-conflicts/sol.go new file mode 100644 index 00000000..5214e46e --- /dev/null +++ b/tests/1501-2000/1626. best-team-with-no-conflicts/sol.go @@ -0,0 +1,35 @@ +import sortpkg "sort" + +func bestTeamScore(scores []int, ages []int) int { + n := len(scores) + players := make([][2]int, n) + for i := 0; i < n; i++ { + players[i] = [2]int{ages[i], scores[i]} + } + sortpkg.Slice(players, func(i, j int) bool { + if players[i][0] != players[j][0] { + return players[i][0] < players[j][0] + } + return players[i][1] < players[j][1] + }) + dp := make([]int, n) + for i := 0; i < n; i++ { + dp[i] = players[i][1] + } + for i := 0; i < n; i++ { + for j := 0; j < i; j++ { + if players[j][1] <= players[i][1] { + if dp[j]+players[i][1] > dp[i] { + dp[i] = dp[j] + players[i][1] + } + } + } + } + ans := 0 + for _, v := range dp { + if v > ans { + ans = v + } + } + return ans +} diff --git a/tests/1501-2000/1626. best-team-with-no-conflicts/sol.java b/tests/1501-2000/1626. best-team-with-no-conflicts/sol.java new file mode 100644 index 00000000..070e6404 --- /dev/null +++ b/tests/1501-2000/1626. best-team-with-no-conflicts/sol.java @@ -0,0 +1,25 @@ +import java.util.*; + +class Solution { + public int bestTeamScore(int[] scores, int[] ages) { + int n = scores.length; + int[][] players = new int[n][2]; + for(int i=0; i a[0] != b[0] ? a[0]-b[0] : a[1]-b[1]); + int[] dp = new int[n]; + for(int i=0; i { it[0] }.thenBy { it[1] }) + val dp = IntArray(n) + for (i in 0 until n) dp[i] = players[i][1] + for (i in 0 until n) { + for (j in 0 until i) { + if (players[j][1] <= players[i][1]) { + dp[i] = maxOf(dp[i], dp[j] + players[i][1]) + } + } + } + return dp.max()!! + } +} diff --git a/tests/1501-2000/1626. best-team-with-no-conflicts/sol.py b/tests/1501-2000/1626. best-team-with-no-conflicts/sol.py new file mode 100644 index 00000000..0005a777 --- /dev/null +++ b/tests/1501-2000/1626. best-team-with-no-conflicts/sol.py @@ -0,0 +1,9 @@ +class Solution: + def bestTeamScore(self, scores: List[int], ages: List[int]) -> int: + players = sorted(zip(ages, scores)) + dp = [score for _, score in players] + for i in range(len(players)): + for j in range(i): + if players[j][1] <= players[i][1]: + dp[i] = max(dp[i], dp[j] + players[i][1]) + return max(dp) diff --git a/tests/1501-2000/1626. best-team-with-no-conflicts/sol.py2 b/tests/1501-2000/1626. best-team-with-no-conflicts/sol.py2 new file mode 100644 index 00000000..2ce25b66 --- /dev/null +++ b/tests/1501-2000/1626. best-team-with-no-conflicts/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def bestTeamScore(self, scores, ages): + """ + :type scores: List[int] + :type ages: List[int] + :rtype: int + """ + players = sorted(zip(ages, scores)) + dp = [score for _, score in players] + for i in range(len(players)): + for j in range(i): + if players[j][1] <= players[i][1]: + dp[i] = max(dp[i], dp[j] + players[i][1]) + return max(dp) diff --git a/tests/1501-2000/1626. best-team-with-no-conflicts/sol.rb b/tests/1501-2000/1626. best-team-with-no-conflicts/sol.rb new file mode 100644 index 00000000..353aabbe --- /dev/null +++ b/tests/1501-2000/1626. best-team-with-no-conflicts/sol.rb @@ -0,0 +1,15 @@ +# @param {Integer[]} scores +# @param {Integer[]} ages +# @return {Integer} +def best_team_score(scores, ages) + players = ages.zip(scores).sort + dp = players.map(&:last) + (0...players.length).each do |i| + (0...i).each do |j| + if players[j][1] <= players[i][1] + dp[i] = [dp[i], dp[j] + players[i][1]].max + end + end + end + dp.max +end diff --git a/tests/1501-2000/1626. best-team-with-no-conflicts/sol.rs b/tests/1501-2000/1626. best-team-with-no-conflicts/sol.rs new file mode 100644 index 00000000..d941d469 --- /dev/null +++ b/tests/1501-2000/1626. best-team-with-no-conflicts/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn best_team_score(scores: Vec, ages: Vec) -> i32 { + let mut players: Vec<(i32,i32)> = ages.iter().zip(scores.iter()).map(|(&a,&s)| (a,s)).collect(); + players.sort(); + let mut dp = players.iter().map(|&(_,s)| s).collect::>(); + for i in 0..players.len() { + for j in 0..i { + if players[j].1 <= players[i].1 { + dp[i] = dp[i].max(dp[j] + players[i].1); + } + } + } + *dp.iter().max().unwrap() + } +} diff --git a/tests/1501-2000/1626. best-team-with-no-conflicts/sol.swift b/tests/1501-2000/1626. best-team-with-no-conflicts/sol.swift new file mode 100644 index 00000000..771daffe --- /dev/null +++ b/tests/1501-2000/1626. best-team-with-no-conflicts/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func bestTeamScore(_ scores: [Int], _ ages: [Int]) -> Int { + let n = scores.count + var players = Array(zip(ages, scores)).sorted { $0.0 != $1.0 ? $0.0 < $1.0 : $0.1 < $1.1 } + var dp = players.map { $0.1 } + for i in 0.. [ages[i], s]); + players.sort((a, b) => (a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1])); + const dp = players.map((p) => p[1]); + for (let i = 0; i < n; i++) { + for (let j = 0; j < i; j++) { + if (players[j][1] <= players[i][1]) { + dp[i] = Math.max(dp[i], dp[j] + players[i][1]); + } + } + } + return Math.max(...dp); +} diff --git a/tests/1501-2000/1627. graph-connectivity-with-threshold/manifest.yaml b/tests/1501-2000/1627. graph-connectivity-with-threshold/manifest.yaml new file mode 100644 index 00000000..fc975a4c --- /dev/null +++ b/tests/1501-2000/1627. graph-connectivity-with-threshold/manifest.yaml @@ -0,0 +1,451 @@ +entry: + id: 1627 + title: "graph-connectivity-with-threshold" + params: + n: + type: int + threshold: + type: int + queries: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().areConnected({n}, {threshold}, {queries})" + rust: "Solution::are_connected({n}, {threshold}, {queries})" + python3: "Solution().areConnected({n}, {threshold}, {queries})" + python2: "Solution().areConnected({n}, {threshold}, {queries})" + ruby: "are_connected({n}, {threshold}, {queries})" + java: "new Solution().areConnected({n}, {threshold}, {queries})" + csharp: "new Solution().AreConnected({n}, {threshold}, {queries})" + kotlin: "Solution().areConnected({n}, {threshold}, {queries})" + go: "areConnected({n}, {threshold}, {queries})" + dart: "Solution().areConnected({n}, {threshold}, {queries})" + swift: "Solution().areConnected({n}, {threshold}, {queries})" + typescript: "areConnected({n}, {threshold}, {queries})" +judge: + type: "exact" +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().areConnected(n, threshold, queries, {result})" + checker: | + class Checker: + def areConnected(self, n, threshold, queries, result): + if not isinstance(result, list) or len(result) != len(queries): + return False + parent = list(range(n + 1)) + size = [1] * (n + 1) + def find(x): + while parent[x] != x: + parent[x] = parent[parent[x]] + x = parent[x] + return x + def union(a, b): + a, b = find(a), find(b) + if a == b: + return + if size[a] < size[b]: + a, b = b, a + parent[b] = a + size[a] += size[b] + for z in range(threshold + 1, n + 1): + for multiple in range(2 * z, n + 1, z): + union(z, multiple) + return all(bool(value) == (find(a) == find(b)) for value, (a, b) in zip(result, queries)) +seed: 1627 +tests: + - name: example-one + in: + n: 6 + threshold: 2 + queries: + - [1, 4] + - [2, 5] + - [3, 6] + out: [false, false, true] + - name: example-two + in: + n: 6 + threshold: 0 + queries: + - [4, 5] + - [3, 4] + - [3, 2] + - [2, 6] + - [1, 3] + out: [true, true, true, true, true] + - name: example-three + in: + n: 5 + threshold: 1 + queries: + - [4, 5] + - [4, 5] + - [3, 2] + - [2, 3] + - [3, 4] + out: [false, false, false, false, false] + - name: threshold-at-n + in: + n: 5 + threshold: 5 + queries: + - [1, 2] + - [2, 3] + - [4, 5] + - [1, 5] + out: [false, false, false, false] + - name: threshold-n-minus-one + in: + n: 6 + threshold: 5 + queries: + - [5, 6] + - [1, 6] + - [2, 4] + out: [false, false, false] + - name: threshold-one + in: + n: 8 + threshold: 1 + queries: + - [2, 4] + - [2, 6] + - [4, 6] + - [3, 6] + - [5, 7] + - [1, 8] + out: [true, true, true, true, false, false] + - name: threshold-zero + in: + n: 4 + threshold: 0 + queries: + - [1, 2] + - [1, 4] + - [2, 3] + - [3, 4] + out: [true, true, true, true] + - name: prime-threshold + in: + n: 11 + threshold: 3 + queries: + - [4, 8] + - [5, 10] + - [6, 9] + - [7, 11] + - [8, 10] + out: [true, true, false, false, false] + - name: divisor-four-components + in: + n: 12 + threshold: 3 + queries: + - [4, 8] + - [4, 12] + - [6, 12] + - [5, 10] + - [8, 9] + - [3, 6] + out: [true, true, true, true, false, false] + - name: threshold-four + in: + n: 12 + threshold: 4 + queries: + - [5, 10] + - [6, 12] + - [7, 11] + - [8, 12] + - [9, 12] + out: [true, true, false, false, false] + - name: threshold-six + in: + n: 6 + threshold: 2 + queries: + - [1, 4] + - [2, 5] + - [3, 6] + out: [false, false, true] + - name: threshold-seven + in: + n: 16 + threshold: 7 + queries: + - [8, 14] + - [9, 15] + - [10, 15] + - [12, 16] + - [14, 16] + out: [false, false, false, false, false] + - name: threshold-ten + in: + n: 20 + threshold: 10 + queries: + - [11, 12] + - [12, 18] + - [14, 20] + - [15, 20] + - [16, 20] + out: [false, false, false, false, false] + - name: repeated-and-reversed + in: + n: 18 + threshold: 2 + queries: + - [3, 6] + - [6, 3] + - [6, 9] + - [9, 6] + - [4, 12] + - [12, 4] + out: [true, true, true, true, true, true] + - name: isolated-primes + in: + n: 20 + threshold: 10 + queries: + - [11, 13] + - [13, 17] + - [17, 19] + - [1, 11] + - [2, 12] + out: [false, false, false, false, false] + - name: connected-by-chain + in: + n: 30 + threshold: 1 + queries: + - [6, 10] + - [10, 15] + - [6, 15] + - [14, 21] + - [14, 25] + - [1, 30] + out: [true, true, true, true, true, false] + - name: threshold-two-chain + in: + n: 24 + threshold: 2 + queries: + - [6, 10] + - [10, 15] + - [6, 15] + - [8, 12] + - [12, 18] + - [8, 18] + out: [true, true, true, true, true, true] + - name: threshold-three-chain + in: + n: 36 + threshold: 3 + queries: + - [8, 14] + - [16, 24] + - [8, 24] + - [10, 20] + - [20, 30] + - [10, 30] + out: [true, true, true, true, true, true] + - name: powers-of-two + in: + n: 32 + threshold: 1 + queries: + - [2, 4] + - [4, 8] + - [8, 14] + - [16, 32] + - [2, 32] + - [3, 6] + out: [true, true, true, true, true, true] + - name: high-threshold-multiples + in: + n: 50 + threshold: 20 + queries: + - [21, 42] + - [22, 44] + - [24, 48] + - [25, 50] + - [21, 44] + out: [true, true, true, true, false] + - name: threshold-half + in: + n: 40 + threshold: 20 + queries: + - [21, 40] + - [22, 33] + - [23, 39] + - [24, 36] + - [25, 35] + - [26, 39] + out: [false, false, false, false, false, false] + - name: small-n-two + in: + n: 3 + threshold: 0 + queries: + - [1, 2] + - [2, 3] + - [1, 3] + out: [true, true, true] + - name: small-n-max-threshold + in: + n: 3 + threshold: 3 + queries: + - [1, 2] + - [2, 3] + - [1, 3] + out: [false, false, false] + - name: threshold-equals-one + in: + n: 10 + threshold: 1 + queries: + - [2, 4] + - [3, 9] + - [4, 8] + - [5, 10] + - [6, 9] + - [7, 10] + out: [true, true, true, true, true, false] + - name: threshold-equals-two + in: + n: 10 + threshold: 2 + queries: + - [3, 6] + - [4, 8] + - [5, 10] + - [6, 9] + - [8, 10] + - [2, 4] + out: [true, true, true, true, false, false] + - name: threshold-equals-five + in: + n: 15 + threshold: 5 + queries: + - [6, 12] + - [7, 14] + - [8, 12] + - [9, 15] + - [10, 15] + - [12, 15] + out: [true, true, false, false, false, false] + - name: threshold-equals-eight + in: + n: 20 + threshold: 8 + queries: + - [9, 18] + - [10, 20] + - [12, 18] + - [14, 16] + - [16, 20] + out: [true, true, false, false, false] + - name: max-query-count-shape + in: + n: 30 + threshold: 14 + queries: + - [15, 30] + - [16, 24] + - [17, 30] + - [18, 27] + - [20, 30] + - [21, 28] + - [22, 24] + out: [true, false, false, false, false, false, false] + - name: divisor-five-components + in: + n: 25 + threshold: 4 + queries: + - [5, 10] + - [10, 15] + - [5, 15] + - [6, 12] + - [12, 18] + - [6, 18] + out: [true, true, true, true, true, true] + - name: large-small-threshold + in: + n: 100 + threshold: 0 + queries: + - [1, 100] + - [37, 89] + - [64, 99] + - [2, 97] + - [50, 75] + out: [true, true, true, true, true] + - name: large-high-threshold + in: + n: 100 + threshold: 50 + queries: + - [51, 100] + - [50, 100] + - [52, 99] + - [60, 90] + - [75, 100] + out: [false, false, false, false, false] + - name: n-one-hundred-threshold-one + in: + n: 100 + threshold: 1 + queries: + - [2, 98] + - [3, 99] + - [7, 91] + - [25, 75] + - [49, 98] + - [1, 100] + out: [true, true, true, true, true, false] + - name: n-one-hundred-threshold-ten + in: + n: 100 + threshold: 10 + queries: + - [11, 12] + - [12, 36] + - [14, 70] + - [15, 45] + - [16, 80] + - [21, 84] + out: [false, true, true, true, true, true] + - name: n-one-hundred-threshold-ninety + in: + n: 100 + threshold: 90 + queries: + - [91, 100] + - [92, 100] + - [95, 100] + - [99, 100] + - [90, 100] + out: [false, false, false, false, false] + - name: edge-multiples + in: + n: 60 + threshold: 19 + queries: + - [20, 40] + - [21, 42] + - [22, 44] + - [25, 50] + - [30, 60] + - [24, 48] + out: [true, true, true, true, true, true] diff --git a/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.cpp b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.cpp new file mode 100644 index 00000000..1d1298fe --- /dev/null +++ b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.cpp @@ -0,0 +1,50 @@ +class Solution { +public: + vector areConnected(int n, int threshold, vector>& queries) { + int limit = n; + for (auto& q : queries) { + limit = max(limit, max(q[0], q[1])); + } + vector parent(limit + 1); + vector rank(limit + 1); + for (int i = 0; i <= limit; i++) { + parent[i] = i; + rank[i] = 1; + } + + function find = [&](int x) -> int { + int res = x; + while (res != parent[res]) { + parent[res] = parent[parent[res]]; + res = parent[res]; + } + return res; + }; + + auto union_sets = [&](int a, int b) -> bool { + int p1 = find(a); + int p2 = find(b); + if (p1 == p2) return false; + if (rank[p1] > rank[p2]) { + parent[p2] = p1; + rank[p1] += rank[p2]; + } else { + parent[p1] = p2; + rank[p2] += rank[p1]; + } + return true; + }; + + for (int i = threshold + 1; i <= limit; i++) { + for (int j = 2 * i; j <= limit; j += i) { + union_sets(i, j); + } + } + + vector result; + for (auto& q : queries) { + result.push_back(find(q[0]) == find(q[1])); + } + return result; + } +}; diff --git a/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.cs b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.cs new file mode 100644 index 00000000..eba359b2 --- /dev/null +++ b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.cs @@ -0,0 +1,50 @@ +public class Solution { + public IList AreConnected(int n, int threshold, int[][] queries) { + int limit = n; + foreach (var q in queries) { + limit = Math.Max(limit, Math.Max(q[0], q[1])); + } + int[] parent = new int[limit + 1]; + int[] rank = new int[limit + 1]; + for (int i = 0; i <= limit; i++) { + parent[i] = i; + rank[i] = 1; + } + + Func find = null; + find = x => { + int res = x; + while (res != parent[res]) { + parent[res] = parent[parent[res]]; + res = parent[res]; + } + return res; + }; + + Func union = (a, b) => { + int p1 = find(a); + int p2 = find(b); + if (p1 == p2) return false; + if (rank[p1] > rank[p2]) { + parent[p2] = p1; + rank[p1] += rank[p2]; + } else { + parent[p1] = p2; + rank[p2] += rank[p1]; + } + return true; + }; + + for (int i = threshold + 1; i <= limit; i++) { + for (int j = 2 * i; j <= limit; j += i) { + union(i, j); + } + } + + var result = new List(); + foreach (var q in queries) { + result.Add(find(q[0]) == find(q[1])); + } + return result; + } +} diff --git a/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.dart b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.dart new file mode 100644 index 00000000..a138cd07 --- /dev/null +++ b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.dart @@ -0,0 +1,42 @@ +class Solution { + List areConnected(int n, int threshold, List> queries) { + int limit = n; + for (var q in queries) { + if (q[0] > limit) limit = q[0]; + if (q[1] > limit) limit = q[1]; + } + List parent = List.generate(limit + 1, (i) => i); + List rank = List.filled(limit + 1, 1); + + int find(int x) { + int res = x; + while (res != parent[res]) { + parent[res] = parent[parent[res]]; + res = parent[res]; + } + return res; + } + + bool union(int a, int b) { + int p1 = find(a); + int p2 = find(b); + if (p1 == p2) return false; + if (rank[p1] > rank[p2]) { + parent[p2] = p1; + rank[p1] += rank[p2]; + } else { + parent[p1] = p2; + rank[p2] += rank[p1]; + } + return true; + } + + for (int i = threshold + 1; i <= limit; i++) { + for (int j = 2 * i; j <= limit; j += i) { + union(i, j); + } + } + + return queries.map((q) => find(q[0]) == find(q[1])).toList(); + } +} diff --git a/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.go b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.go new file mode 100644 index 00000000..c66c95ad --- /dev/null +++ b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.go @@ -0,0 +1,54 @@ +func areConnected(n int, threshold int, queries [][]int) []bool { + limit := n + for _, q := range queries { + if q[0] > limit { + limit = q[0] + } + if q[1] > limit { + limit = q[1] + } + } + parent := make([]int, limit+1) + rank := make([]int, limit+1) + for i := 0; i <= limit; i++ { + parent[i] = i + rank[i] = 1 + } + + var find func(int) int + find = func(x int) int { + res := x + for res != parent[res] { + parent[res] = parent[parent[res]] + res = parent[res] + } + return res + } + + union := func(a, b int) bool { + p1, p2 := find(a), find(b) + if p1 == p2 { + return false + } + if rank[p1] > rank[p2] { + parent[p2] = p1 + rank[p1] += rank[p2] + } else { + parent[p1] = p2 + rank[p2] += rank[p1] + } + return true + } + + for i := threshold + 1; i <= limit; i++ { + for j := 2 * i; j <= limit; j += i { + union(i, j) + } + } + + result := make([]bool, len(queries)) + for idx, q := range queries { + result[idx] = find(q[0]) == find(q[1]) + } + return result +} diff --git a/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.java b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.java new file mode 100644 index 00000000..d54c2cad --- /dev/null +++ b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.java @@ -0,0 +1,51 @@ +class Solution { + private int[] parent; + private int[] rank; + + private int find(int x) { + int res = x; + while (res != parent[res]) { + parent[res] = parent[parent[res]]; + res = parent[res]; + } + return res; + } + + private void union(int a, int b) { + int p1 = find(a); + int p2 = find(b); + if (p1 == p2) return; + if (rank[p1] > rank[p2]) { + parent[p2] = p1; + rank[p1] += rank[p2]; + } else { + parent[p1] = p2; + rank[p2] += rank[p1]; + } + } + + public List areConnected(int n, int threshold, int[][] queries) { + int limit = n; + for (int[] q : queries) { + limit = Math.max(limit, Math.max(q[0], q[1])); + } + parent = new int[limit + 1]; + rank = new int[limit + 1]; + for (int i = 0; i <= limit; i++) { + parent[i] = i; + rank[i] = 1; + } + + for (int i = threshold + 1; i <= limit; i++) { + for (int j = 2 * i; j <= limit; j += i) { + union(i, j); + } + } + + List result = new ArrayList<>(); + for (int[] q : queries) { + result.add(find(q[0]) == find(q[1])); + } + return result; + } +} diff --git a/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.kt b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.kt new file mode 100644 index 00000000..06bb6b24 --- /dev/null +++ b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.kt @@ -0,0 +1,41 @@ +class Solution { + fun areConnected(n: Int, threshold: Int, queries: Array): List { + var limit = n + for (q in queries) { + limit = maxOf(limit, maxOf(q[0], q[1])) + } + val parent = IntArray(limit + 1) { it } + val rank = IntArray(limit + 1) { 1 } + + fun find(x: Int): Int { + var res = x + while (res != parent[res]) { + parent[res] = parent[parent[res]] + res = parent[res] + } + return res + } + + fun union(a: Int, b: Int): Boolean { + val p1 = find(a) + val p2 = find(b) + if (p1 == p2) return false + if (rank[p1] > rank[p2]) { + parent[p2] = p1 + rank[p1] += rank[p2] + } else { + parent[p1] = p2 + rank[p2] += rank[p1] + } + return true + } + + for (i in threshold + 1..limit) { + for (j in 2 * i..limit step i) { + union(i, j) + } + } + + return queries.map { find(it[0]) == find(it[1]) } + } +} diff --git a/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.py b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.py new file mode 100644 index 00000000..39cf243a --- /dev/null +++ b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.py @@ -0,0 +1,38 @@ +class Solution: + def areConnected( + self, n: int, threshold: int, queries: List[List[int]] + ) -> List[bool]: + limit = max([n] + [v for pair in queries for v in pair]) + parent = [i for i in range(limit + 1)] + rank = [1] * (limit + 1) + + def find(n): + res = n + while res != parent[res]: + parent[res] = parent[parent[res]] + res = parent[res] + return res + + def union(z, m): + p1, p2 = find(z), find(m) + + if p1 == p2: + return False + + if rank[p1] > rank[p2]: + parent[p2] = p1 + rank[p1] += rank[p2] + else: + parent[p1] = p2 + rank[p2] += rank[p1] + + return True + + for z in range(threshold + 1, limit + 1): + for m in range(2 * z, limit + 1, z): + union(z, m) + + ans = [] + for x, y in queries: + ans.append(find(x) == find(y)) + return ans diff --git a/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.py2 b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.py2 new file mode 100644 index 00000000..f67a1ae8 --- /dev/null +++ b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.py2 @@ -0,0 +1,39 @@ +class Solution(object): + def areConnected(self, n, threshold, queries): + """ + :type n: int + :type threshold: int + :type queries: List[List[int]] + :rtype: List[bool] + """ + limit = max([n] + [v for pair in queries for v in pair]) + parent = [i for i in range(limit + 1)] + rank = [1] * (limit + 1) + + def find(x): + res = x + while res != parent[res]: + parent[res] = parent[parent[res]] + res = parent[res] + return res + + def union(a, b): + p1, p2 = find(a), find(b) + if p1 == p2: + return False + if rank[p1] > rank[p2]: + parent[p2] = p1 + rank[p1] += rank[p2] + else: + parent[p1] = p2 + rank[p2] += rank[p1] + return True + + for i in range(threshold + 1, limit + 1): + for j in range(2 * i, limit + 1, i): + union(i, j) + + result = [] + for x, y in queries: + result.append(find(x) == find(y)) + return result diff --git a/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.rb b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.rb new file mode 100644 index 00000000..5174ede1 --- /dev/null +++ b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.rb @@ -0,0 +1,39 @@ +# @param {Integer} n +# @param {Integer} threshold +# @param {Integer[][]} queries +# @return {Boolean[]} +def are_connected(n, threshold, queries) + limit = [n, *queries.map(&:to_a).flatten].max + parent = (0..limit).to_a + rank = [1] * (limit + 1) + + find = ->(x) do + res = x + while res != parent[res] + parent[res] = parent[parent[res]] + res = parent[res] + end + res + end + + union = ->(a, b) do + p1, p2 = find.call(a), find.call(b) + return false if p1 == p2 + if rank[p1] > rank[p2] + parent[p2] = p1 + rank[p1] += rank[p2] + else + parent[p1] = p2 + rank[p2] += rank[p1] + end + true + end + + (threshold + 1..limit).each do |i| + (2 * i..limit).step(i).each do |j| + union.call(i, j) + end + end + + queries.map { |x, y| find.call(x) == find.call(y) } +end diff --git a/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.rs b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.rs new file mode 100644 index 00000000..f84d48f5 --- /dev/null +++ b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.rs @@ -0,0 +1,46 @@ +impl Solution { + pub fn are_connected(n: i32, threshold: i32, queries: Vec>) -> Vec { + let limit = queries.iter().fold(n, |acc, q| acc.max(q[0]).max(q[1])) as usize; + let mut parent: Vec = (0..=limit).collect(); + let mut rank: Vec = vec![1; limit + 1]; + + fn find(parent: &mut Vec, x: usize) -> usize { + let mut res = x; + while res != parent[res] { + parent[res] = parent[parent[res]]; + res = parent[res]; + } + res + } + + fn union(parent: &mut Vec, rank: &mut Vec, a: usize, b: usize) -> bool { + let p1 = find(parent, a); + let p2 = find(parent, b); + if p1 == p2 { + return false; + } + if rank[p1] > rank[p2] { + parent[p2] = p1; + rank[p1] += rank[p2]; + } else { + parent[p1] = p2; + rank[p2] += rank[p1]; + } + true + } + + for i in (threshold as usize + 1)..=limit { + let mut j = 2 * i; + while j <= limit { + union(&mut parent, &mut rank, i, j); + j += i; + } + } + + queries.iter().map(|q| { + let x = q[0] as usize; + let y = q[1] as usize; + find(&mut parent, x) == find(&mut parent, y) + }).collect() + } +} diff --git a/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.swift b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.swift new file mode 100644 index 00000000..7febf42a --- /dev/null +++ b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.swift @@ -0,0 +1,43 @@ +class Solution { + func areConnected(_ n: Int, _ threshold: Int, _ queries: [[Int]]) -> [Bool] { + var limit = n + for q in queries { + limit = max(limit, max(q[0], q[1])) + } + var parent = [Int](0...limit) + var rank = [Int](repeating: 1, count: limit + 1) + + func find(_ x: Int) -> Int { + var res = x + while res != parent[res] { + parent[res] = parent[parent[res]] + res = parent[res] + } + return res + } + + func union(_ a: Int, _ b: Int) -> Bool { + let p1 = find(a) + let p2 = find(b) + if p1 == p2 { return false } + if rank[p1] > rank[p2] { + parent[p2] = p1 + rank[p1] += rank[p2] + } else { + parent[p1] = p2 + rank[p2] += rank[p1] + } + return true + } + + if threshold < limit { + for i in (threshold + 1)...limit { + for j in stride(from: 2 * i, through: limit, by: i) { + union(i, j) + } + } + } + + return queries.map { find($0[0]) == find($0[1]) } + } +} diff --git a/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.ts b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.ts new file mode 100644 index 00000000..4bf5f7c0 --- /dev/null +++ b/tests/1501-2000/1627. graph-connectivity-with-threshold/sol.ts @@ -0,0 +1,43 @@ +function areConnected( + n: number, + threshold: number, + queries: number[][], +): boolean[] { + let limit = n; + for (const q of queries) { + limit = Math.max(limit, q[0], q[1]); + } + const parent: number[] = Array.from({ length: limit + 1 }, (_, i) => i); + const rank: number[] = new Array(limit + 1).fill(1); + + const find = (x: number): number => { + let res = x; + while (res !== parent[res]) { + parent[res] = parent[parent[res]]; + res = parent[res]; + } + return res; + }; + + const union = (a: number, b: number): boolean => { + const p1 = find(a); + const p2 = find(b); + if (p1 === p2) return false; + if (rank[p1] > rank[p2]) { + parent[p2] = p1; + rank[p1] += rank[p2]; + } else { + parent[p1] = p2; + rank[p2] += rank[p1]; + } + return true; + }; + + for (let i = threshold + 1; i <= limit; i++) { + for (let j = 2 * i; j <= limit; j += i) { + union(i, j); + } + } + + return queries.map(([x, y]) => find(x) === find(y)); +} diff --git a/tests/1501-2000/1629. slowest-key/manifest.yaml b/tests/1501-2000/1629. slowest-key/manifest.yaml new file mode 100644 index 00000000..681bda7c --- /dev/null +++ b/tests/1501-2000/1629. slowest-key/manifest.yaml @@ -0,0 +1,231 @@ +entry: + id: 1629 + title: "slowest-key" + params: + releaseTimes: + type: array + items: + type: int + keysPressed: + type: string + call: + cpp: "Solution().slowestKey({releaseTimes}, {keysPressed})" + rust: "Solution::slowest_key({releaseTimes}, {keysPressed})" + python3: "Solution().slowestKey({releaseTimes}, {keysPressed})" + python2: "Solution().slowestKey({releaseTimes}, {keysPressed})" + ruby: "slowest_key({releaseTimes}, {keysPressed})" + java: "new Solution().slowestKey({releaseTimes}, {keysPressed})" + csharp: "new Solution().SlowestKey({releaseTimes}, {keysPressed})" + kotlin: "Solution().slowestKey({releaseTimes}, {keysPressed})" + go: "string(slowestKey({releaseTimes}, {keysPressed}))" + dart: "Solution().slowestKey({releaseTimes}, {keysPressed})" + swift: "Solution().slowestKey({releaseTimes}, {keysPressed})" + typescript: "slowestKey({releaseTimes}, {keysPressed})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().slowestKey(releaseTimes, keysPressed, {result})" + checker: | + class Checker: + def slowestKey(self, releaseTimes, keysPressed, result): + if not isinstance(result, str) or len(result) != 1: + return False + best_duration = releaseTimes[0] + best_key = keysPressed[0] + for i in range(1, len(releaseTimes)): + duration = releaseTimes[i] - releaseTimes[i - 1] + if duration > best_duration or (duration == best_duration and keysPressed[i] > best_key): + best_duration = duration + best_key = keysPressed[i] + return result == best_key + +seed: 1629 + +tests: + - name: example-one + in: + releaseTimes: [9, 29, 49, 50] + keysPressed: "cbcd" + out: "c" + - name: example-two + in: + releaseTimes: [12, 23, 36, 46, 62] + keysPressed: "spuda" + out: "a" + - name: minimum-n + in: + releaseTimes: [1, 2, 3] + keysPressed: "abc" + out: "c" + - name: first-key-wins-longest + in: + releaseTimes: [20, 21, 22, 23] + keysPressed: "zabc" + out: "z" + - name: last-key-wins + in: + releaseTimes: [1, 2, 3, 100] + keysPressed: "abcz" + out: "z" + - name: tie-lexicographic + in: + releaseTimes: [5, 15, 25, 35] + keysPressed: "azby" + out: "z" + - name: repeated-key + in: + releaseTimes: [4, 9, 19, 24, 34] + keysPressed: "aaaaa" + out: "a" + - name: repeated-key-different-durations + in: + releaseTimes: [2, 20, 21, 22, 30] + keysPressed: "ababa" + out: "b" + - name: largest-character-tie + in: + releaseTimes: [7, 17, 27, 37, 47] + keysPressed: "qwert" + out: "w" + - name: zero-small-gaps + in: + releaseTimes: [1, 100, 101, 102, 103] + keysPressed: "bcdez" + out: "c" + - name: large-release-values + in: + releaseTimes: [1, 999999998, 999999999] + keysPressed: "mno" + out: "n" + - name: large-final-gap + in: + releaseTimes: [999999990, 999999991, 1000000000] + keysPressed: "xyz" + out: "x" + - name: increasing-durations + in: + releaseTimes: [1, 3, 6, 10, 15] + keysPressed: "abcde" + out: "e" + - name: decreasing-durations + in: + releaseTimes: [10, 19, 27, 34, 40] + keysPressed: "abcde" + out: "a" + - name: tie-at-first-and-middle + in: + releaseTimes: [8, 12, 20, 24, 30] + keysPressed: "zabcy" + out: "z" + - name: tie-at-middle-and-last + in: + releaseTimes: [2, 6, 14, 18, 26] + keysPressed: "abcdy" + out: "y" + - name: all-distinct-durations + in: + releaseTimes: [3, 8, 14, 21, 29, 38] + keysPressed: "abcdef" + out: "f" + - name: alphabet-low + in: + releaseTimes: [30, 31, 32, 62] + keysPressed: "abcd" + out: "d" + - name: alphabet-high + in: + releaseTimes: [30, 60, 61, 62] + keysPressed: "wxyz" + out: "x" + - name: alternating-large-gaps + in: + releaseTimes: [10, 11, 31, 32, 52, 53] + keysPressed: "ababab" + out: "a" + - name: tie-letters-out-of-order + in: + releaseTimes: [6, 16, 17, 27, 28] + keysPressed: "zaybx" + out: "b" + - name: long-small-sequence + in: + releaseTimes: [4, 5, 6, 7, 8, 9, 10, 25] + keysPressed: "abcdefgh" + out: "h" + - name: long-first-sequence + in: + releaseTimes: [40, 41, 42, 43, 44, 45, 46, 47] + keysPressed: "zyxwvuts" + out: "z" + - name: duplicate-maximum + in: + releaseTimes: [11, 22, 23, 34, 35, 46] + keysPressed: "afzbyx" + out: "x" + - name: maximum-is-q + in: + releaseTimes: [1, 4, 12, 13, 21] + keysPressed: "abcqa" + out: "c" + - name: maximum-is-m + in: + releaseTimes: [15, 16, 17, 32, 33] + keysPressed: "zzmab" + out: "z" + - name: maximum-tie-m-and-z + in: + releaseTimes: [5, 10, 20, 25, 35] + keysPressed: "amzby" + out: "z" + - name: one-dominant-middle + in: + releaseTimes: [2, 3, 4, 50, 51, 52] + keysPressed: "abcdef" + out: "d" + - name: near-int-limit + in: + releaseTimes: [999999900, 999999901, 999999950, 999999951] + keysPressed: "azby" + out: "a" + - name: six-keys-tie + in: + releaseTimes: [9, 18, 27, 36, 45, 54] + keysPressed: "qazwsx" + out: "z" + - name: mixed-case-not-allowed-lowercase + in: + releaseTimes: [13, 26, 39, 52] + keysPressed: "mnop" + out: "p" + - name: late-lexicographic-tie + in: + releaseTimes: [3, 13, 14, 24, 25, 35] + keysPressed: "abczay" + out: "z" + - name: alternating-letters + in: + releaseTimes: [8, 9, 17, 18, 26, 27, 35] + keysPressed: "xyxyxyx" + out: "x" + - name: dominant-second + in: + releaseTimes: [3, 80, 81, 82, 83] + keysPressed: "azzzz" + out: "z" + - name: dominant-penultimate + in: + releaseTimes: [1, 2, 3, 70, 71] + keysPressed: "abcza" + out: "z" + - name: all-unique-letters + in: + releaseTimes: [14, 28, 42, 56, 70, 84, 98] + keysPressed: "abcdefg" + out: "g" diff --git a/tests/1501-2000/1629. slowest-key/sol.cpp b/tests/1501-2000/1629. slowest-key/sol.cpp new file mode 100644 index 00000000..a96dfabd --- /dev/null +++ b/tests/1501-2000/1629. slowest-key/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + char slowestKey(vector& releaseTimes, string keysPressed) { + int maxTime = releaseTimes[0]; + char ans = keysPressed[0]; + for (int i = 1; i < releaseTimes.size(); i++) { + int currTime = releaseTimes[i] - releaseTimes[i-1]; + if (currTime > maxTime) { + maxTime = currTime; + ans = keysPressed[i]; + } else if (currTime == maxTime) { + ans = max(ans, keysPressed[i]); + } + } + return ans; + } +}; diff --git a/tests/1501-2000/1629. slowest-key/sol.cs b/tests/1501-2000/1629. slowest-key/sol.cs new file mode 100644 index 00000000..2b57b754 --- /dev/null +++ b/tests/1501-2000/1629. slowest-key/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public char SlowestKey(int[] releaseTimes, string keysPressed) { + int maxTime = releaseTimes[0]; + char ans = keysPressed[0]; + for (int i = 1; i < releaseTimes.Length; i++) { + int currTime = releaseTimes[i] - releaseTimes[i-1]; + if (currTime > maxTime) { + maxTime = currTime; + ans = keysPressed[i]; + } else if (currTime == maxTime) { + ans = (char)Math.Max(ans, keysPressed[i]); + } + } + return ans; + } +} diff --git a/tests/1501-2000/1629. slowest-key/sol.dart b/tests/1501-2000/1629. slowest-key/sol.dart new file mode 100644 index 00000000..acc756d7 --- /dev/null +++ b/tests/1501-2000/1629. slowest-key/sol.dart @@ -0,0 +1,18 @@ +class Solution { + String slowestKey(List releaseTimes, String keysPressed) { + int maxTime = releaseTimes[0]; + String ans = keysPressed[0]; + for (int i = 1; i < releaseTimes.length; i++) { + int currTime = releaseTimes[i] - releaseTimes[i-1]; + if (currTime > maxTime) { + maxTime = currTime; + ans = keysPressed[i]; + } else if (currTime == maxTime) { + if (keysPressed[i].compareTo(ans) > 0) { + ans = keysPressed[i]; + } + } + } + return ans; + } +} diff --git a/tests/1501-2000/1629. slowest-key/sol.go b/tests/1501-2000/1629. slowest-key/sol.go new file mode 100644 index 00000000..d842be1c --- /dev/null +++ b/tests/1501-2000/1629. slowest-key/sol.go @@ -0,0 +1,16 @@ +func slowestKey(releaseTimes []int, keysPressed string) byte { + maxTime := releaseTimes[0] + ans := keysPressed[0] + for i := 1; i < len(releaseTimes); i++ { + currTime := releaseTimes[i] - releaseTimes[i-1] + if currTime > maxTime { + maxTime = currTime + ans = keysPressed[i] + } else if currTime == maxTime { + if keysPressed[i] > ans { + ans = keysPressed[i] + } + } + } + return ans +} diff --git a/tests/1501-2000/1629. slowest-key/sol.java b/tests/1501-2000/1629. slowest-key/sol.java new file mode 100644 index 00000000..2ed3523d --- /dev/null +++ b/tests/1501-2000/1629. slowest-key/sol.java @@ -0,0 +1,16 @@ +class Solution { + public char slowestKey(int[] releaseTimes, String keysPressed) { + int maxTime = releaseTimes[0]; + char ans = keysPressed.charAt(0); + for (int i = 1; i < releaseTimes.length; i++) { + int currTime = releaseTimes[i] - releaseTimes[i-1]; + if (currTime > maxTime) { + maxTime = currTime; + ans = keysPressed.charAt(i); + } else if (currTime == maxTime) { + ans = (char) Math.max(ans, keysPressed.charAt(i)); + } + } + return ans; + } +} diff --git a/tests/1501-2000/1629. slowest-key/sol.kt b/tests/1501-2000/1629. slowest-key/sol.kt new file mode 100644 index 00000000..26b24beb --- /dev/null +++ b/tests/1501-2000/1629. slowest-key/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun slowestKey(releaseTimes: IntArray, keysPressed: String): Char { + var maxTime = releaseTimes[0] + var ans = keysPressed[0] + for (i in 1 until releaseTimes.size) { + val currTime = releaseTimes[i] - releaseTimes[i-1] + if (currTime > maxTime) { + maxTime = currTime + ans = keysPressed[i] + } else if (currTime == maxTime) { + ans = maxOf(ans, keysPressed[i]) + } + } + return ans + } +} diff --git a/tests/1501-2000/1629. slowest-key/sol.py b/tests/1501-2000/1629. slowest-key/sol.py new file mode 100644 index 00000000..2c070b6a --- /dev/null +++ b/tests/1501-2000/1629. slowest-key/sol.py @@ -0,0 +1,16 @@ +class Solution: + def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: + max_time = releaseTimes[0] + ans = keysPressed[0] + + for i in range(1, len(releaseTimes)): + curr_time = releaseTimes[i] - releaseTimes[i - 1] + + if curr_time > max_time: + max_time = curr_time + ans = keysPressed[i] + + elif curr_time == max_time: + ans = max(ans, keysPressed[i]) + + return ans diff --git a/tests/1501-2000/1629. slowest-key/sol.py2 b/tests/1501-2000/1629. slowest-key/sol.py2 new file mode 100644 index 00000000..3b3d0c8c --- /dev/null +++ b/tests/1501-2000/1629. slowest-key/sol.py2 @@ -0,0 +1,17 @@ +class Solution(object): + def slowestKey(self, releaseTimes, keysPressed): + """ + :type releaseTimes: List[int] + :type keysPressed: str + :rtype: str + """ + max_time = releaseTimes[0] + ans = keysPressed[0] + for i in range(1, len(releaseTimes)): + curr_time = releaseTimes[i] - releaseTimes[i-1] + if curr_time > max_time: + max_time = curr_time + ans = keysPressed[i] + elif curr_time == max_time: + ans = max(ans, keysPressed[i]) + return ans diff --git a/tests/1501-2000/1629. slowest-key/sol.rb b/tests/1501-2000/1629. slowest-key/sol.rb new file mode 100644 index 00000000..94c10851 --- /dev/null +++ b/tests/1501-2000/1629. slowest-key/sol.rb @@ -0,0 +1,14 @@ +def slowest_key(release_times, keys_pressed) + max_time = release_times[0] + ans = keys_pressed[0] + (1...release_times.length).each do |i| + curr_time = release_times[i] - release_times[i-1] + if curr_time > max_time + max_time = curr_time + ans = keys_pressed[i] + elsif curr_time == max_time + ans = [ans, keys_pressed[i]].max + end + end + ans +end diff --git a/tests/1501-2000/1629. slowest-key/sol.rs b/tests/1501-2000/1629. slowest-key/sol.rs new file mode 100644 index 00000000..85925dac --- /dev/null +++ b/tests/1501-2000/1629. slowest-key/sol.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn slowest_key(release_times: Vec, keys_pressed: String) -> char { + let mut max_time = release_times[0]; + let mut ans = keys_pressed.chars().next().unwrap(); + for i in 1..release_times.len() { + let curr_time = release_times[i] - release_times[i-1]; + if curr_time > max_time { + max_time = curr_time; + ans = keys_pressed.chars().nth(i).unwrap(); + } else if curr_time == max_time { + let c = keys_pressed.chars().nth(i).unwrap(); + if c > ans { + ans = c; + } + } + } + ans + } +} diff --git a/tests/1501-2000/1629. slowest-key/sol.swift b/tests/1501-2000/1629. slowest-key/sol.swift new file mode 100644 index 00000000..108bd88c --- /dev/null +++ b/tests/1501-2000/1629. slowest-key/sol.swift @@ -0,0 +1,19 @@ +class Solution { + func slowestKey(_ releaseTimes: [Int], _ keysPressed: String) -> Character { + var maxTime = releaseTimes[0] + var ans = keysPressed[keysPressed.startIndex] + let chars = Array(keysPressed) + for i in 1.. maxTime { + maxTime = currTime + ans = chars[i] + } else if currTime == maxTime { + if chars[i] > ans { + ans = chars[i] + } + } + } + return ans + } +} diff --git a/tests/1501-2000/1629. slowest-key/sol.ts b/tests/1501-2000/1629. slowest-key/sol.ts new file mode 100644 index 00000000..9bb77c0c --- /dev/null +++ b/tests/1501-2000/1629. slowest-key/sol.ts @@ -0,0 +1,16 @@ +function slowestKey(releaseTimes: number[], keysPressed: string): string { + let maxTime = releaseTimes[0]; + let ans = keysPressed[0]; + for (let i = 1; i < releaseTimes.length; i++) { + const currTime = releaseTimes[i] - releaseTimes[i - 1]; + if (currTime > maxTime) { + maxTime = currTime; + ans = keysPressed[i]; + } else if (currTime === maxTime) { + if (keysPressed[i] > ans) { + ans = keysPressed[i]; + } + } + } + return ans; +} diff --git a/tests/1501-2000/1630. arithmetic-subarrays/manifest.yaml b/tests/1501-2000/1630. arithmetic-subarrays/manifest.yaml new file mode 100644 index 00000000..d0d7f586 --- /dev/null +++ b/tests/1501-2000/1630. arithmetic-subarrays/manifest.yaml @@ -0,0 +1,338 @@ +entry: + id: 1630 + title: arithmetic-subarrays + params: + nums: + type: array + items: + type: int + l: + type: array + items: + type: int + r: + type: array + items: + type: int + call: + cpp: "Solution().checkArithmeticSubarrays({nums}, {l}, {r})" + rust: "Solution::check_arithmetic_subarrays({nums}, {l}, {r})" + python3: "Solution().checkArithmeticSubarrays({nums}, {l}, {r})" + python2: "Solution().checkArithmeticSubarrays({nums}, {l}, {r})" + ruby: "check_arithmetic_subarrays({nums}, {l}, {r})" + java: "new Solution().checkArithmeticSubarrays({nums}, {l}, {r})" + csharp: "new Solution().CheckArithmeticSubarrays({nums}, {l}, {r})" + kotlin: "Solution().checkArithmeticSubarrays({nums}, {l}, {r})" + go: "checkArithmeticSubarrays({nums}, {l}, {r})" + dart: "Solution().checkArithmeticSubarrays({nums}, {l}, {r})" + swift: "Solution().checkArithmeticSubarrays({nums}, {l}, {r})" + typescript: "checkArithmeticSubarrays({nums}, {l}, {r})" + +judge: + type: exact + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().checkArithmeticSubarrays(nums, l, r, {result})" + checker: | + class Checker: + def checkArithmeticSubarrays(self, nums, l, r, result): + if not isinstance(result, list) or len(result) != len(l) or len(l) != len(r): + return False + expected = [] + for left, right in zip(l, r): + values = sorted(nums[left:right + 1]) + if len(values) < 2: + expected.append(True) + else: + step = values[1] - values[0] + expected.append(all(values[i] - values[i - 1] == step for i in range(2, len(values)))) + return result == expected + +seed: 1630 + +tests: + - name: example-one + in: + nums: [4, 6, 5, 9, 3, 7] + l: [0, 0, 2] + r: [2, 3, 5] + out: [true, false, true] + judge: + type: exact + - name: example-two + in: + nums: [-12, -9, -3, -12, -6, 15, 20, -25, -20, -15, -10] + l: [0, 1, 6, 4, 8, 7] + r: [4, 4, 9, 7, 9, 10] + out: [false, true, false, false, true, true] + judge: + type: exact + - name: two-elements + in: + nums: [9, -4, 9] + l: [0, 1] + r: [1, 2] + out: [true, true] + judge: + type: exact + - name: all-equal + in: + nums: [7, 7, 7, 7, 7] + l: [0, 1, 2] + r: [4, 3, 4] + out: [true, true, true] + judge: + type: exact + - name: descending + in: + nums: [10, 4, 7, 1, -2, 13] + l: [0, 0, 1] + r: [3, 4, 4] + out: [true, true, true] + judge: + type: exact + - name: duplicate-break + in: + nums: [1, 1, 2, 3, 5, 8] + l: [0, 0, 1, 2] + r: [2, 3, 5, 5] + out: [false, false, false, false] + judge: + type: exact + - name: negative-arithmetic + in: + nums: [-9, -1, -5, 3, -13, 7] + l: [0, 0, 1] + r: [3, 4, 4] + out: [true, true, false] + judge: + type: exact + - name: mixed-small + in: + nums: [2, 10, 6, 14, 18, 22, 3] + l: [0, 0, 1, 2] + r: [3, 4, 5, 6] + out: [true, true, true, false] + judge: + type: exact + - name: singleton-slices-not-allowed + in: + nums: [5, 1, 9, 13] + l: [0, 1, 2] + r: [1, 2, 3] + out: [true, true, true] + judge: + type: exact + - name: same-values-different-order + in: + nums: [20, 5, 15, 10, 25, 30] + l: [0, 0, 1] + r: [3, 4, 5] + out: [true, true, false] + judge: + type: exact + - name: large-magnitude + in: + nums: [-100000, 0, 100000, -99999, 1, 100001] + l: [0, 0, 3] + r: [2, 5, 5] + out: [true, false, true] + judge: + type: exact + - name: zero-step-and-outlier + in: + nums: [0, 0, 0, 1, 0, 0] + l: [0, 0, 1] + r: [2, 5, 5] + out: [true, false, false] + judge: + type: exact + - name: step-two-permuted + in: + nums: [9, 1, 7, 3, 5, 12, 15] + l: [0, 0, 1] + r: [4, 5, 6] + out: [true, false, false] + judge: + type: exact + - name: overlapping-queries + in: + nums: [8, 2, 6, 4, 10, 12, 14, 1] + l: [0, 1, 2, 3, 0] + r: [3, 6, 5, 6, 6] + out: [true, false, false, false, true] + judge: + type: exact + - name: alternating-values + in: + nums: [1, 9, 1, 9, 1, 9, 1, 9] + l: [0, 0, 1, 2] + r: [1, 3, 6, 7] + out: [true, false, false, false] + judge: + type: exact + - name: arithmetic-with-negative-step + in: + nums: [-1, -7, -4, 5, -10, -13, -16] + l: [0, 0, 4] + r: [2, 3, 6] + out: [true, false, true] + judge: + type: exact + - name: repeated-query + in: + nums: [11, 3, 7, 15, 19, 23] + l: [0, 0, 0, 1] + r: [3, 3, 3, 5] + out: [true, true, true, false] + judge: + type: exact + - name: short-invalid + in: + nums: [1, 2, 4, 8, 16, 32] + l: [0, 0, 1, 2] + r: [2, 3, 4, 5] + out: [false, false, false, false] + judge: + type: exact + - name: powers-with-valid-pair + in: + nums: [1, 2, 4, 8, 16, 32, 64] + l: [0, 1, 2, 3, 4] + r: [1, 2, 3, 4, 6] + out: [true, true, true, true, false] + judge: + type: exact + - name: broad-valid-subarrays + in: + nums: [30, 10, 50, 20, 40, 60, 70, 0] + l: [0, 0, 1, 2] + r: [4, 5, 6, 7] + out: [true, true, false, false] + judge: + type: exact + - name: extremes-and-zero + in: + nums: [-100000, 100000, 0, -50000, 50000] + l: [0, 0, 2] + r: [1, 4, 4] + out: [true, true, true] + judge: + type: exact + - name: many-duplicates + in: + nums: [4, 4, 8, 4, 12, 16, 4, 20] + l: [0, 0, 1, 2] + r: [1, 4, 5, 7] + out: [true, false, false, false] + judge: + type: exact + - name: odd-step + in: + nums: [13, 1, 7, 10, 4, 16, 19] + l: [0, 0, 1, 2] + r: [4, 5, 5, 6] + out: [true, true, false, false] + judge: + type: exact + - name: query-order + in: + nums: [6, 2, 10, 14, 18, 22, 26] + l: [4, 0, 2, 1] + r: [6, 3, 6, 5] + out: [true, true, true, false] + judge: + type: exact + - name: noncontiguous-values + in: + nums: [0, 100, 3, 6, 9, 12, 15] + l: [0, 1, 2, 3] + r: [2, 2, 6, 6] + out: [false, true, true, true] + judge: + type: exact + - name: negative-and-positive + in: + nums: [-8, 4, 0, -4, 8, 12, -12] + l: [0, 0, 1, 2] + r: [4, 5, 4, 6] + out: [true, true, true, false] + judge: + type: exact + - name: length-three-checks + in: + nums: [2, 5, 8, 3, 7, 11, 0, 0] + l: [0, 1, 2, 3, 4, 6] + r: [2, 3, 4, 5, 5, 7] + out: [true, false, false, true, true, true] + judge: + type: exact + - name: nearly-valid + in: + nums: [2, 6, 10, 14, 19, 22, 26, 30] + l: [0, 0, 1, 3] + r: [3, 4, 7, 7] + out: [true, false, false, false] + judge: + type: exact + - name: valid-window-inside-noise + in: + nums: [99, 15, 3, 9, 21, 27, -50] + l: [1, 1, 2, 0] + r: [5, 4, 5, 6] + out: [true, true, false, false] + judge: + type: exact + - name: all-negative-valid + in: + nums: [-2, -14, -8, -20, -26, 1] + l: [0, 0, 1] + r: [4, 5, 4] + out: [true, false, true] + judge: + type: exact + - name: varied-query-count + in: + nums: [5, 15, 25, 35, 45, 55, 65, 75, 84] + l: [0, 1, 2, 3, 4, 0, 5] + r: [8, 8, 8, 8, 8, 7, 8] + out: [false, false, false, false, false, true, false] + judge: + type: exact + - name: reordered-valid-four + in: + nums: [17, 5, 11, 23, 29, 35, 41] + l: [0, 0, 1, 2] + r: [3, 4, 6, 5] + out: [true, true, false, false] + judge: + type: exact + - name: zero-and-signs + in: + nums: [-6, 0, 6, 12, -12, 18] + l: [0, 0, 1, 2] + r: [2, 3, 5, 5] + out: [true, true, false, false] + judge: + type: exact + - name: final-boundary + in: + nums: [100000, 99999, 99998, 99997, -100000] + l: [0, 0, 1] + r: [3, 4, 3] + out: [true, false, true] + judge: + type: exact + - name: minimum-two-and-full-range + in: + nums: [42, 0, -42, 84, 126, 168] + l: [0, 1, 0] + r: [1, 2, 5] + out: [true, true, true] + judge: + type: exact diff --git a/tests/1501-2000/1630. arithmetic-subarrays/sol.cpp b/tests/1501-2000/1630. arithmetic-subarrays/sol.cpp new file mode 100644 index 00000000..93736b02 --- /dev/null +++ b/tests/1501-2000/1630. arithmetic-subarrays/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + vector checkArithmeticSubarrays(vector& nums, vector& l, vector& r) { + vector ans; + for (int i = 0; i < l.size(); i++) { + vector sub(nums.begin()+l[i], nums.begin()+r[i]+1); + sort(sub.begin(), sub.end()); + bool valid = true; + if (sub.size() > 2) { + int d = sub[1] - sub[0]; + for (int j = 1; j < sub.size()-1; j++) { + if (sub[j+1] - sub[j] != d) { + valid = false; + break; + } + } + } + ans.push_back(valid); + } + return ans; + } +}; diff --git a/tests/1501-2000/1630. arithmetic-subarrays/sol.cs b/tests/1501-2000/1630. arithmetic-subarrays/sol.cs new file mode 100644 index 00000000..0194d046 --- /dev/null +++ b/tests/1501-2000/1630. arithmetic-subarrays/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public IList CheckArithmeticSubarrays(int[] nums, int[] l, int[] r) { + List ans = new List(); + for (int i = 0; i < l.Length; i++) { + int[] sub = new int[r[i]-l[i]+1]; + Array.Copy(nums, l[i], sub, 0, r[i]-l[i]+1); + Array.Sort(sub); + bool valid = true; + if (sub.Length > 2) { + int d = sub[1] - sub[0]; + for (int j = 1; j < sub.Length-1; j++) { + if (sub[j+1] - sub[j] != d) { + valid = false; + break; + } + } + } + ans.Add(valid); + } + return ans; + } +} diff --git a/tests/1501-2000/1630. arithmetic-subarrays/sol.dart b/tests/1501-2000/1630. arithmetic-subarrays/sol.dart new file mode 100644 index 00000000..e639c184 --- /dev/null +++ b/tests/1501-2000/1630. arithmetic-subarrays/sol.dart @@ -0,0 +1,20 @@ +class Solution { + List checkArithmeticSubarrays(List nums, List l, List r) { + List ans = []; + for (int i = 0; i < l.length; i++) { + List sub = nums.sublist(l[i], r[i]+1)..sort(); + bool valid = true; + if (sub.length > 2) { + int d = sub[1] - sub[0]; + for (int j = 1; j < sub.length-1; j++) { + if (sub[j+1] - sub[j] != d) { + valid = false; + break; + } + } + } + ans.add(valid); + } + return ans; + } +} diff --git a/tests/1501-2000/1630. arithmetic-subarrays/sol.go b/tests/1501-2000/1630. arithmetic-subarrays/sol.go new file mode 100644 index 00000000..dd957d05 --- /dev/null +++ b/tests/1501-2000/1630. arithmetic-subarrays/sol.go @@ -0,0 +1,20 @@ +func checkArithmeticSubarrays(nums []int, l []int, r []int) []bool { + ans := make([]bool, len(l)) + for i := 0; i < len(l); i++ { + sub := make([]int, r[i]-l[i]+1) + copy(sub, nums[l[i]:r[i]+1]) + sort.Ints(sub) + valid := true + if len(sub) > 2 { + d := sub[1] - sub[0] + for j := 1; j < len(sub)-1; j++ { + if sub[j+1] - sub[j] != d { + valid = false + break + } + } + } + ans[i] = valid + } + return ans +} diff --git a/tests/1501-2000/1630. arithmetic-subarrays/sol.java b/tests/1501-2000/1630. arithmetic-subarrays/sol.java new file mode 100644 index 00000000..00c1889b --- /dev/null +++ b/tests/1501-2000/1630. arithmetic-subarrays/sol.java @@ -0,0 +1,23 @@ +import java.util.*; + +class Solution { + public List checkArithmeticSubarrays(int[] nums, int[] l, int[] r) { + List ans = new ArrayList<>(); + for (int i = 0; i < l.length; i++) { + int[] sub = Arrays.copyOfRange(nums, l[i], r[i]+1); + Arrays.sort(sub); + boolean valid = true; + if (sub.length > 2) { + int d = sub[1] - sub[0]; + for (int j = 1; j < sub.length-1; j++) { + if (sub[j+1] - sub[j] != d) { + valid = false; + break; + } + } + } + ans.add(valid); + } + return ans; + } +} diff --git a/tests/1501-2000/1630. arithmetic-subarrays/sol.kt b/tests/1501-2000/1630. arithmetic-subarrays/sol.kt new file mode 100644 index 00000000..3ad043dd --- /dev/null +++ b/tests/1501-2000/1630. arithmetic-subarrays/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun checkArithmeticSubarrays(nums: IntArray, l: IntArray, r: IntArray): List { + val ans = mutableListOf() + for (i in l.indices) { + val sub = nums.copyOfRange(l[i], r[i]+1).sorted() + var valid = true + if (sub.size > 2) { + val d = sub[1] - sub[0] + for (j in 1 until sub.size-1) { + if (sub[j+1] - sub[j] != d) { + valid = false + break + } + } + } + ans.add(valid) + } + return ans + } +} diff --git a/tests/1501-2000/1630. arithmetic-subarrays/sol.py b/tests/1501-2000/1630. arithmetic-subarrays/sol.py new file mode 100644 index 00000000..a7351ac4 --- /dev/null +++ b/tests/1501-2000/1630. arithmetic-subarrays/sol.py @@ -0,0 +1,16 @@ +class Solution(object): + def check(self, a): + a = sorted(a) + if len(a) == 1 or len(a) == 2: + return True + d = a[1] - a[0] + for i in range(1, len(a) - 1): + if a[i + 1] - a[i] != d: + return False + return True + + def checkArithmeticSubarrays(self, nums, l, r): + ans = [] + for i in range(len(l)): + ans.append(self.check(nums[l[i] : r[i] + 1])) + return ans diff --git a/tests/1501-2000/1630. arithmetic-subarrays/sol.py2 b/tests/1501-2000/1630. arithmetic-subarrays/sol.py2 new file mode 100644 index 00000000..a76c716c --- /dev/null +++ b/tests/1501-2000/1630. arithmetic-subarrays/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def check(self, a): + a = sorted(a) + if len(a) == 1 or len(a) == 2: + return True + d = a[1] - a[0] + for i in range(1, len(a)-1): + if a[i+1] - a[i] != d: + return False + return True + def checkArithmeticSubarrays(self, nums, l, r): + ans = [] + for i in range(len(l)): + ans.append(self.check(nums[l[i]:r[i]+1])) + return ans diff --git a/tests/1501-2000/1630. arithmetic-subarrays/sol.rb b/tests/1501-2000/1630. arithmetic-subarrays/sol.rb new file mode 100644 index 00000000..afafd133 --- /dev/null +++ b/tests/1501-2000/1630. arithmetic-subarrays/sol.rb @@ -0,0 +1,25 @@ +# @param {Integer[]} nums +# @param {Integer[]} l +# @param {Integer[]} r +# @return {Boolean[]} +def check_arithmetic_subarrays(nums, l, r) + ans = [] + l.each_with_index do |left, i| + right = r[i] + sub = nums[left..right].sort + if sub.length <= 2 + ans << true + else + d = sub[1] - sub[0] + valid = true + (1...sub.length-1).each do |j| + if sub[j+1] - sub[j] != d + valid = false + break + end + end + ans << valid + end + end + ans +end diff --git a/tests/1501-2000/1630. arithmetic-subarrays/sol.rs b/tests/1501-2000/1630. arithmetic-subarrays/sol.rs new file mode 100644 index 00000000..2c77cd7e --- /dev/null +++ b/tests/1501-2000/1630. arithmetic-subarrays/sol.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn check_arithmetic_subarrays(nums: Vec, l: Vec, r: Vec) -> Vec { + let mut ans = Vec::with_capacity(l.len()); + for i in 0..l.len() { + let mut sub: Vec = nums[l[i] as usize..=r[i] as usize].to_vec(); + sub.sort(); + let mut valid = true; + if sub.len() > 2 { + let d = sub[1] - sub[0]; + for j in 1..sub.len()-1 { + if sub[j+1] - sub[j] != d { + valid = false; + break; + } + } + } + ans.push(valid); + } + ans + } +} diff --git a/tests/1501-2000/1630. arithmetic-subarrays/sol.swift b/tests/1501-2000/1630. arithmetic-subarrays/sol.swift new file mode 100644 index 00000000..05681dcf --- /dev/null +++ b/tests/1501-2000/1630. arithmetic-subarrays/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func checkArithmeticSubarrays(_ nums: [Int], _ l: [Int], _ r: [Int]) -> [Bool] { + var ans: [Bool] = [] + for i in 0.. 2 { + let d = sub[1] - sub[0] + for j in 1..<(sub.count-1) { + if sub[j+1] - sub[j] != d { + valid = false + break + } + } + } + ans.append(valid) + } + return ans + } +} diff --git a/tests/1501-2000/1630. arithmetic-subarrays/sol.ts b/tests/1501-2000/1630. arithmetic-subarrays/sol.ts new file mode 100644 index 00000000..1c8ba872 --- /dev/null +++ b/tests/1501-2000/1630. arithmetic-subarrays/sol.ts @@ -0,0 +1,22 @@ +function checkArithmeticSubarrays( + nums: number[], + l: number[], + r: number[], +): boolean[] { + const ans: boolean[] = []; + for (let i = 0; i < l.length; i++) { + const sub = nums.slice(l[i], r[i] + 1).sort((a, b) => a - b); + let valid = true; + if (sub.length > 2) { + const d = sub[1] - sub[0]; + for (let j = 1; j < sub.length - 1; j++) { + if (sub[j + 1] - sub[j] !== d) { + valid = false; + break; + } + } + } + ans.push(valid); + } + return ans; +} diff --git a/tests/1501-2000/1631. path-with-minimum-effort/manifest.yaml b/tests/1501-2000/1631. path-with-minimum-effort/manifest.yaml new file mode 100644 index 00000000..2f67ba45 --- /dev/null +++ b/tests/1501-2000/1631. path-with-minimum-effort/manifest.yaml @@ -0,0 +1,378 @@ +entry: + id: 1631 + title: path-with-minimum-effort + params: + heights: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().minimumEffortPath({heights})" + rust: "Solution::minimum_effort_path({heights})" + python3: "Solution().minimumEffortPath({heights})" + python2: "Solution().minimumEffortPath({heights})" + ruby: "minimum_effort_path({heights})" + java: "new Solution().minimumEffortPath({heights})" + csharp: "new Solution().MinimumEffortPath({heights})" + kotlin: "Solution().minimumEffortPath({heights})" + go: "minimumEffortPath({heights})" + dart: "Solution().minimumEffortPath({heights})" + swift: "Solution().minimumEffortPath({heights})" + typescript: "minimumEffortPath({heights})" + +judge: + type: exact + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minimumEffortPath(heights, {result})" + checker: | + import heapq + + class Checker: + def minimumEffortPath(self, heights, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + rows = len(heights) + cols = len(heights[0]) + best = [[10**18] * cols for _ in range(rows)] + best[0][0] = 0 + heap = [(0, 0, 0)] + while heap: + effort, r, c = heapq.heappop(heap) + if effort != best[r][c]: + continue + if r == rows - 1 and c == cols - 1: + return effort == result + for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): + nr, nc = r + dr, c + dc + if 0 <= nr < rows and 0 <= nc < cols: + candidate = max(effort, abs(heights[r][c] - heights[nr][nc])) + if candidate < best[nr][nc]: + best[nr][nc] = candidate + heapq.heappush(heap, (candidate, nr, nc)) + return False + +seed: 1631 + +tests: + - name: example-1 + in: + heights: + - [1, 2, 2] + - [3, 8, 2] + - [5, 3, 5] + out: 2 + - name: example-2 + in: + heights: + - [1, 2, 3] + - [3, 8, 4] + - [5, 3, 5] + out: 1 + - name: example-3 + in: + heights: + - [1, 2, 1, 1, 1] + - [1, 2, 1, 2, 1] + - [1, 2, 1, 2, 1] + - [1, 2, 1, 2, 1] + - [1, 1, 1, 2, 1] + out: 0 + - name: single-cell + in: + heights: + - [999999] + out: 0 + - name: one-row-increasing + in: + heights: + - [1, 4, 9, 16, 25] + - name: one-row-valley + in: + heights: + - [100, 1, 100, 2, 100] + - name: one-column + in: + heights: + - [7] + - [3] + - [8] + - [2] + - [9] + - name: flat-rectangle + in: + heights: + - [42, 42, 42, 42] + - [42, 42, 42, 42] + - [42, 42, 42, 42] + - name: high-barrier-center + in: + heights: + - [1, 1, 1, 1] + - [1, 1000000, 1000000, 1] + - [1, 1, 1, 1] + - name: low-corridor + in: + heights: + - [100, 1, 100, 100] + - [100, 1, 100, 100] + - [100, 1, 1, 1] + - [100, 100, 100, 1] + - name: checkerboard + in: + heights: + - [1, 100, 1, 100, 1] + - [100, 1, 100, 1, 100] + - [1, 100, 1, 100, 1] + - [100, 1, 100, 1, 100] + - [1, 100, 1, 100, 1] + - name: diagonal-low + in: + heights: + - [5, 100, 100, 100] + - [100, 5, 100, 100] + - [100, 100, 5, 100] + - [100, 100, 100, 5] + - name: negative-direction-gradient + in: + heights: + - [1000, 900, 800, 700] + - [901, 801, 701, 601] + - [802, 702, 602, 502] + - name: large-jump-avoidable + in: + heights: + - [1, 1000000, 2] + - [2, 3, 4] + - [3, 4, 5] + - name: narrow-zigzag + in: + heights: + - [10, 20] + - [11, 19] + - [12, 18] + - [13, 17] + - [14, 16] + - [15, 15] + - name: two-by-two-cross + in: + heights: + - [1, 100] + - [2, 3] + - name: two-by-three + in: + heights: + - [10, 1, 10] + - [10, 1, 10] + - name: prime-heights + in: + heights: + - [2, 3, 5, 7] + - [11, 13, 17, 19] + - [23, 29, 31, 37] + - name: repeated-trap + in: + heights: + - [8, 8, 50, 8, 8] + - [8, 50, 50, 50, 8] + - [8, 8, 8, 8, 8] + - name: monotone-grid + in: + heights: + - [1, 2, 3, 4, 5] + - [2, 3, 4, 5, 6] + - [3, 4, 5, 6, 7] + - [4, 5, 6, 7, 8] + - [5, 6, 7, 8, 9] + - name: alternating-rows + in: + heights: + - [1, 2, 3, 4, 5, 6] + - [12, 11, 10, 9, 8, 7] + - [13, 14, 15, 16, 17, 18] + - [24, 23, 22, 21, 20, 19] + - name: extreme-corners + in: + heights: + - [1, 500000, 500000] + - [500000, 500000, 1] + - [500000, 500000, 1] + - name: narrow-highway + in: + heights: + - [1000000, 999999, 999998, 999997, 999996, 999995, 999994] + - [1, 1, 1, 1, 1, 1, 1] + - [999994, 999995, 999996, 999997, 999998, 999999, 1000000] + - name: five-by-five-random + in: + heights: + - [17, 3, 29, 11, 44] + - [8, 26, 14, 35, 5] + - [31, 9, 22, 18, 40] + - [6, 27, 12, 33, 21] + - [19, 2, 38, 15, 47] + - name: six-by-six-random + in: + heights: + - [91, 12, 47, 3, 88, 25] + - [34, 76, 5, 63, 19, 54] + - [8, 42, 99, 21, 67, 10] + - [73, 16, 58, 4, 81, 36] + - [27, 65, 13, 94, 49, 2] + - [55, 7, 39, 84, 18, 70] + - name: seven-by-three + in: + heights: + - [1, 50, 2] + - [3, 49, 4] + - [5, 48, 6] + - [7, 47, 8] + - [9, 46, 10] + - [11, 45, 12] + - [13, 14, 15] + - name: three-by-seven + in: + heights: + - [1, 3, 5, 7, 9, 11, 13] + - [2, 100, 2, 100, 2, 100, 2] + - [4, 6, 8, 10, 12, 14, 16] + - name: eight-by-eight + in: + heights: + - [1, 2, 3, 4, 5, 6, 7, 8] + - [8, 7, 6, 5, 4, 3, 2, 1] + - [1, 2, 3, 4, 5, 6, 7, 8] + - [8, 7, 6, 5, 4, 3, 2, 1] + - [1, 2, 3, 4, 5, 6, 7, 8] + - [8, 7, 6, 5, 4, 3, 2, 1] + - [1, 2, 3, 4, 5, 6, 7, 8] + - [8, 7, 6, 5, 4, 3, 2, 1] + - name: nine-by-two + in: + heights: + - [100, 1] + - [99, 2] + - [98, 3] + - [97, 4] + - [96, 5] + - [95, 6] + - [94, 7] + - [93, 8] + - [9, 92] + - name: ten-by-ten + in: + heights: + - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - [2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + - [3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + - [4, 5, 6, 7, 8, 9, 10, 11, 12, 13] + - [5, 6, 7, 8, 9, 10, 11, 12, 13, 14] + - [6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + - [7, 8, 9, 10, 11, 12, 13, 14, 15, 16] + - [8, 9, 10, 11, 12, 13, 14, 15, 16, 17] + - [9, 10, 11, 12, 13, 14, 15, 16, 17, 18] + - [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] + - name: ten-by-ten-peaks + in: + heights: + - [1, 1000000, 1, 1000000, 1, 1000000, 1, 1000000, 1, 1000000] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1000000, 1, 1000000, 1, 1000000, 1, 1000000, 1, 1000000, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1000000, 1, 1000000, 1, 1000000, 1, 1000000, 1, 1000000] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1000000, 1, 1000000, 1, 1000000, 1, 1000000, 1, 1000000, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1000000, 1, 1000000, 1, 1000000, 1, 1000000, 1, 1000000] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: ten-by-one-extremes + in: + heights: + - [1] + - [1000000] + - [2] + - [999999] + - [3] + - [999998] + - [4] + - [999997] + - [5] + - [999996] + - name: one-by-ten-extremes + in: + heights: + - [1, 1000000, 2, 999999, 3, 999998, 4, 999997, 5, 999996] + - name: mixed-low-high + in: + heights: + - [500000, 500001, 1, 2, 3, 4] + - [500000, 500001, 1, 1000000, 1000000, 5] + - [500000, 500001, 1, 2, 3, 6] + - [500000, 500001, 1, 2, 3, 7] + - name: winding-corridor + in: + heights: + - [4, 4, 100, 100, 100, 100] + - [100, 4, 4, 4, 4, 100] + - [100, 100, 100, 100, 4, 100] + - [100, 100, 100, 100, 4, 4] + - [100, 100, 100, 100, 100, 4] + - name: large-values-close + in: + heights: + - [999990, 999991, 999992, 999993] + - [999989, 999988, 999987, 999986] + - [999985, 999984, 999983, 999982] + - [999981, 999980, 999979, 1000000] + - name: generated-single-row + in: + heights: + gen: array + len: 100 + of: + gen: int + min: 1 + max: 1000000 + - name: generated-single-column + in: + heights: + gen: array + len: 100 + of: + gen: array + len: 1 + of: + gen: int + min: 1 + max: 1000000 + - name: generated-medium-grid + in: + heights: + gen: array + len: 50 + of: + gen: array + len: 50 + of: + gen: int + min: 1 + max: 1000000 + - name: generated-max-grid + in: + heights: + gen: array + len: 100 + of: + gen: array + len: 100 + of: + gen: int + min: 1 + max: 1000000 diff --git a/tests/1501-2000/1631. path-with-minimum-effort/sol.cpp b/tests/1501-2000/1631. path-with-minimum-effort/sol.cpp new file mode 100644 index 00000000..404bef32 --- /dev/null +++ b/tests/1501-2000/1631. path-with-minimum-effort/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int minimumEffortPath(vector>& heights) { + if (heights.empty()) return 0; + int rows = heights.size(), cols = heights[0].size(); + priority_queue, vector>, greater<>> pq; + pq.push({0, 0, 0}); + int maxEffort = 0; + vector> visited(rows, vector(cols, false)); + int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + while (!pq.empty()) { + auto [effort, r, c] = pq.top(); + pq.pop(); + maxEffort = max(maxEffort, effort); + if (r == rows - 1 && c == cols - 1) return maxEffort; + if (visited[r][c]) continue; + visited[r][c] = true; + for (auto& d : dirs) { + int nr = r + d[0], nc = c + d[1]; + if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && !visited[nr][nc]) { + int newEffort = abs(heights[nr][nc] - heights[r][c]); + pq.push({newEffort, nr, nc}); + } + } + } + return maxEffort; + } +}; diff --git a/tests/1501-2000/1631. path-with-minimum-effort/sol.cs b/tests/1501-2000/1631. path-with-minimum-effort/sol.cs new file mode 100644 index 00000000..80236012 --- /dev/null +++ b/tests/1501-2000/1631. path-with-minimum-effort/sol.cs @@ -0,0 +1,28 @@ +public class Solution { + public int MinimumEffortPath(int[][] heights) { + if (heights.Length == 0) return 0; + int rows = heights.Length, cols = heights[0].Length; + var pq = new SortedSet<(int effort, int r, int c)>(); + pq.Add((0, 0, 0)); + int maxEffort = 0; + bool[,] visited = new bool[rows, cols]; + int[][] dirs = new int[][] { new int[] {1, 0}, new int[] {-1, 0}, new int[] {0, 1}, new int[] {0, -1} }; + while (pq.Count > 0) { + var curr = pq.Min; + pq.Remove(curr); + int effort = curr.effort, r = curr.r, c = curr.c; + maxEffort = Math.Max(maxEffort, effort); + if (r == rows - 1 && c == cols - 1) return maxEffort; + if (visited[r, c]) continue; + visited[r, c] = true; + foreach (var d in dirs) { + int nr = r + d[0], nc = c + d[1]; + if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && !visited[nr, nc]) { + int newEffort = Math.Abs(heights[nr][nc] - heights[r][c]); + pq.Add((newEffort, nr, nc)); + } + } + } + return maxEffort; + } +} diff --git a/tests/1501-2000/1631. path-with-minimum-effort/sol.dart b/tests/1501-2000/1631. path-with-minimum-effort/sol.dart new file mode 100644 index 00000000..893272d2 --- /dev/null +++ b/tests/1501-2000/1631. path-with-minimum-effort/sol.dart @@ -0,0 +1,28 @@ +class Solution { + int minimumEffortPath(List> heights) { + if (heights.isEmpty) return 0; + int rows = heights.length, cols = heights[0].length; + PriorityQueue> pq = PriorityQueue>((a, b) => a[0] - b[0]); + pq.add([0, 0, 0]); + int maxEffort = 0; + Set visited = {}; + List> dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + while (pq.isNotEmpty) { + List curr = pq.removeFirst(); + int effort = curr[0], r = curr[1], c = curr[2]; + maxEffort = max(maxEffort, effort); + if (r == rows - 1 && c == cols - 1) return maxEffort; + String key = '$r,$c'; + if (visited.contains(key)) continue; + visited.add(key); + for (List d in dirs) { + int nr = r + d[0], nc = c + d[1]; + if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && !visited.contains('$nr,$nc')) { + int newEffort = (heights[nr][nc] - heights[r][c]).abs(); + pq.add([newEffort, nr, nc]); + } + } + } + return maxEffort; + } +} diff --git a/tests/1501-2000/1631. path-with-minimum-effort/sol.go b/tests/1501-2000/1631. path-with-minimum-effort/sol.go new file mode 100644 index 00000000..0a7d062d --- /dev/null +++ b/tests/1501-2000/1631. path-with-minimum-effort/sol.go @@ -0,0 +1,60 @@ +type item struct { effort, r, c int } + +func minimumEffortPath(heights [][]int) int { + if len(heights) == 0 { + return 0 + } + rows, cols := len(heights), len(heights[0]) + pq := &itemHeap{} + heap.Init(pq) + heap.Push(pq, item{0, 0, 0}) + maxEffort := 0 + visited := make([][]bool, rows) + for i := range visited { + visited[i] = make([]bool, cols) + } + dirs := [][]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} + for pq.Len() > 0 { + curr := heap.Pop(pq).(item) + effort, r, c := curr.effort, curr.r, curr.c + if effort > maxEffort { + maxEffort = effort + } + if r == rows-1 && c == cols-1 { + return maxEffort + } + if visited[r][c] { + continue + } + visited[r][c] = true + for _, d := range dirs { + nr, nc := r+d[0], c+d[1] + if nr >= 0 && nr < rows && nc >= 0 && nc < cols && !visited[nr][nc] { + newEffort := abs(heights[nr][nc] - heights[r][c]) + heap.Push(pq, item{newEffort, nr, nc}) + } + } + } + return maxEffort +} + +type itemHeap []item + +func (h itemHeap) Len() int { return len(h) } +func (h itemHeap) Less(i, j int) bool { return h[i].effort < h[j].effort } +func (h itemHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *itemHeap) Push(x interface{}) { *h = append(*h, x.(item)) } +func (h *itemHeap) Pop() interface{} { + old := *h + n := len(old) + x := old[n-1] + *h = old[0 : n-1] + return x +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} diff --git a/tests/1501-2000/1631. path-with-minimum-effort/sol.java b/tests/1501-2000/1631. path-with-minimum-effort/sol.java new file mode 100644 index 00000000..5d9eae2b --- /dev/null +++ b/tests/1501-2000/1631. path-with-minimum-effort/sol.java @@ -0,0 +1,27 @@ +class Solution { + public int minimumEffortPath(int[][] heights) { + if (heights == null || heights.length == 0) return 0; + int rows = heights.length, cols = heights[0].length; + PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); + pq.offer(new int[]{0, 0, 0}); + int maxEffort = 0; + boolean[][] visited = new boolean[rows][cols]; + int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + while (!pq.isEmpty()) { + int[] curr = pq.poll(); + int effort = curr[0], r = curr[1], c = curr[2]; + maxEffort = Math.max(maxEffort, effort); + if (r == rows - 1 && c == cols - 1) return maxEffort; + if (visited[r][c]) continue; + visited[r][c] = true; + for (int[] d : dirs) { + int nr = r + d[0], nc = c + d[1]; + if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && !visited[nr][nc]) { + int newEffort = Math.abs(heights[nr][nc] - heights[r][c]); + pq.offer(new int[]{newEffort, nr, nc}); + } + } + } + return maxEffort; + } +} diff --git a/tests/1501-2000/1631. path-with-minimum-effort/sol.kt b/tests/1501-2000/1631. path-with-minimum-effort/sol.kt new file mode 100644 index 00000000..1f62ec5a --- /dev/null +++ b/tests/1501-2000/1631. path-with-minimum-effort/sol.kt @@ -0,0 +1,31 @@ +class Solution { + fun minimumEffortPath(heights: Array): Int { + if (heights.isEmpty()) return 0 + val rows = heights.size + val cols = heights[0].size + val pq = java.util.PriorityQueue() { a, b -> a[0] - b[0] } + pq.add(intArrayOf(0, 0, 0)) + var maxEffort = 0 + val visited = Array(rows) { BooleanArray(cols) } + val dirs = arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1)) + while (pq.isNotEmpty()) { + val curr = pq.poll() + val effort = curr[0] + val r = curr[1] + val c = curr[2] + maxEffort = maxOf(maxEffort, effort) + if (r == rows - 1 && c == cols - 1) return maxEffort + if (visited[r][c]) continue + visited[r][c] = true + for (d in dirs) { + val nr = r + d[0] + val nc = c + d[1] + if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && !visited[nr][nc]) { + val newEffort = kotlin.math.abs(heights[nr][nc] - heights[r][c]) + pq.add(intArrayOf(newEffort, nr, nc)) + } + } + } + return maxEffort + } +} diff --git a/tests/1501-2000/1631. path-with-minimum-effort/sol.py b/tests/1501-2000/1631. path-with-minimum-effort/sol.py new file mode 100644 index 00000000..415b0a99 --- /dev/null +++ b/tests/1501-2000/1631. path-with-minimum-effort/sol.py @@ -0,0 +1,42 @@ +import heapq + + +class Solution: + def minimumEffortPath(self, heights): + + if not heights: + return 0 + + rows, cols = len(heights), len(heights[0]) + + min_heap = [(0, 0, 0)] # (effort, row, col) + + max_effort = 0 + + visited = set() + + while min_heap: + effort, cur_row, cur_col = heapq.heappop(min_heap) + + max_effort = max(max_effort, effort) + + if (cur_row, cur_col) == (rows - 1, cols - 1): + return max_effort + + visited.add((cur_row, cur_col)) + + for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]: + new_row, new_col = cur_row + dr, cur_col + dc + + if ( + 0 <= new_row < rows + and 0 <= new_col < cols + and (new_row, new_col) not in visited + ): + new_effort = abs( + heights[new_row][new_col] - heights[cur_row][cur_col] + ) + + heapq.heappush(min_heap, (new_effort, new_row, new_col)) + + return max_effort diff --git a/tests/1501-2000/1631. path-with-minimum-effort/sol.py2 b/tests/1501-2000/1631. path-with-minimum-effort/sol.py2 new file mode 100644 index 00000000..3e09c2a8 --- /dev/null +++ b/tests/1501-2000/1631. path-with-minimum-effort/sol.py2 @@ -0,0 +1,25 @@ +class Solution(object): + def minimumEffortPath(self, heights): + """ + :type heights: List[List[int]] + :rtype: int + """ + import heapq + if not heights: + return 0 + rows, cols = len(heights), len(heights[0]) + min_heap = [(0, 0, 0)] + max_effort = 0 + visited = set() + while min_heap: + effort, cur_row, cur_col = heapq.heappop(min_heap) + max_effort = max(max_effort, effort) + if (cur_row, cur_col) == (rows - 1, cols - 1): + return max_effort + visited.add((cur_row, cur_col)) + for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]: + new_row, new_col = cur_row + dr, cur_col + dc + if 0 <= new_row < rows and 0 <= new_col < cols and (new_row, new_col) not in visited: + new_effort = abs(heights[new_row][new_col] - heights[cur_row][cur_col]) + heapq.heappush(min_heap, (new_effort, new_row, new_col)) + return max_effort diff --git a/tests/1501-2000/1631. path-with-minimum-effort/sol.rb b/tests/1501-2000/1631. path-with-minimum-effort/sol.rb new file mode 100644 index 00000000..9d57db3b --- /dev/null +++ b/tests/1501-2000/1631. path-with-minimum-effort/sol.rb @@ -0,0 +1,29 @@ +def minimum_effort_path(heights) + return 0 if heights.nil? || heights.empty? + rows, cols = heights.length, heights[0].length + lo, hi = 0, 1_000_000 + while lo < hi + mid = (lo + hi) / 2 + seen = Array.new(rows) { Array.new(cols, false) } + queue = [[0, 0]] + seen[0][0] = true + head = 0 + while head < queue.length + r, c = queue[head] + head += 1 + [[1,0],[-1,0],[0,1],[0,-1]].each do |dr, dc| + nr, nc = r + dr, c + dc + next unless nr >= 0 && nr < rows && nc >= 0 && nc < cols && !seen[nr][nc] + next if (heights[nr][nc] - heights[r][c]).abs > mid + seen[nr][nc] = true + queue << [nr, nc] + end + end + if seen[rows - 1][cols - 1] + hi = mid + else + lo = mid + 1 + end + end + lo +end diff --git a/tests/1501-2000/1631. path-with-minimum-effort/sol.rs b/tests/1501-2000/1631. path-with-minimum-effort/sol.rs new file mode 100644 index 00000000..4772acfc --- /dev/null +++ b/tests/1501-2000/1631. path-with-minimum-effort/sol.rs @@ -0,0 +1,39 @@ +impl Solution { + pub fn minimum_effort_path(heights: Vec>) -> i32 { + if heights.is_empty() { + return 0; + } + let rows = heights.len(); + let cols = heights[0].len(); + use std::collections::BinaryHeap; + use std::cmp::Reverse; + let mut pq: BinaryHeap> = BinaryHeap::new(); + pq.push(Reverse((0, 0, 0))); + let mut max_effort = 0; + let mut visited = vec![vec![false; cols]; rows]; + let dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]; + while let Some(Reverse((effort, r, c))) = pq.pop() { + max_effort = max_effort.max(effort); + if r == rows - 1 && c == cols - 1 { + return max_effort; + } + if visited[r][c] { + continue; + } + visited[r][c] = true; + for &(dr, dc) in &dirs { + let nr = r as i32 + dr; + let nc = c as i32 + dc; + if nr >= 0 && nr < rows as i32 && nc >= 0 && nc < cols as i32 { + let nr = nr as usize; + let nc = nc as usize; + if !visited[nr][nc] { + let new_effort = (heights[nr][nc] - heights[r][c]).abs(); + pq.push(Reverse((new_effort, nr, nc))); + } + } + } + } + max_effort + } +} diff --git a/tests/1501-2000/1631. path-with-minimum-effort/sol.swift b/tests/1501-2000/1631. path-with-minimum-effort/sol.swift new file mode 100644 index 00000000..00ed7cd9 --- /dev/null +++ b/tests/1501-2000/1631. path-with-minimum-effort/sol.swift @@ -0,0 +1,32 @@ +class Solution { + struct Node: Comparable { + let effort: Int + let r: Int + let c: Int + static func < (a: Node, b: Node) -> Bool { a.effort != b.effort ? a.effort < b.effort : (a.r, a.c) < (b.r, b.c) } + } + func minimumEffortPath(_ heights: [[Int]]) -> Int { + if heights.isEmpty { return 0 } + let rows = heights.count, cols = heights[0].count + var pq = Heap() + pq.insert(Node(effort: 0, r: 0, c: 0)) + var maxEffort = 0 + var visited = Set<[Int]>() + let dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]] + while let curr = pq.popMin() { + let effort = curr.effort, r = curr.r, c = curr.c + maxEffort = max(maxEffort, effort) + if r == rows - 1 && c == cols - 1 { return maxEffort } + if visited.contains([r, c]) { continue } + visited.insert([r, c]) + for d in dirs { + let nr = r + d[0], nc = c + d[1] + if nr >= 0 && nr < rows && nc >= 0 && nc < cols && !visited.contains([nr, nc]) { + let newEffort = abs(heights[nr][nc] - heights[r][c]) + pq.insert(Node(effort: newEffort, r: nr, c: nc)) + } + } + } + return maxEffort + } +} diff --git a/tests/1501-2000/1631. path-with-minimum-effort/sol.ts b/tests/1501-2000/1631. path-with-minimum-effort/sol.ts new file mode 100644 index 00000000..76ce0826 --- /dev/null +++ b/tests/1501-2000/1631. path-with-minimum-effort/sol.ts @@ -0,0 +1,45 @@ +function minimumEffortPath(heights: number[][]): number { + if (heights.length === 0) return 0; + const rows = heights.length, + cols = heights[0].length; + const pq: number[][] = [[0, 0, 0]]; + const push = (x: number[]) => { + pq.push(x); + pq.sort((a, b) => a[0] - b[0]); + }; + push([0, 0, 0]); + let maxEffort = 0; + const visited = new Set(); + const dirs = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ]; + while (pq.length > 0) { + const curr = pq.shift()!; + const effort = curr[0], + r = curr[1], + c = curr[2]; + maxEffort = Math.max(maxEffort, effort); + if (r === rows - 1 && c === cols - 1) return maxEffort; + const key = `${r},${c}`; + if (visited.has(key)) continue; + visited.add(key); + for (const d of dirs) { + const nr = r + d[0], + nc = c + d[1]; + if ( + nr >= 0 && + nr < rows && + nc >= 0 && + nc < cols && + !visited.has(`${nr},${nc}`) + ) { + const newEffort = Math.abs(heights[nr][nc] - heights[r][c]); + push([newEffort, nr, nc]); + } + } + } + return maxEffort; +} diff --git a/tests/1501-2000/1632. rank-transform-of-a-matrix/manifest.yaml b/tests/1501-2000/1632. rank-transform-of-a-matrix/manifest.yaml new file mode 100644 index 00000000..b3166169 --- /dev/null +++ b/tests/1501-2000/1632. rank-transform-of-a-matrix/manifest.yaml @@ -0,0 +1,366 @@ +entry: + id: 1632 + title: "rank-transform-of-a-matrix" + params: + matrix: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().matrixRankTransform({matrix})" + rust: "Solution::matrix_rank_transform({matrix})" + python3: "Solution().matrixRankTransform({matrix})" + python2: "Solution().matrixRankTransform({matrix})" + ruby: "matrix_rank_transform({matrix})" + java: "new Solution().matrixRankTransform({matrix})" + csharp: "new Solution().MatrixRankTransform({matrix})" + kotlin: "Solution().matrixRankTransform({matrix})" + go: "matrixRankTransform({matrix})" + dart: "Solution().matrixRankTransform({matrix})" + swift: "Solution().matrixRankTransform({matrix})" + typescript: "matrixRankTransform({matrix})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().matrixRankTransform(matrix, {result})" + checker: | + class Checker: + def matrixRankTransform(self, matrix, result): + if not isinstance(result, list) or len(result) != len(matrix): + return False + if not matrix or not isinstance(result[0], list): + return False + m, n = len(matrix), len(matrix[0]) + if n == 0 or any(not isinstance(row, list) or len(row) != n for row in matrix): + return False + if any(not isinstance(row, list) or len(row) != n for row in result): + return False + expected = [[0] * n for _ in range(m)] + best_row = [0] * m + best_col = [0] * n + groups = {} + for i in range(m): + for j in range(n): + groups.setdefault(matrix[i][j], []).append((i, j)) + for value in sorted(groups): + cells = groups[value] + parent = list(range(m + n)) + def find(x): + while parent[x] != x: + parent[x] = parent[parent[x]] + x = parent[x] + return x + for i, j in cells: + a, b = find(i), find(m + j) + if a != b: + parent[a] = b + comp_max = {} + for i, j in cells: + root = find(i) + comp_max[root] = max(comp_max.get(root, 0), best_row[i], best_col[j]) + assigned = {} + for i, j in cells: + root = find(i) + assigned[root] = comp_max[root] + 1 + for i, j in cells: + rank = assigned[find(i)] + expected[i][j] = rank + best_row[i] = max(best_row[i], rank) + best_col[j] = max(best_col[j], rank) + return result == expected + +seed: 1632 + +tests: + - name: single + in: + matrix: + - [5] + - name: all-equal-2x2 + in: + matrix: + - [7, 7] + - [7, 7] + - name: example-one + in: + matrix: + - [1, 2] + - [3, 4] + - name: example-three + in: + matrix: + - [20, -21, 14] + - [-19, 4, 19] + - [22, -47, 24] + - [-19, 4, 19] + - name: one-row + in: + matrix: + - [4, 1, 9, 1, 7] + - name: one-column + in: + matrix: + - [4] + - [1] + - [9] + - [1] + - [7] + - name: negatives + in: + matrix: + - [-3, -2, -1] + - [-6, -5, -4] + - name: repeated-components + in: + matrix: + - [1, 1, 2] + - [3, 1, 2] + - [3, 4, 2] + - name: duplicate-diagonal + in: + matrix: + - [2, 1, 2] + - [1, 2, 1] + - [2, 1, 2] + - name: descending + in: + matrix: + - [9, 8, 7] + - [6, 5, 4] + - [3, 2, 1] + - name: sparse-large-gaps + in: + matrix: + - [-1000000000, 0, 1000000000] + - [1000000000, -1000000000, 0] + - name: rectangular-2x4 + in: + matrix: + - [8, 3, 8, 2] + - [4, 9, 1, 9] + - name: rectangular-4x2 + in: + matrix: + - [8, 3] + - [8, 2] + - [4, 9] + - [1, 9] + - name: bridge-equalities + in: + matrix: + - [1, 5, 5, 9] + - [2, 5, 7, 9] + - [5, 6, 7, 10] + - name: all-distinct + in: + matrix: + - [11, 2, 19] + - [7, 13, 5] + - name: checkerboard + in: + matrix: + - [0, 1, 0, 1] + - [1, 0, 1, 0] + - [0, 1, 0, 1] + - name: zeros-and-positives + in: + matrix: + - [0, 0, 3] + - [0, 2, 3] + - [1, 2, 4] + - name: mixed-sign-4x4 + in: + matrix: + - [-4, 2, -1, 8] + - [3, -4, 6, 0] + - [7, 2, -1, 8] + - [3, 5, 6, -2] + - name: narrow-3x2 + in: + matrix: + - [3, 3] + - [2, 1] + - [4, 2] + - name: wide-2x6 + in: + matrix: + - [5, 1, 5, 2, 9, 3] + - [4, 8, 0, 2, 9, 3] + - name: equal-row-chains + in: + matrix: + - [1, 2, 3, 4] + - [1, 2, 3, 4] + - [0, 2, 3, 5] + - name: equal-column-chains + in: + matrix: + - [1, 1, 0] + - [2, 2, 2] + - [3, 3, 4] + - [5, 5, 6] + - name: isolated-equalities + in: + matrix: + - [6, 2, 4] + - [3, 6, 1] + - [5, 0, 6] + - name: four-equal + in: + matrix: + - [4, 4, 1] + - [2, 4, 3] + - [4, 0, 4] + - name: extreme-corners + in: + matrix: + - [-1000000000, 5] + - [5, 1000000000] + - name: repeated-negative + in: + matrix: + - [-2, -2, -3] + - [-1, -2, -3] + - [-1, 0, 0] + - name: 5x1 + in: + matrix: + - [0] + - [0] + - [-1] + - [1] + - [0] + - name: 1x7 + in: + matrix: + - [7, 7, 6, 5, 6, 8, 5] + - name: 5x5-pattern + in: + matrix: + - [1, 2, 3, 4, 5] + - [5, 4, 3, 2, 1] + - [2, 3, 4, 5, 1] + - [4, 5, 1, 2, 3] + - [3, 1, 5, 4, 2] + - name: 3x5-pattern + in: + matrix: + - [10, 0, 10, 0, 10] + - [0, 10, 0, 10, 0] + - [5, 5, 5, 5, 5] + - name: 6x3-pattern + in: + matrix: + - [2, 8, 2] + - [3, 7, 3] + - [4, 6, 4] + - [5, 5, 5] + - [6, 4, 6] + - [7, 3, 7] + - name: alternating-extremes + in: + matrix: + - [-1000000000, 1000000000, -1000000000] + - [1000000000, -1000000000, 1000000000] + - name: uniform-3x4 + in: + matrix: + - [12, 12, 12, 12] + - [12, 12, 12, 12] + - [12, 12, 12, 12] + - name: 4x5-small + in: + matrix: + - [0, 1, 2, 3, 4] + - [4, 3, 2, 1, 0] + - [2, 2, 2, 2, 2] + - [1, 3, 0, 4, 2] + - name: 7x2-values + in: + matrix: + - [1, 9] + - [2, 8] + - [3, 7] + - [4, 6] + - [5, 5] + - [6, 4] + - [7, 3] + - name: gen-1x20 + in: + matrix: + gen: "array" + len: 1 + of: + gen: "array" + len: 20 + of: + gen: "int" + min: -1000000000 + max: 1000000000 + elemType: "int" + seed: 163201 + - name: gen-20x1 + in: + matrix: + gen: "array" + len: 20 + of: + gen: "array" + len: 1 + of: + gen: "int" + min: -1000000000 + max: 1000000000 + elemType: "int" + seed: 163202 + - name: gen-10x10 + in: + matrix: + gen: "array" + len: 10 + of: + gen: "array" + len: 10 + of: + gen: "int" + min: -1000 + max: 1000 + elemType: "int" + seed: 163203 + - name: gen-25x16 + in: + matrix: + gen: "array" + len: 25 + of: + gen: "array" + len: 16 + of: + gen: "int" + min: -1000000000 + max: 1000000000 + elemType: "int" + seed: 163204 + - name: gen-100x100 + in: + matrix: + gen: "array" + len: 100 + of: + gen: "array" + len: 100 + of: + gen: "int" + min: -1000000000 + max: 1000000000 + elemType: "int" + seed: 163205 diff --git a/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.cpp b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.cpp new file mode 100644 index 00000000..66ab3825 --- /dev/null +++ b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + vector> matrixRankTransform(vector>& matrix) { + int m = matrix.size(), n = matrix[0].size(); + unordered_map>> mp; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + mp[matrix[i][j]].push_back({i, j}); + } + } + + vector rank(m+n, 0); + vector> ans(m, vector(n, 0)); + + vector keys; + for (auto& p : mp) keys.push_back(p.first); + sort(keys.begin(), keys.end()); + + for (int k : keys) { + vector parent(m+n); + iota(parent.begin(), parent.end(), 0); + function find = [&](int p) { + if (p != parent[p]) parent[p] = find(parent[p]); + return parent[p]; + }; + + for (auto& cell : mp[k]) { + int i = cell.first, j = cell.second; + int ii = find(i); + int jj = find(m+j); + parent[ii] = jj; + rank[jj] = max(rank[ii], rank[jj]); + } + + unordered_set seen; + for (auto& cell : mp[k]) { + int i = cell.first, j = cell.second; + int ii = find(i); + if (!seen.count(ii)) rank[ii] += 1; + seen.insert(ii); + int v = rank[ii]; + rank[i] = rank[m+j] = ans[i][j] = v; + } + } + return ans; + } +}; diff --git a/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.cs b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.cs new file mode 100644 index 00000000..edbbde6c --- /dev/null +++ b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.cs @@ -0,0 +1,46 @@ +public class Solution { + public int[][] MatrixRankTransform(int[][] matrix) { + int m = matrix.Length, n = matrix[0].Length; + var mp = new Dictionary>(); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (!mp.ContainsKey(matrix[i][j])) mp[matrix[i][j]] = new List<(int, int)>(); + mp[matrix[i][j]].Add((i, j)); + } + } + + int[] rank = new int[m+n]; + int[][] ans = new int[m][]; + for (int i = 0; i < m; i++) ans[i] = new int[n]; + + var keys = mp.Keys.ToList(); + keys.Sort(); + foreach (int k in keys) { + int[] parent = Enumerable.Range(0, m+n).ToArray(); + Func find = null; + find = p => { + if (p != parent[p]) parent[p] = find(parent[p]); + return parent[p]; + }; + + foreach (var cell in mp[k]) { + int i = cell.Item1, j = cell.Item2; + int ii = find(i); + int jj = find(m+j); + parent[ii] = jj; + rank[jj] = Math.Max(rank[ii], rank[jj]); + } + + var seen = new HashSet(); + foreach (var cell in mp[k]) { + int i = cell.Item1, j = cell.Item2; + int ii = find(i); + if (!seen.Contains(ii)) rank[ii] += 1; + seen.Add(ii); + int v = rank[ii]; + rank[i] = rank[m+j] = ans[i][j] = v; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.dart b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.dart new file mode 100644 index 00000000..a6a3df72 --- /dev/null +++ b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.dart @@ -0,0 +1,45 @@ +class Solution { + List> matrixRankTransform(List> matrix) { + int m = matrix.length, n = matrix[0].length; + Map>> mp = {}; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + mp.putIfAbsent(matrix[i][j], () => []).add([i, j]); + } + } + + List rank = List.filled(m+n, 0); + List> ans = List.generate(m, (_) => List.filled(n, 0)); + + List keys = mp.keys.toList()..sort(); + for (int k in keys) { + List parent = List.generate(m+n, (i) => i); + late int Function(int) find; + find = (int p) { + if (p != parent[p]) parent[p] = find(parent[p]); + return parent[p]; + }; + + for (var cell in mp[k]!) { + int i = cell[0], j = cell[1]; + int ii = find(i); + int jj = find(m+j); + parent[ii] = jj; + rank[jj] = rank[ii] > rank[jj] ? rank[ii] : rank[jj]; + } + + Set seen = {}; + for (var cell in mp[k]!) { + int i = cell[0], j = cell[1]; + int ii = find(i); + if (!seen.contains(ii)) rank[ii]++; + seen.add(ii); + int v = rank[ii]; + rank[i] = v; + rank[m+j] = v; + ans[i][j] = v; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.go b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.go new file mode 100644 index 00000000..6cc39fbc --- /dev/null +++ b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.go @@ -0,0 +1,52 @@ +func matrixRankTransform(matrix [][]int) [][]int { + m, n := len(matrix), len(matrix[0]) + mp := make(map[int][][2]int) + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + mp[matrix[i][j]] = append(mp[matrix[i][j]], [2]int{i, j}) + } + } + + rank := make([]int, m+n) + ans := make([][]int, m) + for i := range ans { ans[i] = make([]int, n) } + + keys := make([]int, 0, len(mp)) + for k := range mp { keys = append(keys, k) } + sort.Ints(keys) + + for _, k := range keys { + parent := make([]int, m+n) + for i := range parent { parent[i] = i } + var find func(int) int + find = func(p int) int { + if p != parent[p] { + parent[p] = find(parent[p]) + } + return parent[p] + } + + for _, cell := range mp[k] { + i, j := cell[0], cell[1] + ii := find(i) + jj := find(m+j) + parent[ii] = jj + if rank[ii] > rank[jj] { rank[jj] = rank[ii] } + } + + seen := make(map[int]bool) + for _, cell := range mp[k] { + i, j := cell[0], cell[1] + ii := find(i) + if !seen[ii] { + rank[ii]++ + } + seen[ii] = true + v := rank[ii] + rank[i] = v + rank[m+j] = v + ans[i][j] = v + } + } + return ans +} diff --git a/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.java b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.java new file mode 100644 index 00000000..3542dbf6 --- /dev/null +++ b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.java @@ -0,0 +1,41 @@ +class Solution { + public int[][] matrixRankTransform(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + Map> mp = new HashMap<>(); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + mp.computeIfAbsent(matrix[i][j], k -> new ArrayList<>()).add(new int[]{i, j}); + } + } + + int[] rank = new int[m+n]; + int[][] ans = new int[m][n]; + + int[] parent = new int[m+n]; + for (int k : mp.keySet().stream().sorted().mapToInt(Integer::intValue).toArray()) { + for (int p = 0; p < m+n; p++) parent[p] = p; + for (int[] cell : mp.get(k)) { + int i = cell[0], j = cell[1]; + int ii = i; while (ii != parent[ii]) ii = parent[ii]; + int jj = m+j; while (jj != parent[jj]) jj = parent[jj]; + parent[ii] = jj; + rank[jj] = Math.max(rank[ii], rank[jj]); + } + + Set seen = new HashSet<>(); + for (int[] cell : mp.get(k)) { + int i = cell[0], j = cell[1]; + int ii = i; while (ii != parent[ii]) ii = parent[ii]; + if (!seen.contains(ii)) { + rank[ii] += 1; + } + seen.add(ii); + int val = rank[ii]; + rank[i] = val; + rank[m+j] = val; + ans[i][j] = val; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.kt b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.kt new file mode 100644 index 00000000..c94ab1d3 --- /dev/null +++ b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.kt @@ -0,0 +1,42 @@ +class Solution { + fun matrixRankTransform(matrix: Array): Array { + val m = matrix.size + val n = matrix[0].size + val mp = mutableMapOf>>() + for (i in 0 until m) { + for (j in 0 until n) { + mp.getOrPut(matrix[i][j]) { mutableListOf() }.add(i to j) + } + } + + val rank = IntArray(m+n) + val ans = Array(m) { IntArray(n) } + + for (k in mp.keys.sorted()) { + val parent = IntArray(m+n) { it } + fun find(p: Int): Int { + if (p != parent[p]) parent[p] = find(parent[p]) + return parent[p] + } + + for ((i, j) in mp[k]!!) { + val ii = find(i) + val jj = find(m+j) + parent[ii] = jj + rank[jj] = maxOf(rank[ii], rank[jj]) + } + + val seen = mutableSetOf() + for ((i, j) in mp[k]!!) { + val ii = find(i) + if (ii !in seen) rank[ii] += 1 + seen.add(ii) + val v = rank[ii] + rank[i] = v + rank[m+j] = v + ans[i][j] = v + } + } + return ans + } +} diff --git a/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.py b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.py new file mode 100644 index 00000000..0c76a056 --- /dev/null +++ b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.py @@ -0,0 +1,36 @@ +from typing import List + + +class Solution: + def matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]: + m, n = len(matrix), len(matrix[0]) # dimension + # mapping from value to index + mp = {} + for i in range(m): + for j in range(n): + mp.setdefault(matrix[i][j], []).append((i, j)) + + def find(p): + """Find root of p.""" + if p != parent[p]: + parent[p] = find(parent[p]) + return parent[p] + + rank = [0] * (m + n) + ans = [[0] * n for _ in range(m)] + + for k in sorted(mp): # from minimum to maximum + parent = list(range(m + n)) + for i, j in mp[k]: + ii, jj = find(i), find(m + j) # find + parent[ii] = jj # union + rank[jj] = max(rank[ii], rank[jj]) # max rank + + seen = set() + for i, j in mp[k]: + ii = find(i) + if ii not in seen: + rank[ii] += 1 + seen.add(ii) + rank[i] = rank[m + j] = ans[i][j] = rank[ii] + return ans diff --git a/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.py2 b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.py2 new file mode 100644 index 00000000..74a9c87c --- /dev/null +++ b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.py2 @@ -0,0 +1,35 @@ +class Solution(object): + def matrixRankTransform(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: List[List[int]] + """ + m, n = len(matrix), len(matrix[0]) + mp = {} + for i in range(m): + for j in range(n): + mp.setdefault(matrix[i][j], []).append((i, j)) + + def find(p): + if p != parent[p]: + parent[p] = find(parent[p]) + return parent[p] + + rank = [0]*(m+n) + ans = [[0]*n for _ in range(m)] + + for k in sorted(mp): + parent = list(range(m+n)) + for i, j in mp[k]: + ii, jj = find(i), find(m+j) + parent[ii] = jj + rank[jj] = max(rank[ii], rank[jj]) + + seen = set() + for i, j in mp[k]: + ii = find(i) + if ii not in seen: + rank[ii] += 1 + seen.add(ii) + rank[i] = rank[m+j] = ans[i][j] = rank[ii] + return ans diff --git a/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.rb b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.rb new file mode 100644 index 00000000..779b9a30 --- /dev/null +++ b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.rb @@ -0,0 +1,43 @@ +# @param {Integer[][]} matrix +# @return {Integer[][]} +def matrix_rank_transform(matrix) + m, n = matrix.size, matrix[0].size + mp = Hash.new { |h, k| h[k] = [] } + (0...m).each do |i| + (0...n).each do |j| + mp[matrix[i][j]] << [i, j] + end + end + + rank = Array.new(m+n, 0) + ans = Array.new(m) { Array.new(n, 0) } + + mp.keys.sort.each do |k| + parent = (0...(m+n)).to_a + find = lambda do |p| + if p != parent[p] + parent[p] = find.call(parent[p]) + end + parent[p] + end + + mp[k].each do |i, j| + ii = find.call(i) + jj = find.call(m+j) + parent[ii] = jj + rank[jj] = [rank[ii], rank[jj]].max + end + + seen = {} + mp[k].each do |i, j| + ii = find.call(i) + unless seen[ii] + rank[ii] += 1 + end + seen[ii] = true + val = rank[ii] + rank[i] = rank[m+j] = ans[i][j] = val + end + end + ans +end diff --git a/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.rs b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.rs new file mode 100644 index 00000000..31d00ded --- /dev/null +++ b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.rs @@ -0,0 +1,49 @@ +impl Solution { + pub fn matrix_rank_transform(matrix: Vec>) -> Vec> { + let m = matrix.len(); + let n = matrix[0].len(); + let mut mp: std::collections::HashMap> = std::collections::HashMap::new(); + for i in 0..m { + for j in 0..n { + mp.entry(matrix[i][j]).or_default().push((i, j)); + } + } + + let mut rank = vec![0; m+n]; + let mut ans = vec![vec![0; n]; m]; + + let mut keys: Vec = mp.keys().cloned().collect(); + keys.sort(); + + for k in keys { + let mut parent: Vec = (0..m+n).collect(); + fn find(p: usize, parent: &mut Vec) -> usize { + if p != parent[p] { + parent[p] = find(parent[p], parent); + } + parent[p] + } + + for &(i, j) in &mp[&k] { + let ii = find(i, &mut parent); + let jj = find(m+j, &mut parent); + parent[ii] = jj; + if rank[ii] > rank[jj] { rank[jj] = rank[ii]; } + } + + let mut seen = std::collections::HashSet::new(); + for &(i, j) in &mp[&k] { + let ii = find(i, &mut parent); + if !seen.contains(&ii) { + rank[ii] += 1; + } + seen.insert(ii); + let v = rank[ii]; + rank[i] = v; + rank[m+j] = v; + ans[i][j] = v; + } + } + ans + } +} diff --git a/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.swift b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.swift new file mode 100644 index 00000000..8080ddcb --- /dev/null +++ b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.swift @@ -0,0 +1,41 @@ +class Solution { + func matrixRankTransform(_ matrix: [[Int]]) -> [[Int]] { + let m = matrix.count, n = matrix[0].count + var mp: [Int: [(Int, Int)]] = [:] + for i in 0.. Int { + if p != parent[p] { parent[p] = find(parent[p]) } + return parent[p] + } + + for (i, j) in mp[k]! { + let ii = find(i) + let jj = find(m+j) + parent[ii] = jj + rank[jj] = max(rank[ii], rank[jj]) + } + + var seen = Set() + for (i, j) in mp[k]! { + let ii = find(i) + if !seen.contains(ii) { rank[ii] += 1 } + seen.insert(ii) + let v = rank[ii] + rank[i] = v + rank[m+j] = v + ans[i][j] = v + } + } + return ans + } +} diff --git a/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.ts b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.ts new file mode 100644 index 00000000..0ba581c3 --- /dev/null +++ b/tests/1501-2000/1632. rank-transform-of-a-matrix/sol.ts @@ -0,0 +1,41 @@ +function matrixRankTransform(matrix: number[][]): number[][] { + const m = matrix.length, + n = matrix[0].length; + const mp = new Map(); + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + const v = matrix[i][j]; + if (!mp.has(v)) mp.set(v, []); + mp.get(v)!.push([i, j]); + } + } + + const rank = new Array(m + n).fill(0); + const ans: number[][] = Array.from({ length: m }, () => new Array(n).fill(0)); + + const keys = Array.from(mp.keys()).sort((a, b) => a - b); + for (const k of keys) { + const parent = Array.from({ length: m + n }, (_, i) => i); + const find = (p: number): number => { + if (p !== parent[p]) parent[p] = find(parent[p]); + return parent[p]; + }; + + for (const [i, j] of mp.get(k)!) { + const ii = find(i); + const jj = find(m + j); + parent[ii] = jj; + rank[jj] = Math.max(rank[ii], rank[jj]); + } + + const seen = new Set(); + for (const [i, j] of mp.get(k)!) { + const ii = find(i); + if (!seen.has(ii)) rank[ii] += 1; + seen.add(ii); + const v = rank[ii]; + rank[i] = rank[m + j] = ans[i][j] = v; + } + } + return ans; +} diff --git a/tests/1501-2000/1636. sort-array-by-increasing-frequency/manifest.yaml b/tests/1501-2000/1636. sort-array-by-increasing-frequency/manifest.yaml new file mode 100644 index 00000000..cb3428d5 --- /dev/null +++ b/tests/1501-2000/1636. sort-array-by-increasing-frequency/manifest.yaml @@ -0,0 +1,225 @@ +entry: + id: 1636 + title: "sort-array-by-increasing-frequency" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().frequencySort({nums})" + rust: "Solution::frequency_sort({nums})" + python3: "Solution().frequencySort({nums})" + python2: "Solution().frequencySort({nums})" + ruby: "frequency_sort({nums})" + java: "new Solution().frequencySort({nums})" + csharp: "new Solution().FrequencySort({nums})" + kotlin: "Solution().frequencySort({nums})" + go: "frequencySort({nums})" + dart: "Solution().frequencySort({nums})" + swift: "Solution().frequencySort({nums})" + typescript: "frequencySort({nums})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().frequencySort(nums, {result})" + checker: | + from collections import Counter + + class Checker: + def frequencySort(self, nums, result): + if not isinstance(result, list) or len(result) != len(nums): + return False + if Counter(result) != Counter(nums): + return False + freq = Counter(nums) + return result == sorted(nums, key=lambda x: (freq[x], -x)) + +seed: 1636 + +tests: + - name: example-1 + in: + nums: [1, 1, 2, 2, 2, 3] + out: [3, 1, 1, 2, 2, 2] + - name: example-2 + in: + nums: [2, 3, 1, 3, 2] + out: [1, 3, 3, 2, 2] + - name: example-3 + in: + nums: [-1, 1, -6, 4, 5, -6, 1, 4, 1] + out: [5, -1, 4, 4, -6, -6, 1, 1, 1] + - name: two-distinct-equal-frequency + in: + nums: [4, 2] + out: [4, 2] + - name: two-distinct-reversed + in: + nums: [2, 4] + out: [4, 2] + - name: singleton-negative + in: + nums: [-100] + out: [-100] + - name: all-equal + in: + nums: [7, 7, 7, 7, 7] + out: [7, 7, 7, 7, 7] + - name: all-distinct-ascending + in: + nums: [1, 2, 3, 4, 5, 6] + out: [6, 5, 4, 3, 2, 1] + - name: all-distinct-descending + in: + nums: [6, 5, 4, 3, 2, 1] + out: [6, 5, 4, 3, 2, 1] + - name: negatives + in: + nums: [-1, -2, -3, -4, -5] + out: [-1, -2, -3, -4, -5] + - name: mixed-extremes + in: + nums: [-100, 100, -100, 0, 100, 100] + out: [0, -100, -100, 100, 100, 100] + - name: frequency-one-tie + in: + nums: [0, -1, 1, 2] + out: [2, 1, 0, -1] + - name: frequency-two-tie + in: + nums: [1, 2, 3, 1, 2, 3] + out: [3, 3, 2, 2, 1, 1] + - name: three-frequency-levels + in: + nums: [1, 2, 2, 3, 3, 3] + out: [1, 2, 2, 3, 3, 3] + - name: negative-tie-order + in: + nums: [-5, -2, -5, -2, 0] + out: [0, -2, -2, -5, -5] + - name: zero-and-extremes + in: + nums: [100, -100, 0, 100, -100, 0, 0] + out: [100, 100, -100, -100, 0, 0, 0] + - name: repeated-blocks + in: + nums: [3, 3, 1, 1, 1, 2, 2, 4, 4, 4, 4] + out: [3, 3, 2, 2, 1, 1, 1, 4, 4, 4, 4] + - name: alternating + in: + nums: [5, -5, 5, -5, 4, -4, 4, -4, 0] + out: [0, 5, 5, 4, 4, -4, -4, -5, -5] + - name: near-lower-bound + in: + nums: [-99, -98, -99, -97, -98, -98] + out: [-97, -99, -99, -98, -98, -98] + - name: near-upper-bound + in: + nums: [97, 98, 97, 99, 98, 98] + out: [99, 97, 97, 98, 98, 98] + - name: seven-values + in: + nums: [7, 6, 5, 4, 3, 2, 1, 7, 6, 5, 4, 3, 2] + out: [1, 7, 7, 6, 6, 5, 5, 4, 4, 3, 3, 2, 2] + - name: nested-frequency + in: + nums: [0, 0, 1, 1, 1, 2, 2, 2, 2, -1, -1, -1, -1, -1] + out: [0, 0, 1, 1, 1, 2, 2, 2, 2, -1, -1, -1, -1, -1] + - name: duplicate-extreme-tie + in: + nums: [-100, 100, -100, 100, 99, -99] + out: [99, -99, 100, 100, -100, -100] + - name: zeros-and-negatives + in: + nums: [0, 0, 0, -1, -1, -2, -2, -2, -3] + out: [-3, -1, -1, 0, 0, 0, -2, -2, -2] + - name: four-frequency-levels + in: + nums: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] + out: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] + - name: same-frequency-negative-values + in: + nums: [-10, -20, -30, -10, -20, -30, -40] + out: [-40, -10, -10, -20, -20, -30, -30] + - name: boundary-values-distinct + in: + nums: [-100, -99, 99, 100] + out: [100, 99, -99, -100] + - name: repeated-one-and-negative + in: + nums: [1, -1, 1, -1, 1, 2, 2, 0] + out: [0, 2, 2, -1, -1, 1, 1, 1] + - name: eight-distinct + in: + nums: [8, 1, 7, 2, 6, 3, 5, 4] + out: [8, 7, 6, 5, 4, 3, 2, 1] + - name: large-single-frequency + in: + nums: [9, 9, 9, 9, 9, 9, 9, -1, -1, 4, 4, 0] + out: [0, 4, 4, -1, -1, 9, 9, 9, 9, 9, 9, 9] + - name: mixed-sign-ties + in: + nums: [-3, 3, -3, 3, -2, 2, -2, 2, -1] + out: [-1, 3, 3, 2, 2, -2, -2, -3, -3] + - name: max-length-pattern + in: + nums: [1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] + out: [14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 3, 2, 2, 2, 1, 1, 1, 1] + - name: gen-small + in: + nums: + gen: "array" + len: 2 + of: + gen: "int" + min: -100 + max: 100 + elemType: "int" + - name: gen-medium + in: + nums: + gen: "array" + len: 25 + of: + gen: "int" + min: -100 + max: 100 + elemType: "int" + - name: gen-dense + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: -10 + max: 10 + elemType: "int" + - name: gen-wide-values + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: -100 + max: 100 + elemType: "int" + - name: gen-heavy-duplicates + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: -2 + max: 2 + elemType: "int" diff --git a/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.cpp b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.cpp new file mode 100644 index 00000000..88cedc2d --- /dev/null +++ b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector frequencySort(vector& nums) { + unordered_map freq; + for (int num : nums) { + freq[num]++; + } + sort(nums.begin(), nums.end(), [&](int a, int b) { + if (freq[a] != freq[b]) { + return freq[a] < freq[b]; + } + return a > b; + }); + return nums; + } +}; diff --git a/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.cs b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.cs new file mode 100644 index 00000000..4093cffe --- /dev/null +++ b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int[] FrequencySort(int[] nums) { + var freq = new Dictionary(); + foreach (int num in nums) { + if (freq.ContainsKey(num)) freq[num]++; + else freq[num] = 1; + } + Array.Sort(nums, (a, b) => { + int freqCompare = freq[a].CompareTo(freq[b]); + if (freqCompare != 0) return freqCompare; + return b.CompareTo(a); + }); + return nums; + } +} diff --git a/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.dart b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.dart new file mode 100644 index 00000000..b745d178 --- /dev/null +++ b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.dart @@ -0,0 +1,14 @@ +class Solution { + List frequencySort(List nums) { + Map freq = {}; + for (int num in nums) { + freq[num] = (freq[num] ?? 0) + 1; + } + nums.sort((a, b) { + int freqCompare = freq[a]!.compareTo(freq[b]!); + if (freqCompare != 0) return freqCompare; + return b.compareTo(a); + }); + return nums; + } +} diff --git a/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.go b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.go new file mode 100644 index 00000000..d7b9a379 --- /dev/null +++ b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.go @@ -0,0 +1,13 @@ +func frequencySort(nums []int) []int { + freq := make(map[int]int) + for _, num := range nums { + freq[num]++ + } + sort.Slice(nums, func(i, j int) bool { + if freq[nums[i]] != freq[nums[j]] { + return freq[nums[i]] < freq[nums[j]] + } + return nums[i] > nums[j] + }) + return nums +} diff --git a/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.java b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.java new file mode 100644 index 00000000..419f865c --- /dev/null +++ b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.java @@ -0,0 +1,17 @@ +class Solution { + public int[] frequencySort(int[] nums) { + java.util.Map freq = new java.util.HashMap<>(); + for (int num : nums) { + freq.put(num, freq.getOrDefault(num, 0) + 1); + } + return java.util.Arrays.stream(nums) + .boxed() + .sorted((a, b) -> { + int freqCompare = Integer.compare(freq.get(a), freq.get(b)); + if (freqCompare != 0) return freqCompare; + return Integer.compare(b, a); + }) + .mapToInt(Integer::intValue) + .toArray(); + } +} diff --git a/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.kt b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.kt new file mode 100644 index 00000000..ea5f9319 --- /dev/null +++ b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.kt @@ -0,0 +1,7 @@ +class Solution { + fun frequencySort(nums: IntArray): IntArray { + val freq = HashMap() + for (value in nums) freq[value] = (freq[value] ?: 0) + 1 + return nums.sortedWith(compareBy({ freq[it] }, { -it })).toIntArray() + } +} diff --git a/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.py b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.py new file mode 100644 index 00000000..9ba3169b --- /dev/null +++ b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.py @@ -0,0 +1,7 @@ +from collections import Counter + + +class Solution: + def frequencySort(self, nums): + freq = Counter(nums) + return sorted(nums, key=lambda x: (freq[x], -x)) diff --git a/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.py2 b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.py2 new file mode 100644 index 00000000..5d3263bc --- /dev/null +++ b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.py2 @@ -0,0 +1,9 @@ +class Solution(object): + def frequencySort(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + from collections import Counter + freq = Counter(nums) + return sorted(nums, key=lambda x: (freq[x], -x)) diff --git a/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.rb b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.rb new file mode 100644 index 00000000..8557d056 --- /dev/null +++ b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.rb @@ -0,0 +1,6 @@ +# @param {Integer[]} nums +# @return {Integer[]} +def frequency_sort(nums) + freq = nums.tally + nums.sort_by { |x| [freq[x], -x] } +end diff --git a/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.rs b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.rs new file mode 100644 index 00000000..1b173166 --- /dev/null +++ b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn frequency_sort(nums: Vec) -> Vec { + use std::collections::HashMap; + let mut freq: HashMap = HashMap::new(); + for &num in &nums { + *freq.entry(num).or_insert(0) += 1; + } + let mut result = nums; + result.sort_by(|a, b| { + freq.get(a).unwrap_or(&0).cmp(freq.get(b).unwrap_or(&0)) + .then(b.cmp(a)) + }); + result + } +} diff --git a/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.swift b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.swift new file mode 100644 index 00000000..a9f17e19 --- /dev/null +++ b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.swift @@ -0,0 +1,14 @@ +class Solution { + func frequencySort(_ nums: [Int]) -> [Int] { + var freq: [Int: Int] = [:] + for num in nums { + freq[num, default: 0] += 1 + } + return nums.sorted { + if freq[$0]! != freq[$1]! { + return freq[$0]! < freq[$1]! + } + return $0 > $1 + } + } +} diff --git a/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.ts b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.ts new file mode 100644 index 00000000..77b06aee --- /dev/null +++ b/tests/1501-2000/1636. sort-array-by-increasing-frequency/sol.ts @@ -0,0 +1,11 @@ +function frequencySort(nums: number[]): number[] { + const freq: Map = new Map(); + for (const num of nums) { + freq.set(num, (freq.get(num) || 0) + 1); + } + return nums.sort((a, b) => { + const freqCompare = (freq.get(a) || 0) - (freq.get(b) || 0); + if (freqCompare !== 0) return freqCompare; + return b - a; + }); +} diff --git a/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/manifest.yaml b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/manifest.yaml new file mode 100644 index 00000000..c45381b4 --- /dev/null +++ b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/manifest.yaml @@ -0,0 +1,439 @@ +entry: + id: 1637 + title: "widest-vertical-area-between-two-points-containing-no-points" + params: + points: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().maxWidthOfVerticalArea({points})" + rust: "Solution::max_width_of_vertical_area({points})" + python3: "Solution().maxWidthOfVerticalArea({points})" + python2: "Solution().maxWidthOfVerticalArea({points})" + ruby: "max_width_of_vertical_area({points})" + java: "new Solution().maxWidthOfVerticalArea({points})" + csharp: "new Solution().MaxWidthOfVerticalArea({points})" + kotlin: "Solution().maxWidthOfVerticalArea({points})" + go: "maxWidthOfVerticalArea({points})" + dart: "Solution().maxWidthOfVerticalArea({points})" + swift: "Solution().maxWidthOfVerticalArea({points})" + typescript: "maxWidthOfVerticalArea({points})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxWidthOfVerticalArea(points, {result})" + checker: | + class Checker: + def maxWidthOfVerticalArea(self, points, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + xs = sorted(p[0] for p in points) + expected = max(xs[i + 1] - xs[i] for i in range(len(xs) - 1)) + return result == expected + +seed: 1637 + +tests: + - name: example-one + in: + points: + - [8, 7] + - [9, 9] + - [7, 4] + - [9, 7] + out: 1 + - name: example-two + in: + points: + - [3, 1] + - [9, 0] + - [1, 0] + - [1, 4] + - [5, 3] + - [8, 8] + out: 3 + - name: two-points + in: + points: + - [0, 0] + - [1000000000, 1000000000] + out: 1000000000 + - name: adjacent-x + in: + points: + - [4, 1] + - [5, 99] + - [6, 0] + - [7, 12] + out: 1 + - name: duplicate-x + in: + points: + - [10, 1] + - [10, 2] + - [10, 3] + - [20, 4] + - [20, 5] + - [31, 6] + out: 11 + - name: all-same-x + in: + points: + - [42, 0] + - [42, 1] + - [42, 2] + - [42, 1000000000] + out: 0 + - name: y-does-not-matter + in: + points: + - [1, 1000000000] + - [4, 0] + - [9, 500] + - [15, 7] + out: 6 + - name: zero-and-one + in: + points: + - [0, 8] + - [1, 3] + - [2, 5] + - [3, 1] + - [4, 9] + out: 1 + - name: large-first-gap + in: + points: + - [0, 1] + - [1, 2] + - [2, 3] + - [999999999, 4] + - [1000000000, 5] + out: 999999997 + - name: large-last-gap + in: + points: + - [0, 1] + - [999999998, 2] + - [999999999, 3] + - [1000000000, 4] + out: 999999998 + - name: unsorted-input + in: + points: + - [50, 0] + - [3, 1] + - [27, 2] + - [11, 3] + - [90, 4] + - [4, 5] + out: 40 + - name: repeated-x-clusters + in: + points: + - [0, 1] + - [0, 2] + - [2, 3] + - [2, 4] + - [5, 5] + - [5, 6] + - [10, 7] + out: 5 + - name: arithmetic-x + in: + points: + - [2, 8] + - [12, 7] + - [22, 6] + - [32, 5] + - [42, 4] + out: 10 + - name: uneven-gaps + in: + points: + - [1, 0] + - [2, 0] + - [10, 0] + - [11, 0] + - [100, 0] + - [101, 0] + out: 89 + - name: negative-free-minimum + in: + points: + - [0, 100] + - [100, 99] + - [101, 98] + - [1000, 97] + out: 899 + - name: powers-of-two + in: + points: + - [1, 0] + - [2, 0] + - [4, 0] + - [8, 0] + - [16, 0] + - [32, 0] + out: 16 + - name: near-max-coordinates + in: + points: + - [999999990, 1] + - [999999991, 2] + - [999999995, 3] + - [1000000000, 4] + out: 5 + - name: six-spread-points + in: + points: + - [0, 0] + - [17, 1] + - [18, 2] + - [45, 3] + - [46, 4] + - [100, 5] + out: 54 + - name: dense-then-gap + in: + points: + - [100, 0] + - [101, 1] + - [102, 2] + - [103, 3] + - [104, 4] + - [500, 5] + - [501, 6] + out: 396 + - name: alternating-y + in: + points: + - [7, 1000000000] + - [8, 0] + - [30, 999999999] + - [31, 1] + - [60, 999999998] + out: 29 + - name: nine-points + in: + points: + - [3, 1] + - [14, 2] + - [15, 3] + - [16, 4] + - [40, 5] + - [41, 6] + - [42, 7] + - [80, 8] + - [100, 9] + out: 38 + - name: x-zero-cluster + in: + points: + - [0, 0] + - [0, 100] + - [1, 200] + - [50, 300] + - [51, 400] + out: 49 + - name: max-x-cluster + in: + points: + - [1, 0] + - [500000000, 1] + - [999999999, 2] + - [1000000000, 3] + - [1000000000, 4] + out: 499999999 + - name: close-and-far + in: + points: + - [10, 0] + - [11, 1] + - [12, 2] + - [1000, 3] + - [1001, 4] + - [1002, 5] + - [10000, 6] + out: 8998 + - name: sorted-input + in: + points: + - [5, 1] + - [9, 2] + - [20, 3] + - [21, 4] + - [70, 5] + out: 49 + - name: reverse-input + in: + points: + - [70, 5] + - [21, 4] + - [20, 3] + - [9, 2] + - [5, 1] + out: 49 + - name: two-x-levels + in: + points: + - [123, 1] + - [123, 2] + - [456, 3] + - [456, 4] + - [456, 5] + out: 333 + - name: small-gaps-with-middle + in: + points: + - [0, 1] + - [2, 2] + - [3, 3] + - [5, 4] + - [6, 5] + - [8, 6] + - [9, 7] + out: 2 + - name: gap-100 + in: + points: + - [100, 1] + - [200, 2] + - [300, 3] + - [400, 4] + - [500, 5] + out: 100 + - name: gap-unequal-large + in: + points: + - [1, 1] + - [100000, 2] + - [100001, 3] + - [200000, 4] + - [1000000, 5] + out: 800000 + - name: many-duplicates + in: + points: + - [5, 1] + - [5, 2] + - [5, 3] + - [5, 4] + - [6, 5] + - [6, 6] + - [100, 7] + - [100, 8] + out: 94 + - name: scattered-small + in: + points: + - [2, 1] + - [7, 2] + - [13, 3] + - [19, 4] + - [26, 5] + - [35, 6] + out: 9 + - name: endpoint-boundaries + in: + points: + - [0, 0] + - [999999999, 1] + - [1000000000, 2] + out: 999999999 + - name: repeated-extremes + in: + points: + - [0, 1] + - [0, 2] + - [0, 3] + - [1000000000, 4] + - [1000000000, 5] + out: 1000000000 + - name: medium-random-pattern + in: + points: + - [13, 91] + - [88, 2] + - [34, 77] + - [201, 5] + - [55, 43] + - [144, 9] + - [56, 10] + - [300, 11] + out: 99 + - name: generator-small-shape + in: + points: + gen: "array" + len: 100 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" + - name: generator-medium-shape + in: + points: + gen: "array" + len: 1000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" + - name: generator-large-shape + in: + points: + gen: "array" + len: 10000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" + - name: generator-near-limit-one + in: + points: + gen: "array" + len: 50000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" + - name: generator-near-limit-two + in: + points: + gen: "array" + len: 100000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" diff --git a/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.cpp b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.cpp new file mode 100644 index 00000000..5c4ffbcb --- /dev/null +++ b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int maxWidthOfVerticalArea(vector>& points) { + int maxWidth = 0; + sort(points.begin(), points.end(), [](const vector& a, const vector& b) { + return a[0] < b[0]; + }); + for (int i = 0; i < points.size() - 1; i++) { + int width = points[i+1][0] - points[i][0]; + maxWidth = max(maxWidth, width); + } + return maxWidth; + } +}; diff --git a/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.cs b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.cs new file mode 100644 index 00000000..42f69e53 --- /dev/null +++ b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.cs @@ -0,0 +1,11 @@ +public class Solution { + public int MaxWidthOfVerticalArea(int[][] points) { + int maxWidth = 0; + Array.Sort(points, (a, b) => a[0].CompareTo(b[0])); + for (int i = 0; i < points.Length - 1; i++) { + int width = points[i+1][0] - points[i][0]; + maxWidth = Math.Max(maxWidth, width); + } + return maxWidth; + } +} diff --git a/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.dart b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.dart new file mode 100644 index 00000000..e1de1655 --- /dev/null +++ b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.dart @@ -0,0 +1,11 @@ +class Solution { + int maxWidthOfVerticalArea(List> points) { + int maxWidth = 0; + points.sort((a, b) => a[0].compareTo(b[0])); + for (int i = 0; i < points.length - 1; i++) { + int width = points[i+1][0] - points[i][0]; + if (width > maxWidth) maxWidth = width; + } + return maxWidth; + } +} diff --git a/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.go b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.go new file mode 100644 index 00000000..f2ed3764 --- /dev/null +++ b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.go @@ -0,0 +1,13 @@ +func maxWidthOfVerticalArea(points [][]int) int { + maxWidth := 0 + sort.Slice(points, func(i, j int) bool { + return points[i][0] < points[j][0] + }) + for i := 0; i < len(points)-1; i++ { + width := points[i+1][0] - points[i][0] + if width > maxWidth { + maxWidth = width + } + } + return maxWidth +} diff --git a/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.java b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.java new file mode 100644 index 00000000..b562d37f --- /dev/null +++ b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.java @@ -0,0 +1,11 @@ +class Solution { + public int maxWidthOfVerticalArea(int[][] points) { + int maxWidth = 0; + Arrays.sort(points, (a, b) -> Integer.compare(a[0], b[0])); + for (int i = 0; i < points.length - 1; i++) { + int width = points[i+1][0] - points[i][0]; + maxWidth = Math.max(maxWidth, width); + } + return maxWidth; + } +} diff --git a/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.kt b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.kt new file mode 100644 index 00000000..c449386f --- /dev/null +++ b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.kt @@ -0,0 +1,11 @@ +class Solution { + fun maxWidthOfVerticalArea(points: Array): Int { + var maxWidth = 0 + points.sortBy { it[0] } + for (i in 0 until points.size - 1) { + val width = points[i+1][0] - points[i][0] + maxWidth = maxOf(maxWidth, width) + } + return maxWidth + } +} diff --git a/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.py b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.py new file mode 100644 index 00000000..1fffef8f --- /dev/null +++ b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.py @@ -0,0 +1,13 @@ +class Solution: + def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: + max_width = 0 + + # Sort points based on x-coordinate + l = sorted(points, key=lambda x: x[0]) + + # Compare adjacent x-coordinates to find the maximum gap + for i in range(len(l) - 1): + width = l[i + 1][0] - l[i][0] + max_width = max(max_width, width) + + return max_width diff --git a/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.py2 b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.py2 new file mode 100644 index 00000000..4bc840d7 --- /dev/null +++ b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def maxWidthOfVerticalArea(self, points): + """ + :type points: List[List[int]] + :rtype: int + """ + max_width = 0 + points.sort(key=lambda x: x[0]) + for i in range(len(points)-1): + width = points[i+1][0] - points[i][0] + max_width = max(max_width, width) + return max_width diff --git a/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.rb b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.rb new file mode 100644 index 00000000..fa0bae9d --- /dev/null +++ b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.rb @@ -0,0 +1,11 @@ +# @param {Integer[][]} points +# @return {Integer} +def max_width_of_vertical_area(points) + max_width = 0 + points.sort_by! { |p| p[0] } + (0...points.length-1).each do |i| + width = points[i+1][0] - points[i][0] + max_width = [max_width, width].max + end + max_width +end diff --git a/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.rs b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.rs new file mode 100644 index 00000000..1c4e6de6 --- /dev/null +++ b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.rs @@ -0,0 +1,14 @@ +impl Solution { + pub fn max_width_of_vertical_area(points: Vec>) -> i32 { + let mut points = points; + points.sort_by_key(|p| p[0]); + let mut max_width = 0; + for i in 0..points.len()-1 { + let width = points[i+1][0] - points[i][0]; + if width > max_width { + max_width = width; + } + } + max_width + } +} diff --git a/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.swift b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.swift new file mode 100644 index 00000000..efe58980 --- /dev/null +++ b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.swift @@ -0,0 +1,11 @@ +class Solution { + func maxWidthOfVerticalArea(_ points: [[Int]]) -> Int { + var maxWidth = 0 + let sorted = points.sorted { $0[0] < $1[0] } + for i in 0..<(sorted.count - 1) { + let width = sorted[i+1][0] - sorted[i][0] + maxWidth = max(maxWidth, width) + } + return maxWidth + } +} diff --git a/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.ts b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.ts new file mode 100644 index 00000000..41d92f39 --- /dev/null +++ b/tests/1501-2000/1637. widest-vertical-area-between-two-points-containing-no-points/sol.ts @@ -0,0 +1,9 @@ +function maxWidthOfVerticalArea(points: number[][]): number { + let maxWidth = 0; + points.sort((a, b) => a[0] - b[0]); + for (let i = 0; i < points.length - 1; i++) { + const width = points[i + 1][0] - points[i][0]; + maxWidth = Math.max(maxWidth, width); + } + return maxWidth; +} diff --git a/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/manifest.yaml b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/manifest.yaml new file mode 100644 index 00000000..8784da78 --- /dev/null +++ b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/manifest.yaml @@ -0,0 +1,278 @@ +entry: + id: 1638 + title: "count-substrings-that-differ-by-one-character" + params: + s: + type: string + t: + type: string + call: + cpp: "Solution().countSubstrings({s}, {t})" + rust: "Solution::count_substrings({s}, {t})" + python3: "Solution().countSubstrings({s}, {t})" + python2: "Solution().countSubstrings({s}, {t})" + ruby: "count_substrings({s}, {t})" + java: "new Solution().countSubstrings({s}, {t})" + csharp: "new Solution().CountSubstrings({s}, {t})" + kotlin: "Solution().countSubstrings({s}, {t})" + go: "countSubstrings({s}, {t})" + dart: "Solution().countSubstrings({s}, {t})" + swift: "Solution().countSubstrings({s}, {t})" + typescript: "countSubstrings({s}, {t})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().countSubstrings(s, t, {result})" + checker: | + class Checker: + def countSubstrings(self, s, t, result): + expected = 0 + for i in range(len(s)): + for j in range(len(t)): + differences = 0 + k = 0 + while i + k < len(s) and j + k < len(t): + if s[i + k] != t[j + k]: + differences += 1 + if differences > 1: + break + if differences == 1: + expected += 1 + k += 1 + return isinstance(result, int) and not isinstance(result, bool) and result == expected + +seed: 1638 + +tests: + - name: example-aba-baba + in: + s: "aba" + t: "baba" + out: 6 + - name: example-ab-bb + in: + s: "ab" + t: "bb" + out: 3 + - name: one-equal-character + in: + s: "a" + t: "a" + out: 0 + - name: one-different-character + in: + s: "a" + t: "b" + out: 1 + - name: one-character-t-longer + in: + s: "a" + t: "ab" + out: 1 + - name: one-character-s-longer + in: + s: "ab" + t: "a" + out: 1 + - name: identical-two-strings + in: + s: "abc" + t: "abc" + out: 6 + - name: all-a-identical + in: + s: "aaa" + t: "aaaa" + out: 0 + - name: all-a-versus-b + in: + s: "aaa" + t: "bbb" + out: 9 + - name: alternating-equal + in: + s: "abab" + t: "abab" + out: 8 + - name: alternating-shifted + in: + s: "abab" + t: "baba" + out: 8 + - name: repeated-pattern + in: + s: "abcabc" + t: "bcabca" + out: 24 + - name: disjoint-alphabet + in: + s: "abc" + t: "xyz" + out: 9 + - name: one-mismatch-at-start + in: + s: "xbc" + t: "abc" + out: 9 + - name: one-mismatch-at-end + in: + s: "abx" + t: "abc" + out: 9 + - name: mismatch-middle + in: + s: "axc" + t: "abc" + out: 10 + - name: mismatch-and-overlap + in: + s: "aaaaab" + t: "baaaaa" + out: 30 + - name: short-s-inside-t + in: + s: "cat" + t: "concatenate" + out: 30 + - name: short-t-inside-s + in: + s: "concatenate" + t: "cat" + out: 30 + - name: four-distinct + in: + s: "abcd" + t: "efgh" + out: 16 + - name: same-prefix-different-suffix + in: + s: "abca" + t: "abcb" + out: 15 + - name: same-suffix-different-prefix + in: + s: "xabc" + t: "yabc" + out: 16 + - name: repeated-single-mismatch + in: + s: "aab" + t: "aba" + out: 6 + - name: nested-overlaps + in: + s: "aaaa" + t: "aaab" + out: 10 + - name: length-five-disjoint + in: + s: "abcde" + t: "vwxyz" + out: 25 + - name: length-five-shift + in: + s: "abcde" + t: "bcdef" + out: 21 + - name: duplicate-blocks + in: + s: "ababab" + t: "ababac" + out: 30 + - name: long-equal-block + in: + s: "aaaaaaaaaa" + t: "aaaaaaaaab" + out: 55 + - name: long-different-block + in: + s: "aaaaaaaaaa" + t: "bbbbbbbbbb" + out: 100 + - name: long-shifted-block + in: + s: "ababababab" + t: "bababababa" + out: 50 + - name: mixed-lowercase + in: + s: "qwerty" + t: "qazwsx" + out: 37 + - name: repeated-mixed + in: + s: "abcabcabc" + t: "abcabcabd" + out: 72 + - name: unequal-long-pattern + in: + s: "abcdefghijklmnopqrst" + t: "bcdefghijklmnopqrstuv" + out: 401 + - name: maximal-equal + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + t: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: 0 + - name: maximal-single-difference + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" + t: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: 820 + - name: generated-small + in: + s: + gen: "str" + len: 17 + alphabet: "abc" + t: + gen: "str" + len: 19 + alphabet: "abc" + - name: generated-medium + in: + s: + gen: "str" + len: 41 + alphabet: "abcd" + t: + gen: "str" + len: 37 + alphabet: "abcd" + - name: generated-large-one + in: + s: + gen: "str" + len: 100 + alphabet: "abcde" + t: + gen: "str" + len: 100 + alphabet: "abcde" + - name: generated-large-two + in: + s: + gen: "str" + len: 100 + alphabet: "ab" + t: + gen: "str" + len: 97 + alphabet: "ab" + - name: generated-large-three + in: + s: + gen: "str" + len: 83 + alphabet: "xyz" + t: + gen: "str" + len: 100 + alphabet: "xyz" diff --git a/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.cpp b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.cpp new file mode 100644 index 00000000..ef04e1ce --- /dev/null +++ b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int countSubstrings(string s, string t) { + int m = s.length(), n = t.length(); + int result = 0; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + int diff = 0; + int k = 0; + while (i + k < m && j + k < n) { + if (s[i + k] != t[j + k]) { + diff++; + } + if (diff > 1) { + break; + } + if (diff == 1) { + result++; + } + k++; + } + } + } + + return result; + } +}; diff --git a/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.cs b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.cs new file mode 100644 index 00000000..b663c3dc --- /dev/null +++ b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.cs @@ -0,0 +1,27 @@ +public class Solution { + public int CountSubstrings(string s, string t) { + int m = s.Length, n = t.Length; + int result = 0; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + int diff = 0; + int k = 0; + while (i + k < m && j + k < n) { + if (s[i + k] != t[j + k]) { + diff++; + } + if (diff > 1) { + break; + } + if (diff == 1) { + result++; + } + k++; + } + } + } + + return result; + } +} diff --git a/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.dart b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.dart new file mode 100644 index 00000000..abcdfe9d --- /dev/null +++ b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.dart @@ -0,0 +1,27 @@ +class Solution { + int countSubstrings(String s, String t) { + int m = s.length, n = t.length; + int result = 0; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + int diff = 0; + int k = 0; + while (i + k < m && j + k < n) { + if (s[i + k] != t[j + k]) { + diff++; + } + if (diff > 1) { + break; + } + if (diff == 1) { + result++; + } + k++; + } + } + } + + return result; + } +} diff --git a/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.go b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.go new file mode 100644 index 00000000..14d32d01 --- /dev/null +++ b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.go @@ -0,0 +1,25 @@ +func countSubstrings(s string, t string) int { + m, n := len(s), len(t) + result := 0 + + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + diff := 0 + k := 0 + for i+k < m && j+k < n { + if s[i+k] != t[j+k] { + diff++ + } + if diff > 1 { + break + } + if diff == 1 { + result++ + } + k++ + } + } + } + + return result +} diff --git a/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.java b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.java new file mode 100644 index 00000000..c7c8a7ce --- /dev/null +++ b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.java @@ -0,0 +1,27 @@ +class Solution { + public int countSubstrings(String s, String t) { + int m = s.length(), n = t.length(); + int result = 0; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + int diff = 0; + int k = 0; + while (i + k < m && j + k < n) { + if (s.charAt(i + k) != t.charAt(j + k)) { + diff++; + } + if (diff > 1) { + break; + } + if (diff == 1) { + result++; + } + k++; + } + } + } + + return result; + } +} diff --git a/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.kt b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.kt new file mode 100644 index 00000000..46a82044 --- /dev/null +++ b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.kt @@ -0,0 +1,28 @@ +class Solution { + fun countSubstrings(s: String, t: String): Int { + val m = s.length + val n = t.length + var result = 0 + + for (i in 0 until m) { + for (j in 0 until n) { + var diff = 0 + var k = 0 + while (i + k < m && j + k < n) { + if (s[i + k] != t[j + k]) { + diff++ + } + if (diff > 1) { + break + } + if (diff == 1) { + result++ + } + k++ + } + } + } + + return result + } +} diff --git a/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.py b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.py new file mode 100644 index 00000000..3b030814 --- /dev/null +++ b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.py @@ -0,0 +1,24 @@ +class Solution(object): + def countSubstrings(self, s, t): + """ + :type s: str + :type t: str + :rtype: int + """ + m, n = len(s), len(t) + result = 0 + + for i in range(m): + for j in range(n): + diff = 0 + k = 0 + while i + k < m and j + k < n: + if s[i + k] != t[j + k]: + diff += 1 + if diff > 1: + break + if diff == 1: + result += 1 + k += 1 + + return result diff --git a/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.py2 b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.py2 new file mode 100644 index 00000000..3b030814 --- /dev/null +++ b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.py2 @@ -0,0 +1,24 @@ +class Solution(object): + def countSubstrings(self, s, t): + """ + :type s: str + :type t: str + :rtype: int + """ + m, n = len(s), len(t) + result = 0 + + for i in range(m): + for j in range(n): + diff = 0 + k = 0 + while i + k < m and j + k < n: + if s[i + k] != t[j + k]: + diff += 1 + if diff > 1: + break + if diff == 1: + result += 1 + k += 1 + + return result diff --git a/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.rb b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.rb new file mode 100644 index 00000000..74c1003a --- /dev/null +++ b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.rb @@ -0,0 +1,28 @@ +# @param {String} s +# @param {String} t +# @return {Integer} +def count_substrings(s, t) + m, n = s.length, t.length + result = 0 + + for i in 0...m + for j in 0...n + diff = 0 + k = 0 + while i + k < m && j + k < n + if s[i + k] != t[j + k] + diff += 1 + end + if diff > 1 + break + end + if diff == 1 + result += 1 + end + k += 1 + end + end + end + + result +end diff --git a/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.rs b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.rs new file mode 100644 index 00000000..b4d5eb7a --- /dev/null +++ b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.rs @@ -0,0 +1,30 @@ +impl Solution { + pub fn count_substrings(s: String, t: String) -> i32 { + let s_bytes = s.as_bytes(); + let t_bytes = t.as_bytes(); + let m = s_bytes.len(); + let n = t_bytes.len(); + let mut result = 0; + + for i in 0..m { + for j in 0..n { + let mut diff = 0; + let mut k = 0; + while i + k < m && j + k < n { + if s_bytes[i + k] != t_bytes[j + k] { + diff += 1; + } + if diff > 1 { + break; + } + if diff == 1 { + result += 1; + } + k += 1; + } + } + } + + result as i32 + } +} diff --git a/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.swift b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.swift new file mode 100644 index 00000000..b025e024 --- /dev/null +++ b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.swift @@ -0,0 +1,29 @@ +class Solution { + func countSubstrings(_ s: String, _ t: String) -> Int { + let sChars = Array(s) + let tChars = Array(t) + let m = sChars.count, n = tChars.count + var result = 0 + + for i in 0.. 1 { + break + } + if diff == 1 { + result += 1 + } + k += 1 + } + } + } + + return result + } +} diff --git a/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.ts b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.ts new file mode 100644 index 00000000..8bcbf464 --- /dev/null +++ b/tests/1501-2000/1638. count-substrings-that-differ-by-one-character/sol.ts @@ -0,0 +1,26 @@ +function countSubstrings(s: string, t: string): number { + const m = s.length, + n = t.length; + let result = 0; + + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + let diff = 0; + let k = 0; + while (i + k < m && j + k < n) { + if (s[i + k] !== t[j + k]) { + diff++; + } + if (diff > 1) { + break; + } + if (diff === 1) { + result++; + } + k++; + } + } + } + + return result; +} diff --git a/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/manifest.yaml b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/manifest.yaml new file mode 100644 index 00000000..1523a3f8 --- /dev/null +++ b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/manifest.yaml @@ -0,0 +1,302 @@ +entry: + id: 1639 + title: "number-of-ways-to-form-a-target-string-given-a-dictionary" + params: + words: + type: array + items: + type: string + target: + type: string + call: + cpp: "Solution().numWays({words}, {target})" + rust: "Solution::num_ways({words}, {target})" + python3: "Solution().numWays({words}, {target})" + python2: "Solution().numWays({words}, {target})" + ruby: "num_ways({words}, {target})" + java: "new Solution().numWays({words}, {target})" + csharp: "new Solution().NumWays({words}, {target})" + kotlin: "Solution().numWays({words}, {target})" + go: "numWays({words}, {target})" + dart: "Solution().numWays({words}, {target})" + swift: "Solution().numWays({words}, {target})" + typescript: "numWays({words}, {target})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().numWays(words, target, {result})" + checker: | + class Checker: + def numWays(self, words, target, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + mod = 1000000007 + if not words or not target or any(len(w) != len(words[0]) for w in words): + return False + counts = [[0] * 26 for _ in range(len(words[0]))] + for word in words: + for i, ch in enumerate(word): + counts[i][ord(ch) - 97] += 1 + dp = [0] * (len(target) + 1) + dp[0] = 1 + for column in counts: + for j in range(len(target) - 1, -1, -1): + dp[j + 1] = (dp[j + 1] + dp[j] * column[ord(target[j]) - 97]) % mod + return result == dp[len(target)] + +seed: 1639 + +tests: + - name: example-one + in: + words: ["acca", "bbbb", "caca"] + target: "aba" + out: 6 + - name: example-two + in: + words: ["abba", "baab"] + target: "bab" + out: 4 + - name: one-word-exact + in: + words: ["abcd"] + target: "abcd" + out: 1 + - name: one-word-impossible-order + in: + words: ["abcd"] + target: "dcba" + out: 0 + - name: one-word-subsequence + in: + words: ["abcde"] + target: "ace" + out: 1 + - name: repeated-single-character + in: + words: ["aaaa", "aaaa", "aaaa"] + target: "aaa" + out: 108 + - name: repeated-character-full-width + in: + words: ["aaa", "aaa"] + target: "aaa" + out: 8 + - name: impossible-letter + in: + words: ["abc", "abc"] + target: "abd" + out: 0 + - name: target-longer-than-word + in: + words: ["ab", "ab"] + target: "aba" + out: 0 + - name: single-character-match + in: + words: ["a", "b", "a", "c"] + target: "a" + out: 2 + - name: single-character-miss + in: + words: ["a", "b", "c"] + target: "z" + out: 0 + - name: two-columns-two-letters + in: + words: ["aa", "ab", "ba", "bb"] + target: "ab" + out: 4 + - name: two-columns-same-letter + in: + words: ["aa", "aa", "ba"] + target: "aa" + out: 6 + - name: choice-at-first-column + in: + words: ["ab", "ac", "db"] + target: "ab" + out: 4 + - name: choice-at-second-column + in: + words: ["aa", "ba", "ca"] + target: "aa" + out: 3 + - name: all-columns-required + in: + words: ["abc", "abc", "abc"] + target: "abc" + out: 27 + - name: duplicate-word-counts + in: + words: ["abc", "abc", "abd", "abd"] + target: "abd" + out: 32 + - name: alternating-target + in: + words: ["abab", "baba"] + target: "aba" + out: 4 + - name: no-increasing-match + in: + words: ["ba", "ba", "ab"] + target: "ba" + out: 4 + - name: length-three-mixed + in: + words: ["abc", "bac", "cba", "acb"] + target: "ac" + out: 8 + - name: target-single-from-four-columns + in: + words: ["aaaa", "baaa", "aaba"] + target: "a" + out: 10 + - name: target-two-from-four-columns + in: + words: ["aaaa", "baaa", "aaba"] + target: "aa" + out: 37 + - name: target-three-from-four-columns + in: + words: ["aaaa", "baaa", "aaba"] + target: "aaa" + out: 60 + - name: target-four-from-four-columns + in: + words: ["aaaa", "baaa", "aaba"] + target: "aaaa" + out: 36 + - name: sparse-letter + in: + words: ["azaz", "zaza", "azza"] + target: "zz" + out: 13 + - name: repeated-target-with-gaps + in: + words: ["aaaaa", "aaaaa"] + target: "aaa" + out: 80 + - name: many-identical-words + in: + words: ["abcd", "abcd", "abcd", "abcd", "abcd"] + target: "bd" + out: 25 + - name: mixed-counts + in: + words: ["aabb", "abab", "bbaa", "baab"] + target: "ab" + out: 29 + - name: impossible-after-prefix + in: + words: ["abc", "bbc", "cbc"] + target: "acd" + out: 0 + - name: target-uses-last-column + in: + words: ["aaab", "baab", "cabb"] + target: "ab" + out: 22 + - name: alphabet-boundary + in: + words: ["azaz", "zaza", "zzzz"] + target: "az" + out: 12 + - name: generator-short-one + in: + words: ["acca", "bbbb", "caca"] + target: + gen: "str" + len: 1 + alphabet: "abc" + - name: generator-short-two + in: + words: ["acca", "bbbb", "caca"] + target: + gen: "str" + len: 2 + alphabet: "abc" + - name: generator-short-three + in: + words: ["acca", "bbbb", "caca"] + target: + gen: "str" + len: 3 + alphabet: "abc" + - name: generator-full-width + in: + words: ["acca", "bbbb", "caca"] + target: + gen: "str" + len: 4 + alphabet: "abc" + - name: generator-rare-alphabet + in: + words: ["azaz", "zaza", "azza"] + target: + gen: "str" + len: 2 + alphabet: "az" + - name: generator-medium-dictionary + in: + words: + gen: array + len: 25 + of: + gen: str + len: 40 + alphabet: "abc" + target: + gen: str + len: 20 + alphabet: "abc" + seed: 163901 + - name: generator-wide-dictionary + in: + words: + gen: array + len: 1000 + of: + gen: str + len: 100 + alphabet: "abcd" + target: + gen: str + len: 50 + alphabet: "abcd" + seed: 163902 + - name: generator-long-columns + in: + words: + gen: array + len: 20 + of: + gen: str + len: 1000 + alphabet: "xyz" + target: + gen: str + len: 500 + alphabet: "xyz" + seed: 163903 + - name: generator-max-shape + in: + words: + gen: array + len: 1000 + of: + gen: str + len: 1000 + alphabet: "ab" + target: + gen: str + len: 1000 + alphabet: "ab" + seed: 163904 diff --git a/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.cpp b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.cpp new file mode 100644 index 00000000..01e3b0c6 --- /dev/null +++ b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int numWays(vector& words, string target) { + const int MOD = 1000000007; + int n = words.size(); + int m = words[0].size(); + vector> A(m, vector(26, 0)); + for (const string& word : words) { + for (int j = 0; j < m; ++j) { + A[j][word[j] - 'a']++; + } + } + vector> dp(m, vector(target.size(), -1)); + + function F = [&](int i, int j) -> int { + if (j == target.size()) return 1; + if (i == m) return 0; + if (dp[i][j] != -1) return dp[i][j]; + long long count = F(i+1, j); + count = (count + (long long)A[i][target[j]-'a'] * F(i+1, j+1)) % MOD; + dp[i][j] = (int)count; + return dp[i][j]; + }; + return F(0, 0); + } +}; diff --git a/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.cs b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.cs new file mode 100644 index 00000000..d04344cd --- /dev/null +++ b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.cs @@ -0,0 +1,31 @@ +public class Solution { + public int NumWays(string[] words, string target) { + const int MOD = 1000000007; + int m = words[0].Length; + int[][] A = new int[m][]; + for (int i = 0; i < m; i++) A[i] = new int[26]; + foreach (string word in words) { + for (int j = 0; j < m; j++) { + A[j][word[j] - 'a']++; + } + } + int[][] dp = new int[m][]; + for (int i = 0; i < m; i++) { + dp[i] = new int[target.Length]; + for (int j = 0; j < target.Length; j++) dp[i][j] = -1; + } + + Func F = null; + F = (i, j) => { + if (j == target.Length) return 1; + if (i == m) return 0; + if (dp[i][j] != -1) return dp[i][j]; + + long count = F(i + 1, j) % MOD; + count = (count + (long)A[i][target[j] - 'a'] * F(i + 1, j + 1)) % MOD; + dp[i][j] = (int)count; + return (int)count; + }; + return F(0, 0); + } +} diff --git a/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.dart b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.dart new file mode 100644 index 00000000..fefc0f30 --- /dev/null +++ b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.dart @@ -0,0 +1,24 @@ +class Solution { + int numWays(List words, String target) { + const int MOD = 1000000007; + int m = words[0].length; + List> A = List.generate(m, (_) => List.filled(26, 0)); + for (String word in words) { + for (int j = 0; j < m; j++) { + A[j][word.codeUnitAt(j) - 'a'.codeUnitAt(0)]++; + } + } + List> dp = List.generate(m, (_) => List.filled(target.length, -1)); + + int F(int i, int j) { + if (j == target.length) return 1; + if (i == m) return 0; + if (dp[i][j] != -1) return dp[i][j]; + int count = F(i + 1, j) % MOD; + count = (count + (A[i][target.codeUnitAt(j) - 'a'.codeUnitAt(0)] * F(i + 1, j + 1)) % MOD) % MOD; + dp[i][j] = count; + return count; + } + return F(0, 0); + } +} diff --git a/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.go b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.go new file mode 100644 index 00000000..1b786fad --- /dev/null +++ b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.go @@ -0,0 +1,37 @@ +func numWays(words []string, target string) int { + const MOD = 1000000007 + m := len(words[0]) + A := make([][]int, m) + for i := range A { + A[i] = make([]int, 26) + } + for _, word := range words { + for j := 0; j < m; j++ { + A[j][word[j]-'a']++ + } + } + dp := make([][]int, m) + for i := range dp { + dp[i] = make([]int, len(target)) + for j := range dp[i] { + dp[i][j] = -1 + } + } + var F func(int, int) int + F = func(i, j int) int { + if j == len(target) { + return 1 + } + if i == m { + return 0 + } + if dp[i][j] != -1 { + return dp[i][j] + } + count := F(i+1, j) % MOD + count = (count + (A[i][target[j]-'a'] % MOD) * F(i+1, j+1) % MOD) % MOD + dp[i][j] = count + return count + } + return F(0, 0) +} diff --git a/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.java b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.java new file mode 100644 index 00000000..4846655c --- /dev/null +++ b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.java @@ -0,0 +1,24 @@ +class Solution { + public int numWays(String[] words, String target) { + final int MOD = 1_000_000_007; + int m = words[0].length(); + int[][] A = new int[m][26]; + for (String word : words) { + for (int j = 0; j < m; j++) { + A[j][word.charAt(j) - 'a']++; + } + } + int[][] dp = new int[m][target.length()]; + for (int[] row : dp) Arrays.fill(row, -1); + return (int) solve(0, 0, A, target, dp, MOD); + } + private long solve(int i, int j, int[][] A, String target, int[][] dp, int MOD) { + if (j == target.length()) return 1; + if (i == A.length) return 0; + if (dp[i][j] != -1) return dp[i][j]; + long count = solve(i+1, j, A, target, dp, MOD) % MOD; + count = (count + (long)A[i][target.charAt(j)-'a'] * solve(i+1, j+1, A, target, dp, MOD)) % MOD; + dp[i][j] = (int)count; + return count; + } +} diff --git a/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.kt b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.kt new file mode 100644 index 00000000..0c809684 --- /dev/null +++ b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.kt @@ -0,0 +1,24 @@ +class Solution { + fun numWays(words: Array, target: String): Int { + val MOD = 1_000_000_007L + val m = words[0].length + val A = Array(m) { IntArray(26) } + for (word in words) { + for (j in 0 until m) { + A[j][word[j] - 'a']++ + } + } + val dp = Array(m) { IntArray(target.length) { -1 } } + + fun F(i: Int, j: Int): Long { + if (j == target.length) return 1 + if (i == m) return 0 + if (dp[i][j] != -1) return dp[i][j].toLong() + var count = F(i+1, j) % MOD + count = (count + (A[i][target[j] - 'a'].toLong() * F(i+1, j+1)) % MOD) % MOD + dp[i][j] = count.toInt() + return count + } + return F(0, 0).toInt() + } +} diff --git a/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.py b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.py new file mode 100644 index 00000000..536f0aa5 --- /dev/null +++ b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.py @@ -0,0 +1,28 @@ +class Solution: + def numWays(self, words: List[str], target: str) -> int: + mod = 10**9 + 7 + n = len(words) + m = len(words[0]) + A = [[0] * 26 for _ in range(m)] + for word in words: + for j in range(m): + A[j][ord(word[j]) - ord("a")] += 1 + + dp = [[-1] * len(target) for _ in range(m)] + + def F(i: int, j: int) -> int: + if j == len(target): + return 1 + if i == len(A): + return 0 + if dp[i][j] != -1: + return dp[i][j] + + count = F(i + 1, j) + count %= mod + count += (A[i][ord(target[j]) - ord("a")] * F(i + 1, j + 1)) % mod + count %= mod + dp[i][j] = count + return dp[i][j] + + return F(0, 0) diff --git a/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.py2 b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.py2 new file mode 100644 index 00000000..988e675b --- /dev/null +++ b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.py2 @@ -0,0 +1,33 @@ +class Solution(object): + def numWays(self, words, target): + """ + :type words: List[str] + :type target: str + :rtype: int + """ + mod = 10**9 + 7 + n = len(words) + m = len(words[0]) + A = [[0] * 26 for _ in range(m)] + for word in words: + for j in range(m): + A[j][ord(word[j]) - ord('a')] += 1 + + dp = [[-1] * len(target) for _ in range(m)] + + def F(i, j): + if j == len(target): + return 1 + if i == m: + return 0 + if dp[i][j] != -1: + return dp[i][j] + + count = F(i + 1, j) + count %= mod + count += (A[i][ord(target[j]) - ord('a')] * F(i + 1, j + 1)) % mod + count %= mod + dp[i][j] = count + return dp[i][j] + + return F(0, 0) diff --git a/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.rb b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.rb new file mode 100644 index 00000000..4f1fd24e --- /dev/null +++ b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.rb @@ -0,0 +1,27 @@ +# @param {String[]} words +# @param {String} target +# @return {Integer} +def num_ways(words, target) + words = words.scan(/[a-z]+/) if words.is_a?(String) + mod = 10**9 + 7 + m = words[0].length + counts = Array.new(m) { Array.new(26, 0) } + words.each do |word| + word.chars.each_with_index do |ch, j| + counts[j][ch.ord - 'a'.ord] += 1 + end + end + dp = Array.new(m) { Array.new(target.length, -1) } + + solve = ->(i, j) { + return 1 if j == target.length + return 0 if i == m + return dp[i][j] if dp[i][j] != -1 + + count = solve.call(i+1, j) % mod + count = (count + counts[i][target[j].ord - 'a'.ord] * solve.call(i+1, j+1)) % mod + dp[i][j] = count + count + } + solve.call(0, 0) +end diff --git a/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.rs b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.rs new file mode 100644 index 00000000..731dc79a --- /dev/null +++ b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn num_ways(words: Vec, target: String) -> i32 { + const MOD: i64 = 1_000_000_007; + let n = words.len(); + let m = words[0].len(); + let mut A = vec![vec![0i64; 26]; m]; + for word in words.iter() { + for (j, ch) in word.chars().enumerate() { + A[j][ch as usize - 'a' as usize] += 1; + } + } + let t: Vec = target.chars().collect(); + let mut dp = vec![vec![-1i64; t.len()]; m]; + + fn F(i: usize, j: usize, A: &Vec>, t: &Vec, dp: &mut Vec>) -> i64 { + if j == t.len() { return 1; } + if i == A.len() { return 0; } + if dp[i][j] != -1 { return dp[i][j]; } + let mut count = F(i+1, j, A, t, dp) % MOD; + count = (count + A[i][t[j] as usize - 'a' as usize] * F(i+1, j+1, A, t, dp)) % MOD; + dp[i][j] = count; + count + } + F(0, 0, &A, &t, &mut dp) as i32 + } +} diff --git a/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.swift b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.swift new file mode 100644 index 00000000..19923e9c --- /dev/null +++ b/tests/1501-2000/1639. number-of-ways-to-form-a-target-string-given-a-dictionary/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func numWays(_ words: [String], _ target: String) -> Int { + let MOD: Int64 = 1_000_000_007 + let m = words[0].count + var A = [[Int]](repeating: [Int](repeating: 0, count: 26), count: m) + for word in words { + let chars = Array(word) + for j in 0.. Array(26).fill(0)); + for (const word of words) { + for (let j = 0; j < m; j++) { + A[j][word.charCodeAt(j) - 97]++; + } + } + const dp: number[][] = Array(m) + .fill(0) + .map(() => Array(target.length).fill(-1)); + const targetArr = Array.from(target); + + const F = (i: number, j: number): number => { + if (j === target.length) return 1; + if (i === m) return 0; + if (dp[i][j] !== -1) return dp[i][j]; + + let count = F(i + 1, j) % MOD; + count = + (count + + ((A[i][targetArr[j].charCodeAt(0) - 97] * F(i + 1, j + 1)) % MOD)) % + MOD; + dp[i][j] = count; + return count; + }; + return F(0, 0); +} diff --git a/tests/1501-2000/1640. check-array-formation-through-concatenation/manifest.yaml b/tests/1501-2000/1640. check-array-formation-through-concatenation/manifest.yaml new file mode 100644 index 00000000..516139ba --- /dev/null +++ b/tests/1501-2000/1640. check-array-formation-through-concatenation/manifest.yaml @@ -0,0 +1,377 @@ +entry: + id: 1640 + title: "check-array-formation-through-concatenation" + params: + arr: + type: array + items: + type: int + pieces: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().canFormArray({arr}, {pieces})" + rust: "Solution::can_form_array({arr}, {pieces})" + python3: "Solution().canFormArray({arr}, {pieces})" + python2: "Solution().canFormArray({arr}, {pieces})" + ruby: "can_form_array({arr}, {pieces})" + java: "new Solution().canFormArray({arr}, {pieces})" + csharp: "new Solution().CanFormArray({arr}, {pieces})" + kotlin: "Solution().canFormArray({arr}, {pieces})" + go: "canFormArray({arr}, {pieces})" + dart: "Solution().canFormArray({arr}, {pieces})" + swift: "Solution().canFormArray({arr}, {pieces})" + typescript: "canFormArray({arr}, {pieces})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().canFormArray(arr, pieces, {result})" + checker: | + class Checker: + def canFormArray(self, arr, pieces, result): + if not isinstance(result, bool): + return False + by_first = {piece[0]: piece for piece in pieces if piece} + i = 0 + used = set() + while i < len(arr): + piece = by_first.get(arr[i]) + if piece is None or id(piece) in used: + return result is False + end = i + len(piece) + if end > len(arr) or arr[i:end] != piece: + return result is False + used.add(id(piece)) + i = end + return result is (i == len(arr) and len(used) == len(pieces)) + +seed: 1640 + +tests: + - name: example-one + in: + arr: [15, 88] + pieces: + - [88] + - [15] + out: true + - name: example-two-order-inside-piece + in: + arr: [49, 18, 16] + pieces: + - [16, 18, 49] + out: false + - name: example-three + in: + arr: [91, 4, 64, 78] + pieces: + - [78] + - [4, 64] + - [91] + out: true + - name: single-piece + in: + arr: [1, 2, 3, 4] + pieces: + - [1, 2, 3, 4] + out: true + - name: single-element-arr + in: + arr: [7] + pieces: + - [7] + out: true + - name: one-piece-mismatch + in: + arr: [7] + pieces: + - [8] + out: false + - name: all-singletons + in: + arr: [5, 1, 9, 3, 7] + pieces: + - [7] + - [3] + - [9] + - [1] + - [5] + out: true + - name: reversed-piece-order + in: + arr: [1, 2, 3, 4, 5, 6] + pieces: + - [5, 6] + - [1, 2] + - [3, 4] + out: true + - name: wrong-piece-boundary + in: + arr: [1, 2, 3, 4] + pieces: + - [1, 2] + - [4] + - [3] + out: true + - name: internal-order-failure + in: + arr: [1, 2, 3, 4] + pieces: + - [2, 1] + - [3, 4] + out: false + - name: wrong-first-value + in: + arr: [10, 20, 30] + pieces: + - [10, 21] + - [30] + - [20] + out: false + - name: missing-value + in: + arr: [2, 4, 6, 8] + pieces: + - [2] + - [4, 6] + - [9] + out: false + - name: extra-value-in-piece + in: + arr: [2, 4, 6] + pieces: + - [2, 4, 6, 8] + out: false + - name: two-long-pieces + in: + arr: [11, 12, 13, 21, 22, 23] + pieces: + - [21, 22, 23] + - [11, 12, 13] + out: true + - name: alternating-singletons + in: + arr: [100, 1, 99, 2, 98, 3] + pieces: + - [98] + - [1] + - [3] + - [100] + - [2] + - [99] + out: true + - name: duplicate-piece-start-impossible + in: + arr: [1, 2, 3, 4] + pieces: + - [1, 3] + - [2, 4] + out: false + - name: negative-not-allowed-domain-edge + in: + arr: [1, 100, 2, 99] + pieces: + - [99] + - [1, 100] + - [2] + out: true + - name: max-value-singletons + in: + arr: [100, 99, 98, 97] + pieces: + - [97] + - [98] + - [99] + - [100] + out: true + - name: adjacent-piece-split + in: + arr: [4, 8, 15, 16, 23, 42] + pieces: + - [15] + - [42] + - [4, 8] + - [23] + - [16] + out: true + - name: adjacent-piece-merge-invalid + in: + arr: [4, 8, 15, 16] + pieces: + - [4, 8, 16] + - [15] + out: false + - name: three-singletons + in: + arr: [12, 34, 56] + pieces: + - [56] + - [12] + - [34] + out: true + - name: two-elements-wrong-order + in: + arr: [1, 2] + pieces: + - [2, 1] + out: false + - name: two-elements-correct + in: + arr: [1, 2] + pieces: + - [1, 2] + out: true + - name: long-piece-at-end + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8, 9] + pieces: + - [1] + - [2] + - [3] + - [4] + - [5, 6, 7, 8, 9] + out: true + - name: long-piece-at-start + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8, 9] + pieces: + - [6] + - [7] + - [8] + - [9] + - [1, 2, 3, 4, 5] + out: true + - name: long-piece-corrupted-tail + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8, 9] + pieces: + - [1, 2, 3, 4, 6] + - [5] + - [7] + - [8] + - [9] + out: false + - name: every-piece-length-varies + in: + arr: [2, 3, 10, 11, 12, 20, 30, 31] + pieces: + - [30, 31] + - [2, 3] + - [20] + - [10, 11, 12] + out: true + - name: wrong-piece-selected-by-first + in: + arr: [1, 2, 3, 4, 5] + pieces: + - [1, 2, 5] + - [3, 4] + out: false + - name: all-values-high + in: + arr: [96, 97, 98, 99, 100] + pieces: + - [98, 99] + - [100] + - [96, 97] + out: true + - name: interleaved-piece-list + in: + arr: [6, 7, 8, 9, 10, 11] + pieces: + - [9, 10] + - [6] + - [11] + - [7, 8] + out: true + - name: one-element-piece-breaks-order + in: + arr: [6, 7, 8, 9] + pieces: + - [6, 8] + - [7] + - [9] + out: false + - name: length-eight-balanced + in: + arr: [13, 14, 15, 16, 17, 18, 19, 20] + pieces: + - [17, 18] + - [13, 14, 15, 16] + - [19] + - [20] + out: true + - name: length-eight-invalid + in: + arr: [13, 14, 15, 16, 17, 18, 19, 20] + pieces: + - [13, 14, 16] + - [15, 17] + - [18, 19, 20] + out: false + - name: maximum-length-single-piece + in: + arr: + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] + pieces: + - [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + ] + out: true + - name: maximum-length-piece-wrong-middle + in: + arr: + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] + pieces: + - [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 12, + 11, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + ] + out: false diff --git a/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.cpp b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.cpp new file mode 100644 index 00000000..b1f639f8 --- /dev/null +++ b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool canFormArray(vector& arr, vector>& pieces) { + vector a; + vector> remaining = pieces; + for (int i : arr) { + for (int j = 0; j < remaining.size(); j++) { + if (find(remaining[j].begin(), remaining[j].end(), i) != remaining[j].end()) { + a.insert(a.end(), remaining[j].begin(), remaining[j].end()); + remaining.erase(remaining.begin() + j); + break; + } + } + } + return a == arr; + } +}; diff --git a/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.cs b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.cs new file mode 100644 index 00000000..d20c18c8 --- /dev/null +++ b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public bool CanFormArray(int[] arr, int[][] pieces) { + List a = new List(); + List remaining = pieces.ToList(); + foreach (int i in arr) { + for (int j = 0; j < remaining.Count; j++) { + if (remaining[j].Contains(i)) { + a.AddRange(remaining[j]); + remaining.RemoveAt(j); + break; + } + } + } + if (a.Count != arr.Length) return false; + for (int idx = 0; idx < a.Count; idx++) { + if (a[idx] != arr[idx]) return false; + } + return true; + } +} diff --git a/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.dart b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.dart new file mode 100644 index 00000000..19bb6201 --- /dev/null +++ b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.dart @@ -0,0 +1,20 @@ +class Solution { + bool canFormArray(List arr, List> pieces) { + List a = []; + List> remaining = List.from(pieces); + for (int i in arr) { + for (int j = 0; j < remaining.length; j++) { + if (remaining[j].contains(i)) { + a.addAll(remaining[j]); + remaining.removeAt(j); + break; + } + } + } + if (a.length != arr.length) return false; + for (int idx = 0; idx < a.length; idx++) { + if (a[idx] != arr[idx]) return false; + } + return true; + } +} diff --git a/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.go b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.go new file mode 100644 index 00000000..2d42aa07 --- /dev/null +++ b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.go @@ -0,0 +1,32 @@ +func canFormArray(arr []int, pieces [][]int) bool { + a := []int{} + remaining := make([][]int, len(pieces)) + copy(remaining, pieces) + for _, i := range arr { + for j, piece := range remaining { + if contains(piece, i) { + a = append(a, piece...) + remaining = append(remaining[:j], remaining[j+1:]...) + break + } + } + } + if len(a) != len(arr) { + return false + } + for idx, val := range a { + if val != arr[idx] { + return false + } + } + return true +} + +func contains(slice []int, val int) bool { + for _, v := range slice { + if v == val { + return true + } + } + return false +} diff --git a/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.java b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.java new file mode 100644 index 00000000..4021559e --- /dev/null +++ b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.java @@ -0,0 +1,26 @@ +class Solution { + public boolean canFormArray(int[] arr, int[][] pieces) { + List a = new ArrayList<>(); + List> p = new ArrayList<>(); + for (int[] piece : pieces) { + List list = new ArrayList<>(); + for (int num : piece) list.add(num); + p.add(list); + } + for (int i : arr) { + for (int j = 0; j < p.size(); j++) { + List piece = p.get(j); + if (piece.contains(i)) { + a.addAll(piece); + p.remove(j); + break; + } + } + } + if (a.size() != arr.length) return false; + for (int i = 0; i < arr.length; i++) { + if (a.get(i) != arr[i]) return false; + } + return true; + } +} diff --git a/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.kt b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.kt new file mode 100644 index 00000000..01270e50 --- /dev/null +++ b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun canFormArray(arr: IntArray, pieces: Array): Boolean { + val a = mutableListOf() + val p = pieces.toMutableList() + for (i in arr) { + for (j in p.indices) { + if (p[j].contains(i)) { + a.addAll(p[j].toList()) + p.removeAt(j) + break + } + } + } + return a == arr.toList() + } +} diff --git a/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.py b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.py new file mode 100644 index 00000000..cda83222 --- /dev/null +++ b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.py @@ -0,0 +1,13 @@ +class Solution(object): + def canFormArray(self, arr, pieces): + a = [] + for i in arr: + for j in pieces: + if i in j: + for k in j: + a.append(k) + pieces.remove(j) + break + if a == arr: + return True + return False diff --git a/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.py2 b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.py2 new file mode 100644 index 00000000..64a5472a --- /dev/null +++ b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def canFormArray(self, arr, pieces): + """ + :type arr: List[int] + :type pieces: List[List[int]] + :rtype: bool + """ + a=[] + for i in arr: + for j in pieces: + if i in j: + for k in j: + a.append(k) + pieces.remove(j) + break + if a==arr: + return True + return False diff --git a/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.rb b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.rb new file mode 100644 index 00000000..e29bc2fe --- /dev/null +++ b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.rb @@ -0,0 +1,16 @@ +# @param {Integer[]} arr +# @param {Integer[][]} pieces +# @return {Boolean} +def can_form_array(arr, pieces) + a = [] + arr.each do |i| + pieces.each_with_index do |j, idx| + if j.include?(i) + j.each { |k| a << k } + pieces.delete_at(idx) + break + end + end + end + a == arr +end diff --git a/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.rs b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.rs new file mode 100644 index 00000000..3ee02b70 --- /dev/null +++ b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn can_form_array(arr: Vec, pieces: Vec>) -> bool { + let mut a: Vec = Vec::new(); + let mut remaining = pieces.clone(); + for &i in &arr { + for j in 0..remaining.len() { + if remaining[j].contains(&i) { + a.extend(&remaining[j]); + remaining.remove(j); + break; + } + } + } + a == arr + } +} diff --git a/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.swift b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.swift new file mode 100644 index 00000000..80d23d24 --- /dev/null +++ b/tests/1501-2000/1640. check-array-formation-through-concatenation/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func canFormArray(_ arr: [Int], _ pieces: [[Int]]) -> Bool { + var a: [Int] = [] + var remaining = pieces + for i in arr { + for j in 0.. v === arr[idx]); +} diff --git a/tests/1501-2000/1641. count-sorted-vowel-strings/manifest.yaml b/tests/1501-2000/1641. count-sorted-vowel-strings/manifest.yaml new file mode 100644 index 00000000..dd5c3d7f --- /dev/null +++ b/tests/1501-2000/1641. count-sorted-vowel-strings/manifest.yaml @@ -0,0 +1,213 @@ +entry: + id: 1641 + title: "count-sorted-vowel-strings" + params: + n: + type: int + call: + cpp: "Solution().countVowelStrings({n})" + rust: "Solution::count_vowel_strings({n})" + python3: "Solution().countVowelStrings({n})" + python2: "Solution().countVowelStrings({n})" + ruby: "count_vowel_strings({n})" + java: "new Solution().countVowelStrings({n})" + csharp: "new Solution().CountVowelStrings({n})" + kotlin: "Solution().countVowelStrings({n})" + go: "countVowelStrings({n})" + dart: "Solution().countVowelStrings({n})" + swift: "Solution().countVowelStrings({n})" + typescript: "countVowelStrings({n})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().countVowelStrings(n, {result})" + checker: | + class Checker: + def countVowelStrings(self, n, result): + return isinstance(result, int) and result == (n + 4) * (n + 3) * (n + 2) * (n + 1) // 24 + +seed: 1641 + +tests: + - name: n-1 + in: + n: 1 + out: 5 + - name: n-2 + in: + n: 2 + out: 15 + - name: n-3 + in: + n: 3 + out: 35 + - name: n-4 + in: + n: 4 + out: 70 + - name: n-5 + in: + n: 5 + out: 126 + - name: n-6 + in: + n: 6 + out: 210 + - name: n-7 + in: + n: 7 + out: 330 + - name: n-8 + in: + n: 8 + out: 495 + - name: n-9 + in: + n: 9 + out: 715 + - name: n-10 + in: + n: 10 + out: 1001 + - name: n-11 + in: + n: 11 + out: 1365 + - name: n-12 + in: + n: 12 + out: 1820 + - name: n-13 + in: + n: 13 + out: 2380 + - name: n-14 + in: + n: 14 + out: 3060 + - name: n-15 + in: + n: 15 + out: 3876 + - name: n-16 + in: + n: 16 + out: 4845 + - name: n-17 + in: + n: 17 + out: 5985 + - name: n-18 + in: + n: 18 + out: 7315 + - name: n-19 + in: + n: 19 + out: 8855 + - name: n-20 + in: + n: 20 + out: 10626 + - name: n-21 + in: + n: 21 + out: 12650 + - name: n-22 + in: + n: 22 + out: 14950 + - name: n-23 + in: + n: 23 + out: 17550 + - name: n-24 + in: + n: 24 + out: 20475 + - name: n-25 + in: + n: 25 + out: 23751 + - name: n-26 + in: + n: 26 + out: 27405 + - name: n-27 + in: + n: 27 + out: 31465 + - name: n-28 + in: + n: 28 + out: 35960 + - name: n-29 + in: + n: 29 + out: 40920 + - name: n-30 + in: + n: 30 + out: 46376 + - name: n-31 + in: + n: 31 + out: 52360 + - name: n-32 + in: + n: 32 + out: 58905 + - name: n-33 + in: + n: 33 + out: 66045 + - name: n-34 + in: + n: 34 + out: 73815 + - name: n-35 + in: + n: 35 + out: 82251 + - name: generated-36 + in: + n: + gen: "int" + min: 36 + max: 36 + seed: 3601641 + - name: generated-40 + in: + n: + gen: "int" + min: 40 + max: 40 + seed: 4001641 + - name: generated-45 + in: + n: + gen: "int" + min: 45 + max: 45 + seed: 4501641 + - name: generated-49 + in: + n: + gen: "int" + min: 49 + max: 49 + seed: 4901641 + - name: generated-50 + in: + n: + gen: "int" + min: 50 + max: 50 + seed: 5001641 diff --git a/tests/1501-2000/1641. count-sorted-vowel-strings/sol.cpp b/tests/1501-2000/1641. count-sorted-vowel-strings/sol.cpp new file mode 100644 index 00000000..6e010b51 --- /dev/null +++ b/tests/1501-2000/1641. count-sorted-vowel-strings/sol.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int countVowelStrings(int n) { + if(n==1){ + return 5; + }else if(n==2){ + return 15; + }else if(n==3){ + return 35; + } + vector x(n-2,0); + x[0]=10; + int c=5; + for(int i=0;i y(n-1,0); + y[0]=10; + for(int i=0;i x=List.filled(n-2,0); + x[0]=10; + int c=5; + for(int i=0;i y=List.filled(n-1,0); + y[0]=10; + for(int i=0;i int: + if n == 1: + return 5 + elif n == 2: + return 15 + elif n == 3: + return 35 + x = [10] + c = 5 + for i in range(n - 3): + x.append(x[i] + c) + c += 1 + y = [10] + for i in range(n - 2): + y.append(y[i] + x[i]) + return sum(y) + 5 diff --git a/tests/1501-2000/1641. count-sorted-vowel-strings/sol.py2 b/tests/1501-2000/1641. count-sorted-vowel-strings/sol.py2 new file mode 100644 index 00000000..8cafd0bb --- /dev/null +++ b/tests/1501-2000/1641. count-sorted-vowel-strings/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def countVowelStrings(self, n): + """ + :type n: int + :rtype: int + """ + if n==1: + return 5 + elif n==2: + return 15 + elif n==3: + return 35 + x=[10] + c=5 + for i in range(n-3): + x.append(x[i]+c) + c+=1 + y=[10] + for i in range(n-2): + y.append(y[i]+x[i]) + return sum(y)+5 diff --git a/tests/1501-2000/1641. count-sorted-vowel-strings/sol.rb b/tests/1501-2000/1641. count-sorted-vowel-strings/sol.rb new file mode 100644 index 00000000..32fc83c2 --- /dev/null +++ b/tests/1501-2000/1641. count-sorted-vowel-strings/sol.rb @@ -0,0 +1,22 @@ +# @param {Integer} n +# @return {Integer} +def count_vowel_strings(n) + if n==1 + return 5 + elsif n==2 + return 15 + elsif n==3 + return 35 + end + x=[10] + c=5 + (0...(n-3)).each do |i| + x.append(x[i]+c) + c+=1 + end + y=[10] + (0...(n-2)).each do |i| + y.append(y[i]+x[i]) + end + return y.sum+5 +end diff --git a/tests/1501-2000/1641. count-sorted-vowel-strings/sol.rs b/tests/1501-2000/1641. count-sorted-vowel-strings/sol.rs new file mode 100644 index 00000000..aabe4661 --- /dev/null +++ b/tests/1501-2000/1641. count-sorted-vowel-strings/sol.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn count_vowel_strings(n: i32) -> i32 { + if n==1{ + return 5; + }else if n==2{ + return 15; + }else if n==3{ + return 35; + } + let n=n as usize; + let mut x:Vec=vec![0;n-2]; + x[0]=10; + let mut c=5; + for i in 0..n-3{ + x[i+1]=x[i]+c; + c+=1; + } + let mut y:Vec=vec![0;n-1]; + y[0]=10; + for i in 0..n-2{ + y[i+1]=y[i]+x[i]; + } + let sum:i32=y.iter().sum(); + return sum+5; + } +} diff --git a/tests/1501-2000/1641. count-sorted-vowel-strings/sol.swift b/tests/1501-2000/1641. count-sorted-vowel-strings/sol.swift new file mode 100644 index 00000000..9b0a88f0 --- /dev/null +++ b/tests/1501-2000/1641. count-sorted-vowel-strings/sol.swift @@ -0,0 +1,26 @@ +class Solution { + func countVowelStrings(_ n: Int) -> Int { + if n==1{ + return 5 + }else if n==2{ + return 15 + }else if n==3{ + return 35 + } + var x=Array(repeating:0,count:n-2) + x[0]=10 + var c=5 + if n>3{ + for i in 0..<(n-3){ + x[i+1]=x[i]+c + c+=1 + } + } + var y=Array(repeating:0,count:n-1) + y[0]=10 + for i in 0..<(n-2){ + y[i+1]=y[i]+x[i] + } + return y.reduce(0,+)+5 + } +} diff --git a/tests/1501-2000/1641. count-sorted-vowel-strings/sol.ts b/tests/1501-2000/1641. count-sorted-vowel-strings/sol.ts new file mode 100644 index 00000000..4f801bdd --- /dev/null +++ b/tests/1501-2000/1641. count-sorted-vowel-strings/sol.ts @@ -0,0 +1,23 @@ +function countVowelStrings(n: number): number { + if (n === 1) { + return 5; + } else if (n === 2) { + return 15; + } else if (n === 3) { + return 35; + } + const x: number[] = new Array(n - 2).fill(0); + x[0] = 10; + let c = 5; + for (let i = 0; i < n - 3; i++) { + x[i + 1] = x[i] + c; + c++; + } + const y: number[] = new Array(n - 1).fill(0); + y[0] = 10; + for (let i = 0; i < n - 2; i++) { + y[i + 1] = y[i] + x[i]; + } + let sum = y.reduce((a, b) => a + b, 0); + return sum + 5; +} diff --git a/tests/1501-2000/1642. furthest-building-you-can-reach/manifest.yaml b/tests/1501-2000/1642. furthest-building-you-can-reach/manifest.yaml new file mode 100644 index 00000000..4a94075a --- /dev/null +++ b/tests/1501-2000/1642. furthest-building-you-can-reach/manifest.yaml @@ -0,0 +1,331 @@ +entry: + id: 1642 + title: "furthest-building-you-can-reach" + params: + heights: + type: array + items: + type: int + bricks: + type: int + ladders: + type: int + call: + cpp: "Solution().furthestBuilding({heights}, {bricks}, {ladders})" + rust: "Solution::furthest_building({heights}, {bricks}, {ladders})" + python3: "Solution().furthestBuilding({heights}, {bricks}, {ladders})" + python2: "Solution().furthestBuilding({heights}, {bricks}, {ladders})" + ruby: "furthest_building({heights}, {bricks}, {ladders})" + java: "new Solution().furthestBuilding({heights}, {bricks}, {ladders})" + csharp: "new Solution().FurthestBuilding({heights}, {bricks}, {ladders})" + kotlin: "Solution().furthestBuilding({heights}, {bricks}, {ladders})" + go: "furthestBuilding({heights}, {bricks}, {ladders})" + dart: "Solution().furthestBuilding({heights}, {bricks}, {ladders})" + swift: "Solution().furthestBuilding({heights}, {bricks}, {ladders})" + typescript: "furthestBuilding({heights}, {bricks}, {ladders})" +judge: + type: exact +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().furthestBuilding(heights, bricks, ladders, {result})" + checker: | + import heapq + class Checker: + def furthestBuilding(self, heights, bricks, ladders, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + heap = [] + remaining = bricks + answer = len(heights) - 1 + for i in range(1, len(heights)): + climb = heights[i] - heights[i - 1] + if climb <= 0: + continue + heapq.heappush(heap, climb) + if len(heap) > ladders: + remaining -= heapq.heappop(heap) + if remaining < 0: + answer = i - 1 + break + return result == answer +seed: 1642 +tests: + - name: example-one + in: + heights: [4, 2, 7, 6, 9, 14, 12] + bricks: 5 + ladders: 1 + out: 4 + - name: example-two + in: + heights: [4, 12, 2, 7, 3, 18, 20, 3, 19] + bricks: 10 + ladders: 2 + out: 7 + - name: example-three + in: + heights: [14, 3, 19, 3] + bricks: 17 + ladders: 0 + out: 3 + - name: single-building + in: + heights: [9] + bricks: 0 + ladders: 0 + out: 0 + - name: all-descending + in: + heights: [10, 9, 8, 7, 6, 5] + bricks: 0 + ladders: 0 + out: 5 + - name: equal-heights + in: + heights: [7, 7, 7, 7, 7] + bricks: 0 + ladders: 0 + out: 4 + - name: no-resources + in: + heights: [1, 2, 3] + bricks: 0 + ladders: 0 + out: 0 + - name: one-ladder + in: + heights: [1, 5, 2, 6] + bricks: 0 + ladders: 1 + out: 2 + - name: bricks-exact + in: + heights: [1, 4, 2, 6] + bricks: 7 + ladders: 0 + out: 3 + - name: bricks-one-short + in: + heights: [1, 4, 2, 6] + bricks: 6 + ladders: 0 + out: 2 + - name: ladder-saves-largest + in: + heights: [1, 6, 2, 10] + bricks: 5 + ladders: 1 + out: 3 + - name: ladder-saves-early + in: + heights: [1, 10, 11] + bricks: 1 + ladders: 1 + out: 2 + - name: ladders-more-than-climbs + in: + heights: [1, 4, 2, 8] + bricks: 0 + ladders: 3 + out: 3 + - name: zero-bricks-many-ladders + in: + heights: [2, 100, 1, 99, 3] + bricks: 0 + ladders: 2 + out: 4 + - name: alternating-small + in: + heights: [5, 6, 5, 6, 5, 6] + bricks: 2 + ladders: 0 + out: 4 + - name: large-climb-first + in: + heights: [1, 1000000, 2] + bricks: 999998 + ladders: 0 + out: 0 + - name: large-climb-ladder + in: + heights: [1, 1000000, 2] + bricks: 0 + ladders: 1 + out: 2 + - name: delayed-large-climb + in: + heights: [1, 2, 3, 1000, 4] + bricks: 2 + ladders: 1 + out: 4 + - name: several-equal-climbs + in: + heights: [3, 8, 13, 18, 23] + bricks: 10 + ladders: 1 + out: 3 + - name: descending-then-climb + in: + heights: [20, 10, 9, 15, 14, 30] + bricks: 10 + ladders: 1 + out: 5 + - name: alternating-large + in: + heights: [1, 50, 2, 49, 3, 48, 4] + bricks: 47 + ladders: 2 + out: 6 + - name: all-resources + in: + heights: [1, 100, 2, 200, 3] + bricks: 0 + ladders: 4 + out: 4 + - name: exact-ladder-count + in: + heights: [1, 5, 10, 15] + bricks: 0 + ladders: 3 + out: 3 + - name: zero-ladder-flat + in: + heights: [5, 4, 4, 3, 3] + bricks: 0 + ladders: 0 + out: 4 + - name: mixed-tiny + in: + heights: [3, 1, 2, 1, 4, 2] + bricks: 2 + ladders: 0 + out: 3 + - name: mixed-tiny-ladder + in: + heights: [3, 1, 2, 1, 4, 2] + bricks: 0 + ladders: 1 + out: 3 + - name: expensive-climb-choice + in: + heights: [1, 2, 100, 3, 4] + bricks: 3 + ladders: 1 + out: 4 + - name: many-downs + in: + heights: [100, 1, 2, 1, 3, 1, 4] + bricks: 3 + ladders: 0 + out: 5 + - name: high-bricks + in: + heights: [1000000, 999999, 1000000] + bricks: 1 + ladders: 0 + out: 2 + - name: high-ladder-count + in: + heights: [1, 100, 1, 100, 1, 100] + bricks: 0 + ladders: 5 + out: 5 + - name: repeated-plateaus + in: + heights: [2, 2, 5, 5, 3, 8, 8, 9] + bricks: 5 + ladders: 1 + out: 7 + - name: generator-random-small + in: + heights: + gen: array + len: 100 + of: + gen: int + min: 1 + max: 1000 + elemType: int + bricks: + gen: int + min: 0 + max: 10000 + ladders: + gen: int + min: 0 + max: 100 + - name: generator-medium + in: + heights: + gen: array + len: 1000 + of: + gen: int + min: 1 + max: 100000 + elemType: int + bricks: + gen: int + min: 0 + max: 1000000 + ladders: + gen: int + min: 0 + max: 1000 + - name: generator-large + in: + heights: + gen: array + len: 100000 + of: + gen: int + min: 1 + max: 1000000 + elemType: int + bricks: + gen: int + min: 0 + max: 1000000000 + ladders: + gen: int + min: 0 + max: 100000 + - name: generator-large-low-bricks + in: + heights: + gen: array + len: 100000 + of: + gen: int + min: 1 + max: 1000000 + elemType: int + bricks: + gen: int + min: 0 + max: 1000 + ladders: + gen: int + min: 0 + max: 20 + - name: generator-large-many-ladders + in: + heights: + gen: array + len: 50000 + of: + gen: int + min: 1 + max: 1000000 + elemType: int + bricks: + gen: int + min: 0 + max: 100000 + ladders: + gen: int + min: 0 + max: 50000 diff --git a/tests/1501-2000/1642. furthest-building-you-can-reach/sol.cpp b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.cpp new file mode 100644 index 00000000..879dbc9d --- /dev/null +++ b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.cpp @@ -0,0 +1,24 @@ +#include + +class Solution { +public: + int furthestBuilding(vector& heights, int bricks, int ladders) { + priority_queue, greater> heap; + int n = heights.size(); + for (int i = 1; i < n; i++) { + int climb = heights[i] - heights[i-1]; + if (climb <= 0) continue; + heap.push(climb); + if (heap.size() > ladders) { + int diff = heap.top(); + heap.pop(); + if (bricks >= diff) { + bricks -= diff; + } else { + return i-1; + } + } + } + return n-1; + } +}; diff --git a/tests/1501-2000/1642. furthest-building-you-can-reach/sol.cs b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.cs new file mode 100644 index 00000000..3f55463a --- /dev/null +++ b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; + +public class Solution { + public int FurthestBuilding(int[] heights, int bricks, int ladders) { + var heap = new SortedDictionary(); + int heapCount = 0; + int n = heights.Length; + for (int i = 1; i < n; i++) { + int climb = heights[i] - heights[i-1]; + if (climb <= 0) continue; + heap[climb] = heap.TryGetValue(climb, out int count) ? count + 1 : 1; + heapCount++; + if (heapCount > ladders) { + int min = heap.Keys.First(); + if (heap[min] == 1) heap.Remove(min); + else heap[min]--; + heapCount--; + if (bricks >= min) { + bricks -= min; + } else { + return i-1; + } + } + } + return n-1; + } +} diff --git a/tests/1501-2000/1642. furthest-building-you-can-reach/sol.dart b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.dart new file mode 100644 index 00000000..9e16a882 --- /dev/null +++ b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.dart @@ -0,0 +1,22 @@ +import 'dart:collection'; + +class Solution { + int furthestBuilding(List heights, int bricks, int ladders) { + final heap = PriorityQueue((a, b) => a - b); + final n = heights.length; + for (int i = 1; i < n; i++) { + final climb = heights[i] - heights[i-1]; + if (climb <= 0) continue; + heap.add(climb); + if (heap.length > ladders) { + final diff = heap.removeFirst(); + if (bricks >= diff) { + bricks -= diff; + } else { + return i-1; + } + } + } + return n-1; + } +} diff --git a/tests/1501-2000/1642. furthest-building-you-can-reach/sol.go b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.go new file mode 100644 index 00000000..1e2a0f51 --- /dev/null +++ b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.go @@ -0,0 +1,37 @@ +import containerheap "container/heap" + +type IntHeap []int + +func (h IntHeap) Len() int { return len(h) } +func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } +func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.(int)) } +func (h *IntHeap) Pop() interface{} { + old := *h + n := len(old) + x := old[n-1] + *h = old[0:n-1] + return x +} + +func furthestBuilding(heights []int, bricks int, ladders int) int { + h := &IntHeap{} + containerheap.Init(h) + n := len(heights) + for i := 1; i < n; i++ { + climb := heights[i] - heights[i-1] + if climb <= 0 { + continue + } + containerheap.Push(h, climb) + if h.Len() > ladders { + diff := containerheap.Pop(h).(int) + if bricks >= diff { + bricks -= diff + } else { + return i-1 + } + } + } + return n-1 +} diff --git a/tests/1501-2000/1642. furthest-building-you-can-reach/sol.java b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.java new file mode 100644 index 00000000..27d97a4f --- /dev/null +++ b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.java @@ -0,0 +1,22 @@ +import java.util.PriorityQueue; + +class Solution { + public int furthestBuilding(int[] heights, int bricks, int ladders) { + PriorityQueue heap = new PriorityQueue<>(); + int n = heights.length; + for (int i = 1; i < n; i++) { + int climb = heights[i] - heights[i-1]; + if (climb <= 0) continue; + heap.offer(climb); + if (heap.size() > ladders) { + int diff = heap.poll(); + if (bricks >= diff) { + bricks -= diff; + } else { + return i-1; + } + } + } + return n-1; + } +} diff --git a/tests/1501-2000/1642. furthest-building-you-can-reach/sol.kt b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.kt new file mode 100644 index 00000000..13f92c8a --- /dev/null +++ b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.kt @@ -0,0 +1,23 @@ +import java.util.PriorityQueue + +class Solution { + fun furthestBuilding(heights: IntArray, bricks: Int, ladders: Int): Int { + var bricks = bricks + val heap = PriorityQueue() + val n = heights.size + for (i in 1 until n) { + val climb = heights[i] - heights[i-1] + if (climb <= 0) continue + heap.offer(climb) + if (heap.size > ladders) { + val diff = heap.poll() + if (bricks >= diff) { + bricks -= diff + } else { + return i-1 + } + } + } + return n-1 + } +} diff --git a/tests/1501-2000/1642. furthest-building-you-can-reach/sol.py b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.py new file mode 100644 index 00000000..9be39c31 --- /dev/null +++ b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.py @@ -0,0 +1,16 @@ +class Solution: + def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int: + heap = [] + n = len(heights) + for i in range(1, n): + climb = heights[i] - heights[i - 1] + if climb <= 0: + continue + heapq.heappush(heap, climb) + if len(heap) > ladders: + diff = heapq.heappop(heap) + if bricks >= diff: + bricks -= diff + else: + return i - 1 + return n - 1 diff --git a/tests/1501-2000/1642. furthest-building-you-can-reach/sol.py2 b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.py2 new file mode 100644 index 00000000..861f4ae1 --- /dev/null +++ b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def furthestBuilding(self, heights, bricks, ladders): + """ + :type heights: List[int] + :type bricks: int + :type ladders: int + :rtype: int + """ + import heapq + heap = [] + n = len(heights) + for i in range(1, n): + climb = heights[i] - heights[i-1] + if climb <= 0: + continue + heapq.heappush(heap, climb) + if len(heap) > ladders: + diff = heapq.heappop(heap) + if bricks >= diff: + bricks -= diff + else: + return i-1 + return n-1 diff --git a/tests/1501-2000/1642. furthest-building-you-can-reach/sol.rb b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.rb new file mode 100644 index 00000000..604ed787 --- /dev/null +++ b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.rb @@ -0,0 +1,23 @@ +# @param {Integer[]} heights +# @param {Integer} bricks +# @param {Integer} ladders +# @return {Integer} +def furthest_building(heights, bricks, ladders) + require 'algorithms' + heap = Containers::MinHeap.new + n = heights.length + (1...n).each do |i| + climb = heights[i] - heights[i-1] + next if climb <= 0 + heap.push(climb) + if heap.size > ladders + diff = heap.pop + if bricks >= diff + bricks -= diff + else + return i-1 + end + end + end + n-1 +end diff --git a/tests/1501-2000/1642. furthest-building-you-can-reach/sol.rs b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.rs new file mode 100644 index 00000000..305bd067 --- /dev/null +++ b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.rs @@ -0,0 +1,26 @@ +use std::collections::BinaryHeap; +use std::cmp::Reverse; + +impl Solution { + pub fn furthest_building(heights: Vec, bricks: i32, ladders: i32) -> i32 { + let mut heap = BinaryHeap::new(); + let n = heights.len(); + let mut bricks = bricks; + let mut ladders = ladders; + for i in 1..n { + let climb = heights[i] - heights[i-1]; + if climb <= 0 { continue; } + heap.push(Reverse(climb)); + if heap.len() > ladders as usize { + if let Some(Reverse(diff)) = heap.pop() { + if bricks >= diff { + bricks -= diff; + } else { + return i as i32 - 1; + } + } + } + } + n as i32 - 1 + } +} diff --git a/tests/1501-2000/1642. furthest-building-you-can-reach/sol.swift b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.swift new file mode 100644 index 00000000..fe006822 --- /dev/null +++ b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.swift @@ -0,0 +1,39 @@ +class Solution { + func furthestBuilding(_ heights: [Int], _ bricks: Int, _ ladders: Int) -> Int { + var bricksLeft = bricks + var heap = [Int]() + let n = heights.count + for i in 1.. 0 { + let parent = (child - 1) / 2 + if heap[parent] <= heap[child] { break } + heap.swapAt(parent, child) + child = parent + } + if heap.count > ladders { + let diff = heap[0] + let last = heap.removeLast() + if !heap.isEmpty { heap[0] = last } + var parent = 0 + while true { + child = parent * 2 + 1 + if child >= heap.count { break } + if child + 1 < heap.count && heap[child + 1] < heap[child] { child += 1 } + if heap[parent] <= heap[child] { break } + heap.swapAt(parent, child) + parent = child + } + if bricksLeft >= diff { + bricksLeft -= diff + } else { + return i-1 + } + } + } + return n-1 + } +} diff --git a/tests/1501-2000/1642. furthest-building-you-can-reach/sol.ts b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.ts new file mode 100644 index 00000000..c4c8bc7e --- /dev/null +++ b/tests/1501-2000/1642. furthest-building-you-can-reach/sol.ts @@ -0,0 +1,49 @@ +function furthestBuilding( + heights: number[], + bricks: number, + ladders: number, +): number { + const heap: number[] = []; + const n = heights.length; + const push = (val: number) => { + heap.push(val); + let i = heap.length - 1; + while (i > 0) { + const p = Math.floor((i - 1) / 2); + if (heap[p] <= heap[i]) break; + [heap[p], heap[i]] = [heap[i], heap[p]]; + i = p; + } + }; + const pop = (): number => { + const result = heap[0]; + const last = heap.pop()!; + if (heap.length > 0) { + heap[0] = last; + let i = 0; + while (true) { + let child = i * 2 + 1; + if (child >= heap.length) break; + if (child + 1 < heap.length && heap[child + 1] < heap[child]) child++; + if (heap[i] <= heap[child]) break; + [heap[i], heap[child]] = [heap[child], heap[i]]; + i = child; + } + } + return result; + }; + for (let i = 1; i < n; i++) { + const climb = heights[i] - heights[i - 1]; + if (climb <= 0) continue; + push(climb); + if (heap.length > ladders) { + const diff = pop(); + if (bricks >= diff) { + bricks -= diff; + } else { + return i - 1; + } + } + } + return n - 1; +} diff --git a/tests/1501-2000/1643. kth-smallest-instructions/manifest.yaml b/tests/1501-2000/1643. kth-smallest-instructions/manifest.yaml new file mode 100644 index 00000000..e261f8bd --- /dev/null +++ b/tests/1501-2000/1643. kth-smallest-instructions/manifest.yaml @@ -0,0 +1,237 @@ +entry: + id: 1643 + title: "kth-smallest-instructions" + params: + destination: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().kthSmallestPath({destination}, {k})" + rust: "Solution::kth_smallest_path({destination}, {k})" + python3: "Solution().kthSmallestPath({destination}, {k})" + python2: "Solution().kthSmallestPath({destination}, {k})" + ruby: "kth_smallest_path({destination}, {k})" + java: "new Solution().kthSmallestPath({destination}, {k})" + csharp: "new Solution().KthSmallestPath({destination}, {k})" + kotlin: "Solution().kthSmallestPath({destination}, {k})" + go: "kthSmallestPath({destination}, {k})" + dart: "Solution().kthSmallestPath({destination}, {k})" + swift: "Solution().kthSmallestPath({destination}, {k})" + typescript: "kthSmallestPath({destination}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().kthSmallestPath(destination, k, {result})" + checker: | + from math import comb + + class Checker: + def kthSmallestPath(self, destination, k, result): + if not isinstance(result, str): + return False + rows, cols = destination + if len(result) != rows + cols: + return False + if result.count("H") != cols or result.count("V") != rows: + return False + expected = [] + rank = k - 1 + while rows or cols: + block = comb(rows + cols - 1, cols - 1) if cols else 0 + if rank < block: + expected.append("H") + cols -= 1 + else: + expected.append("V") + rank -= block + rows -= 1 + return result == "".join(expected) + +seed: 1643 + +tests: + - name: "one-one-first" + in: + destination: [1, 1] + k: 1 + out: "HV" + - name: "one-one-last" + in: + destination: [1, 1] + k: 2 + out: "VH" + - name: "one-two-first" + in: + destination: [1, 2] + k: 1 + out: "HHV" + - name: "one-two-middle" + in: + destination: [1, 2] + k: 2 + out: "HVH" + - name: "one-two-last" + in: + destination: [1, 2] + k: 3 + out: "VHH" + - name: "two-one-first" + in: + destination: [2, 1] + k: 1 + out: "HVV" + - name: "two-one-middle" + in: + destination: [2, 1] + k: 2 + out: "VHV" + - name: "two-one-last" + in: + destination: [2, 1] + k: 3 + out: "VVH" + - name: "example-first" + in: + destination: [2, 3] + k: 1 + out: "HHHVV" + - name: "example-second" + in: + destination: [2, 3] + k: 2 + out: "HHVHV" + - name: "example-third" + in: + destination: [2, 3] + k: 3 + out: "HHVVH" + - name: "example-last" + in: + destination: [2, 3] + k: 10 + out: "VVHHH" + - name: "three-two-first" + in: + destination: [3, 2] + k: 1 + out: "HHVVV" + - name: "three-two-last" + in: + destination: [3, 2] + k: 10 + out: "VVVHH" + - name: "three-three-first" + in: + destination: [3, 3] + k: 1 + out: "HHHVVV" + - name: "three-three-middle" + in: + destination: [3, 3] + k: 10 + out: "HVVVHH" + - name: "three-three-last" + in: + destination: [3, 3] + k: 20 + out: "VVVHHH" + - name: "four-one-first" + in: + destination: [4, 1] + k: 1 + out: "HVVVV" + - name: "four-one-last" + in: + destination: [4, 1] + k: 5 + out: "VVVVH" + - name: "one-four-first" + in: + destination: [1, 4] + k: 1 + out: "HHHHV" + - name: "one-four-last" + in: + destination: [1, 4] + k: 5 + out: "VHHHH" + - name: "five-two-first" + in: + destination: [5, 2] + k: 1 + out: "HHVVVVV" + - name: "five-two-middle" + in: + destination: [5, 2] + k: 10 + out: "VHVVVHV" + - name: "two-five-first" + in: + destination: [2, 5] + k: 1 + out: "HHHHHVV" + - name: "two-five-middle" + in: + destination: [2, 5] + k: 10 + out: "HHVVHHH" + - name: "five-five-first" + in: + destination: [5, 5] + k: 1 + out: "HHHHHVVVVV" + - name: "five-five-middle" + in: + destination: [5, 5] + k: 50 + out: "HHVVVHVHHV" + - name: "five-five-last" + in: + destination: [5, 5] + k: 252 + out: "VVVVVHHHHH" + - name: "ten-one-first" + in: + destination: [10, 1] + k: 1 + out: "HVVVVVVVVVV" + - name: "one-ten-middle" + in: + destination: [1, 10] + k: 10 + out: "HVHHHHHHHHH" + - name: "ten-ten-first" + in: + destination: [10, 10] + k: 1 + out: "HHHHHHHHHHVVVVVVVVVV" + - name: "ten-ten-middle" + in: + destination: [10, 10] + k: 500 + out: "HHHHHHVHVVVVVVVHVHHV" + - name: "ten-ten-last" + in: + destination: [10, 10] + k: 184756 + out: "VVVVVVVVVVHHHHHHHHHH" + - name: "fifteen-one-last" + in: + destination: [15, 1] + k: 15 + out: "VVVVVVVVVVVVVVHV" + - name: "one-fifteen-middle" + in: + destination: [1, 15] + k: 15 + out: "HVHHHHHHHHHHHHHH" diff --git a/tests/1501-2000/1643. kth-smallest-instructions/sol.cpp b/tests/1501-2000/1643. kth-smallest-instructions/sol.cpp new file mode 100644 index 00000000..2d968e2a --- /dev/null +++ b/tests/1501-2000/1643. kth-smallest-instructions/sol.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + string kthSmallestPath(vector& destination, int k) { + int rows = destination[0]; + int cols = destination[1]; + string path; + long long k_local = k - 1; + + while (rows > 0 || cols > 0) { + long long paths_with_h = 0; + if (cols > 0) { + paths_with_h = combination(rows + cols - 1, cols - 1); + } + + if (k_local < paths_with_h) { + path.push_back('H'); + cols--; + } else { + path.push_back('V'); + k_local -= paths_with_h; + rows--; + } + } + return path; + } + +private: + long long combination(int n, int r) { + if (r == 0 || r == n) return 1; + r = min(r, n - r); + long long result = 1; + for (int i = 1; i <= r; ++i) { + result = result * (n - r + i) / i; + } + return result; + } +}; diff --git a/tests/1501-2000/1643. kth-smallest-instructions/sol.cs b/tests/1501-2000/1643. kth-smallest-instructions/sol.cs new file mode 100644 index 00000000..dc9a6b1a --- /dev/null +++ b/tests/1501-2000/1643. kth-smallest-instructions/sol.cs @@ -0,0 +1,35 @@ +public class Solution { + public string KthSmallestPath(int[] destination, int k) { + int rows = destination[0]; + int cols = destination[1]; + var path = new StringBuilder(); + long kLocal = k - 1; + + while (rows > 0 || cols > 0) { + long pathsWithH = 0; + if (cols > 0) { + pathsWithH = Combination(rows + cols - 1, cols - 1); + } + + if (kLocal < pathsWithH) { + path.Append('H'); + cols--; + } else { + path.Append('V'); + kLocal -= pathsWithH; + rows--; + } + } + return path.ToString(); + } + + private long Combination(int n, int r) { + if (r == 0 || r == n) return 1; + r = Math.Min(r, n - r); + long result = 1; + for (int i = 1; i <= r; i++) { + result = result * (n - r + i) / i; + } + return result; + } +} diff --git a/tests/1501-2000/1643. kth-smallest-instructions/sol.dart b/tests/1501-2000/1643. kth-smallest-instructions/sol.dart new file mode 100644 index 00000000..b4371950 --- /dev/null +++ b/tests/1501-2000/1643. kth-smallest-instructions/sol.dart @@ -0,0 +1,35 @@ +class Solution { + String kthSmallestPath(List destination, int k) { + int rows = destination[0]; + int cols = destination[1]; + List path = []; + int kLocal = k - 1; + + while (rows > 0 || cols > 0) { + int pathsWithH = 0; + if (cols > 0) { + pathsWithH = combination(rows + cols - 1, cols - 1); + } + + if (kLocal < pathsWithH) { + path.add('H'); + cols--; + } else { + path.add('V'); + kLocal -= pathsWithH; + rows--; + } + } + return path.join(); + } + + int combination(int n, int r) { + if (r == 0 || r == n) return 1; + r = r > n - r ? n - r : r; + int result = 1; + for (int i = 1; i <= r; i++) { + result = result * (n - r + i) ~/ i; + } + return result; + } +} diff --git a/tests/1501-2000/1643. kth-smallest-instructions/sol.go b/tests/1501-2000/1643. kth-smallest-instructions/sol.go new file mode 100644 index 00000000..92b98396 --- /dev/null +++ b/tests/1501-2000/1643. kth-smallest-instructions/sol.go @@ -0,0 +1,37 @@ +func kthSmallestPath(destination []int, k int) string { + rows := destination[0] + cols := destination[1] + path := []byte{} + k-- + + for rows > 0 || cols > 0 { + pathsWithH := 0 + if cols > 0 { + pathsWithH = combination(rows+cols-1, cols-1) + } + + if k < pathsWithH { + path = append(path, 'H') + cols-- + } else { + path = append(path, 'V') + k -= pathsWithH + rows-- + } + } + return string(path) +} + +func combination(n, r int) int { + if r == 0 || r == n { + return 1 + } + if r > n-r { + r = n - r + } + result := 1 + for i := 1; i <= r; i++ { + result = result * (n - r + i) / i + } + return result +} diff --git a/tests/1501-2000/1643. kth-smallest-instructions/sol.java b/tests/1501-2000/1643. kth-smallest-instructions/sol.java new file mode 100644 index 00000000..0bf56aac --- /dev/null +++ b/tests/1501-2000/1643. kth-smallest-instructions/sol.java @@ -0,0 +1,35 @@ +class Solution { + public String kthSmallestPath(int[] destination, int k) { + int rows = destination[0]; + int cols = destination[1]; + StringBuilder path = new StringBuilder(); + k--; + + while (rows > 0 || cols > 0) { + long pathsWithH = 0; + if (cols > 0) { + pathsWithH = combination(rows + cols - 1, cols - 1); + } + + if (k < pathsWithH) { + path.append('H'); + cols--; + } else { + path.append('V'); + k -= pathsWithH; + rows--; + } + } + return path.toString(); + } + + private long combination(int n, int r) { + if (r == 0 || r == n) return 1; + r = Math.min(r, n - r); + long result = 1; + for (int i = 1; i <= r; i++) { + result = result * (n - r + i) / i; + } + return result; + } +} diff --git a/tests/1501-2000/1643. kth-smallest-instructions/sol.kt b/tests/1501-2000/1643. kth-smallest-instructions/sol.kt new file mode 100644 index 00000000..2b45812d --- /dev/null +++ b/tests/1501-2000/1643. kth-smallest-instructions/sol.kt @@ -0,0 +1,37 @@ +class Solution { + fun kthSmallestPath(destination: IntArray, k: Int): String { + var rows = destination[0] + var cols = destination[1] + val path = StringBuilder() + var kLocal = (k - 1).toLong() + + while (rows > 0 || cols > 0) { + val pathsWithH: Long + if (cols > 0) { + pathsWithH = combination(rows + cols - 1, cols - 1) + } else { + pathsWithH = 0 + } + + if (kLocal < pathsWithH) { + path.append('H') + cols-- + } else { + path.append('V') + kLocal -= pathsWithH + rows-- + } + } + return path.toString() + } + + private fun combination(n: Int, r: Int): Long { + if (r == 0 || r == n) return 1 + var rLocal = minOf(r, n - r) + var result: Long = 1 + for (i in 1..rLocal) { + result = result * (n - rLocal + i) / i + } + return result + } +} diff --git a/tests/1501-2000/1643. kth-smallest-instructions/sol.py b/tests/1501-2000/1643. kth-smallest-instructions/sol.py new file mode 100644 index 00000000..0b32d08b --- /dev/null +++ b/tests/1501-2000/1643. kth-smallest-instructions/sol.py @@ -0,0 +1,30 @@ +def comb(n, r): + r = min(r, n - r) + result = 1 + for i in range(1, r + 1): + result = result * (n - r + i) // i + return result + + +class Solution: + def kthSmallestPath(self, destination, k): + rows, cols = destination + path = [] + k -= 1 # Convert k to 0-indexed + + while rows > 0 or cols > 0: + # Number of paths starting with 'H' + if cols > 0: + paths_with_H = comb(rows + cols - 1, cols - 1) + else: + paths_with_H = 0 + + if k < paths_with_H: + path.append("H") + cols -= 1 + else: + path.append("V") + k -= paths_with_H + rows -= 1 + + return "".join(path) diff --git a/tests/1501-2000/1643. kth-smallest-instructions/sol.py2 b/tests/1501-2000/1643. kth-smallest-instructions/sol.py2 new file mode 100644 index 00000000..64bb315a --- /dev/null +++ b/tests/1501-2000/1643. kth-smallest-instructions/sol.py2 @@ -0,0 +1,32 @@ +class Solution(object): + def kthSmallestPath(self, destination, k): + """ + :type destination: List[int] + :type k: int + :rtype: str + """ + def comb(n, r): + r = min(r, n - r) + result = 1 + for value in range(1, r + 1): + result = result * (n - r + value) // value + return result + rows, cols = destination + path = [] + k -= 1 + + while rows > 0 or cols > 0: + if cols > 0: + paths_with_H = comb(rows + cols - 1, cols - 1) + else: + paths_with_H = 0 + + if k < paths_with_H: + path.append('H') + cols -= 1 + else: + path.append('V') + k -= paths_with_H + rows -= 1 + + return ''.join(path) diff --git a/tests/1501-2000/1643. kth-smallest-instructions/sol.rb b/tests/1501-2000/1643. kth-smallest-instructions/sol.rb new file mode 100644 index 00000000..68f989c9 --- /dev/null +++ b/tests/1501-2000/1643. kth-smallest-instructions/sol.rb @@ -0,0 +1,37 @@ +# @param {Integer[]} destination +# @param {Integer} k +# @return {String} +def kth_smallest_path(destination, k) + rows, cols = destination + path = [] + k -= 1 + + while rows > 0 || cols > 0 + if cols > 0 + paths_with_h = combination(rows + cols - 1, cols - 1) + else + paths_with_h = 0 + end + + if k < paths_with_h + path << 'H' + cols -= 1 + else + path << 'V' + k -= paths_with_h + rows -= 1 + end + end + + path.join +end + +def combination(n, r) + return 1 if r == 0 || r == n + r = [r, n - r].min + result = 1 + (1..r).each do |i| + result = result * (n - r + i) / i + end + result +end diff --git a/tests/1501-2000/1643. kth-smallest-instructions/sol.rs b/tests/1501-2000/1643. kth-smallest-instructions/sol.rs new file mode 100644 index 00000000..0ee827ff --- /dev/null +++ b/tests/1501-2000/1643. kth-smallest-instructions/sol.rs @@ -0,0 +1,39 @@ +impl Solution { + pub fn kth_smallest_path(destination: Vec, k: i32) -> String { + let mut rows = destination[0]; + let mut cols = destination[1]; + let mut path = String::new(); + let mut k_local = k - 1; + + while rows > 0 || cols > 0 { + let paths_with_h: i64; + if cols > 0 { + paths_with_h = Self::combination((rows + cols - 1) as usize, (cols - 1) as usize); + } else { + paths_with_h = 0; + } + + if (k_local as i64) < paths_with_h { + path.push('H'); + cols -= 1; + } else { + path.push('V'); + k_local -= paths_with_h as i32; + rows -= 1; + } + } + path + } + + fn combination(n: usize, r: usize) -> i64 { + if r == 0 || r == n { + return 1; + } + let r = r.min(n - r); + let mut result: i64 = 1; + for i in 1..=r { + result = result * (n - r + i) as i64 / i as i64; + } + result + } +} diff --git a/tests/1501-2000/1643. kth-smallest-instructions/sol.swift b/tests/1501-2000/1643. kth-smallest-instructions/sol.swift new file mode 100644 index 00000000..c8d30840 --- /dev/null +++ b/tests/1501-2000/1643. kth-smallest-instructions/sol.swift @@ -0,0 +1,35 @@ +class Solution { + func kthSmallestPath(_ destination: [Int], _ k: Int) -> String { + var rows = destination[0] + var cols = destination[1] + var path = "" + var kLocal = k - 1 + + while rows > 0 || cols > 0 { + var pathsWithH = 0 + if cols > 0 { + pathsWithH = combination(rows + cols - 1, cols - 1) + } + + if kLocal < pathsWithH { + path.append("H") + cols -= 1 + } else { + path.append("V") + kLocal -= pathsWithH + rows -= 1 + } + } + return path + } + + private func combination(_ n: Int, _ r: Int) -> Int { + if r == 0 || r == n { return 1 } + var rLocal = min(r, n - r) + var result = 1 + for i in 1...rLocal { + result = result * (n - rLocal + i) / i + } + return result + } +} diff --git a/tests/1501-2000/1643. kth-smallest-instructions/sol.ts b/tests/1501-2000/1643. kth-smallest-instructions/sol.ts new file mode 100644 index 00000000..dae56e96 --- /dev/null +++ b/tests/1501-2000/1643. kth-smallest-instructions/sol.ts @@ -0,0 +1,33 @@ +function kthSmallestPath(destination: number[], k: number): string { + let rows = destination[0]; + let cols = destination[1]; + let path: string[] = []; + let kLocal = k - 1; + + while (rows > 0 || cols > 0) { + let pathsWithH = 0; + if (cols > 0) { + pathsWithH = combination(rows + cols - 1, cols - 1); + } + + if (kLocal < pathsWithH) { + path.push("H"); + cols--; + } else { + path.push("V"); + kLocal -= pathsWithH; + rows--; + } + } + return path.join(""); +} + +function combination(n: number, r: number): number { + if (r === 0 || r === n) return 1; + r = Math.min(r, n - r); + let result = 1; + for (let i = 1; i <= r; i++) { + result = (result * (n - r + i)) / i; + } + return result; +} diff --git a/tests/1501-2000/1646. get-maximum-in-generated-array/manifest.yaml b/tests/1501-2000/1646. get-maximum-in-generated-array/manifest.yaml new file mode 100644 index 00000000..34faafc7 --- /dev/null +++ b/tests/1501-2000/1646. get-maximum-in-generated-array/manifest.yaml @@ -0,0 +1,224 @@ +entry: + id: 1646 + title: "get-maximum-in-generated-array" + params: + n: + type: int + call: + cpp: "Solution().getMaximumGenerated({n})" + rust: "Solution::get_maximum_generated({n})" + python3: "Solution().getMaximumGenerated({n})" + python2: "Solution().getMaximumGenerated({n})" + ruby: "get_maximum_generated({n})" + java: "new Solution().getMaximumGenerated({n})" + csharp: "new Solution().GetMaximumGenerated({n})" + kotlin: "Solution().getMaximumGenerated({n})" + go: "getMaximumGenerated({n})" + dart: "Solution().getMaximumGenerated({n})" + swift: "Solution().getMaximumGenerated({n})" + typescript: "getMaximumGenerated({n})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(n, {result})" + checker: | + class Checker: + def check(self, n, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if n == 0: + return result == 0 + nums = [0] * (n + 1) + nums[1] = 1 + for i in range(2, n + 1): + if i % 2 == 0: + nums[i] = nums[i // 2] + else: + nums[i] = nums[i // 2] + nums[i // 2 + 1] + return result == max(nums) + +seed: 1646 + +tests: + - name: zero + in: + n: 0 + out: 0 + - name: one + in: + n: 1 + out: 1 + - name: two + in: + n: 2 + out: 1 + - name: three + in: + n: 3 + out: 2 + - name: four + in: + n: 4 + out: 2 + - name: five + in: + n: 5 + out: 3 + - name: six + in: + n: 6 + out: 3 + - name: seven + in: + n: 7 + out: 3 + - name: eight + in: + n: 8 + out: 3 + - name: nine + in: + n: 9 + out: 4 + - name: ten + in: + n: 10 + out: 4 + - name: eleven + in: + n: 11 + out: 5 + - name: twelve + in: + n: 12 + out: 5 + - name: thirteen + in: + n: 13 + out: 5 + - name: fourteen + in: + n: 14 + out: 5 + - name: fifteen + in: + n: 15 + out: 5 + - name: sixteen + in: + n: 16 + out: 5 + - name: seventeen + in: + n: 17 + out: 5 + - name: eighteen + in: + n: 18 + out: 5 + - name: nineteen + in: + n: 19 + out: 7 + - name: twenty + in: + n: 20 + out: 7 + - name: twenty-four + in: + n: 24 + out: 8 + - name: twenty-five + in: + n: 25 + out: 8 + - name: thirty-one + in: + n: 31 + out: 8 + - name: thirty-two + in: + n: 32 + out: 8 + - name: thirty-three + in: + n: 33 + out: 8 + - name: forty + in: + n: 40 + out: 11 + - name: fifty + in: + n: 50 + out: 13 + - name: sixty-three + in: + n: 63 + out: 13 + - name: sixty-four + in: + n: 64 + out: 13 + - name: sixty-five + in: + n: 65 + out: 13 + - name: seventy-five + in: + n: 75 + out: 18 + - name: ninety + in: + n: 90 + out: 21 + - name: ninety-nine + in: + n: 99 + out: 21 + - name: maximum + in: + n: 100 + out: 21 + - name: generated-small + in: + n: + gen: "int" + min: 0 + max: 10 + seed: 1646001 + - name: generated-medium + in: + n: + gen: "int" + min: 11 + max: 40 + seed: 1646002 + - name: generated-upper + in: + n: + gen: "int" + min: 41 + max: 75 + seed: 1646003 + - name: generated-boundary + in: + n: + gen: "int" + min: 76 + max: 100 + seed: 1646004 + - name: generated-full-range + in: + n: + gen: "int" + min: 0 + max: 100 + seed: 1646005 diff --git a/tests/1501-2000/1646. get-maximum-in-generated-array/sol.cpp b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.cpp new file mode 100644 index 00000000..492322b3 --- /dev/null +++ b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int getMaximumGenerated(int n) { + if (n == 0) { + return 0; + } else if (n == 1 || n == 2) { + return 1; + } else { + vector a(n + 1, 0); + a[0] = 0; + a[1] = 1; + int v = 1; + for (int i = 2; i <= n; i++) { + if (i % 2 == 0) { + a[i] = a[v]; + } else { + a[i] = a[v] + a[v + 1]; + v++; + } + } + return *max_element(a.begin(), a.end()); + } + } +}; diff --git a/tests/1501-2000/1646. get-maximum-in-generated-array/sol.cs b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.cs new file mode 100644 index 00000000..7299f6d1 --- /dev/null +++ b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.cs @@ -0,0 +1,23 @@ +public class Solution { + public int GetMaximumGenerated(int n) { + if (n == 0) { + return 0; + } else if (n == 1 || n == 2) { + return 1; + } else { + int[] a = new int[n + 1]; + a[0] = 0; + a[1] = 1; + int v = 1; + for (int i = 2; i <= n; i++) { + if (i % 2 == 0) { + a[i] = a[v]; + } else { + a[i] = a[v] + a[v + 1]; + v++; + } + } + return a.Max(); + } + } +} diff --git a/tests/1501-2000/1646. get-maximum-in-generated-array/sol.dart b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.dart new file mode 100644 index 00000000..ecc31924 --- /dev/null +++ b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.dart @@ -0,0 +1,27 @@ +class Solution { + int getMaximumGenerated(int n) { + if (n == 0) { + return 0; + } else if (n == 1 || n == 2) { + return 1; + } else { + List a = List.filled(n + 1, 0); + a[0] = 0; + a[1] = 1; + int v = 1; + for (int i = 2; i <= n; i++) { + if (i % 2 == 0) { + a[i] = a[v]; + } else { + a[i] = a[v] + a[v + 1]; + v++; + } + } + int max = 0; + for (int val in a) { + if (val > max) max = val; + } + return max; + } + } +} diff --git a/tests/1501-2000/1646. get-maximum-in-generated-array/sol.go b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.go new file mode 100644 index 00000000..035744c6 --- /dev/null +++ b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.go @@ -0,0 +1,27 @@ +func getMaximumGenerated(n int) int { + if n == 0 { + return 0 + } else if n == 1 || n == 2 { + return 1 + } else { + a := make([]int, n+1) + a[0] = 0 + a[1] = 1 + v := 1 + for i := 2; i <= n; i++ { + if i%2 == 0 { + a[i] = a[v] + } else { + a[i] = a[v] + a[v+1] + v++ + } + } + max := 0 + for _, val := range a { + if val > max { + max = val + } + } + return max + } +} diff --git a/tests/1501-2000/1646. get-maximum-in-generated-array/sol.java b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.java new file mode 100644 index 00000000..0c5f8482 --- /dev/null +++ b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.java @@ -0,0 +1,27 @@ +class Solution { + public int getMaximumGenerated(int n) { + if (n == 0) { + return 0; + } else if (n == 1 || n == 2) { + return 1; + } else { + int[] a = new int[n + 1]; + a[0] = 0; + a[1] = 1; + int v = 1; + for (int i = 2; i <= n; i++) { + if (i % 2 == 0) { + a[i] = a[v]; + } else { + a[i] = a[v] + a[v + 1]; + v++; + } + } + int max = 0; + for (int num : a) { + if (num > max) max = num; + } + return max; + } + } +} diff --git a/tests/1501-2000/1646. get-maximum-in-generated-array/sol.kt b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.kt new file mode 100644 index 00000000..e02d0623 --- /dev/null +++ b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.kt @@ -0,0 +1,23 @@ +class Solution { + fun getMaximumGenerated(n: Int): Int { + if (n == 0) { + return 0 + } else if (n == 1 || n == 2) { + return 1 + } else { + val a = IntArray(n + 1) + a[0] = 0 + a[1] = 1 + var v = 1 + for (i in 2..n) { + if (i % 2 == 0) { + a[i] = a[v] + } else { + a[i] = a[v] + a[v + 1] + v++ + } + } + return a.max()!! + } + } +} diff --git a/tests/1501-2000/1646. get-maximum-in-generated-array/sol.py b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.py new file mode 100644 index 00000000..007e4e05 --- /dev/null +++ b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.py @@ -0,0 +1,16 @@ +class Solution(object): + def getMaximumGenerated(self, n): + if n == 0: + return 0 + elif n == 2 or n == 1: + return 1 + else: + a = [0, 1] + v = 1 + for i in range(2, n + 1): + if i % 2 == 0: + a.append(a[v]) + else: + a.append(a[v] + a[v + 1]) + v += 1 + return max(a) diff --git a/tests/1501-2000/1646. get-maximum-in-generated-array/sol.py2 b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.py2 new file mode 100644 index 00000000..3d981585 --- /dev/null +++ b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def getMaximumGenerated(self, n): + """ + :type n: int + :rtype: int + """ + if n == 0: + return 0 + elif n in (1, 2): + return 1 + else: + a = [0, 1] + v = 1 + for i in range(2, n + 1): + if i % 2 == 0: + a.append(a[v]) + else: + a.append(a[v] + a[v + 1]) + v += 1 + return max(a) diff --git a/tests/1501-2000/1646. get-maximum-in-generated-array/sol.rb b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.rb new file mode 100644 index 00000000..92fdb060 --- /dev/null +++ b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.rb @@ -0,0 +1,21 @@ +# @param {Integer} n +# @return {Integer} +def get_maximum_generated(n) + if n == 0 + return 0 + elsif n == 1 || n == 2 + return 1 + else + a = [0, 1] + v = 1 + for i in 2..n + if i % 2 == 0 + a << a[v] + else + a << a[v] + a[v + 1] + v += 1 + end + end + return a.max + end +end diff --git a/tests/1501-2000/1646. get-maximum-in-generated-array/sol.rs b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.rs new file mode 100644 index 00000000..45499d7a --- /dev/null +++ b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn get_maximum_generated(n: i32) -> i32 { + if n == 0 { + return 0; + } else if n == 1 || n == 2 { + return 1; + } else { + let n = n as usize; + let mut a = vec![0; n + 1]; + a[0] = 0; + a[1] = 1; + let mut v = 1; + for i in 2..=n { + if i % 2 == 0 { + a[i] = a[v]; + } else { + a[i] = a[v] + a[v + 1]; + v += 1; + } + } + return *a.iter().max().unwrap(); + } + } +} diff --git a/tests/1501-2000/1646. get-maximum-in-generated-array/sol.swift b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.swift new file mode 100644 index 00000000..7787af91 --- /dev/null +++ b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func getMaximumGenerated(_ n: Int) -> Int { + if n == 0 { + return 0 + } else if n == 1 || n == 2 { + return 1 + } else { + var a = [Int](repeating: 0, count: n + 1) + a[0] = 0 + a[1] = 1 + var v = 1 + for i in 2...n { + if i % 2 == 0 { + a[i] = a[v] + } else { + a[i] = a[v] + a[v + 1] + v += 1 + } + } + return a.max()! + } + } +} diff --git a/tests/1501-2000/1646. get-maximum-in-generated-array/sol.ts b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.ts new file mode 100644 index 00000000..1726dc9d --- /dev/null +++ b/tests/1501-2000/1646. get-maximum-in-generated-array/sol.ts @@ -0,0 +1,21 @@ +function getMaximumGenerated(n: number): number { + if (n === 0) { + return 0; + } else if (n === 1 || n === 2) { + return 1; + } else { + const a: number[] = new Array(n + 1).fill(0); + a[0] = 0; + a[1] = 1; + let v = 1; + for (let i = 2; i <= n; i++) { + if (i % 2 === 0) { + a[i] = a[v]; + } else { + a[i] = a[v] + a[v + 1]; + v++; + } + } + return Math.max(...a); + } +} diff --git a/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/manifest.yaml b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/manifest.yaml new file mode 100644 index 00000000..37dd438b --- /dev/null +++ b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/manifest.yaml @@ -0,0 +1,215 @@ +entry: + id: 1647 + title: "minimum-deletions-to-make-character-frequencies-unique" + params: + s: + type: string + call: + cpp: "Solution().minDeletions({s})" + rust: "Solution::min_deletions({s})" + python3: "Solution().minDeletions({s})" + python2: "Solution().minDeletions({s})" + ruby: "min_deletions({s})" + java: "new Solution().minDeletions({s})" + csharp: "new Solution().MinDeletions({s})" + kotlin: "Solution().minDeletions({s})" + go: "minDeletions({s})" + dart: "Solution().minDeletions({s})" + swift: "Solution().minDeletions({s})" + typescript: "minDeletions({s})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(s, {result})" + checker: | + from collections import Counter + class Checker: + def check(self, s, result): + if not isinstance(result, int) or isinstance(result, bool) or result < 0: + return False + freqs = sorted(Counter(s).values(), reverse=True) + expected = 0 + for i in range(1, len(freqs)): + if freqs[i] >= freqs[i - 1]: + target = max(0, freqs[i - 1] - 1) + expected += freqs[i] - target + freqs[i] = target + return result == expected + +seed: 1647 + +tests: + - name: single + in: + s: "a" + out: 0 + - name: two-distinct + in: + s: "ab" + out: 1 + - name: already-good + in: + s: "aab" + out: 0 + - name: example-two + in: + s: "aaabbbcc" + out: 2 + - name: example-three + in: + s: "ceabaacb" + out: 2 + - name: one-frequency + in: + s: "aaaa" + out: 0 + - name: two-equal + in: + s: "aabb" + out: 1 + - name: three-equal + in: + s: "aabbcc" + out: 3 + - name: two-triples + in: + s: "aaabbb" + out: 1 + - name: two-fours + in: + s: "aaaabbbb" + out: 1 + - name: repeated-pairs + in: + s: "abcabc" + out: 3 + - name: three-two-one + in: + s: "aabbccd" + out: 4 + - name: four-pairs + in: + s: "aabbccdd" + out: 5 + - name: five-pairs + in: + s: "aabbccdde" + out: 6 + - name: one-character-long + in: + s: "zzzzzzzzzz" + out: 0 + - name: twenty-five-singletons + in: + s: "abcdefghijklmnopqrstuvwxy" + out: 24 + - name: all-lowercase-singletons + in: + s: "abcdefghijklmnopqrstuvwxyz" + out: 25 + - name: one-hundred-same + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: 0 + - name: two-hundred-halves + in: + s: "abababababababababababababababababababababababababababababababababababababababababababababababababab" + out: 1 + - name: balanced-three + in: + s: "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc" + out: 3 + - name: descending-frequencies + in: + s: "aaaaaaaaaabbbbbbbbbccccccccdddddddeeeeee" + out: 0 + - name: four-close-frequencies + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbccccccccccccccccccccccccdddddddddddddddddddddddd" + out: 4 + - name: five-equal-frequencies + in: + s: "aaaabbbbccccddddeeee" + out: 10 + - name: six-near-equal + in: + s: "aaaaabbbbbcccccdddddeeeeef" + out: 11 + - name: seven-equal + in: + s: "aaaaaabbbbbbccccccddddddeeeeeeffffffgggggg" + out: 21 + - name: eight-equal + in: + s: "aaaaaaabbbbbbbcccccccdddddddeeeeeeeffffffffggggggghhhhhhh" + out: 21 + - name: nine-equal + in: + s: "aaaaaaaabbbbbbbbccccccccddddddddeeeeeeeefffffffffgggggggghhhhhhhhiiiiiiii" + out: 28 + - name: ten-equal + in: + s: "aaaaaaaaabbbbbbbbbcccccccccddddddddddeeeeeeeeeefffffffffffgggggggggghhhhhhhhhhhiiiiiiiiiiijjjjjjjjjj" + out: 35 + - name: alternating-two + in: + s: "abababababababababababababababababababababababababababababababababababababababababababababababababab" + out: 1 + - name: all-nineteen-singletons + in: + s: "abcdefghijklmnopqrs" + out: 18 + - name: repeated-three-symbols + in: + s: "aaabbbcccddd" + out: 6 + - name: skewed-tail + in: + s: "aaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbcccdd" + out: 0 + - name: many-singletons + in: + s: "aabbccddeeffgghhiijjklmno" + out: 22 + - name: generated-small + in: + s: + gen: "str" + len: 37 + alphabet: "abcdef" + seed: 164701 + - name: generated-medium + in: + s: + gen: "str" + len: 1000 + alphabet: "abcdefghij" + seed: 164702 + - name: generated-large + in: + s: + gen: "str" + len: 10000 + alphabet: "abcdefghijklm" + seed: 164703 + - name: generated-maximum + in: + s: + gen: "str" + len: 100000 + alphabet: "abcdefghijklmnopqrstuvwxyz" + seed: 164704 + - name: generated-narrow-maximum + in: + s: + gen: "str" + len: 100000 + alphabet: "ab" + seed: 164705 diff --git a/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.cpp b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.cpp new file mode 100644 index 00000000..8f169e29 --- /dev/null +++ b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int minDeletions(string s) { + vector count(26, 0); + for (char c : s) { + count[c - 'a']++; + } + vector freqs; + for (int f : count) { + if (f > 0) freqs.push_back(f); + } + sort(freqs.rbegin(), freqs.rend()); + int deletes = 0; + for (int idx = 1; idx < freqs.size(); idx++) { + if (freqs[idx] >= freqs[idx - 1]) { + int target = max(0, freqs[idx - 1] - 1); + deletes += (freqs[idx] - target); + freqs[idx] = target; + } + } + return deletes; + } +}; diff --git a/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.cs b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.cs new file mode 100644 index 00000000..7db5fa0b --- /dev/null +++ b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public int MinDeletions(string s) { + int[] count = new int[26]; + foreach (char c in s) { + count[c - 'a']++; + } + List freqs = new List(); + foreach (int f in count) { + if (f > 0) freqs.Add(f); + } + freqs.Sort((a, b) => b.CompareTo(a)); + int deletes = 0; + for (int idx = 1; idx < freqs.Count; idx++) { + if (freqs[idx] >= freqs[idx - 1]) { + int target = Math.Max(0, freqs[idx - 1] - 1); + deletes += (freqs[idx] - target); + freqs[idx] = target; + } + } + return deletes; + } +} diff --git a/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.dart b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.dart new file mode 100644 index 00000000..00d7c63f --- /dev/null +++ b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.dart @@ -0,0 +1,18 @@ +class Solution { + int minDeletions(String s) { + List count = List.filled(26, 0); + for (int i = 0; i < s.length; i++) { + count[s.codeUnitAt(i) - 97]++; + } + List freqs = count.where((f) => f > 0).toList()..sort((a, b) => b.compareTo(a)); + int deletes = 0; + for (int idx = 1; idx < freqs.length; idx++) { + if (freqs[idx] >= freqs[idx - 1]) { + int target = max(0, freqs[idx - 1] - 1); + deletes += (freqs[idx] - target); + freqs[idx] = target; + } + } + return deletes; + } +} diff --git a/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.go b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.go new file mode 100644 index 00000000..4e9a937a --- /dev/null +++ b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.go @@ -0,0 +1,22 @@ +func minDeletions(s string) int { + count := make([]int, 26) + for _, c := range s { + count[c-'a']++ + } + freqs := []int{} + for _, f := range count { + if f > 0 { + freqs = append(freqs, f) + } + } + sort.Sort(sort.Reverse(sort.IntSlice(freqs))) + deletes := 0 + for idx := 1; idx < len(freqs); idx++ { + if freqs[idx] >= freqs[idx-1] { + target := max(0, freqs[idx-1]-1) + deletes += (freqs[idx] - target) + freqs[idx] = target + } + } + return deletes +} diff --git a/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.java b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.java new file mode 100644 index 00000000..e8399bfc --- /dev/null +++ b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.java @@ -0,0 +1,22 @@ +class Solution { + public int minDeletions(String s) { + int[] count = new int[26]; + for (char c : s.toCharArray()) { + count[c - 'a']++; + } + java.util.List freqs = new java.util.ArrayList<>(); + for (int f : count) { + if (f > 0) freqs.add(f); + } + freqs.sort(java.util.Collections.reverseOrder()); + int deletes = 0; + for (int idx = 1; idx < freqs.size(); idx++) { + if (freqs.get(idx) >= freqs.get(idx - 1)) { + int target = Math.max(0, freqs.get(idx - 1) - 1); + deletes += (freqs.get(idx) - target); + freqs.set(idx, target); + } + } + return deletes; + } +} diff --git a/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.kt b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.kt new file mode 100644 index 00000000..070ddc81 --- /dev/null +++ b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun minDeletions(s: String): Int { + val count = IntArray(26) + for (c in s) count[c - 'a']++ + val freqs = count.filter { it > 0 }.sortedDescending().toMutableList() + var deletes = 0 + for (idx in 1 until freqs.size) { + if (freqs[idx] >= freqs[idx - 1]) { + val target = maxOf(0, freqs[idx - 1] - 1) + deletes += (freqs[idx] - target) + freqs[idx] = target + } + } + return deletes + } +} diff --git a/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.py b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.py new file mode 100644 index 00000000..cde4c0ec --- /dev/null +++ b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.py @@ -0,0 +1,19 @@ +class Solution: + def minDeletions(self, s: str) -> int: + # Count the frequencies of each character + counter = Counter(s) + # We just care about the frequencies, + # so just get the values and sort in desc order + freqs = sorted(counter.values(), reverse=True) + deletes = 0 + # Because we can only reduce the frequencies (can't increase) + # So we expect each value should less than its previous value + for idx in range(1, len(freqs)): + if freqs[idx] >= freqs[idx - 1]: + # We need to decrease the value to previous value - 1 + # But if the previous value is already 0, + # we should decrease current value to also 0 + target_value = max(0, freqs[idx - 1] - 1) + deletes += freqs[idx] - target_value + freqs[idx] = target_value + return deletes diff --git a/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.py2 b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.py2 new file mode 100644 index 00000000..37c9efbe --- /dev/null +++ b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def minDeletions(self, s): + """ + :type s: str + :rtype: int + """ + from collections import Counter + counter = Counter(s) + freqs = sorted(counter.values(), reverse=True) + deletes = 0 + for idx in range(1, len(freqs)): + if freqs[idx] >= freqs[idx - 1]: + target_value = max(0, freqs[idx - 1] - 1) + deletes += (freqs[idx] - target_value) + freqs[idx] = target_value + return deletes diff --git a/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.rb b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.rb new file mode 100644 index 00000000..c014c20c --- /dev/null +++ b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.rb @@ -0,0 +1,16 @@ +# @param {String} s +# @return {Integer} +def min_deletions(s) + counter = Hash.new(0) + s.each_char { |c| counter[c] += 1 } + freqs = counter.values.sort.reverse + deletes = 0 + (1...freqs.length).each do |idx| + if freqs[idx] >= freqs[idx - 1] + target_value = [0, freqs[idx - 1] - 1].max + deletes += (freqs[idx] - target_value) + freqs[idx] = target_value + end + end + deletes +end diff --git a/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.rs b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.rs new file mode 100644 index 00000000..c37cc718 --- /dev/null +++ b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn min_deletions(s: String) -> i32 { + let mut count = vec![0; 26]; + for c in s.bytes() { + count[(c - b'a') as usize] += 1; + } + let mut freqs: Vec = count.into_iter().filter(|&f| f > 0).collect(); + freqs.sort_by(|a, b| b.cmp(a)); + let mut deletes = 0; + for idx in 1..freqs.len() { + if freqs[idx] >= freqs[idx - 1] { + let target = std::cmp::max(0, freqs[idx - 1] - 1); + deletes += (freqs[idx] - target); + freqs[idx] = target; + } + } + deletes + } +} diff --git a/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.swift b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.swift new file mode 100644 index 00000000..d308bb35 --- /dev/null +++ b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.swift @@ -0,0 +1,18 @@ +class Solution { + func minDeletions(_ s: String) -> Int { + var count = Array(repeating: 0, count: 26) + for ch in s.utf8 { + count[Int(ch) - 97] += 1 + } + var freqs = count.filter { $0 > 0 }.sorted(by: >) + var deletes = 0 + for idx in 1..= freqs[idx - 1] { + let target = max(0, freqs[idx - 1] - 1) + deletes += (freqs[idx] - target) + freqs[idx] = target + } + } + return deletes + } +} diff --git a/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.ts b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.ts new file mode 100644 index 00000000..558f3a3a --- /dev/null +++ b/tests/1501-2000/1647. minimum-deletions-to-make-character-frequencies-unique/sol.ts @@ -0,0 +1,16 @@ +function minDeletions(s: string): number { + const count = new Array(26).fill(0); + for (const c of s) { + count[c.charCodeAt(0) - 97]++; + } + let freqs = count.filter((f) => f > 0).sort((a, b) => b - a); + let deletes = 0; + for (let idx = 1; idx < freqs.length; idx++) { + if (freqs[idx] >= freqs[idx - 1]) { + const target = Math.max(0, freqs[idx - 1] - 1); + deletes += freqs[idx] - target; + freqs[idx] = target; + } + } + return deletes; +} diff --git a/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/manifest.yaml b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/manifest.yaml new file mode 100644 index 00000000..452f0af4 --- /dev/null +++ b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/manifest.yaml @@ -0,0 +1,271 @@ +entry: + id: 1648 + title: "sell-diminishing-valued-colored-balls" + params: + inventory: + type: array + items: + type: int + orders: + type: int + call: + cpp: "Solution().maxProfit({inventory}, {orders})" + rust: "Solution::max_profit({inventory}, {orders})" + python3: "Solution().maxProfit({inventory}, {orders})" + python2: "Solution().maxProfit({inventory}, {orders})" + ruby: "max_profit({inventory}, {orders})" + java: "new Solution().maxProfit({inventory}, {orders})" + csharp: "new Solution().MaxProfit({inventory}, {orders})" + kotlin: "Solution().maxProfit({inventory}, {orders})" + go: "maxProfit({inventory}, {orders})" + dart: "Solution().maxProfit({inventory}, {orders})" + swift: "Solution().maxProfit({inventory}, {orders})" + typescript: "maxProfit({inventory}, {orders})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxProfit(inventory, orders, {result})" + checker: | + class Checker: + def maxProfit(self, inventory, orders, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + lo, hi = 0, max(inventory) + while lo < hi: + mid = (lo + hi + 1) // 2 + count = sum(max(x - mid, 0) for x in inventory) + if count >= orders: + lo = mid + else: + hi = mid - 1 + level = lo + sold = sum(max(x - level, 0) for x in inventory) + value = sum((x + level + 1) * (x - level) // 2 for x in inventory if x > level) + expected = (value - (sold - orders) * (level + 1)) % 1000000007 + return result == expected + +seed: 1648 + +tests: + - name: example-one + in: + inventory: [2, 5] + orders: 4 + out: 14 + - name: example-two + in: + inventory: [3, 5] + orders: 6 + out: 19 + - name: one-ball + in: + inventory: [1] + orders: 1 + out: 1 + - name: sell-entire-color + in: + inventory: [10] + orders: 10 + out: 55 + - name: first-most-valuable + in: + inventory: [10] + orders: 1 + out: 10 + - name: identical-singletons + in: + inventory: [1, 1, 1] + orders: 2 + out: 2 + - name: identical-colors + in: + inventory: [2, 2, 2] + orders: 5 + out: 8 + - name: dominant-color + in: + inventory: [100, 1] + orders: 50 + out: 3775 + - name: maximum-single-color + in: + inventory: [1000000000] + orders: 1000000000 + out: 21 + - name: three-colors + in: + inventory: [5, 4, 3] + orders: 7 + out: 24 + - name: tied-colors + in: + inventory: [7, 7] + orders: 8 + out: 44 + - name: uneven-small + in: + inventory: [8, 1, 2] + orders: 5 + out: 30 + - name: four-equal + in: + inventory: [6, 6, 6, 6] + orders: 10 + out: 52 + - name: increasing-colors + in: + inventory: [1, 2, 3, 4, 5] + orders: 10 + out: 30 + - name: descending-colors + in: + inventory: [9, 8, 7, 6] + orders: 20 + out: 112 + - name: one-sale-among-ties + in: + inventory: [100, 100, 100] + orders: 1 + out: 100 + - name: almost-all-tied + in: + inventory: [100, 100, 100] + orders: 250 + out: 14708 + - name: one-dominant-small + in: + inventory: [11, 1, 1, 1] + orders: 4 + out: 38 + - name: mixed-fourteen + in: + inventory: [2, 9, 4, 7] + orders: 13 + out: 71 + - name: two-nearby + in: + inventory: [20, 19] + orders: 30 + out: 375 + - name: two-peaks + in: + inventory: [50, 1, 50] + orders: 75 + out: 2381 + - name: five-equal + in: + inventory: [3, 3, 3, 3, 3] + orders: 7 + out: 19 + - name: mixed-three + in: + inventory: [17, 2, 8] + orders: 12 + out: 140 + - name: broad-distribution + in: + inventory: [30, 25, 10, 5] + orders: 40 + out: 728 + - name: near-max-two-colors + in: + inventory: [999999999, 1000000000] + orders: 1000000000 + out: 750000042 + - name: tiny-order-huge-color + in: + inventory: [1, 1000000000] + orders: 2 + out: 999999992 + - name: first-of-four + in: + inventory: [4, 5, 6, 7] + orders: 1 + out: 7 + - name: exhaust-four + in: + inventory: [4, 5, 6, 7] + orders: 22 + out: 74 + - name: two-high-one-low + in: + inventory: [12, 12, 1] + orders: 15 + out: 131 + - name: dominant-plus-singletons + in: + inventory: [13, 2, 2, 2] + orders: 10 + out: 85 + - name: generated-unit-colors + in: + inventory: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1 + distinct: false + sorted: false + elemType: "int" + orders: 100000 + - name: generated-small-levels + in: + inventory: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 10 + distinct: false + sorted: false + elemType: "int" + orders: 100000 + - name: generated-medium-levels + in: + inventory: + gen: "array" + len: 50000 + of: + gen: "int" + min: 10 + max: 100 + distinct: false + sorted: false + elemType: "int" + orders: 250000 + - name: generated-large-levels + in: + inventory: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1000 + max: 1000000 + distinct: false + sorted: false + elemType: "int" + orders: 100000000 + - name: generated-maximum-values + in: + inventory: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1000000000 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + orders: 1000000000 diff --git a/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.cpp b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.cpp new file mode 100644 index 00000000..f3d796e8 --- /dev/null +++ b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int maxProfit(vector& inventory, int orders) { + int max_val = 0; + for (int v : inventory) max_val = max(max_val, v); + long long t = binarySearch(inventory, 0, max_val, orders); + long long total = 0, sold = 0; + for (int ball : inventory) { + if (ball > t) { + long long cnt = ball - t; + total += (ball + t + 1) * cnt / 2; + sold += cnt; + } + } + long long extra = sold - orders; + long long res = total - extra * (t + 1); + const long long MOD = 1000000007; + return (int)((res % MOD + MOD) % MOD); + } + +private: + long long binarySearch(vector& arr, int left, int right, int target) { + while (left < right) { + int mid = (left + right + 1) / 2; + long long count = 0; + for (int x : arr) { + if (x > mid) count += x - mid; + } + if (count >= target) left = mid; + else right = mid - 1; + } + return left; + } +}; diff --git a/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.cs b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.cs new file mode 100644 index 00000000..e5d9a0cf --- /dev/null +++ b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.cs @@ -0,0 +1,32 @@ +public class Solution { + public int MaxProfit(int[] inventory, int orders) { + int maxVal = 0; + foreach (int v in inventory) maxVal = Math.Max(maxVal, v); + long t = BinarySearch(inventory, 0, maxVal, orders); + long total = 0, sold = 0; + foreach (int ball in inventory) { + if (ball > t) { + long cnt = ball - t; + total += (ball + t + 1) * cnt / 2; + sold += cnt; + } + } + long extra = sold - orders; + long res = total - extra * (t + 1); + const long MOD = 1000000007; + return (int)((res % MOD + MOD) % MOD); + } + + private long BinarySearch(int[] arr, int left, int right, int target) { + while (left < right) { + int mid = (left + right + 1) / 2; + long count = 0; + foreach (int x in arr) { + if (x > mid) count += x - mid; + } + if (count >= target) left = mid; + else right = mid - 1; + } + return left; + } +} diff --git a/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.dart b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.dart new file mode 100644 index 00000000..6923bbfa --- /dev/null +++ b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.dart @@ -0,0 +1,34 @@ +class Solution { + int maxProfit(List inventory, int orders) { + int max = inventory.reduce((a, b) => a > b ? a : b); + int t = binarySearch(inventory, 0, max, orders); + int total = 0; + int sold = 0; + for (int ball in inventory) { + if (ball > t) { + int cnt = ball - t; + total += (ball + t + 1) * cnt ~/ 2; + sold += cnt; + } + } + int extra = sold - orders; + int res = total - extra * (t + 1); + return res % 1000000007; + } + + int binarySearch(List arr, int left, int right, int target) { + while (left < right) { + int mid = (left + right + 1) ~/ 2; + int count = 0; + for (int x in arr) { + if (x > mid) count += x - mid; + } + if (count >= target) { + left = mid; + } else { + right = mid - 1; + } + } + return left; + } +} diff --git a/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.go b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.go new file mode 100644 index 00000000..08621f13 --- /dev/null +++ b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.go @@ -0,0 +1,37 @@ +func maxProfit(inventory []int, orders int) int { + maxVal := 0 + for _, v := range inventory { + if v > maxVal { maxVal = v } + } + t := binarySearch(inventory, 0, maxVal, int64(orders)) + var total, sold int64 + for _, ball := range inventory { + if int64(ball) > t { + cnt := int64(ball) - t + total += (int64(ball) + t + 1) * cnt / 2 + sold += cnt + } + } + extra := sold - int64(orders) + res := total - extra * (t + 1) + mod := int64(1000000007) + return int((res % mod + mod) % mod) +} + +func binarySearch(arr []int, left, right int, target int64) int64 { + for left < right { + mid := (left + right + 1) / 2 + var count int64 + for _, x := range arr { + if x > mid { + count += int64(x - mid) + } + } + if count >= target { + left = mid + } else { + right = mid - 1 + } + } + return int64(left) +} diff --git a/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.java b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.java new file mode 100644 index 00000000..46e94908 --- /dev/null +++ b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.java @@ -0,0 +1,32 @@ +class Solution { + public int maxProfit(int[] inventory, int orders) { + int max = 0; + for (int ball : inventory) max = Math.max(max, ball); + long t = binarySearch(inventory, 0, max, orders); + long total = 0; + long sold = 0; + for (int ball : inventory) { + if (ball > t) { + long cnt = ball - t; + total += (ball + t + 1) * cnt / 2; + sold += cnt; + } + } + long extra = sold - orders; + long res = total - extra * (t + 1); + return (int)(res % 1000000007); + } + + private long binarySearch(int[] arr, int left, int right, int target) { + while (left < right) { + int mid = (left + right + 1) / 2; + long count = 0; + for (int x : arr) { + if (x > mid) count += x - mid; + } + if (count >= target) left = mid; + else right = mid - 1; + } + return left; + } +} diff --git a/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.kt b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.kt new file mode 100644 index 00000000..2d73950b --- /dev/null +++ b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.kt @@ -0,0 +1,33 @@ +class Solution { + fun maxProfit(inventory: IntArray, orders: Int): Int { + val max = inventory.max()!! + val t = binarySearch(inventory, 0, max, orders.toLong()) + var total = 0L + var sold = 0L + for (ball in inventory) { + if (ball > t) { + val cnt = ball - t + total += (ball + t + 1) * cnt / 2 + sold += cnt + } + } + val extra = sold - orders + val res = total - extra * (t + 1) + return (res % 1000000007).toInt() + } + + private fun binarySearch(arr: IntArray, left: Int, right: Int, target: Long): Long { + var l = left + var r = right + while (l < r) { + val mid = (l + r + 1) / 2 + var count = 0L + for (x in arr) { + if (x > mid) count += x - mid + } + if (count >= target) l = mid + else r = mid - 1 + } + return l.toLong() + } +} diff --git a/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.py b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.py new file mode 100644 index 00000000..56ba15b3 --- /dev/null +++ b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.py @@ -0,0 +1,28 @@ +class Solution: + def maxProfit(self, inventory: List[int], orders: int) -> int: + t = self.binary_search(inventory, 0, max(inventory), orders) + total = 0 + sold = 0 + for ball in inventory: + if ball > t: + cnt = ball - t + total += (ball + t + 1) * cnt // 2 + sold += cnt + + extra = sold - orders + res = total - extra * (t + 1) + return res % (10**9 + 7) + + def binary_search(self, arr, left, right, target): + while left < right: + mid = (left + right + 1) // 2 + count = 0 + for x in arr: + if x > mid: + count += x - mid + + if count >= target: + left = mid + else: + right = mid - 1 + return left diff --git a/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.py2 b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.py2 new file mode 100644 index 00000000..3df5482f --- /dev/null +++ b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.py2 @@ -0,0 +1,33 @@ +class Solution(object): + def maxProfit(self, inventory, orders): + """ + :type inventory: List[int] + :type orders: int + :rtype: int + """ + t = self.binary_search(inventory, 0, max(inventory), orders) + total = 0 + sold = 0 + for ball in inventory: + if ball > t: + cnt = ball - t + total += (ball + t + 1) * cnt // 2 + sold += cnt + + extra = sold - orders + res = total - extra * (t + 1) + return res % (10**9 + 7) + + def binary_search(self, arr, left, right, target): + while left < right: + mid = (left + right + 1) // 2 + count = 0 + for x in arr: + if x > mid: + count += x - mid + + if count >= target: + left = mid + else: + right = mid - 1 + return left diff --git a/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.rb b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.rb new file mode 100644 index 00000000..b99d9bc9 --- /dev/null +++ b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.rb @@ -0,0 +1,36 @@ +# @param {Integer[]} inventory +# @param {Integer} orders +# @return {Integer} +def max_profit(inventory, orders) + t = binary_search(inventory, 0, inventory.max, orders) + total = 0 + sold = 0 + inventory.each do |ball| + if ball > t + cnt = ball - t + total += (ball + t + 1) * cnt / 2 + sold += cnt + end + end + extra = sold - orders + res = total - extra * (t + 1) + res % (10**9 + 7) +end + +def binary_search(arr, left, right, target) + while left < right + mid = (left + right + 1) / 2 + count = 0 + arr.each do |x| + if x > mid + count += x - mid + end + end + if count >= target + left = mid + else + right = mid - 1 + end + end + left +end diff --git a/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.rs b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.rs new file mode 100644 index 00000000..e9c1b5dd --- /dev/null +++ b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.rs @@ -0,0 +1,39 @@ +impl Solution { + pub fn max_profit(inventory: Vec, orders: i32) -> i32 { + let max_val = *inventory.iter().max().unwrap(); + let t = Self::binary_search(&inventory, 0, max_val as i64, orders as i64); + let mut total: i64 = 0; + let mut sold: i64 = 0; + for &ball in &inventory { + let ball_i64 = ball as i64; + if ball_i64 > t { + let cnt = ball_i64 - t; + total += (ball_i64 + t + 1) * cnt / 2; + sold += cnt; + } + } + let extra = sold - orders as i64; + let res = total - extra * (t + 1); + let modulo = 1_000_000_007i64; + ((res % modulo + modulo) % modulo) as i32 + } + + fn binary_search(arr: &Vec, mut left: i64, mut right: i64, target: i64) -> i64 { + while left < right { + let mid = (left + right + 1) / 2; + let mut count: i64 = 0; + for &x in arr { + let x_i64 = x as i64; + if x_i64 > mid { + count += x_i64 - mid; + } + } + if count >= target { + left = mid; + } else { + right = mid - 1; + } + } + left + } +} diff --git a/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.swift b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.swift new file mode 100644 index 00000000..a207a0d9 --- /dev/null +++ b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.swift @@ -0,0 +1,39 @@ +class Solution { + func maxProfit(_ inventory: [Int], _ orders: Int) -> Int { + let maxVal = inventory.max()! + let t = binarySearch(inventory, 0, maxVal, orders) + var total: Int64 = 0 + var sold: Int64 = 0 + for ball in inventory { + if Int64(ball) > t { + let cnt = Int64(ball) - t + total += (Int64(ball) + t + 1) * cnt / 2 + sold += cnt + } + } + let extra = sold - Int64(orders) + let res = total - extra * (t + 1) + let mod: Int64 = 1000000007 + return Int((res % mod + mod) % mod) + } + + private func binarySearch(_ arr: [Int], _ left: Int, _ right: Int, _ target: Int) -> Int64 { + var l = left + var r = right + while l < r { + let mid = (l + r + 1) / 2 + var count: Int64 = 0 + for x in arr { + if x > mid { + count += Int64(x - mid) + } + } + if count >= Int64(target) { + l = mid + } else { + r = mid - 1 + } + } + return Int64(l) + } +} diff --git a/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.ts b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.ts new file mode 100644 index 00000000..ce36a5b2 --- /dev/null +++ b/tests/1501-2000/1648. sell-diminishing-valued-colored-balls/sol.ts @@ -0,0 +1,37 @@ +function maxProfit(inventory: number[], orders: number): number { + const max = Math.max(...inventory); + let t = binarySearch(inventory, 0, max, orders); + let total = 0n; + let sold = 0n; + for (const ball of inventory) { + if (ball > t) { + const cnt = ball - t; + total += (BigInt(ball + t + 1) * BigInt(cnt)) / 2n; + sold += BigInt(cnt); + } + } + const extra = sold - BigInt(orders); + const res = total - extra * BigInt(t + 1); + return Number(((res % 1000000007n) + 1000000007n) % 1000000007n); +} + +function binarySearch( + arr: number[], + left: number, + right: number, + target: number, +): number { + while (left < right) { + const mid = Math.floor((left + right + 1) / 2); + let count = 0; + for (const x of arr) { + if (x > mid) count += x - mid; + } + if (count >= target) { + left = mid; + } else { + right = mid - 1; + } + } + return left; +} diff --git a/tests/1501-2000/1649. create-sorted-array-through-instructions/manifest.yaml b/tests/1501-2000/1649. create-sorted-array-through-instructions/manifest.yaml new file mode 100644 index 00000000..6358300d --- /dev/null +++ b/tests/1501-2000/1649. create-sorted-array-through-instructions/manifest.yaml @@ -0,0 +1,271 @@ +entry: + id: 1649 + title: "create-sorted-array-through-instructions" + params: + instructions: + type: array + items: + type: int + call: + cpp: "Solution().createSortedArray({instructions})" + rust: "Solution::create_sorted_array({instructions})" + python3: "Solution().createSortedArray({instructions})" + python2: "Solution().createSortedArray({instructions})" + ruby: "create_sorted_array({instructions})" + java: "new Solution().createSortedArray({instructions})" + csharp: "new Solution().CreateSortedArray({instructions})" + kotlin: "Solution().createSortedArray({instructions})" + go: "createSortedArray({instructions})" + dart: "Solution().createSortedArray({instructions})" + swift: "Solution().createSortedArray({instructions})" + typescript: "createSortedArray({instructions})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().createSortedArray(instructions, {result})" + checker: | + class Checker: + def createSortedArray(self, instructions, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + mod = 1000000007 + n = len(instructions) + bit = [0] * (100002) + def add(i): + while i < len(bit): + bit[i] += 1 + i += i & -i + def prefix(i): + total = 0 + while i: + total += bit[i] + i -= i & -i + return total + expected = 0 + for i, value in enumerate(instructions): + less = prefix(value) + not_greater = prefix(value + 1) + greater = i - not_greater + expected = (expected + min(less, greater)) % mod + add(value + 1) + return result == expected + +seed: 1649 + +tests: + - name: example-one + in: + instructions: [1, 5, 6, 2] + out: 1 + - name: example-two + in: + instructions: [1, 2, 3, 6, 5, 4] + out: 3 + - name: example-three + in: + instructions: [1, 3, 3, 3, 2, 4, 2, 1, 2] + out: 4 + - name: single + in: + instructions: [1] + out: 0 + - name: equal-single-value + in: + instructions: [1, 1, 1] + out: 0 + - name: descending + in: + instructions: [3, 2, 1] + out: 0 + - name: ascending + in: + instructions: [1, 2, 3, 4, 5] + out: 0 + - name: descending-longer + in: + instructions: [5, 4, 3, 2, 1] + out: 0 + - name: duplicate-blocks + in: + instructions: [2, 2, 1, 1, 3, 3] + out: 0 + - name: maximum-value + in: + instructions: [100000] + out: 0 + - name: alternating-extremes + in: + instructions: [1, 100000, 1, 100000] + out: 0 + - name: repeated-extremes + in: + instructions: [7, 1, 7, 1, 7, 1] + out: 0 + - name: alternating-near-sorted + in: + instructions: [1, 2, 1, 2, 1, 2, 1, 2] + out: 0 + - name: descending-ten + in: + instructions: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + out: 0 + - name: wide-values + in: + instructions: [1, 100000, 99999, 2, 50000] + out: 4 + - name: zero-is-invalid-not-used + in: + instructions: [4, 1, 3, 2, 5, 1] + out: 2 + - name: evens-then-odds + in: + instructions: [2, 4, 6, 8, 10, 1, 3, 5, 7, 9] + out: 8 + - name: zigzag + in: + instructions: [1, 10, 2, 9, 3, 8, 4, 7, 5, 6] + out: 20 + - name: paired-descending + in: + instructions: [50, 50, 49, 49, 48, 48] + out: 0 + - name: three-extreme-cycles + in: + instructions: [1, 100000, 1, 100000, 1] + out: 0 + - name: mixed-permutation + in: + instructions: [8, 6, 7, 5, 3, 2, 9] + out: 1 + - name: repeated-pairs + in: + instructions: [1, 1, 2, 2, 3, 3, 4, 4, 5, 5] + out: 0 + - name: high-low-alternation + in: + instructions: [99999, 1, 99998, 2, 99997, 3] + out: 6 + - name: all-equal + in: + instructions: + [ + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + ] + out: 0 + - name: valley + in: + instructions: [1, 2, 3, 4, 5, 4, 3, 2, 1] + out: 4 + - name: triple-repeat + in: + instructions: [17, 3, 17, 3, 17, 3, 17] + out: 0 + - name: interleaved-halves + in: + instructions: [1, 50000, 25000, 75000, 12500, 87500] + out: 2 + - name: high-descending-then-ascending + in: + instructions: [100000, 99999, 99998, 1, 2, 3] + out: 3 + - name: two-runs + in: + instructions: [6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6] + out: 7 + - name: alternating-small-ranges + in: + instructions: [1, 4, 2, 5, 3, 6] + out: 3 + - name: powers-of-two + in: + instructions: [1, 2, 4, 8, 16, 32, 64] + out: 0 + - name: mixed-boundaries + in: + instructions: [100000, 1, 2, 99999, 3, 99998] + out: 6 + - name: duplicate-staircase + in: + instructions: [1, 1, 1, 2, 2, 3, 3, 4, 4, 5] + out: 0 + - name: generated-small + in: + instructions: + gen: "array" + len: 37 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + seed: 164901 + - name: generated-medium + in: + instructions: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + seed: 164902 + - name: generated-large + in: + instructions: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + seed: 164903 + - name: generated-large-narrow-domain + in: + instructions: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 3 + elemType: "int" + seed: 164904 + - name: generated-large-two-values + in: + instructions: + gen: "array" + len: 100000 + of: + gen: "int" + min: 99999 + max: 100000 + elemType: "int" + seed: 164905 diff --git a/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.cpp b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.cpp new file mode 100644 index 00000000..c77e5ef5 --- /dev/null +++ b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.cpp @@ -0,0 +1,74 @@ +class Solution { +private: + vector nums; + vector> ans; + +public: + int createSortedArray(vector& instructions) { + int n = instructions.size(); + nums = instructions; + ans = vector>(n, vector(2, 0)); + + vector arr(n); + for (int i = 0; i < n; i++) arr[i] = i; + + split(0, n - 1, arr); + + long long real_ans = 0; + for (int i = 0; i < n; i++) { + real_ans += min(ans[i][0], ans[i][1]); + } + return real_ans % 1000000007; + } + + vector merge(vector& left, vector& right) { + int l = left.size() - 1; + int r = right.size() - 1; + while (l > -1 && r > -1) { + if (nums[left[l]] <= nums[right[r]]) { + ans[right[r]][1] += (left.size() - 1) - l; + r--; + } else { + l--; + } + } + while (r > -1) { + ans[right[r]][1] += left.size(); + r--; + } + + l = 0; + r = 0; + vector res; + while (l < left.size() && r < right.size()) { + if (nums[left[l]] < nums[right[r]]) { + res.push_back(left[l]); + l++; + } else { + ans[right[r]][0] += l; + res.push_back(right[r]); + r++; + } + } + while (r < right.size()) { + ans[right[r]][0] += l; + res.push_back(right[r]); + r++; + } + while (l < left.size()) { + res.push_back(left[l]); + l++; + } + return res; + } + + vector split(int l, int r, vector& arr) { + if (l == r) { + return {arr[r]}; + } + int mid = (l + r) / 2; + vector left = split(l, mid, arr); + vector right = split(mid + 1, r, arr); + return merge(left, right); + } +}; diff --git a/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.cs b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.cs new file mode 100644 index 00000000..a5da1a58 --- /dev/null +++ b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.cs @@ -0,0 +1,70 @@ +public class Solution { + private int[] nums; + private int[][] ans; + + public int CreateSortedArray(int[] instructions) { + int n = instructions.Length; + nums = instructions; + ans = new int[n][]; + for (int i = 0; i < n; i++) ans[i] = new int[2]; + + int[] arr = new int[n]; + for (int i = 0; i < n; i++) arr[i] = i; + + Split(0, n - 1, arr); + + long realAns = 0; + for (int i = 0; i < n; i++) { + realAns += Math.Min(ans[i][0], ans[i][1]); + } + return (int)(realAns % 1000000007); + } + + private int[] Merge(int[] left, int[] right) { + int l = left.Length - 1; + int r = right.Length - 1; + while (l > -1 && r > -1) { + if (nums[left[l]] <= nums[right[r]]) { + ans[right[r]][1] += (left.Length - 1) - l; + r--; + } else { + l--; + } + } + while (r > -1) { + ans[right[r]][1] += left.Length; + r--; + } + + l = 0; + r = 0; + int[] res = new int[left.Length + right.Length]; + int idx = 0; + while (l < left.Length && r < right.Length) { + if (nums[left[l]] < nums[right[r]]) { + res[idx++] = left[l++]; + } else { + ans[right[r]][0] += l; + res[idx++] = right[r++]; + } + } + while (r < right.Length) { + ans[right[r]][0] += l; + res[idx++] = right[r++]; + } + while (l < left.Length) { + res[idx++] = left[l++]; + } + return res; + } + + private int[] Split(int l, int r, int[] arr) { + if (l == r) { + return new int[] { arr[r] }; + } + int mid = (l + r) / 2; + int[] left = Split(l, mid, arr); + int[] right = Split(mid + 1, r, arr); + return Merge(left, right); + } +} diff --git a/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.dart b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.dart new file mode 100644 index 00000000..6b919501 --- /dev/null +++ b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.dart @@ -0,0 +1,32 @@ +class Solution { + int createSortedArray(List instructions) { + const int mod = 1000000007; + final bit = List.filled(100002, 0); + + void add(int index) { + while (index < bit.length) { + bit[index]++; + index += index & -index; + } + } + + int prefix(int index) { + var total = 0; + while (index > 0) { + total += bit[index]; + index -= index & -index; + } + return total; + } + + var cost = 0; + for (var i = 0; i < instructions.length; i++) { + final value = instructions[i]; + final less = prefix(value); + final greater = i - prefix(value + 1); + cost = (cost + (less < greater ? less : greater)) % mod; + add(value + 1); + } + return cost; + } +} diff --git a/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.go b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.go new file mode 100644 index 00000000..cadf10ee --- /dev/null +++ b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.go @@ -0,0 +1,72 @@ +func createSortedArray(instructions []int) int { + n := len(instructions) + nums := instructions + ans := make([][2]int, n) + + arr := make([]int, n) + for i := 0; i < n; i++ { + arr[i] = i + } + + var merge func([]int, []int) []int + merge = func(left, right []int) []int { + l := len(left) - 1 + r := len(right) - 1 + for l > -1 && r > -1 { + if nums[left[l]] <= nums[right[r]] { + ans[right[r]][1] += (len(left) - 1) - l + r-- + } else { + l-- + } + } + for r > -1 { + ans[right[r]][1] += len(left) + r-- + } + + l = 0 + r = 0 + res := make([]int, 0, len(left)+len(right)) + for l < len(left) && r < len(right) { + if nums[left[l]] < nums[right[r]] { + res = append(res, left[l]) + l++ + } else { + ans[right[r]][0] += l + res = append(res, right[r]) + r++ + } + } + for r < len(right) { + ans[right[r]][0] += l + res = append(res, right[r]) + r++ + } + res = append(res, left[l:]...) + return res + } + + var split func(int, int, []int) []int + split = func(l, r int, arr []int) []int { + if l == r { + return []int{arr[r]} + } + mid := (l + r) / 2 + left := split(l, mid, arr) + right := split(mid+1, r, arr) + return merge(left, right) + } + + split(0, n-1, arr) + + realAns := 0 + for i := 0; i < n; i++ { + if ans[i][0] < ans[i][1] { + realAns += ans[i][0] + } else { + realAns += ans[i][1] + } + } + return realAns % 1000000007 +} diff --git a/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.java b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.java new file mode 100644 index 00000000..46be348c --- /dev/null +++ b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.java @@ -0,0 +1,69 @@ +class Solution { + private int[] nums; + private int[][] ans; + + public int createSortedArray(int[] instructions) { + int n = instructions.length; + this.nums = instructions; + this.ans = new int[n][2]; + + int[] arr = new int[n]; + for (int i = 0; i < n; i++) arr[i] = i; + + split(0, n - 1, arr); + + long realAns = 0; + for (int i = 0; i < n; i++) { + realAns += Math.min(ans[i][0], ans[i][1]); + } + return (int)(realAns % 1000000007); + } + + private int[] merge(int[] left, int[] right) { + int l = left.length - 1; + int r = right.length - 1; + while (l > -1 && r > -1) { + if (nums[left[l]] <= nums[right[r]]) { + ans[right[r]][1] += (left.length - 1) - l; + r--; + } else { + l--; + } + } + while (r > -1) { + ans[right[r]][1] += left.length; + r--; + } + + l = 0; + r = 0; + int[] res = new int[left.length + right.length]; + int idx = 0; + while (l < left.length && r < right.length) { + if (nums[left[l]] < nums[right[r]]) { + res[idx++] = left[l++]; + } else { + ans[right[r]][0] += l; + res[idx++] = right[r++]; + } + } + while (r < right.length) { + ans[right[r]][0] += l; + res[idx++] = right[r++]; + } + while (l < left.length) { + res[idx++] = left[l++]; + } + return res; + } + + private int[] split(int l, int r, int[] arr) { + if (l == r) { + return new int[]{arr[r]}; + } + int mid = (l + r) / 2; + int[] left = split(l, mid, arr); + int[] right = split(mid + 1, r, arr); + return merge(left, right); + } +} diff --git a/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.kt b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.kt new file mode 100644 index 00000000..ce3af3a9 --- /dev/null +++ b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.kt @@ -0,0 +1,67 @@ +class Solution { + private lateinit var nums: IntArray + private lateinit var ans: Array + + fun createSortedArray(instructions: IntArray): Int { + val n = instructions.size + nums = instructions + ans = Array(n) { IntArray(2) } + + val arr = IntArray(n) { it } + split(0, n - 1, arr) + + var realAns = 0L + for (i in 0 until n) { + realAns += minOf(ans[i][0], ans[i][1]) + } + return (realAns % 1000000007).toInt() + } + + private fun merge(left: IntArray, right: IntArray): IntArray { + var l = left.size - 1 + var r = right.size - 1 + while (l > -1 && r > -1) { + if (nums[left[l]] <= nums[right[r]]) { + ans[right[r]][1] += (left.size - 1) - l + r-- + } else { + l-- + } + } + while (r > -1) { + ans[right[r]][1] += left.size + r-- + } + + l = 0 + r = 0 + val res = IntArray(left.size + right.size) + var idx = 0 + while (l < left.size && r < right.size) { + if (nums[left[l]] < nums[right[r]]) { + res[idx++] = left[l++] + } else { + ans[right[r]][0] += l + res[idx++] = right[r++] + } + } + while (r < right.size) { + ans[right[r]][0] += l + res[idx++] = right[r++] + } + while (l < left.size) { + res[idx++] = left[l++] + } + return res + } + + private fun split(l: Int, r: Int, arr: IntArray): IntArray { + if (l == r) { + return intArrayOf(arr[r]) + } + val mid = (l + r) / 2 + val left = split(l, mid, arr) + val right = split(mid + 1, r, arr) + return merge(left, right) + } +} diff --git a/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.py b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.py new file mode 100644 index 00000000..a800839f --- /dev/null +++ b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.py @@ -0,0 +1,76 @@ +class Solution: + def createSortedArray(self, instructions: List[int]) -> int: + nums = instructions + # ans stores the ind : [min , max] for each ind in nums + ans = {i: [0, 0] for i in range(len(nums))} + + def merge(left, right): + # Note that we are only concerned about finding numbers strictly greater that and... + # ...numbers strictly less that, for the numbers in the right list if we insert them in the left list + # Note that this can be done using Bisection also, but this is for the pure merge sort lovers :) + + # NOW + # starting from the end left and right we can find the numbers ... + # ...strictly greater than the numbers on the right if we find the first number + # ... less that or equal to it on numbers in the left list + l = len(left) - 1 + r = len(right) - 1 + while l > -1 and r > -1: + if nums[left[l]] <= nums[right[r]]: + ans[right[r]][1] += (len(left) - 1) - l + r -= 1 + else: + l -= 1 + + # if the right pointer is not out of bound this means it is greater that all the numbers on the left list + while r > -1: + ans[right[r]][1] += len(left) + r -= 1 + + # now while merging we can find numbers strictly less than the numbers in the right list + # ...if we find a number on the left list greater that or equal to it while we iterate from start to end on both + + l = 0 + r = 0 + res = [] + while l < len(left) and r < len(right): + # since the left and right lists hold indexes nums[ ... ] they go in here + if nums[left[l]] < nums[right[r]]: + res.append(left[l]) + l += 1 + else: + ans[right[r]][0] += l + res.append(right[r]) + r += 1 + + # if the right pointer is not out of bound it means all the numbers on the left are less that what its holding... + # ...and same for the elements that come after it. + while r < len(right): + ans[right[r]][0] += l + res.append(right[r]) + r += 1 + + res.extend(left[l:]) + return res + + def split(l, r, arr): + if l == r: + return [arr[r]] + + mid = (l + r) // 2 + + left = split(l, mid, arr) + right = split(mid + 1, r, arr) + + return merge(left, right) + + # It is better to give the mergesort the indexes and also use the indexes for the dictionary + # ... to account for repeated numbers!! + split(0, len(nums) - 1, [i for i in range(len(nums))]) + + # take only the mean for the real answer + real_ans = 0 + for i in ans.keys(): + real_ans += min(ans[i]) + + return real_ans % ((10**9) + 7) diff --git a/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.py2 b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.py2 new file mode 100644 index 00000000..0f34b63b --- /dev/null +++ b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.py2 @@ -0,0 +1,54 @@ +class Solution(object): + def createSortedArray(self, instructions): + """ + :type instructions: List[int] + :rtype: int + """ + n = len(instructions) + ans = {i: [0, 0] for i in range(n)} + + def merge(left, right): + l = len(left) - 1 + r = len(right) - 1 + while l > -1 and r > -1: + if instructions[left[l]] <= instructions[right[r]]: + ans[right[r]][1] += (len(left) - 1) - l + r -= 1 + else: + l -= 1 + while r > -1: + ans[right[r]][1] += len(left) + r -= 1 + + l = 0 + r = 0 + res = [] + while l < len(left) and r < len(right): + if instructions[left[l]] < instructions[right[r]]: + res.append(left[l]) + l += 1 + else: + ans[right[r]][0] += l + res.append(right[r]) + r += 1 + while r < len(right): + ans[right[r]][0] += l + res.append(right[r]) + r += 1 + res.extend(left[l:]) + return res + + def split(l, r, arr): + if l == r: + return [arr[r]] + mid = (l + r) // 2 + left = split(l, mid, arr) + right = split(mid + 1, r, arr) + return merge(left, right) + + split(0, n - 1, list(range(n))) + + real_ans = 0 + for i in ans: + real_ans += min(ans[i]) + return real_ans % (10**9 + 7) diff --git a/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.rb b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.rb new file mode 100644 index 00000000..96f57099 --- /dev/null +++ b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.rb @@ -0,0 +1,62 @@ +# @param {Integer[]} instructions +# @return {Integer} +def create_sorted_array(instructions) + n = instructions.length + ans = {} + (0...n).each { |i| ans[i] = [0, 0] } + + merge = ->(left, right) { + l = left.length - 1 + r = right.length - 1 + while l > -1 && r > -1 + if instructions[left[l]] <= instructions[right[r]] + ans[right[r]][1] += (left.length - 1) - l + r -= 1 + else + l -= 1 + end + end + while r > -1 + ans[right[r]][1] += left.length + r -= 1 + end + + l = 0 + r = 0 + res = [] + while l < left.length && r < right.length + if instructions[left[l]] < instructions[right[r]] + res << left[l] + l += 1 + else + ans[right[r]][0] += l + res << right[r] + r += 1 + end + end + while r < right.length + ans[right[r]][0] += l + res << right[r] + r += 1 + end + res.concat(left[l..-1] || []) + res + } + + split = nil + split = ->(l, r, arr) { + if l == r + return [arr[r]] + end + mid = (l + r) / 2 + left = split.call(l, mid, arr) + right = split.call(mid + 1, r, arr) + merge.call(left, right) + } + + split.call(0, n - 1, (0...n).to_a) + + real_ans = 0 + ans.each_value { |v| real_ans += v.min } + real_ans % (10**9 + 7) +end diff --git a/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.rs b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.rs new file mode 100644 index 00000000..46dc9696 --- /dev/null +++ b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.rs @@ -0,0 +1,68 @@ +impl Solution { + pub fn create_sorted_array(instructions: Vec) -> i32 { + let n = instructions.len(); + let nums = instructions; + let mut ans = vec![vec![0, 0]; n]; + + let arr: Vec = (0..n).collect(); + + fn merge(nums: &Vec, ans: &mut Vec>, left: &Vec, right: &Vec) -> Vec { + let mut l = left.len() as i32 - 1; + let mut r = right.len() as i32 - 1; + while l > -1 && r > -1 { + if nums[left[l as usize]] <= nums[right[r as usize]] { + ans[right[r as usize]][1] += (left.len() as i32 - 1) - l; + r -= 1; + } else { + l -= 1; + } + } + while r > -1 { + ans[right[r as usize]][1] += left.len() as i32; + r -= 1; + } + + l = 0; + r = 0; + let mut res = Vec::new(); + while (l as usize) < left.len() && (r as usize) < right.len() { + if nums[left[l as usize]] < nums[right[r as usize]] { + res.push(left[l as usize]); + l += 1; + } else { + ans[right[r as usize]][0] += l; + res.push(right[r as usize]); + r += 1; + } + } + while (r as usize) < right.len() { + ans[right[r as usize]][0] += l; + res.push(right[r as usize]); + r += 1; + } + while (l as usize) < left.len() { + res.push(left[l as usize]); + l += 1; + } + res + } + + fn split(nums: &Vec, ans: &mut Vec>, l: usize, r: usize, arr: &Vec) -> Vec { + if l == r { + return vec![arr[r]]; + } + let mid = (l + r) / 2; + let left = split(nums, ans, l, mid, arr); + let right = split(nums, ans, mid + 1, r, arr); + merge(nums, ans, &left, &right) + } + + split(&nums, &mut ans, 0, n - 1, &arr); + + let mut real_ans = 0i64; + for i in 0..n { + real_ans += ans[i][0].min(ans[i][1]) as i64; + } + (real_ans % 1000000007) as i32 + } +} diff --git a/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.swift b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.swift new file mode 100644 index 00000000..e07006f7 --- /dev/null +++ b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.swift @@ -0,0 +1,67 @@ +class Solution { + private var nums: [Int] = [] + private var ans: [[Int]] = [] + + func createSortedArray(_ instructions: [Int]) -> Int { + let n = instructions.count + nums = instructions + ans = Array(repeating: [0, 0], count: n) + + let arr = Array(0.. [Int] { + var l = left.count - 1 + var r = right.count - 1 + while l > -1 && r > -1 { + if nums[left[l]] <= nums[right[r]] { + ans[right[r]][1] += (left.count - 1) - l + r -= 1 + } else { + l -= 1 + } + } + while r > -1 { + ans[right[r]][1] += left.count + r -= 1 + } + + l = 0 + r = 0 + var res: [Int] = [] + while l < left.count && r < right.count { + if nums[left[l]] < nums[right[r]] { + res.append(left[l]) + l += 1 + } else { + ans[right[r]][0] += l + res.append(right[r]) + r += 1 + } + } + while r < right.count { + ans[right[r]][0] += l + res.append(right[r]) + r += 1 + } + res.append(contentsOf: left[l...]) + return res + } + + private func split(_ l: Int, _ r: Int, _ arr: [Int]) -> [Int] { + if l == r { + return [arr[r]] + } + let mid = (l + r) / 2 + let left = split(l, mid, arr) + let right = split(mid + 1, r, arr) + return merge(left, right) + } +} diff --git a/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.ts b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.ts new file mode 100644 index 00000000..4e96aac2 --- /dev/null +++ b/tests/1501-2000/1649. create-sorted-array-through-instructions/sol.ts @@ -0,0 +1,68 @@ +function createSortedArray(instructions: number[]): number { + const n = instructions.length; + const nums = instructions; + const ans: number[][] = Array.from({ length: n }, () => [0, 0]); + + const merge = (left: number[], right: number[]): number[] => { + let l = left.length - 1; + let r = right.length - 1; + while (l > -1 && r > -1) { + if (nums[left[l]] <= nums[right[r]]) { + ans[right[r]][1] += left.length - 1 - l; + r--; + } else { + l--; + } + } + while (r > -1) { + ans[right[r]][1] += left.length; + r--; + } + + l = 0; + r = 0; + const res: number[] = []; + while (l < left.length && r < right.length) { + if (nums[left[l]] < nums[right[r]]) { + res.push(left[l]); + l++; + } else { + ans[right[r]][0] += l; + res.push(right[r]); + r++; + } + } + while (r < right.length) { + ans[right[r]][0] += l; + res.push(right[r]); + r++; + } + while (l < left.length) { + res.push(left[l]); + l++; + } + return res; + }; + + const split = (l: number, r: number, arr: number[]): number[] => { + if (l === r) { + return [arr[r]]; + } + const mid = Math.floor((l + r) / 2); + const left = split(l, mid, arr); + const right = split(mid + 1, r, arr); + return merge(left, right); + }; + + split( + 0, + n - 1, + Array.from({ length: n }, (_, i) => i), + ); + + let realAns = 0; + for (let i = 0; i < n; i++) { + realAns += Math.min(ans[i][0], ans[i][1]); + } + return realAns % 1000000007; +} diff --git a/tests/1501-2000/1652. defuse-the-bomb/manifest.yaml b/tests/1501-2000/1652. defuse-the-bomb/manifest.yaml new file mode 100644 index 00000000..64d088df --- /dev/null +++ b/tests/1501-2000/1652. defuse-the-bomb/manifest.yaml @@ -0,0 +1,269 @@ +entry: + id: 1652 + title: "defuse-the-bomb" + params: + code: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().decrypt({code}, {k})" + rust: "Solution::decrypt({code}, {k})" + python3: "Solution().decrypt({code}, {k})" + python2: "Solution().decrypt({code}, {k})" + ruby: "decrypt({code}, {k})" + java: "new Solution().decrypt({code}, {k})" + csharp: "new Solution().Decrypt({code}, {k})" + kotlin: "Solution().decrypt({code}, {k})" + go: "decrypt({code}, {k})" + dart: "Solution().decrypt({code}, {k})" + swift: "Solution().decrypt({code}, {k})" + typescript: "decrypt({code}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().decrypt(code, k, {result})" + checker: | + class Checker: + def decrypt(self, code, k, result): + if not isinstance(result, list) or len(result) != len(code): + return False + n = len(code) + expected = [] + for i in range(n): + if k == 0: + expected.append(0) + elif k > 0: + expected.append(sum(code[(i + j) % n] for j in range(1, k + 1))) + else: + expected.append(sum(code[(i - j) % n] for j in range(1, -k + 1))) + return result == expected + +seed: 1652 + +tests: + - name: example-positive + in: + code: [5, 7, 1, 4] + k: 3 + out: [12, 10, 16, 13] + - name: example-zero + in: + code: [1, 2, 3, 4] + k: 0 + out: [0, 0, 0, 0] + - name: example-negative + in: + code: [2, 4, 9, 3] + k: -2 + out: [12, 5, 6, 13] + - name: one-element-zero + in: + code: [1] + k: 0 + out: [0] + - name: two-positive + in: + code: [1, 2] + k: 1 + out: [2, 1] + - name: two-negative + in: + code: [1, 2] + k: -1 + out: [2, 1] + - name: min-length-positive + in: + code: [100, 1] + k: 1 + out: [1, 100] + - name: min-length-negative + in: + code: [100, 1] + k: -1 + out: [1, 100] + - name: all-ones-positive + in: + code: [1, 1, 1, 1, 1] + k: 4 + out: [4, 4, 4, 4, 4] + - name: all-ones-negative + in: + code: [1, 1, 1, 1, 1] + k: -4 + out: [4, 4, 4, 4, 4] + - name: all-max-zero + in: + code: [100, 100, 100, 100] + k: 0 + out: [0, 0, 0, 0] + - name: positive-one + in: + code: [1, 2, 3, 4, 5] + k: 1 + out: [2, 3, 4, 5, 1] + - name: negative-one + in: + code: [1, 2, 3, 4, 5] + k: -1 + out: [5, 1, 2, 3, 4] + - name: positive-two + in: + code: [1, 2, 3, 4, 5] + k: 2 + out: [5, 7, 9, 6, 3] + - name: negative-two + in: + code: [1, 2, 3, 4, 5] + k: -2 + out: [9, 6, 3, 5, 7] + - name: positive-three + in: + code: [2, 5, 1, 7, 3, 4] + k: 3 + out: [13, 11, 14, 9, 11, 8] + - name: negative-three + in: + code: [2, 5, 1, 7, 3, 4] + k: -3 + out: [14, 9, 11, 8, 13, 11] + - name: max-positive-six + in: + code: [1, 2, 3, 4, 5, 6, 7] + k: 6 + out: [27, 26, 25, 24, 23, 22, 21] + - name: max-negative-six + in: + code: [1, 2, 3, 4, 5, 6, 7] + k: -6 + out: [27, 26, 25, 24, 23, 22, 21] + - name: alternating-positive + in: + code: [1, 100, 1, 100, 1, 100] + k: 2 + out: [101, 101, 101, 101, 101, 101] + - name: alternating-negative + in: + code: [1, 100, 1, 100, 1, 100] + k: -2 + out: [101, 101, 101, 101, 101, 101] + - name: repeated-pattern + in: + code: [3, 8, 2, 8, 3, 8, 2, 8] + k: 3 + out: [18, 13, 19, 13, 18, 13, 19, 13] + - name: repeated-pattern-negative + in: + code: [3, 8, 2, 8, 3, 8, 2, 8] + k: -3 + out: [18, 13, 19, 13, 18, 13, 19, 13] + - name: nine-values + in: + code: [9, 1, 8, 2, 7, 3, 6, 4, 5] + k: 4 + out: [18, 20, 18, 20, 18, 24, 19, 23, 20] + - name: nine-values-negative + in: + code: [9, 1, 8, 2, 7, 3, 6, 4, 5] + k: -4 + out: [18, 24, 19, 23, 20, 18, 20, 18, 20] + - name: large-values-positive + in: + code: [100, 99, 98, 97, 96, 95] + k: 5 + out: [485, 486, 487, 488, 489, 490] + - name: large-values-negative + in: + code: [100, 99, 98, 97, 96, 95] + k: -5 + out: [485, 486, 487, 488, 489, 490] + - name: single-high-positive + in: + code: [100] + k: 0 + out: [0] + - name: six-zero + in: + code: [1, 3, 5, 7, 9, 11] + k: 0 + out: [0, 0, 0, 0, 0, 0] + - name: uneven-positive + in: + code: [4, 1, 9, 2, 8, 3, 7] + k: 2 + out: [10, 11, 10, 11, 10, 11, 5] + - name: uneven-negative + in: + code: [4, 1, 9, 2, 8, 3, 7] + k: -2 + out: [10, 11, 5, 10, 11, 10, 11] + - name: gen-random-small + in: + code: + gen: "array" + len: 10 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + k: + gen: "int" + min: -9 + max: 9 + - name: gen-random-medium + in: + code: + gen: "array" + len: 37 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + k: + gen: "int" + min: -36 + max: 36 + - name: gen-max-length-positive + in: + code: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + k: 99 + - name: gen-max-length-negative + in: + code: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + k: -99 + - name: gen-max-length-zero + in: + code: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + k: 0 diff --git a/tests/1501-2000/1652. defuse-the-bomb/sol.cpp b/tests/1501-2000/1652. defuse-the-bomb/sol.cpp new file mode 100644 index 00000000..28f5c245 --- /dev/null +++ b/tests/1501-2000/1652. defuse-the-bomb/sol.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + vector decrypt(vector& code, int k) { + int n = code.size(); + vector result(n, 0); + + if (k == 0) return result; + + int window = abs(k); + int total = 0; + + int start = k > 0 ? 1 : n - window; + int end = k > 0 ? window : n - 1; + + for (int i = start; i <= end; i++) { + total += code[i % n]; + } + for (int i = 0; i < n; i++) { + result[i] = total; + + total -= code[start % n]; + start++; + + end++; + total += code[end % n]; + } + return result; + } +}; diff --git a/tests/1501-2000/1652. defuse-the-bomb/sol.cs b/tests/1501-2000/1652. defuse-the-bomb/sol.cs new file mode 100644 index 00000000..9b2a4c27 --- /dev/null +++ b/tests/1501-2000/1652. defuse-the-bomb/sol.cs @@ -0,0 +1,28 @@ +public class Solution { + public int[] Decrypt(int[] code, int k) { + int n = code.Length; + int[] result = new int[n]; + + if (k == 0) return result; + + int window = Math.Abs(k); + int total = 0; + + int start = k > 0 ? 1 : n - window; + int end = k > 0 ? window : n - 1; + + for (int i = start; i <= end; i++) { + total += code[i % n]; + } + for (int i = 0; i < n; i++) { + result[i] = total; + + total -= code[start % n]; + start++; + + end++; + total += code[end % n]; + } + return result; + } +} diff --git a/tests/1501-2000/1652. defuse-the-bomb/sol.dart b/tests/1501-2000/1652. defuse-the-bomb/sol.dart new file mode 100644 index 00000000..1b48b3fb --- /dev/null +++ b/tests/1501-2000/1652. defuse-the-bomb/sol.dart @@ -0,0 +1,28 @@ +class Solution { + List decrypt(List code, int k) { + int n = code.length; + List result = List.filled(n, 0); + + if (k == 0) return result; + + int window = k.abs(); + int total = 0; + + int start = k > 0 ? 1 : n - window; + int end = k > 0 ? window : n - 1; + + for (int i = start; i <= end; i++) { + total += code[i % n]; + } + for (int i = 0; i < n; i++) { + result[i] = total; + + total -= code[start % n]; + start++; + + end++; + total += code[end % n]; + } + return result; + } +} diff --git a/tests/1501-2000/1652. defuse-the-bomb/sol.go b/tests/1501-2000/1652. defuse-the-bomb/sol.go new file mode 100644 index 00000000..55cf9577 --- /dev/null +++ b/tests/1501-2000/1652. defuse-the-bomb/sol.go @@ -0,0 +1,41 @@ +func decrypt(code []int, k int) []int { + n := len(code) + result := make([]int, n) + + if k == 0 { + return result + } + + window := abs(k) + total := 0 + + start := 1 + if k < 0 { + start = n - window + } + end := window + if k < 0 { + end = n - 1 + } + + for i := start; i <= end; i++ { + total += code[i%n] + } + for i := 0; i < n; i++ { + result[i] = total + + total -= code[start%n] + start++ + + end++ + total += code[end%n] + } + return result +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} diff --git a/tests/1501-2000/1652. defuse-the-bomb/sol.java b/tests/1501-2000/1652. defuse-the-bomb/sol.java new file mode 100644 index 00000000..7f5dbde9 --- /dev/null +++ b/tests/1501-2000/1652. defuse-the-bomb/sol.java @@ -0,0 +1,28 @@ +class Solution { + public int[] decrypt(int[] code, int k) { + int n = code.length; + int[] result = new int[n]; + + if (k == 0) return result; + + int window = Math.abs(k); + int total = 0; + + int start = k > 0 ? 1 : n - window; + int end = k > 0 ? window : n - 1; + + for (int i = start; i <= end; i++) { + total += code[i % n]; + } + for (int i = 0; i < n; i++) { + result[i] = total; + + total -= code[start % n]; + start++; + + end++; + total += code[end % n]; + } + return result; + } +} diff --git a/tests/1501-2000/1652. defuse-the-bomb/sol.kt b/tests/1501-2000/1652. defuse-the-bomb/sol.kt new file mode 100644 index 00000000..c44931d0 --- /dev/null +++ b/tests/1501-2000/1652. defuse-the-bomb/sol.kt @@ -0,0 +1,28 @@ +class Solution { + fun decrypt(code: IntArray, k: Int): IntArray { + val n = code.size + val result = IntArray(n) + + if (k == 0) return result + + val window = Math.abs(k) + var total = 0 + + var start = if (k > 0) 1 else n - window + var end = if (k > 0) window else n - 1 + + for (i in start..end) { + total += code[i % n] + } + for (i in 0 until n) { + result[i] = total + + total -= code[start % n] + start++ + + end++ + total += code[end % n] + } + return result + } +} diff --git a/tests/1501-2000/1652. defuse-the-bomb/sol.py b/tests/1501-2000/1652. defuse-the-bomb/sol.py new file mode 100644 index 00000000..576ebcdd --- /dev/null +++ b/tests/1501-2000/1652. defuse-the-bomb/sol.py @@ -0,0 +1,25 @@ +class Solution: + def decrypt(self, code: List[int], k: int) -> List[int]: + n = len(code) + result = [0] * n + + if k == 0: + return result + + window = abs(k) + total = 0 + + start = 1 if k > 0 else n - window + end = window if k > 0 else n - 1 + + for i in range(start, end + 1): + total += code[i % n] + for i in range(n): + result[i] = total + + total -= code[start % n] + start += 1 + + end += 1 + total += code[end % n] + return result diff --git a/tests/1501-2000/1652. defuse-the-bomb/sol.py2 b/tests/1501-2000/1652. defuse-the-bomb/sol.py2 new file mode 100644 index 00000000..ff7a0f7f --- /dev/null +++ b/tests/1501-2000/1652. defuse-the-bomb/sol.py2 @@ -0,0 +1,15 @@ + +class Solution(object): + def decrypt(self, code, k): + n = len(code) + if k == 0: + return [0] * n + + answer = [] + direction = 1 if k > 0 else -1 + for i in range(n): + total = 0 + for offset in range(1, abs(k) + 1): + total += code[(i + direction * offset) % n] + answer.append(total) + return answer diff --git a/tests/1501-2000/1652. defuse-the-bomb/sol.rb b/tests/1501-2000/1652. defuse-the-bomb/sol.rb new file mode 100644 index 00000000..959e1138 --- /dev/null +++ b/tests/1501-2000/1652. defuse-the-bomb/sol.rb @@ -0,0 +1,29 @@ +# @param {Integer[]} code +# @param {Integer} k +# @return {Integer[]} +def decrypt(code, k) + n = code.length + result = Array.new(n, 0) + + return result if k == 0 + + window = k.abs + total = 0 + + start = k > 0 ? 1 : n - window + end_idx = k > 0 ? window : n - 1 + + (start..end_idx).each do |i| + total += code[i % n] + end + n.times do |i| + result[i] = total + + total -= code[start % n] + start += 1 + + end_idx += 1 + total += code[end_idx % n] + end + result +end diff --git a/tests/1501-2000/1652. defuse-the-bomb/sol.rs b/tests/1501-2000/1652. defuse-the-bomb/sol.rs new file mode 100644 index 00000000..69c97508 --- /dev/null +++ b/tests/1501-2000/1652. defuse-the-bomb/sol.rs @@ -0,0 +1,30 @@ +impl Solution { + pub fn decrypt(code: Vec, k: i32) -> Vec { + let n = code.len(); + let mut result = vec![0; n]; + + if k == 0 { + return result; + } + + let window = k.abs() as usize; + let mut total = 0; + + let mut start = if k > 0 { 1 } else { n - window }; + let mut end = if k > 0 { window } else { n - 1 }; + + for i in start..=end { + total += code[i % n]; + } + for i in 0..n { + result[i] = total; + + total -= code[start % n]; + start += 1; + + end += 1; + total += code[end % n]; + } + result + } +} diff --git a/tests/1501-2000/1652. defuse-the-bomb/sol.swift b/tests/1501-2000/1652. defuse-the-bomb/sol.swift new file mode 100644 index 00000000..e682bd31 --- /dev/null +++ b/tests/1501-2000/1652. defuse-the-bomb/sol.swift @@ -0,0 +1,28 @@ +class Solution { + func decrypt(_ code: [Int], _ k: Int) -> [Int] { + let n = code.count + var result = [Int](repeating: 0, count: n) + + if k == 0 { return result } + + let window = abs(k) + var total = 0 + + var start = k > 0 ? 1 : n - window + var end = k > 0 ? window : n - 1 + + for i in start...end { + total += code[i % n] + } + for i in 0.. 0 ? 1 : n - window; + let end = k > 0 ? window : n - 1; + + for (let i = start; i <= end; i++) { + total += code[i % n]; + } + for (let i = 0; i < n; i++) { + result[i] = total; + + total -= code[start % n]; + start++; + + end++; + total += code[end % n]; + } + return result; +} diff --git a/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/manifest.yaml b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/manifest.yaml new file mode 100644 index 00000000..0f4c4b8d --- /dev/null +++ b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/manifest.yaml @@ -0,0 +1,194 @@ +entry: + id: 1653 + title: "minimum-deletions-to-make-string-balanced" + params: + s: + type: string + call: + cpp: "Solution().minimumDeletions({s})" + rust: "Solution::minimum_deletions({s})" + python3: "Solution().minimumDeletions({s})" + python2: "Solution().minimumDeletions({s})" + ruby: "minimum_deletions({s})" + java: "new Solution().minimumDeletions({s})" + csharp: "new Solution().MinimumDeletions({s})" + kotlin: "Solution().minimumDeletions({s})" + go: "minimumDeletions({s})" + dart: "Solution().minimumDeletions({s})" + swift: "Solution().minimumDeletions({s})" + typescript: "minimumDeletions({s})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().minimumDeletions(s, {result})" + checker: | + class Checker: + def minimumDeletions(self, s, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + b = 0 + suffix_a = s.count('a') + best = suffix_a + for ch in s: + if ch == 'a': + suffix_a -= 1 + else: + b += 1 + best = min(best, b + suffix_a) + return result == best +seed: 1653 +tests: + - name: example-one + in: + s: "aababbab" + out: 2 + - name: example-two + in: + s: "bbaaaaabb" + out: 2 + - name: one-a + in: + s: "a" + out: 0 + - name: one-b + in: + s: "b" + out: 0 + - name: all-a-short + in: + s: "aaaaaa" + out: 0 + - name: all-b-short + in: + s: "bbbbbb" + out: 0 + - name: already-balanced + in: + s: "aaabbbb" + out: 0 + - name: reverse-two + in: + s: "ba" + out: 1 + - name: alternating-four + in: + s: "abab" + out: 1 + - name: alternating-five + in: + s: "babab" + out: 2 + - name: central-ba + in: + s: "aaabaaa" + out: 1 + - name: repeated-blocks + in: + s: "bbbaaa" + out: 3 + - name: one-inversion + in: + s: "aabbaaabbbb" + out: 2 + - name: late-inversion + in: + s: "aaaaabaaaa" + out: 1 + - name: many-inversions + in: + s: "ababababab" + out: 4 + - name: b-run-between-a + in: + s: "abbbba" + out: 1 + - name: balanced-with-empty-side + in: + s: "aaaab" + out: 0 + - name: minimal-middle + in: + s: "baaab" + out: 1 + - name: two-bands + in: + s: "aabbaabb" + out: 2 + - name: alternating-six + in: + s: "ababab" + out: 2 + - name: alternating-seven + in: + s: "bababab" + out: 3 + - name: long-a-then-ba + in: + s: "aaaaaaaab" + out: 0 + - name: long-b-then-a + in: + s: "bbbbbbba" + out: 1 + - name: equal-runs + in: + s: "aaabbbbaaaabbbb" + out: 4 + - name: several-small-runs + in: + s: "aabbabbaba" + out: 3 + - name: generator-short + in: + s: + gen: "str" + len: 17 + alphabet: "ab" + - name: generator-medium + in: + s: + gen: "str" + len: 101 + alphabet: "ab" + - name: generator-large + in: + s: + gen: "str" + len: 10000 + alphabet: "ab" + - name: generator-near-limit + in: + s: + gen: "str" + len: 50000 + alphabet: "ab" + - name: generator-maximum + in: + s: + gen: "str" + len: 100000 + alphabet: "ab" + - name: long-all-a + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: 0 + - name: long-all-b + in: + s: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + out: 0 + - name: long-single-inversion + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: 1 + - name: long-balanced-boundary + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + out: 0 + - name: long-two-inversions + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: 2 diff --git a/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.cpp b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.cpp new file mode 100644 index 00000000..58306e97 --- /dev/null +++ b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int minimumDeletions(string s) { + int res = 0; + int count = 0; + for (char ch : s) { + if (ch == 'b') { + count++; + } else if (count > 0) { + res++; + count--; + } + } + return res; + } +}; diff --git a/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.cs b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.cs new file mode 100644 index 00000000..0c85d9c2 --- /dev/null +++ b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int MinimumDeletions(string s) { + int res = 0; + int count = 0; + foreach (char ch in s) { + if (ch == 'b') { + count++; + } else if (count > 0) { + res++; + count--; + } + } + return res; + } +} diff --git a/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.dart b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.dart new file mode 100644 index 00000000..492840d5 --- /dev/null +++ b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.dart @@ -0,0 +1,15 @@ +class Solution { + int minimumDeletions(String s) { + int res = 0; + int count = 0; + for (int i = 0; i < s.length; i++) { + if (s[i] == 'b') { + count++; + } else if (count > 0) { + res++; + count--; + } + } + return res; + } +} diff --git a/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.go b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.go new file mode 100644 index 00000000..6d68cf26 --- /dev/null +++ b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.go @@ -0,0 +1,13 @@ +func minimumDeletions(s string) int { + res := 0 + count := 0 + for _, ch := range s { + if ch == 'b' { + count++ + } else if count > 0 { + res++ + count-- + } + } + return res +} diff --git a/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.java b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.java new file mode 100644 index 00000000..74f97fe4 --- /dev/null +++ b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.java @@ -0,0 +1,15 @@ +class Solution { + public int minimumDeletions(String s) { + int res = 0; + int count = 0; + for (char ch : s.toCharArray()) { + if (ch == 'b') { + count++; + } else if (count > 0) { + res++; + count--; + } + } + return res; + } +} diff --git a/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.kt b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.kt new file mode 100644 index 00000000..a7639355 --- /dev/null +++ b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun minimumDeletions(s: String): Int { + var res = 0 + var count = 0 + for (ch in s) { + if (ch == 'b') { + count++ + } else if (count > 0) { + res++ + count-- + } + } + return res + } +} diff --git a/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.py b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.py new file mode 100644 index 00000000..7f91416d --- /dev/null +++ b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.py @@ -0,0 +1,12 @@ +class Solution: + def minimumDeletions(self, s: str) -> int: + res = 0 + count = 0 + for ch in s: + if ch == "b": + count += 1 + elif count: + res += 1 + count -= 1 + + return res diff --git a/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.py2 b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.py2 new file mode 100644 index 00000000..eac2eba9 --- /dev/null +++ b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def minimumDeletions(self, s): + """ + :type s: str + :rtype: int + """ + res = 0 + count = 0 + for ch in s: + if ch == 'b': + count += 1 + elif count: + res += 1 + count -= 1 + return res diff --git a/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.rb b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.rb new file mode 100644 index 00000000..54468ab1 --- /dev/null +++ b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.rb @@ -0,0 +1,15 @@ +# @param {String} s +# @return {Integer} +def minimum_deletions(s) + res = 0 + count = 0 + s.each_char do |ch| + if ch == 'b' + count += 1 + elsif count > 0 + res += 1 + count -= 1 + end + end + res +end diff --git a/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.rs b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.rs new file mode 100644 index 00000000..af59bf13 --- /dev/null +++ b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn minimum_deletions(s: String) -> i32 { + let mut res = 0; + let mut count = 0; + for ch in s.chars() { + if ch == 'b' { + count += 1; + } else if count > 0 { + res += 1; + count -= 1; + } + } + res + } +} diff --git a/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.swift b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.swift new file mode 100644 index 00000000..85342e58 --- /dev/null +++ b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func minimumDeletions(_ s: String) -> Int { + var res = 0 + var count = 0 + for ch in s { + if ch == "b" { + count += 1 + } else if count > 0 { + res += 1 + count -= 1 + } + } + return res + } +} diff --git a/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.ts b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.ts new file mode 100644 index 00000000..dbcb968f --- /dev/null +++ b/tests/1501-2000/1653. minimum-deletions-to-make-string-balanced/sol.ts @@ -0,0 +1,13 @@ +function minimumDeletions(s: string): number { + let res = 0; + let count = 0; + for (const ch of s) { + if (ch === "b") { + count++; + } else if (count > 0) { + res++; + count--; + } + } + return res; +} diff --git a/tests/1501-2000/1654. minimum-jumps-to-reach-home/manifest.yaml b/tests/1501-2000/1654. minimum-jumps-to-reach-home/manifest.yaml new file mode 100644 index 00000000..a7740a62 --- /dev/null +++ b/tests/1501-2000/1654. minimum-jumps-to-reach-home/manifest.yaml @@ -0,0 +1,344 @@ +entry: + id: 1654 + title: "minimum-jumps-to-reach-home" + params: + forbidden: + type: array + items: + type: int + a: + type: int + b: + type: int + x: + type: int + call: + cpp: "Solution().minimumJumps({forbidden}, {a}, {b}, {x})" + rust: "Solution::minimum_jumps({forbidden}, {a}, {b}, {x})" + python3: "Solution().minimumJumps({forbidden}, {a}, {b}, {x})" + python2: "Solution().minimumJumps({forbidden}, {a}, {b}, {x})" + ruby: "minimum_jumps({forbidden}, {a}, {b}, {x})" + java: "new Solution().minimumJumps({forbidden}, {a}, {b}, {x})" + csharp: "new Solution().MinimumJumps({forbidden}, {a}, {b}, {x})" + kotlin: "Solution().minimumJumps({forbidden}, {a}, {b}, {x})" + go: "minimumJumps({forbidden}, {a}, {b}, {x})" + dart: "Solution().minimumJumps({forbidden}, {a}, {b}, {x})" + swift: "Solution().minimumJumps({forbidden}, {a}, {b}, {x})" + typescript: "minimumJumps({forbidden}, {a}, {b}, {x})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minimumJumps(forbidden, a, b, x, {result})" + checker: | + from collections import deque + class Checker: + def minimumJumps(self, forbidden, a, b, x, result): + blocked = set(forbidden) + if x in blocked or 0 in blocked: + return False + bound = max(max(blocked) if blocked else 0, x) + a + b + q = deque([(0, False, 0)]) + seen = {(0, False)} + answer = -1 + while q: + pos, last_back, dist = q.popleft() + if pos == x: + answer = dist + break + nxt = pos + a + state = (nxt, False) + if nxt <= bound and nxt not in blocked and state not in seen: + seen.add(state) + q.append((nxt, False, dist + 1)) + if not last_back: + nxt = pos - b + state = (nxt, True) + if nxt >= 0 and nxt not in blocked and state not in seen: + seen.add(state) + q.append((nxt, True, dist + 1)) + return isinstance(result, int) and result == answer + +seed: 1654 + +tests: + - name: example-1 + in: + forbidden: [14, 4, 18, 1, 15] + a: 3 + b: 15 + x: 9 + out: 3 + - name: example-2 + in: + forbidden: [8, 3, 16, 6, 12, 20] + a: 15 + b: 13 + x: 11 + out: -1 + - name: example-3 + in: + forbidden: [1, 6, 2, 14, 5, 17, 4] + a: 16 + b: 9 + x: 7 + out: 2 + - name: home-at-zero + in: + forbidden: [1] + a: 2 + b: 3 + x: 0 + out: 0 + - name: one-forward + in: + forbidden: [2] + a: 7 + b: 3 + x: 7 + out: 1 + - name: one-backward-after-forward + in: + forbidden: [5] + a: 10 + b: 3 + x: 7 + out: 2 + - name: blocked-home + in: + forbidden: [9, 1, 4] + a: 3 + b: 2 + x: 9 + out: -1 + - name: gcd-impossible + in: + forbidden: [10] + a: 6 + b: 4 + x: 7 + out: -1 + - name: direct-with-obstacle + in: + forbidden: [6] + a: 3 + b: 5 + x: 9 + out: -1 + - name: no-backward-needed + in: + forbidden: [3, 7] + a: 4 + b: 9 + x: 12 + out: 3 + - name: parity-impossible + in: + forbidden: [2, 4, 6] + a: 8 + b: 6 + x: 5 + out: -1 + - name: backward-required + in: + forbidden: [4] + a: 6 + b: 4 + x: 2 + out: 2 + - name: trapped-by-forbidden + in: + forbidden: [3, 6, 9, 12] + a: 3 + b: 2 + x: 10 + out: -1 + - name: repeated-forward + in: + forbidden: [1, 2, 5] + a: 4 + b: 7 + x: 16 + out: 4 + - name: overshoot-and-return + in: + forbidden: [8, 11] + a: 7 + b: 5 + x: 9 + out: 3 + - name: large-a + in: + forbidden: [10, 20, 30] + a: 100 + b: 37 + x: 63 + out: 2 + - name: large-b + in: + forbidden: [5, 9, 13] + a: 17 + b: 100 + x: 34 + out: 2 + - name: dense-small-blocks + in: + forbidden: [1, 2, 3, 4, 5, 6, 8, 9, 10] + a: 7 + b: 3 + x: 14 + out: 2 + - name: sparse-large-x + in: + forbidden: [100, 203, 407, 811] + a: 37 + b: 19 + x: 185 + out: 5 + - name: x-forbidden-not-last + in: + forbidden: [17, 1, 13] + a: 8 + b: 5 + x: 17 + out: -1 + - name: exact-return + in: + forbidden: [3] + a: 5 + b: 2 + x: 8 + out: 3 + - name: two-backward-alternation + in: + forbidden: [6, 12] + a: 9 + b: 4 + x: 5 + out: 2 + - name: unreachable-wall + in: + forbidden: [1, 2, 3, 4, 5, 6, 7] + a: 8 + b: 3 + x: 1 + out: -1 + - name: max-x-direct + in: + forbidden: [1999] + a: 2000 + b: 1 + x: 2000 + out: 1 + - name: max-values + in: + forbidden: [1, 1999] + a: 2000 + b: 2000 + x: 2000 + out: 1 + - name: unit-forward + in: + forbidden: [2, 4, 6] + a: 1 + b: 2 + x: 7 + out: -1 + - name: unit-backward + in: + forbidden: [1, 3] + a: 2 + b: 1 + x: 4 + out: 2 + - name: coprime-detour + in: + forbidden: [6, 10, 14] + a: 4 + b: 3 + x: 11 + out: -1 + - name: isolated-target + in: + forbidden: [2, 3, 4, 5, 6, 7, 8, 9] + a: 10 + b: 1 + x: 10 + out: 1 + - name: high-forbidden-tail + in: + forbidden: [1500, 1600, 1700, 1800, 1900] + a: 13 + b: 17 + x: 999 + out: 93 + - name: target-behind-first-jump + in: + forbidden: [2, 15] + a: 15 + b: 8 + x: 7 + out: -1 + - name: blocked-forward-route + in: + forbidden: [5, 10, 15, 20] + a: 5 + b: 3 + x: 25 + out: -1 + - name: long-detour + in: + forbidden: [19, 38, 57, 76, 95] + a: 19 + b: 11 + x: 114 + out: -1 + - name: near-boundary + in: + forbidden: [1990, 1991, 1992] + a: 997 + b: 991 + x: 1994 + out: 2 + - name: large-forbidden-set + in: + forbidden: + [ + 1, + 3, + 5, + 7, + 9, + 11, + 13, + 15, + 17, + 19, + 21, + 23, + 25, + 27, + 29, + 31, + 33, + 35, + 37, + 39, + ] + a: 2 + b: 3 + x: 40 + out: 20 + - name: final-bfs-case + in: + forbidden: [4, 12, 18, 23, 29, 34] + a: 7 + b: 6 + x: 31 + out: 10 diff --git a/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.cpp b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.cpp new file mode 100644 index 00000000..c0aa4055 --- /dev/null +++ b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int minimumJumps(vector& forbidden, int a, int b, int x) { + int idx = 1; + int m = min(a, b); + for (int i = 2; i <= m; i++) { + if (a % i == 0 && b % i == 0) idx = i; + } + if (x % idx != 0) return -1; + queue> q; + q.push({0, 1, 0}); + unordered_set visited; + visited.insert(0); + for (int f : forbidden) visited.insert(f); + int top = *max_element(forbidden.begin(), forbidden.end()); + int limit = top + x + a + b; + while (!q.empty()) { + auto cur = q.front(); + q.pop(); + int curr = cur[0], prev = cur[1], step = cur[2]; + if (curr == x) return step; + if (prev == 1) { + int nb = curr - b; + if (nb >= 0 && visited.find(nb) == visited.end()) { + visited.insert(nb); + q.push({nb, -1, step + 1}); + } + } + int na = curr + a; + if (na <= limit && visited.find(na) == visited.end()) { + visited.insert(na); + q.push({na, 1, step + 1}); + } + } + return -1; + } +}; diff --git a/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.cs b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.cs new file mode 100644 index 00000000..aceda92e --- /dev/null +++ b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.cs @@ -0,0 +1,35 @@ +public class Solution { + public int MinimumJumps(int[] forbidden, int a, int b, int x) { + int idx = 1; + int m = Math.Min(a, b); + for (int i = 2; i <= m; i++) { + if (a % i == 0 && b % i == 0) idx = i; + } + if (x % idx != 0) return -1; + var q = new Queue<(int, int, int)>(); + q.Enqueue((0, 1, 0)); + var visited = new HashSet(); + visited.Add(0); + foreach (int f in forbidden) visited.Add(f); + int top = forbidden.Max(); + int limit = top + x + a + b; + while (q.Count > 0) { + var cur = q.Dequeue(); + int curr = cur.Item1, prev = cur.Item2, step = cur.Item3; + if (curr == x) return step; + if (prev == 1) { + int nb = curr - b; + if (nb >= 0 && !visited.Contains(nb)) { + visited.Add(nb); + q.Enqueue((nb, -1, step + 1)); + } + } + int na = curr + a; + if (na <= limit && !visited.Contains(na)) { + visited.Add(na); + q.Enqueue((na, 1, step + 1)); + } + } + return -1; + } +} diff --git a/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.dart b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.dart new file mode 100644 index 00000000..a80cfd12 --- /dev/null +++ b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.dart @@ -0,0 +1,34 @@ +class Solution { + int minimumJumps(List forbidden, int a, int b, int x) { + int idx = 1; + for (int i = 2; i <= (a < b ? a : b); i++) { + if (a % i == 0 && b % i == 0) idx = i; + } + if (x % idx != 0) return -1; + Queue> q = Queue(); + q.add([0, 1, 0]); + Set visited = Set(); + visited.add(0); + forbidden.forEach((f) => visited.add(f)); + int top = forbidden.reduce((m, e) => e > m ? e : m); + int limit = top + x + a + b; + while (q.isNotEmpty) { + var cur = q.removeFirst(); + int curr = cur[0], prev = cur[1], step = cur[2]; + if (curr == x) return step; + if (prev == 1) { + int nb = curr - b; + if (nb >= 0 && !visited.contains(nb)) { + visited.add(nb); + q.add([nb, -1, step + 1]); + } + } + int na = curr + a; + if (na <= limit && !visited.contains(na)) { + visited.add(na); + q.add([na, 1, step + 1]); + } + } + return -1; + } +} diff --git a/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.go b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.go new file mode 100644 index 00000000..0bf714e7 --- /dev/null +++ b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.go @@ -0,0 +1,52 @@ +func minimumJumps(forbidden []int, a int, b int, x int) int { + idx := 1 + for i := 2; i <= min(a, b); i++ { + if a%i == 0 && b%i == 0 { + idx = i + } + } + if x%idx != 0 { + return -1 + } + type triple struct{ curr, prev, step int } + q := []triple{{0, 1, 0}} + visited := make(map[int]bool) + visited[0] = true + for _, f := range forbidden { + visited[f] = true + } + top := 0 + for _, f := range forbidden { + if f > top { + top = f + } + } + limit := top + x + a + b + for len(q) > 0 { + cur := q[0] + q = q[1:] + if cur.curr == x { + return cur.step + } + if cur.prev == 1 { + nb := cur.curr - b + if nb >= 0 && !visited[nb] { + visited[nb] = true + q = append(q, triple{nb, -1, cur.step + 1}) + } + } + na := cur.curr + a + if na <= limit && !visited[na] { + visited[na] = true + q = append(q, triple{na, 1, cur.step + 1}) + } + } + return -1 +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} diff --git a/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.java b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.java new file mode 100644 index 00000000..74fcb68c --- /dev/null +++ b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.java @@ -0,0 +1,36 @@ +// (already provided) +class Solution { + public int minimumJumps(int[] forbidden, int a, int b, int x) { + int idx = 1; + for (int i = 2; i <= Math.min(a, b); i++) { + if (a % i == 0 && b % i == 0) idx = i; + } + if (x % idx != 0) return -1; + java.util.ArrayDeque q = new java.util.ArrayDeque<>(); + q.add(new int[]{0, 1, 0}); + java.util.Set visited = new java.util.HashSet<>(); + visited.add(0); + for (int f : forbidden) visited.add(f); + int top = 0; + for (int f : forbidden) top = Math.max(top, f); + int limit = top + x + a + b; + while (!q.isEmpty()) { + int[] cur = q.poll(); + int curr = cur[0], prev = cur[1], step = cur[2]; + if (curr == x) return step; + if (prev == 1) { + int nb = curr - b; + if (nb >= 0 && !visited.contains(nb)) { + visited.add(nb); + q.add(new int[]{nb, -1, step + 1}); + } + } + int na = curr + a; + if (na <= limit && !visited.contains(na)) { + visited.add(na); + q.add(new int[]{na, 1, step + 1}); + } + } + return -1; + } +} diff --git a/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.kt b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.kt new file mode 100644 index 00000000..2dddf167 --- /dev/null +++ b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.kt @@ -0,0 +1,33 @@ +class Solution { + fun minimumJumps(forbidden: IntArray, a: Int, b: Int, x: Int): Int { + var idx = 1 + for (i in 2..minOf(a, b)) { + if (a % i == 0 && b % i == 0) idx = i + } + if (x % idx != 0) return -1 + val q = ArrayDeque>() + q.add(Triple(0, 1, 0)) + val visited = HashSet() + visited.add(0) + forbidden.forEach { visited.add(it) } + val top = forbidden.maxOrNull() ?: 0 + val limit = top + x + a + b + while (q.isNotEmpty()) { + val (curr, prev, step) = q.removeFirst() + if (curr == x) return step + if (prev == 1) { + val nb = curr - b + if (nb >= 0 && !visited.contains(nb)) { + visited.add(nb) + q.add(Triple(nb, -1, step + 1)) + } + } + val na = curr + a + if (na <= limit && !visited.contains(na)) { + visited.add(na) + q.add(Triple(na, 1, step + 1)) + } + } + return -1 + } +} diff --git a/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.py b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.py new file mode 100644 index 00000000..3184ecbb --- /dev/null +++ b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.py @@ -0,0 +1,34 @@ +class Solution(object): + def minimumJumps(self, forbidden, a, b, x): + """ + :type forbidden: List[int] + :type a: int + :type b: int + :type x: int + :rtype: int + """ + idx = 1 + for i in range(2, min(a, b) + 1): + if a % i == 0 and b % i == 0: + idx = i + if x % idx != 0: + return -1 + q = deque([]) + q.append([0, 1, 0]) + visited = set() + visited.add(0) + not_allowed = set(forbidden) + visited = visited.union(not_allowed) + top = max(forbidden) + while q: + curr, prev, step = q.popleft() + if curr == x: + return step + if prev == 1: + if curr - b >= 0 and curr - b not in visited: + visited.add(curr - b) + q.append([curr - b, -1, step + 1]) + if curr + a not in visited and curr + a <= max(top, x) + a + b: + visited.add(curr + a) + q.append([curr + a, 1, step + 1]) + return -1 diff --git a/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.py2 b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.py2 new file mode 100644 index 00000000..783ec957 --- /dev/null +++ b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.py2 @@ -0,0 +1,38 @@ +class Solution(object): + def minimumJumps(self, forbidden, a, b, x): + """ + :type forbidden: List[int] + :type a: int + :type b: int + :type x: int + :rtype: int + """ + idx = 1 + for i in range(2, min(a, b) + 1): + if a % i == 0 and b % i == 0: + idx = i + if x % idx != 0: + return -1 + from collections import deque + q = deque() + q.append((0, 1, 0)) + visited = set() + visited.add(0) + for f in forbidden: + visited.add(f) + top = max(forbidden) + limit = top + x + a + b + while q: + curr, prev, step = q.popleft() + if curr == x: + return step + if prev == 1: + nb = curr - b + if nb >= 0 and nb not in visited: + visited.add(nb) + q.append((nb, -1, step + 1)) + na = curr + a + if na <= limit and na not in visited: + visited.add(na) + q.append((na, 1, step + 1)) + return -1 diff --git a/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.rb b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.rb new file mode 100644 index 00000000..380b2509 --- /dev/null +++ b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.rb @@ -0,0 +1,30 @@ +def minimum_jumps(forbidden, a, b, x) + idx = 1 + (2..[a, b].min).each do |i| + idx = i if a % i == 0 && b % i == 0 + end + return -1 if x % idx != 0 + q = [[0, 1, 0]] + visited = Set.new + visited.add(0) + forbidden.each { |f| visited.add(f) } + top = forbidden.max + limit = top + x + a + b + while !q.empty? + curr, prev, step = q.shift + return step if curr == x + if prev == 1 + nb = curr - b + if nb >= 0 && !visited.include?(nb) + visited.add(nb) + q.push([nb, -1, step + 1]) + end + end + na = curr + a + if na <= limit && !visited.include?(na) + visited.add(na) + q.push([na, 1, step + 1]) + end + end + -1 +end diff --git a/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.rs b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.rs new file mode 100644 index 00000000..84577815 --- /dev/null +++ b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.rs @@ -0,0 +1,39 @@ +impl Solution { + pub fn minimum_jumps(forbidden: Vec, a: i32, b: i32, x: i32) -> i32 { + let mut idx = 1; + let m = a.min(b); + if m >= 2 { + for i in 2..=m { + if a % i == 0 && b % i == 0 { + idx = i; + } + } + } + if x % idx != 0 { return -1; } + let mut queue: std::collections::VecDeque<(i32, i32, i32)> = std::collections::VecDeque::new(); + queue.push_back((0, 1, 0)); + let mut visited: std::collections::HashSet = std::collections::HashSet::new(); + visited.insert(0); + for &f in &forbidden { + visited.insert(f); + } + let top = forbidden.iter().max().copied().unwrap_or(0); + let limit = top + x + a + b; + while let Some((curr, prev, step)) = queue.pop_front() { + if curr == x { return step; } + if prev == 1 { + let nb = curr - b; + if nb >= 0 && !visited.contains(&nb) { + visited.insert(nb); + queue.push_back((nb, -1, step + 1)); + } + } + let na = curr + a; + if na <= limit && !visited.contains(&na) { + visited.insert(na); + queue.push_back((na, 1, step + 1)); + } + } + -1 + } +} diff --git a/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.swift b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.swift new file mode 100644 index 00000000..08dde57c --- /dev/null +++ b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.swift @@ -0,0 +1,39 @@ +class Solution { + func minimumJumps(_ forbidden: [Int], _ a: Int, _ b: Int, _ x: Int) -> Int { + var idx = 1 + let m = min(a, b) + if m >= 2 { + for i in 2...m { + if a % i == 0 && b % i == 0 { + idx = i + } + } + } + if x % idx != 0 { return -1 } + var queue: [(Int, Int, Int)] = [(0, 1, 0)] + var visited = Set() + visited.insert(0) + for f in forbidden { visited.insert(f) } + let top = forbidden.max() ?? 0 + let limit = top + x + a + b + var qIndex = 0 + while qIndex < queue.count { + let (curr, prev, step) = queue[qIndex] + qIndex += 1 + if curr == x { return step } + if prev == 1 { + let nb = curr - b + if nb >= 0 && !visited.contains(nb) { + visited.insert(nb) + queue.append((nb, -1, step + 1)) + } + } + let na = curr + a + if na <= limit && !visited.contains(na) { + visited.insert(na) + queue.append((na, 1, step + 1)) + } + } + return -1 + } +} diff --git a/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.ts b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.ts new file mode 100644 index 00000000..25047dc5 --- /dev/null +++ b/tests/1501-2000/1654. minimum-jumps-to-reach-home/sol.ts @@ -0,0 +1,36 @@ +function minimumJumps( + forbidden: number[], + a: number, + b: number, + x: number, +): number { + let idx = 1; + for (let i = 2; i <= Math.min(a, b); i++) { + if (a % i === 0 && b % i === 0) idx = i; + } + if (x % idx !== 0) return -1; + const queue: Array<[number, number, number]> = [[0, 1, 0]]; + const visited: Set = new Set(); + visited.add(0); + for (const f of forbidden) visited.add(f); + const top = Math.max(...forbidden); + const limit = top + x + a + b; + let index = 0; + while (index < queue.length) { + const [curr, prev, step] = queue[index++]; + if (curr === x) return step; + if (prev === 1) { + const nb = curr - b; + if (nb >= 0 && !visited.has(nb)) { + visited.add(nb); + queue.push([nb, -1, step + 1]); + } + } + const na = curr + a; + if (na <= limit && !visited.has(na)) { + visited.add(na); + queue.push([na, 1, step + 1]); + } + } + return -1; +} diff --git a/tests/1501-2000/1655. distribute-repeating-integers/manifest.yaml b/tests/1501-2000/1655. distribute-repeating-integers/manifest.yaml new file mode 100644 index 00000000..4f253049 --- /dev/null +++ b/tests/1501-2000/1655. distribute-repeating-integers/manifest.yaml @@ -0,0 +1,373 @@ +entry: + id: 1655 + title: distribute-repeating-integers + params: + nums: + type: array + items: + type: int + quantity: + type: array + items: + type: int + call: + cpp: "Solution().canDistribute({nums}, {quantity})" + rust: "Solution::can_distribute({nums}, {quantity})" + python3: "Solution().canDistribute({nums}, {quantity})" + python2: "Solution().canDistribute({nums}, {quantity})" + ruby: "can_distribute({nums}, {quantity})" + java: "new Solution().canDistribute({nums}, {quantity})" + csharp: "new Solution().CanDistribute({nums}, {quantity})" + kotlin: "Solution().canDistribute({nums}, {quantity})" + go: "canDistribute({nums}, {quantity})" + dart: "Solution().canDistribute({nums}, {quantity})" + swift: "Solution().canDistribute({nums}, {quantity})" + typescript: "canDistribute({nums}, {quantity})" + +judge: + type: exact + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().canDistribute(nums, quantity, {result})" + checker: | + from collections import Counter + + class Checker: + def canDistribute(self, nums, quantity, result): + if not isinstance(result, bool): + return False + capacities = list(Counter(nums).values()) + orders = sorted(quantity, reverse=True) + memo = {} + + def feasible(i, caps): + if i == len(orders): + return True + key = (i, tuple(sorted(caps, reverse=True))) + if key in memo: + return memo[key] + need = orders[i] + seen = set() + for j, cap in enumerate(caps): + if cap >= need and cap not in seen: + seen.add(cap) + nxt = list(caps) + nxt[j] -= need + if feasible(i + 1, nxt): + memo[key] = True + return True + memo[key] = False + return False + + return result == feasible(0, capacities) + +seed: 1655 + +tests: + - name: example-one + in: + nums: [1, 2, 3, 4] + quantity: [2] + out: false + judge: + type: exact + - name: example-two + in: + nums: [1, 2, 3, 3] + quantity: [2] + out: true + judge: + type: exact + - name: example-three + in: + nums: [1, 1, 2, 2] + quantity: [2, 2] + out: true + judge: + type: exact + - name: one-item-order + in: + nums: [7] + quantity: [1] + out: true + judge: + type: exact + - name: single-frequency-insufficient + in: + nums: [5, 5, 5] + quantity: [4] + out: false + judge: + type: exact + - name: split-one-frequency + in: + nums: [2, 2, 2, 2, 2] + quantity: [3, 2] + out: true + judge: + type: exact + - name: two-orders-one-capacity + in: + nums: [2, 2, 2, 2, 2] + quantity: [3, 1] + out: true + judge: + type: exact + - name: multiple-equal-capacities + in: + nums: [1, 1, 2, 2, 3, 3] + quantity: [1, 1, 1] + out: true + judge: + type: exact + - name: impossible-total-capacity + in: + nums: [1, 1, 2, 2, 3, 3] + quantity: [2, 2, 1] + out: true + judge: + type: exact + - name: exact-disjoint-groups + in: + nums: [1, 1, 1, 2, 2, 2, 3, 3] + quantity: [3, 2, 2] + out: true + judge: + type: exact + - name: order-independent + in: + nums: [4, 4, 4, 4, 5, 5, 5, 6, 6] + quantity: [2, 3, 1] + out: true + judge: + type: exact + - name: duplicate-demand + in: + nums: [1, 1, 1, 1, 2, 2, 2, 2] + quantity: [3, 3] + out: true + judge: + type: exact + - name: exact-duplicate-demand + in: + nums: [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3] + quantity: [4, 4, 4] + out: true + judge: + type: exact + - name: many-singletons + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + quantity: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: true + judge: + type: exact + - name: too-many-customers + in: + nums: [1, 1, 2, 2, 3, 3] + quantity: [2, 2, 2, 1] + out: false + judge: + type: exact + - name: scarce-large-order + in: + nums: [1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3] + quantity: [5, 4, 3] + out: true + judge: + type: exact + - name: scarce-large-order-fail + in: + nums: [1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3] + quantity: [6, 4, 2] + out: false + judge: + type: exact + - name: capacity-remainder + in: + nums: [1, 1, 1, 1, 1, 1, 2, 2, 2] + quantity: [4, 2, 2] + out: true + judge: + type: exact + - name: capacity-remainder-success + in: + nums: [1, 1, 1, 1, 1, 1, 2, 2, 2] + quantity: [4, 2, 1] + out: true + judge: + type: exact + - name: values-at-upper-bound + in: + nums: [1000, 1000, 999, 999, 998] + quantity: [2, 2, 1] + out: true + judge: + type: exact + - name: value-irrelevance + in: + nums: [1000, 1, 1000, 1, 500, 500] + quantity: [2, 2, 2] + out: true + judge: + type: exact + - name: five-capacities + in: + nums: [1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5] + quantity: [4, 3, 2, 1] + out: true + judge: + type: exact + - name: five-capacities-fail + in: + nums: [1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5] + quantity: [4, 4, 2, 2] + out: false + judge: + type: exact + - name: m-ten-success + in: + nums: [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10] + quantity: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2] + out: true + judge: + type: exact + - name: m-ten-fail + in: + nums: [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10] + quantity: [3, 3, 2, 2, 2, 2, 2, 2, 2, 2] + out: false + judge: + type: exact + - name: large-single-capacity + in: + nums: + gen: array + len: 100000 + of: + gen: int + min: 1 + max: 1 + elemType: int + quantity: [100000] + - name: large-balanced + in: + nums: + gen: array + len: 100000 + of: + gen: int + min: 1 + max: 10 + elemType: int + quantity: + [10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000] + - name: large-impossible-demand + in: + nums: + gen: array + len: 100000 + of: + gen: int + min: 1 + max: 50 + elemType: int + quantity: [100000] + - name: generated-small + in: + nums: + gen: array + len: 60 + of: + gen: int + min: 1 + max: 6 + elemType: int + quantity: + gen: array + len: 5 + of: + gen: int + min: 1 + max: 12 + elemType: int + - name: generated-medium + in: + nums: + gen: array + len: 1000 + of: + gen: int + min: 1 + max: 20 + elemType: int + quantity: + gen: array + len: 10 + of: + gen: int + min: 1 + max: 100 + elemType: int + - name: generated-large-skewed + in: + nums: + gen: array + len: 50000 + of: + gen: int + min: 1 + max: 2 + elemType: int + quantity: + gen: array + len: 8 + of: + gen: int + min: 1 + max: 5000 + elemType: int + - name: generated-large-many-values + in: + nums: + gen: array + len: 100000 + of: + gen: int + min: 1 + max: 50 + elemType: int + quantity: + gen: array + len: 10 + of: + gen: int + min: 1 + max: 10000 + elemType: int + - name: all-orders-one-value + in: + nums: [7, 7, 7, 7, 7, 7, 7] + quantity: [2, 2, 2] + out: true + judge: + type: exact + - name: one-order-uses-all + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8] + quantity: [8] + out: false + judge: + type: exact + - name: exact-largest-group + in: + nums: [1, 1, 1, 1, 1, 1, 2, 2, 3] + quantity: [6, 2] + out: true + judge: + type: exact diff --git a/tests/1501-2000/1655. distribute-repeating-integers/sol.cpp b/tests/1501-2000/1655. distribute-repeating-integers/sol.cpp new file mode 100644 index 00000000..61eb599b --- /dev/null +++ b/tests/1501-2000/1655. distribute-repeating-integers/sol.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + bool canDistribute(vector& nums, vector& quantity) { + sort(quantity.rbegin(), quantity.rend()); + unordered_map freqCounts, freqMap; + for (int n : nums) freqMap[n]++; + for (auto& [k, v] : freqMap) freqCounts[v]++; + + function backtrack = [&](int i) { + if (i == quantity.size()) return true; + for (auto& [freq, count] : freqCounts) { + if (freq >= quantity[i] && count > 0) { + freqCounts[freq]--; + int newFreq = freq - quantity[i]; + freqCounts[newFreq]++; + if (backtrack(i + 1)) return true; + freqCounts[freq]++; + freqCounts[newFreq]--; + if (freqCounts[newFreq] == 0) freqCounts.erase(newFreq); + } + } + return false; + }; + + return backtrack(0); + } +}; diff --git a/tests/1501-2000/1655. distribute-repeating-integers/sol.cs b/tests/1501-2000/1655. distribute-repeating-integers/sol.cs new file mode 100644 index 00000000..d5e543db --- /dev/null +++ b/tests/1501-2000/1655. distribute-repeating-integers/sol.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +public class Solution { + public bool CanDistribute(int[] nums, int[] quantity) { + Array.Sort(quantity); + Array.Reverse(quantity); + var freqCounts = new Dictionary(); + var freqMap = new Dictionary(); + foreach (var n in nums) { + if (freqMap.ContainsKey(n)) freqMap[n]++; + else freqMap[n] = 1; + } + foreach (var f in freqMap.Values) { + if (freqCounts.ContainsKey(f)) freqCounts[f]++; + else freqCounts[f] = 1; + } + + bool Backtrack(int i) { + if (i == quantity.Length) return true; + var keys = freqCounts.Keys.ToList(); + foreach (var freq in keys) { + int count = freqCounts[freq]; + if (freq >= quantity[i] && count > 0) { + freqCounts[freq] = count - 1; + int newFreq = freq - quantity[i]; + if (freqCounts.ContainsKey(newFreq)) freqCounts[newFreq]++; + else freqCounts[newFreq] = 1; + if (Backtrack(i + 1)) return true; + freqCounts[freq] = count; + int newCount = freqCounts[newFreq]; + if (newCount == 1) freqCounts.Remove(newFreq); + else freqCounts[newFreq] = newCount - 1; + } + } + return false; + } + + return Backtrack(0); + } +} diff --git a/tests/1501-2000/1655. distribute-repeating-integers/sol.dart b/tests/1501-2000/1655. distribute-repeating-integers/sol.dart new file mode 100644 index 00000000..5edd3ffa --- /dev/null +++ b/tests/1501-2000/1655. distribute-repeating-integers/sol.dart @@ -0,0 +1,36 @@ +class Solution { + bool canDistribute(List nums, List quantity) { + quantity.sort((a, b) => b.compareTo(a)); + Map freqCounts = {}; + Map freqMap = {}; + for (int n in nums) { + freqMap[n] = (freqMap[n] ?? 0) + 1; + } + freqMap.values.forEach((f) { + freqCounts[f] = (freqCounts[f] ?? 0) + 1; + }); + + bool backtrack(int i) { + if (i == quantity.length) return true; + for (int freq in freqCounts.keys.toList()) { + int count = freqCounts[freq]!; + if (freq >= quantity[i] && count > 0) { + freqCounts[freq] = count - 1; + int newFreq = freq - quantity[i]; + freqCounts[newFreq] = (freqCounts[newFreq] ?? 0) + 1; + if (backtrack(i + 1)) return true; + freqCounts[freq] = count; + int newCount = freqCounts[newFreq]!; + if (newCount == 1) { + freqCounts.remove(newFreq); + } else { + freqCounts[newFreq] = newCount - 1; + } + } + } + return false; + } + + return backtrack(0); + } +} diff --git a/tests/1501-2000/1655. distribute-repeating-integers/sol.go b/tests/1501-2000/1655. distribute-repeating-integers/sol.go new file mode 100644 index 00000000..5d93736a --- /dev/null +++ b/tests/1501-2000/1655. distribute-repeating-integers/sol.go @@ -0,0 +1,37 @@ +func canDistribute(nums []int, quantity []int) bool { + sort.Sort(sort.Reverse(sort.IntSlice(quantity))) + freqCounts := make(map[int]int) + freqMap := make(map[int]int) + for _, n := range nums { + freqMap[n]++ + } + for _, f := range freqMap { + freqCounts[f]++ + } + + var backtrack func(int) bool + backtrack = func(i int) bool { + if i == len(quantity) { + return true + } + for freq := range freqCounts { + count := freqCounts[freq] + if freq >= quantity[i] && count > 0 { + freqCounts[freq]-- + newFreq := freq - quantity[i] + freqCounts[newFreq]++ + if backtrack(i + 1) { + return true + } + freqCounts[freq]++ + freqCounts[newFreq]-- + if freqCounts[newFreq] == 0 { + delete(freqCounts, newFreq) + } + } + } + return false + } + + return backtrack(0) +} diff --git a/tests/1501-2000/1655. distribute-repeating-integers/sol.java b/tests/1501-2000/1655. distribute-repeating-integers/sol.java new file mode 100644 index 00000000..51d17778 --- /dev/null +++ b/tests/1501-2000/1655. distribute-repeating-integers/sol.java @@ -0,0 +1,35 @@ +import java.util.*; + +class Solution { + public boolean canDistribute(int[] nums, int[] quantity) { + Arrays.sort(quantity); + int[] reversed = new int[quantity.length]; + for (int i = 0; i < quantity.length; i++) reversed[i] = quantity[quantity.length - 1 - i]; + quantity = reversed; + + Map freqCounts = new HashMap<>(); + Map freqMap = new HashMap<>(); + for (int n : nums) freqMap.put(n, freqMap.getOrDefault(n, 0) + 1); + for (int f : freqMap.values()) freqCounts.put(f, freqCounts.getOrDefault(f, 0) + 1); + + return backtrack(0, freqCounts, quantity); + } + + private boolean backtrack(int i, Map freqCounts, int[] quantity) { + if (i == quantity.length) return true; + for (int freq : new ArrayList<>(freqCounts.keySet())) { + int count = freqCounts.get(freq); + if (freq >= quantity[i] && count > 0) { + freqCounts.put(freq, count - 1); + freqCounts.put(freq - quantity[i], freqCounts.getOrDefault(freq - quantity[i], 0) + 1); + if (backtrack(i + 1, freqCounts, quantity)) return true; + freqCounts.put(freq, count); + int newFreq = freq - quantity[i]; + int newCount = freqCounts.get(newFreq); + if (newCount == 1) freqCounts.remove(newFreq); + else freqCounts.put(newFreq, newCount - 1); + } + } + return false; + } +} diff --git a/tests/1501-2000/1655. distribute-repeating-integers/sol.kt b/tests/1501-2000/1655. distribute-repeating-integers/sol.kt new file mode 100644 index 00000000..47b8f445 --- /dev/null +++ b/tests/1501-2000/1655. distribute-repeating-integers/sol.kt @@ -0,0 +1,28 @@ +class Solution { + fun canDistribute(nums: IntArray, quantity: IntArray): Boolean { + quantity.sortDescending() + val freqCounts = mutableMapOf() + val freqMap = mutableMapOf() + for (n in nums) freqMap[n] = freqMap.getOrDefault(n, 0) + 1 + for (f in freqMap.values) freqCounts[f] = freqCounts.getOrDefault(f, 0) + 1 + + fun backtrack(i: Int): Boolean { + if (i == quantity.size) return true + for ((freq, count) in freqCounts.toList()) { + if (freq >= quantity[i] && count > 0) { + freqCounts[freq] = count - 1 + val newFreq = freq - quantity[i] + freqCounts[newFreq] = freqCounts.getOrDefault(newFreq, 0) + 1 + if (backtrack(i + 1)) return true + freqCounts[freq] = count + val newCount = freqCounts[newFreq]!! + if (newCount == 1) freqCounts.remove(newFreq) + else freqCounts[newFreq] = newCount - 1 + } + } + return false + } + + return backtrack(0) + } +} diff --git a/tests/1501-2000/1655. distribute-repeating-integers/sol.py b/tests/1501-2000/1655. distribute-repeating-integers/sol.py new file mode 100644 index 00000000..d5e938e7 --- /dev/null +++ b/tests/1501-2000/1655. distribute-repeating-integers/sol.py @@ -0,0 +1,24 @@ +from collections import Counter, defaultdict + + +class Solution: + def canDistribute(self, nums: List[int], quantity: List[int]) -> bool: + quantity.sort(reverse=True) + freqCounts = defaultdict(int, Counter(Counter(nums).values())) + + def backtrack(i: int = 0) -> bool: + if i == len(quantity): + return True + + for freq, count in list(freqCounts.items()): + if freq >= quantity[i] and count > 0: + freqCounts[freq] -= 1 + freqCounts[freq - quantity[i]] += 1 + if backtrack(i + 1): + return True + freqCounts[freq] += 1 + freqCounts[freq - quantity[i]] -= 1 + + return False + + return backtrack() diff --git a/tests/1501-2000/1655. distribute-repeating-integers/sol.py2 b/tests/1501-2000/1655. distribute-repeating-integers/sol.py2 new file mode 100644 index 00000000..a9942693 --- /dev/null +++ b/tests/1501-2000/1655. distribute-repeating-integers/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def canDistribute(self, nums, quantity): + """ + :type nums: List[int] + :type quantity: List[int] + :rtype: bool + """ + from collections import Counter, defaultdict + quantity.sort(reverse=True) + freqCounts = defaultdict(int, Counter(Counter(nums).values())) + def backtrack(i=0): + if i == len(quantity): + return True + for freq, count in list(freqCounts.items()): + if freq >= quantity[i] and count > 0: + freqCounts[freq] -= 1 + freqCounts[freq - quantity[i]] += 1 + if backtrack(i + 1): + return True + freqCounts[freq] += 1 + freqCounts[freq - quantity[i]] -= 1 + return False + return backtrack() diff --git a/tests/1501-2000/1655. distribute-repeating-integers/sol.rb b/tests/1501-2000/1655. distribute-repeating-integers/sol.rb new file mode 100644 index 00000000..14b86f2b --- /dev/null +++ b/tests/1501-2000/1655. distribute-repeating-integers/sol.rb @@ -0,0 +1,25 @@ +# @param {Integer[]} nums +# @param {Integer[]} quantity +# @return {Boolean} +def can_distribute(nums, quantity) + quantity.sort.reverse! + freq_counts = Hash.new(0) + nums.group_by(&:itself).transform_values(&:length).values.each { |f| freq_counts[f] += 1 } + + backtrack = lambda do |i| + return true if i == quantity.length + freq_counts.keys.each do |freq| + count = freq_counts[freq] + if freq >= quantity[i] && count > 0 + freq_counts[freq] -= 1 + freq_counts[freq - quantity[i]] += 1 + return true if backtrack.call(i + 1) + freq_counts[freq] += 1 + freq_counts[freq - quantity[i]] -= 1 + end + end + false + end + + backtrack.call(0) +end diff --git a/tests/1501-2000/1655. distribute-repeating-integers/sol.rs b/tests/1501-2000/1655. distribute-repeating-integers/sol.rs new file mode 100644 index 00000000..390ca294 --- /dev/null +++ b/tests/1501-2000/1655. distribute-repeating-integers/sol.rs @@ -0,0 +1,44 @@ +impl Solution { + pub fn can_distribute(nums: Vec, quantity: Vec) -> bool { + let mut quantity = quantity; + quantity.sort_by(|a, b| b.cmp(a)); + + use std::collections::HashMap; + let mut freq_counts: HashMap = HashMap::new(); + let mut freq_map: HashMap = HashMap::new(); + for n in nums { + *freq_map.entry(n).or_insert(0) += 1; + } + for f in freq_map.values() { + *freq_counts.entry(*f).or_insert(0) += 1; + } + + fn backtrack(i: usize, quantity: &Vec, freq_counts: &mut HashMap) -> bool { + if i == quantity.len() { + return true; + } + let keys: Vec = freq_counts.keys().cloned().collect(); + for freq in keys { + let count = *freq_counts.get(&freq).unwrap(); + if freq >= quantity[i] && count > 0 { + *freq_counts.get_mut(&freq).unwrap() -= 1; + let new_freq = freq - quantity[i]; + *freq_counts.entry(new_freq).or_insert(0) += 1; + if backtrack(i + 1, quantity, freq_counts) { + return true; + } + *freq_counts.get_mut(&freq).unwrap() += 1; + let new_count = *freq_counts.get(&new_freq).unwrap(); + if new_count == 1 { + freq_counts.remove(&new_freq); + } else { + *freq_counts.get_mut(&new_freq).unwrap() -= 1; + } + } + } + false + } + + backtrack(0, &quantity, &mut freq_counts) + } +} diff --git a/tests/1501-2000/1655. distribute-repeating-integers/sol.swift b/tests/1501-2000/1655. distribute-repeating-integers/sol.swift new file mode 100644 index 00000000..3d691976 --- /dev/null +++ b/tests/1501-2000/1655. distribute-repeating-integers/sol.swift @@ -0,0 +1,35 @@ +class Solution { + func canDistribute(_ nums: [Int], _ quantity: [Int]) -> Bool { + var quantity = quantity.sorted(by: >) + var freqCounts: [Int: Int] = [:] + var freqMap: [Int: Int] = [:] + for n in nums { + freqMap[n, default: 0] += 1 + } + for f in freqMap.values { + freqCounts[f, default: 0] += 1 + } + + func backtrack(_ i: Int) -> Bool { + if i == quantity.count { return true } + for (freq, count) in Array(freqCounts) { + if freq >= quantity[i] && count > 0 { + freqCounts[freq] = count - 1 + let newFreq = freq - quantity[i] + freqCounts[newFreq, default: 0] += 1 + if backtrack(i + 1) { return true } + freqCounts[freq] = count + let newCount = freqCounts[newFreq]! + if newCount == 1 { + freqCounts.removeValue(forKey: newFreq) + } else { + freqCounts[newFreq] = newCount - 1 + } + } + } + return false + } + + return backtrack(0) + } +} diff --git a/tests/1501-2000/1655. distribute-repeating-integers/sol.ts b/tests/1501-2000/1655. distribute-repeating-integers/sol.ts new file mode 100644 index 00000000..973a59bd --- /dev/null +++ b/tests/1501-2000/1655. distribute-repeating-integers/sol.ts @@ -0,0 +1,33 @@ +function canDistribute(nums: number[], quantity: number[]): boolean { + quantity.sort((a, b) => b - a); + const freqCounts = new Map(); + const freqMap = new Map(); + for (const n of nums) { + freqMap.set(n, (freqMap.get(n) || 0) + 1); + } + for (const f of freqMap.values()) { + freqCounts.set(f, (freqCounts.get(f) || 0) + 1); + } + + function backtrack(i: number): boolean { + if (i === quantity.length) return true; + for (const [freq, count] of Array.from(freqCounts.entries())) { + if (freq >= quantity[i] && count > 0) { + freqCounts.set(freq, count - 1); + const newFreq = freq - quantity[i]; + freqCounts.set(newFreq, (freqCounts.get(newFreq) || 0) + 1); + if (backtrack(i + 1)) return true; + freqCounts.set(freq, count); + const newCount = freqCounts.get(newFreq)!; + if (newCount === 1) { + freqCounts.delete(newFreq); + } else { + freqCounts.set(newFreq, newCount - 1); + } + } + } + return false; + } + + return backtrack(0); +} diff --git a/tests/1501-2000/1657. determine-if-two-strings-are-close/manifest.yaml b/tests/1501-2000/1657. determine-if-two-strings-are-close/manifest.yaml new file mode 100644 index 00000000..c3c7d1db --- /dev/null +++ b/tests/1501-2000/1657. determine-if-two-strings-are-close/manifest.yaml @@ -0,0 +1,272 @@ +entry: + id: 1657 + title: "determine-if-two-strings-are-close" + params: + word1: + type: string + word2: + type: string + call: + cpp: "Solution().closeStrings({word1}, {word2})" + rust: "Solution::close_strings({word1}, {word2})" + python3: "Solution().closeStrings({word1}, {word2})" + python2: "Solution().closeStrings({word1}, {word2})" + ruby: "close_strings({word1}, {word2})" + java: "new Solution().closeStrings({word1}, {word2})" + csharp: "new Solution().CloseStrings({word1}, {word2})" + kotlin: "Solution().closeStrings({word1}, {word2})" + go: "closeStrings({word1}, {word2})" + dart: "Solution().closeStrings({word1}, {word2})" + swift: "Solution().closeStrings({word1}, {word2})" + typescript: "closeStrings({word1}, {word2})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().closeStrings(word1, word2, {result})" + checker: | + class Checker: + def closeStrings(self, word1, word2, result): + if not isinstance(result, bool): + return False + if len(word1) != len(word2): + expected = False + else: + counts1 = {} + counts2 = {} + for ch in word1: + counts1[ch] = counts1.get(ch, 0) + 1 + for ch in word2: + counts2[ch] = counts2.get(ch, 0) + 1 + expected = set(counts1) == set(counts2) and sorted(counts1.values()) == sorted(counts2.values()) + return result == expected + +seed: 1657 + +tests: + - name: example-abc-bca + in: + word1: "abc" + word2: "bca" + out: true + - name: example-length-mismatch + in: + word1: "a" + word2: "aa" + out: false + - name: example-cabbba-abbccc + in: + word1: "cabbba" + word2: "abbccc" + out: true + - name: identical-single + in: + word1: "a" + word2: "a" + out: true + - name: different-single + in: + word1: "a" + word2: "b" + out: false + - name: identical-repeated + in: + word1: "aaaa" + word2: "aaaa" + out: true + - name: same-frequency-one-letter-set + in: + word1: "aaaaabbbb" + word2: "bbbbbbaaa" + out: false + - name: swapped-frequency-multiset + in: + word1: "aabbcc" + word2: "ccbbaa" + out: true + - name: operation-two + in: + word1: "aabccc" + word2: "ccbbaa" + out: false + - name: missing-character + in: + word1: "aabb" + word2: "aacc" + out: false + - name: same-length-but-frequency-mismatch + in: + word1: "aaabbc" + word2: "aabbbc" + out: true + - name: all-lowercase-alphabet + in: + word1: "abcdefghijklmnopqrstuvwxyz" + word2: "zyxwvutsrqponmlkjihgfedcba" + out: true + - name: alphabet-frequency-permutation + in: + word1: "aabbccddeeff" + word2: "ffeeddccbbaa" + out: true + - name: singleton-and-pair + in: + word1: "abb" + word2: "aab" + out: true + - name: three-frequency-pattern + in: + word1: "aaabbbbcc" + word2: "ccbbbbaaa" + out: true + - name: absent-character-with-same-length + in: + word1: "abca" + word2: "abcb" + out: true + - name: two-symbol-balanced + in: + word1: "abababab" + word2: "bbaabbaa" + out: true + - name: two-symbol-unbalanced + in: + word1: "aaaaabbb" + word2: "aaaabbbb" + out: false + - name: repeated-blocks + in: + word1: "aabbbaaccc" + word2: "cccaaabbaa" + out: false + - name: same-alphabet-different-counts + in: + word1: "aabbbcccc" + word2: "aaabbbbcc" + out: true + - name: five-symbol-permuted-counts + in: + word1: "aabbcccddddeeeee" + word2: "eeeeeddddcccbbaa" + out: true + - name: disjoint-alphabets + in: + word1: "abcabc" + word2: "defdef" + out: false + - name: one-symbol-length-mismatch + in: + word1: "zzzzzz" + word2: "zzzzz" + out: false + - name: all-letters-different-counts + in: + word1: "aabbbccccdddddeeeeee" + word2: "eeeeeecccccddddbbbaaa" + out: false + - name: same-counts-reordered + in: + word1: "abcdddeee" + word2: "eeedddcba" + out: true + - name: frequency-multiset-but-missing-symbol + in: + word1: "aabbccdd" + word2: "aabbccee" + out: false + - name: long-two-symbols + in: + word1: "aaaaaaaaaaabbbbbbbbbb" + word2: "bbbbbbbbbbbaaaaaaaaaa" + out: true + - name: long-two-symbols-mismatch + in: + word1: "aaaaaaaaaabbbbbbbbbb" + word2: "aaaaaaaaabbbbbbbbbbb" + out: false + - name: six-symbols + in: + word1: "aabbcccddddeeeeefffffff" + word2: "fffffffeeeeeddddcccbbaa" + out: true + - name: punctuation-not-allowed-but-lowercase-boundary + in: + word1: "mnopqq" + word2: "qqmnop" + out: true + - name: maximal-alphabet-unequal-support + in: + word1: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" + word2: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx" + out: false + - name: all-a-large-static + in: + word1: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + word2: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: true + - name: all-a-vs-b-large-static + in: + word1: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + word2: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + out: false + - name: generators-balanced-alphabet + in: + word1: + gen: "str" + len: 100000 + alphabet: "abcde" + word2: + gen: "str" + len: 100000 + alphabet: "abcde" + seed: 1 + - name: generators-binary + in: + word1: + gen: "str" + len: 100000 + alphabet: "ab" + word2: + gen: "str" + len: 100000 + alphabet: "ab" + seed: 2 + - name: generators-full-alphabet + in: + word1: + gen: "str" + len: 100000 + alphabet: "abcdefghijklmnopqrstuvwxyz" + word2: + gen: "str" + len: 100000 + alphabet: "abcdefghijklmnopqrstuvwxyz" + seed: 3 + - name: generators-short + in: + word1: + gen: "str" + len: 1 + alphabet: "xyz" + word2: + gen: "str" + len: 1 + alphabet: "xyz" + seed: 4 + - name: generators-medium + in: + word1: + gen: "str" + len: 4096 + alphabet: "abcdefgh" + word2: + gen: "str" + len: 4096 + alphabet: "abcdefgh" + seed: 5 diff --git a/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.cpp b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.cpp new file mode 100644 index 00000000..0ea8cb0f --- /dev/null +++ b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + bool closeStrings(string word1, string word2) { + if (word1.length() != word2.length()) { + return false; + } + set set1(word1.begin(), word1.end()); + set set2(word2.begin(), word2.end()); + if (set1 != set2) { + return false; + } + unordered_map dct; + for (char x : set1) { + int n1 = count(word1.begin(), word1.end(), x); + int n2 = count(word2.begin(), word2.end(), x); + dct[n1]++; + dct[n2]--; + } + for (auto& [k, v] : dct) { + if (v != 0) { + return false; + } + } + return true; + } +}; diff --git a/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.cs b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.cs new file mode 100644 index 00000000..2cee0efd --- /dev/null +++ b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public bool CloseStrings(string word1, string word2) { + if (word1.Length != word2.Length) return false; + HashSet set1 = new HashSet(word1); + HashSet set2 = new HashSet(word2); + if (!set1.SetEquals(set2)) return false; + Dictionary dct = new Dictionary(); + foreach (char x in set1) { + int n1 = word1.Count(c => c == x); + int n2 = word2.Count(c => c == x); + dct[n1] = dct.GetValueOrDefault(n1) + 1; + dct[n2] = dct.GetValueOrDefault(n2) - 1; + } + return dct.Values.All(v => v == 0); + } +} diff --git a/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.dart b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.dart new file mode 100644 index 00000000..6a61741f --- /dev/null +++ b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.dart @@ -0,0 +1,16 @@ +class Solution { + bool closeStrings(String word1, String word2) { + if (word1.length != word2.length) return false; + Set set1 = word1.split('').toSet(); + Set set2 = word2.split('').toSet(); + if (!set1.containsAll(set2) || !set2.containsAll(set1)) return false; + Map dct = {}; + set1.forEach((x) { + int n1 = word1.split('').where((c) => c == x).length; + int n2 = word2.split('').where((c) => c == x).length; + dct[n1] = (dct[n1] ?? 0) + 1; + dct[n2] = (dct[n2] ?? 0) - 1; + }); + return dct.values.every((v) => v == 0); + } +} diff --git a/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.go b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.go new file mode 100644 index 00000000..f03ec28f --- /dev/null +++ b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.go @@ -0,0 +1,44 @@ +func closeStrings(word1 string, word2 string) bool { + if len(word1) != len(word2) { + return false + } + set1 := map[rune]struct{}{} + set2 := map[rune]struct{}{} + for _, c := range word1 { + set1[c] = struct{}{} + } + for _, c := range word2 { + set2[c] = struct{}{} + } + if len(set1) != len(set2) { + return false + } + for k := range set1 { + if _, ok := set2[k]; !ok { + return false + } + } + dct := map[int]int{} + for x := range set1 { + n1 := countChar(word1, x) + n2 := countChar(word2, x) + dct[n1]++ + dct[n2]-- + } + for _, v := range dct { + if v != 0 { + return false + } + } + return true +} + +func countChar(s string, c rune) int { + count := 0 + for _, r := range s { + if r == c { + count++ + } + } + return count +} diff --git a/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.java b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.java new file mode 100644 index 00000000..fe20b69b --- /dev/null +++ b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.java @@ -0,0 +1,26 @@ +class Solution { + public boolean closeStrings(String word1, String word2) { + if (word1.length() != word2.length()) return false; + Set set1 = new HashSet<>(); + Set set2 = new HashSet<>(); + for (char c : word1.toCharArray()) set1.add(c); + for (char c : word2.toCharArray()) set2.add(c); + if (!set1.equals(set2)) return false; + Map dct = new HashMap<>(); + for (char x : set1) { + int n1 = countChar(word1, x); + int n2 = countChar(word2, x); + dct.put(n1, dct.getOrDefault(n1, 0) + 1); + dct.put(n2, dct.getOrDefault(n2, 0) - 1); + } + for (int v : dct.values()) { + if (v != 0) return false; + } + return true; + } + private int countChar(String s, char c) { + int cnt = 0; + for (char ch : s.toCharArray()) if (ch == c) cnt++; + return cnt; + } +} diff --git a/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.kt b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.kt new file mode 100644 index 00000000..abaf7bf2 --- /dev/null +++ b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun closeStrings(word1: String, word2: String): Boolean { + if (word1.length != word2.length) return false + val set1 = word1.toSet() + val set2 = word2.toSet() + if (set1 != set2) return false + val dct = mutableMapOf() + for (x in set1) { + val n1 = word1.count { it == x } + val n2 = word2.count { it == x } + dct[n1] = dct.getOrDefault(n1, 0) + 1 + dct[n2] = dct.getOrDefault(n2, 0) - 1 + } + return dct.values.all { it == 0 } + } +} diff --git a/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.py b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.py new file mode 100644 index 00000000..0bfaf8e3 --- /dev/null +++ b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.py @@ -0,0 +1,16 @@ +class Solution: + def closeStrings(self, word1: str, word2: str) -> bool: + if len(word1) != len(word2): + return False + set1, set2 = set(word1), set(word2) + if set1 != set2: + return False + dct = {} + for x in set1: + n1, n2 = word1.count(x), word2.count(x) + dct[n1] = dct.get(n1, 0) + 1 + dct[n2] = dct.get(n2, 0) - 1 + for x in dct.values(): + if x != 0: + return False + return True diff --git a/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.py2 b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.py2 new file mode 100644 index 00000000..f692c8e5 --- /dev/null +++ b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def closeStrings(self, word1, word2): + """ + :type word1: str + :type word2: str + :rtype: bool + """ + if len(word1) != len(word2): + return False + set1 = set(word1) + set2 = set(word2) + if set1 != set2: + return False + dct = {} + for x in set1: + n1 = word1.count(x) + n2 = word2.count(x) + dct[n1] = dct.get(n1, 0) + 1 + dct[n2] = dct.get(n2, 0) - 1 + for v in dct.values(): + if v != 0: + return False + return True diff --git a/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.rb b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.rb new file mode 100644 index 00000000..4f0e631b --- /dev/null +++ b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.rb @@ -0,0 +1,20 @@ +# @param {String} word1 +# @param {String} word2 +# @return {Boolean} +def close_strings(word1, word2) + return false if word1.length != word2.length + set1 = word1.chars.to_set + set2 = word2.chars.to_set + return false if set1 != set2 + dct = {} + set1.each do |x| + n1 = word1.count(x) + n2 = word2.count(x) + dct[n1] = dct.fetch(n1, 0) + 1 + dct[n2] = dct.fetch(n2, 0) - 1 + end + dct.each_value do |v| + return false if v != 0 + end + true +end diff --git a/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.rs b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.rs new file mode 100644 index 00000000..a4d5f797 --- /dev/null +++ b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn close_strings(word1: String, word2: String) -> bool { + if word1.len() != word2.len() { + return false; + } + let set1: std::collections::HashSet = word1.chars().collect(); + let set2: std::collections::HashSet = word2.chars().collect(); + if set1 != set2 { + return false; + } + let mut dct: std::collections::HashMap = std::collections::HashMap::new(); + for x in &set1 { + let n1 = word1.chars().filter(|c| c == x).count() as i32; + let n2 = word2.chars().filter(|c| c == x).count() as i32; + *dct.entry(n1).or_insert(0) += 1; + *dct.entry(n2).or_insert(0) -= 1; + } + dct.values().all(|&v| v == 0) + } +} diff --git a/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.swift b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.swift new file mode 100644 index 00000000..709534f2 --- /dev/null +++ b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func closeStrings(_ word1: String, _ word2: String) -> Bool { + if word1.count != word2.count { return false } + let set1 = Set(word1) + let set2 = Set(word2) + if set1 != set2 { return false } + var dct: [Int: Int] = [:] + for x in set1 { + let n1 = word1.filter { $0 == x }.count + let n2 = word2.filter { $0 == x }.count + dct[n1, default: 0] += 1 + dct[n2, default: 0] -= 1 + } + return dct.values.allSatisfy { $0 == 0 } + } +} diff --git a/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.ts b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.ts new file mode 100644 index 00000000..450933fc --- /dev/null +++ b/tests/1501-2000/1657. determine-if-two-strings-are-close/sol.ts @@ -0,0 +1,24 @@ +function closeStrings(word1: string, word2: string): boolean { + if (word1.length !== word2.length) return false; + const set1 = new Set(word1); + const set2 = new Set(word2); + if (set1.size !== set2.size) return false; + for (const c of set1) { + if (!set2.has(c)) return false; + } + const dct: Map = new Map(); + for (const x of set1) { + const n1 = countChar(word1, x); + const n2 = countChar(word2, x); + dct.set(n1, (dct.get(n1) ?? 0) + 1); + dct.set(n2, (dct.get(n2) ?? 0) - 1); + } + for (const v of dct.values()) { + if (v !== 0) return false; + } + return true; +} + +function countChar(s: string, c: string): number { + return s.split("").filter((ch) => ch === c).length; +} diff --git a/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/manifest.yaml b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/manifest.yaml new file mode 100644 index 00000000..7b3e9aa0 --- /dev/null +++ b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/manifest.yaml @@ -0,0 +1,281 @@ +entry: + id: 1658 + title: "minimum-operations-to-reduce-x-to-zero" + params: + nums: + type: array + items: + type: int + x: + type: int + call: + cpp: "Solution().minOperations({nums}, {x})" + rust: "Solution::min_operations({nums}, {x})" + python3: "Solution().minOperations({nums}, {x})" + python2: "Solution().minOperations({nums}, {x})" + ruby: "min_operations({nums}, {x})" + java: "new Solution().minOperations({nums}, {x})" + csharp: "new Solution().MinOperations({nums}, {x})" + kotlin: "Solution().minOperations({nums}, {x})" + go: "minOperations({nums}, {x})" + dart: "Solution().minOperations({nums}, {x})" + swift: "Solution().minOperations({nums}, {x})" + typescript: "minOperations({nums}, {x})" +judge: + type: "exact" +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().minOperations(nums, x, {result})" + checker: | + class Checker: + def minOperations(self, nums, x, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + target = sum(nums) - x + best = -1 + left = 0 + total = 0 + for right, value in enumerate(nums): + total += value + while left <= right and total > target: + total -= nums[left] + left += 1 + if total == target: + best = max(best, right - left + 1) + expected = len(nums) - best if best >= 0 else -1 + return result == expected +seed: 1658 +tests: + - name: example-one + in: + nums: [1, 1, 4, 2, 3] + x: 5 + out: 2 + - name: example-two-impossible + in: + nums: [5, 6, 7, 8, 9] + x: 4 + out: -1 + - name: example-three + in: + nums: [3, 2, 20, 1, 1, 3] + x: 10 + out: 5 + - name: remove-all + in: + nums: [1, 2, 3] + x: 6 + out: 3 + - name: remove-one-left + in: + nums: [7] + x: 7 + out: 1 + - name: impossible-single + in: + nums: [7] + x: 3 + out: -1 + - name: remove-one-right + in: + nums: [4, 5, 6] + x: 6 + out: 1 + - name: remove-one-middle-impossible + in: + nums: [4, 5, 6] + x: 5 + out: -1 + - name: whole-prefix + in: + nums: [2, 2, 2, 2] + x: 6 + out: 3 + - name: whole-suffix + in: + nums: [2, 2, 2, 2] + x: 4 + out: 2 + - name: duplicate-choice + in: + nums: [1, 1, 1, 1, 1] + x: 2 + out: 2 + - name: all-ones + in: + nums: [1, 1, 1, 1, 1, 1] + x: 5 + out: 5 + - name: large-values-exact + in: + nums: [10000, 10000, 10000] + x: 20000 + out: 2 + - name: large-values-impossible + in: + nums: [10000, 9999] + x: 1 + out: -1 + - name: alternating-small + in: + nums: [1, 100, 1, 100, 1] + x: 101 + out: 2 + - name: interior-kept-long + in: + nums: [5, 1, 1, 1, 1, 5] + x: 10 + out: 2 + - name: one-from-each-side + in: + nums: [8, 1, 1, 8] + x: 16 + out: 2 + - name: zero-target-not-allowed + in: + nums: [3, 4, 5] + x: 12 + out: 3 + - name: exact-prefix-two + in: + nums: [3, 4, 9, 2] + x: 7 + out: 2 + - name: exact-suffix-two + in: + nums: [9, 2, 3, 4] + x: 7 + out: 2 + - name: minimum-not-greedy + in: + nums: [1, 2, 3, 4, 5] + x: 6 + out: 2 + - name: no-contiguous-kept-sum + in: + nums: [2, 4, 6, 8] + x: 5 + out: -1 + - name: many-equal-options + in: + nums: [2, 2, 2, 2, 2, 2, 2] + x: 8 + out: 4 + - name: mixed-large + in: + nums: [10000, 1, 9999, 2, 9998, 3] + x: 10001 + out: 2 + - name: large-x-near-total + in: + nums: [9, 8, 7, 6, 5] + x: 34 + out: -1 + - name: x-over-total + in: + nums: [1, 2, 3] + x: 7 + out: -1 + - name: exact-total-with-large-prefix + in: + nums: [10000, 1, 1, 1, 1] + x: 10003 + out: 4 + - name: max-element-single + in: + nums: [10000] + x: 10000 + out: 1 + - name: max-length-pattern + in: + nums: [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] + x: 6 + out: 4 + - name: alternating-end-optimum + in: + nums: [10, 1, 1, 1, 10] + x: 20 + out: 2 + - name: gen-small-random + in: + nums: + gen: "array" + len: 25 + of: + gen: "int" + min: 1 + max: 20 + distinct: false + sorted: false + elemType: "int" + x: + gen: "int" + min: 1 + max: 500 + - name: gen-medium-values + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" + x: + gen: "int" + min: 1 + max: 10000000 + - name: gen-large-uniform + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" + x: + gen: "int" + min: 1 + max: 1000000000 + - name: gen-large-small-values + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 3 + distinct: false + sorted: false + elemType: "int" + x: + gen: "int" + min: 1 + max: 300000 + - name: gen-large-max-values + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 9998 + max: 10000 + distinct: false + sorted: false + elemType: "int" + x: + gen: "int" + min: 1 + max: 1000000000 diff --git a/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.cpp b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.cpp new file mode 100644 index 00000000..d0a00801 --- /dev/null +++ b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int minOperations(vector& nums, int x) { + int sub_sum = accumulate(nums.begin(), nums.end(), 0) - x; + int n = nums.size(); + int opes = n; + if (sub_sum == 0) return n; + int l = 0, r = 0, sld_sum = 0; + + while (r < n) { + if (sld_sum == sub_sum) { + opes = min(opes, n - (r - l)); + } + sld_sum += nums[r]; + while (l < r && sld_sum > sub_sum) { + sld_sum -= nums[l]; + l++; + } + r++; + } + + if (sld_sum == sub_sum) { + opes = min(opes, n - (r - l)); + } + + return opes == n ? -1 : opes; + } +}; diff --git a/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.cs b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.cs new file mode 100644 index 00000000..d56008ad --- /dev/null +++ b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.cs @@ -0,0 +1,27 @@ +public class Solution { + public int MinOperations(int[] nums, int x) { + int sub_sum = nums.Sum() - x; + int n = nums.Length; + int opes = n; + if (sub_sum == 0) return n; + int l = 0, r = 0, sld_sum = 0; + + while (r < n) { + if (sld_sum == sub_sum) { + opes = Math.Min(opes, n - (r - l)); + } + sld_sum += nums[r]; + while (l < r && sld_sum > sub_sum) { + sld_sum -= nums[l]; + l++; + } + r++; + } + + if (sld_sum == sub_sum) { + opes = Math.Min(opes, n - (r - l)); + } + + return opes == n ? -1 : opes; + } +} diff --git a/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.dart b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.dart new file mode 100644 index 00000000..1cce4e7c --- /dev/null +++ b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.dart @@ -0,0 +1,27 @@ +class Solution { + int minOperations(List nums, int x) { + int sub_sum = nums.reduce((a, b) => a + b) - x; + int n = nums.length; + int opes = n; + if (sub_sum == 0) return n; + int l = 0, r = 0, sld_sum = 0; + + while (r < n) { + if (sld_sum == sub_sum) { + opes = opes < n - (r - l) ? opes : n - (r - l); + } + sld_sum += nums[r]; + while (l < r && sld_sum > sub_sum) { + sld_sum -= nums[l]; + l++; + } + r++; + } + + if (sld_sum == sub_sum) { + opes = opes < n - (r - l) ? opes : n - (r - l); + } + + return opes == n ? -1 : opes; + } +} diff --git a/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.go b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.go new file mode 100644 index 00000000..a19f7e50 --- /dev/null +++ b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.go @@ -0,0 +1,38 @@ +func minOperations(nums []int, x int) int { + sub_sum := 0 + for _, num := range nums { + sub_sum += num + } + sub_sum -= x + n := len(nums) + opes := n + if sub_sum == 0 { + return n + } + l, r, sld_sum := 0, 0, 0 + + for r < n { + if sld_sum == sub_sum { + if n - (r - l) < opes { + opes = n - (r - l) + } + } + sld_sum += nums[r] + for l < r && sld_sum > sub_sum { + sld_sum -= nums[l] + l++ + } + r++ + } + + if sld_sum == sub_sum { + if n - (r - l) < opes { + opes = n - (r - l) + } + } + + if opes == n { + return -1 + } + return opes +} diff --git a/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.java b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.java new file mode 100644 index 00000000..b4cfe69c --- /dev/null +++ b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.java @@ -0,0 +1,29 @@ +class Solution { + public int minOperations(int[] nums, int x) { + int sub_sum = 0; + for (int num : nums) sub_sum += num; + sub_sum -= x; + int n = nums.length; + int opes = n; + if (sub_sum == 0) return n; + int l = 0, r = 0, sld_sum = 0; + + while (r < n) { + if (sld_sum == sub_sum) { + opes = Math.min(opes, n - (r - l)); + } + sld_sum += nums[r]; + while (l < r && sld_sum > sub_sum) { + sld_sum -= nums[l]; + l++; + } + r++; + } + + if (sld_sum == sub_sum) { + opes = Math.min(opes, n - (r - l)); + } + + return opes == n ? -1 : opes; + } +} diff --git a/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.kt b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.kt new file mode 100644 index 00000000..9564b569 --- /dev/null +++ b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.kt @@ -0,0 +1,29 @@ +class Solution { + fun minOperations(nums: IntArray, x: Int): Int { + var sub_sum = nums.sum() - x + val n = nums.size + var opes = n + if (sub_sum == 0) return n + var l = 0 + var r = 0 + var sld_sum = 0 + + while (r < n) { + if (sld_sum == sub_sum) { + opes = minOf(opes, n - (r - l)) + } + sld_sum += nums[r] + while (l < r && sld_sum > sub_sum) { + sld_sum -= nums[l] + l++ + } + r++ + } + + if (sld_sum == sub_sum) { + opes = minOf(opes, n - (r - l)) + } + + return if (opes == n) -1 else opes + } +} diff --git a/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.py b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.py new file mode 100644 index 00000000..e8e57ae1 --- /dev/null +++ b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.py @@ -0,0 +1,22 @@ +class Solution: + def minOperations(self, nums: List[int], x: int) -> int: + sub_sum = sum(nums) - x + n = len(nums) + opes = n + if sub_sum == 0: + return n + l, r, sld_sum = 0, 0, 0 + + while r < n: + if sld_sum == sub_sum: + opes = min(opes, n - (r - l)) + sld_sum += nums[r] + while l < r and sld_sum > sub_sum: + sld_sum -= nums[l] + l += 1 + r += 1 + + if sld_sum == sub_sum: + opes = min(opes, n - (r - l)) + + return -1 if opes == n else opes diff --git a/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.py2 b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.py2 new file mode 100644 index 00000000..67b028b5 --- /dev/null +++ b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.py2 @@ -0,0 +1,27 @@ +class Solution(object): + def minOperations(self, nums, x): + """ + :type nums: List[int] + :type x: int + :rtype: int + """ + sub_sum = sum(nums) - x + n = len(nums) + opes = n + if sub_sum == 0: + return n + l, r, sld_sum = 0, 0, 0 + + while r < n: + if sld_sum == sub_sum: + opes = min(opes, n - (r - l)) + sld_sum += nums[r] + while l < r and sld_sum > sub_sum: + sld_sum -= nums[l] + l += 1 + r += 1 + + if sld_sum == sub_sum: + opes = min(opes, n - (r - l)) + + return -1 if opes == n else opes diff --git a/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.rb b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.rb new file mode 100644 index 00000000..21634c4c --- /dev/null +++ b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.rb @@ -0,0 +1,24 @@ +# @param {Integer[]} nums +# @param {Integer} x +# @return {Integer} +def min_operations(nums, x) + sub_sum = nums.sum - x + n = nums.length + opes = n + return n if sub_sum == 0 + l, r, sld_sum = 0, 0, 0 + + while r < n + opes = [opes, n - (r - l)].min if sld_sum == sub_sum + sld_sum += nums[r] + while l < r && sld_sum > sub_sum + sld_sum -= nums[l] + l += 1 + end + r += 1 + end + + opes = [opes, n - (r - l)].min if sld_sum == sub_sum + + opes == n ? -1 : opes +end diff --git a/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.rs b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.rs new file mode 100644 index 00000000..99cf356f --- /dev/null +++ b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.rs @@ -0,0 +1,29 @@ +impl Solution { + pub fn min_operations(nums: Vec, x: i32) -> i32 { + let sub_sum: i32 = nums.iter().sum::() - x; + let n = nums.len(); + let mut opes = n as i32; + if sub_sum == 0 { + return n as i32; + } + let (mut l, mut r, mut sld_sum) = (0usize, 0usize, 0i32); + + while r < n { + if sld_sum == sub_sum { + opes = opes.min(n as i32 - (r - l) as i32); + } + sld_sum += nums[r]; + while l < r && sld_sum > sub_sum { + sld_sum -= nums[l]; + l += 1; + } + r += 1; + } + + if sld_sum == sub_sum { + opes = opes.min(n as i32 - (r - l) as i32); + } + + if opes == n as i32 { -1 } else { opes } + } +} diff --git a/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.swift b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.swift new file mode 100644 index 00000000..16ce820b --- /dev/null +++ b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.swift @@ -0,0 +1,27 @@ +class Solution { + func minOperations(_ nums: [Int], _ x: Int) -> Int { + var sub_sum = nums.reduce(0, +) - x + let n = nums.count + var opes = n + if sub_sum == 0 { return n } + var l = 0, r = 0, sld_sum = 0 + + while r < n { + if sld_sum == sub_sum { + opes = min(opes, n - (r - l)) + } + sld_sum += nums[r] + while l < r && sld_sum > sub_sum { + sld_sum -= nums[l] + l += 1 + } + r += 1 + } + + if sld_sum == sub_sum { + opes = min(opes, n - (r - l)) + } + + return opes == n ? -1 : opes + } +} diff --git a/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.ts b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.ts new file mode 100644 index 00000000..5cc68507 --- /dev/null +++ b/tests/1501-2000/1658. minimum-operations-to-reduce-x-to-zero/sol.ts @@ -0,0 +1,27 @@ +function minOperations(nums: number[], x: number): number { + let sub_sum = nums.reduce((a, b) => a + b, 0) - x; + const n = nums.length; + let opes = n; + if (sub_sum === 0) return n; + let l = 0, + r = 0, + sld_sum = 0; + + while (r < n) { + if (sld_sum === sub_sum) { + opes = Math.min(opes, n - (r - l)); + } + sld_sum += nums[r]; + while (l < r && sld_sum > sub_sum) { + sld_sum -= nums[l]; + l++; + } + r++; + } + + if (sld_sum === sub_sum) { + opes = Math.min(opes, n - (r - l)); + } + + return opes === n ? -1 : opes; +} diff --git a/tests/1501-2000/1659. maximize-grid-happiness/manifest.yaml b/tests/1501-2000/1659. maximize-grid-happiness/manifest.yaml new file mode 100644 index 00000000..69a8d005 --- /dev/null +++ b/tests/1501-2000/1659. maximize-grid-happiness/manifest.yaml @@ -0,0 +1,341 @@ +entry: + id: 1659 + title: maximize-grid-happiness + params: + m: + type: int + n: + type: int + introvertsCount: + type: int + extrovertsCount: + type: int + call: + cpp: "Solution().getMaxGridHappiness({m}, {n}, {introvertsCount}, {extrovertsCount})" + rust: "Solution::get_max_grid_happiness({m}, {n}, {introvertsCount}, {extrovertsCount})" + python3: "Solution().getMaxGridHappiness({m}, {n}, {introvertsCount}, {extrovertsCount})" + python2: "Solution().getMaxGridHappiness({m}, {n}, {introvertsCount}, {extrovertsCount})" + ruby: "get_max_grid_happiness({m}, {n}, {introvertsCount}, {extrovertsCount})" + java: "new Solution().getMaxGridHappiness({m}, {n}, {introvertsCount}, {extrovertsCount})" + csharp: "new Solution().GetMaxGridHappiness({m}, {n}, {introvertsCount}, {extrovertsCount})" + kotlin: "Solution().getMaxGridHappiness({m}, {n}, {introvertsCount}, {extrovertsCount})" + go: "getMaxGridHappiness({m}, {n}, {introvertsCount}, {extrovertsCount})" + dart: "Solution().getMaxGridHappiness({m}, {n}, {introvertsCount}, {extrovertsCount})" + swift: "Solution().getMaxGridHappiness({m}, {n}, {introvertsCount}, {extrovertsCount})" + typescript: "getMaxGridHappiness({m}, {n}, {introvertsCount}, {extrovertsCount})" + +judge: + type: exact + +limits: + time_ms: 5000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().check(m, n, introvertsCount, extrovertsCount, {result})" + checker: | + from functools import lru_cache + class Checker: + def check(self, m, n, introvertsCount, extrovertsCount, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if n > m: + m, n = n, m + rows = [] + for mask in range(3 ** n): + x = mask + row = [] + for _ in range(n): + row.append(x % 3) + x //= 3 + rows.append(tuple(row)) + def stats(row): + h = ii = ee = 0 + for i, v in enumerate(row): + if v == 1: + h += 120 + ii += 1 + if i and row[i - 1]: h -= 30 + if i + 1 < n and row[i + 1]: h -= 30 + elif v == 2: + h += 40 + ee += 1 + if i and row[i - 1]: h += 20 + if i + 1 < n and row[i + 1]: h += 20 + return h, ii, ee + st = {r: stats(r) for r in rows} + def between(a, b): + s = 0 + for u, v in zip(a, b): + if u and v: + s += -30 if u == 1 else 20 + s += -30 if v == 1 else 20 + return s + @lru_cache(None) + def dp(r, ic, ec, prev): + if r == m: + return 0 + best = 0 + for row in rows: + h, ii, ee = st[row] + if ii <= ic and ee <= ec: + best = max(best, h + between(prev, row) + dp(r + 1, ic - ii, ec - ee, row)) + return best + return result == dp(0, introvertsCount, extrovertsCount, (0,) * n) + +seed: 1659 + +tests: + - name: example-1 + in: + m: 2 + n: 3 + introvertsCount: 1 + extrovertsCount: 2 + - name: example-2 + in: + m: 3 + n: 1 + introvertsCount: 2 + extrovertsCount: 1 + - name: example-3 + in: + m: 2 + n: 2 + introvertsCount: 4 + extrovertsCount: 0 + - name: empty-grid-quotas + in: + m: 1 + n: 1 + introvertsCount: 0 + extrovertsCount: 0 + - name: one-introvert + in: + m: 1 + n: 1 + introvertsCount: 1 + extrovertsCount: 0 + - name: one-extrovert + in: + m: 1 + n: 1 + introvertsCount: 0 + extrovertsCount: 1 + - name: single-cell-both + in: + m: 1 + n: 1 + introvertsCount: 1 + extrovertsCount: 1 + - name: one-row-two-introverts + in: + m: 1 + n: 2 + introvertsCount: 2 + extrovertsCount: 0 + - name: one-row-two-extroverts + in: + m: 1 + n: 2 + introvertsCount: 0 + extrovertsCount: 2 + - name: one-row-mixed + in: + m: 1 + n: 3 + introvertsCount: 1 + extrovertsCount: 2 + - name: one-column-mixed + in: + m: 4 + n: 1 + introvertsCount: 2 + extrovertsCount: 2 + - name: square-2-empty + in: + m: 2 + n: 2 + introvertsCount: 0 + extrovertsCount: 0 + - name: square-2-intros + in: + m: 2 + n: 2 + introvertsCount: 2 + extrovertsCount: 0 + - name: square-2-extros + in: + m: 2 + n: 2 + introvertsCount: 0 + extrovertsCount: 2 + - name: square-2-balanced + in: + m: 2 + n: 2 + introvertsCount: 2 + extrovertsCount: 2 + - name: square-2-capacity + in: + m: 2 + n: 2 + introvertsCount: 4 + extrovertsCount: 4 + - name: rectangle-2x3-empty + in: + m: 2 + n: 3 + introvertsCount: 0 + extrovertsCount: 0 + - name: rectangle-2x3-intros + in: + m: 2 + n: 3 + introvertsCount: 3 + extrovertsCount: 0 + - name: rectangle-2x3-extros + in: + m: 2 + n: 3 + introvertsCount: 0 + extrovertsCount: 3 + - name: rectangle-2x3-balanced + in: + m: 2 + n: 3 + introvertsCount: 3 + extrovertsCount: 3 + - name: rectangle-2x4-intros + in: + m: 2 + n: 4 + introvertsCount: 4 + extrovertsCount: 0 + - name: rectangle-2x4-extros + in: + m: 2 + n: 4 + introvertsCount: 0 + extrovertsCount: 4 + - name: rectangle-2x4-mixed + in: + m: 2 + n: 4 + introvertsCount: 2 + extrovertsCount: 4 + - name: rectangle-3x3-sparse + in: + m: 3 + n: 3 + introvertsCount: 1 + extrovertsCount: 1 + - name: rectangle-3x3-intros + in: + m: 3 + n: 3 + introvertsCount: 6 + extrovertsCount: 0 + - name: rectangle-3x3-extros + in: + m: 3 + n: 3 + introvertsCount: 0 + extrovertsCount: 6 + - name: rectangle-3x3-balanced + in: + m: 3 + n: 3 + introvertsCount: 4 + extrovertsCount: 4 + - name: rectangle-3x4-mixed + in: + m: 3 + n: 4 + introvertsCount: 5 + extrovertsCount: 1 + - name: rectangle-3x4-reverse + in: + m: 3 + n: 4 + introvertsCount: 1 + extrovertsCount: 5 + - name: rectangle-4x3-balanced + in: + m: 4 + n: 3 + introvertsCount: 6 + extrovertsCount: 6 + - name: rectangle-4x4-sparse + in: + m: 4 + n: 4 + introvertsCount: 2 + extrovertsCount: 2 + - name: rectangle-4x4-balanced + in: + m: 4 + n: 4 + introvertsCount: 6 + extrovertsCount: 6 + - name: generated-5x1 + in: + m: 5 + n: 1 + introvertsCount: + gen: int + min: 0 + max: 5 + extrovertsCount: + gen: int + min: 0 + max: 5 + - name: generated-5x2 + in: + m: 5 + n: 2 + introvertsCount: + gen: int + min: 0 + max: 6 + extrovertsCount: + gen: int + min: 0 + max: 6 + - name: generated-5x3-intro + in: + m: 5 + n: 3 + introvertsCount: + gen: int + min: 0 + max: 6 + extrovertsCount: + gen: int + min: 0 + max: 6 + - name: generated-5x3-extro + in: + m: 5 + n: 3 + introvertsCount: + gen: int + min: 0 + max: 6 + extrovertsCount: + gen: int + min: 0 + max: 6 + - name: generated-5x4 + in: + m: 5 + n: 4 + introvertsCount: + gen: int + min: 0 + max: 6 + extrovertsCount: + gen: int + min: 0 + max: 6 diff --git a/tests/1501-2000/1659. maximize-grid-happiness/sol.cpp b/tests/1501-2000/1659. maximize-grid-happiness/sol.cpp new file mode 100644 index 00000000..faa31a7a --- /dev/null +++ b/tests/1501-2000/1659. maximize-grid-happiness/sol.cpp @@ -0,0 +1,2 @@ +#include +using namespace std; class Solution{public:int getMaxGridHappiness(int m,int n,int introvertsCount,int extrovertsCount){int I=introvertsCount,E=extrovertsCount;if(n>m)swap(n,m);int k=1;for(int i=0;ih(k),a(k),b(k);for(int x=0;x,int>M;functionf=[&](int r,int i,int e,int p){if(r==m)return 0;auto z=make_tuple(r,i,e,p);if(M.count(z))return M[z];int v=0;for(int c=0;cm){int t=m;m=n;n=t;}int k=1;for(int j=0;j0&&p>0)h[x]+=(d==1?-30:20)+(p==1?-30:20);p=d;}}var M=new Dictionary();int F(int r,int i,int e,int p){if(r==m)return 0;string z=$"{r},{i},{e},{p}";if(M.TryGetValue(z,out var v))return v;v=0;for(int c=0;c0&&d>0)s+=(u==1?-30:20)+(d==1?-30:20);}v=Math.Max(v,h[c]+s+F(r+1,i-a[c],e-b[c],c));}M[z]=v;return v;}return F(0,I,E,0);}} diff --git a/tests/1501-2000/1659. maximize-grid-happiness/sol.dart b/tests/1501-2000/1659. maximize-grid-happiness/sol.dart new file mode 100644 index 00000000..5ad97be3 --- /dev/null +++ b/tests/1501-2000/1659. maximize-grid-happiness/sol.dart @@ -0,0 +1 @@ +class Solution { int getMaxGridHappiness(int m,int n,int introvertsCount,int extrovertsCount){final I=introvertsCount,E=extrovertsCount;if(n>m){final t=m;m=n;n=t;}var p=1;for(var i=0;i.filled(p,0),ii=List.filled(p,0),ee=List.filled(p,0);for(var x=0;x0&&pr>0)h[x]+=(d==1?-30:20)+(pr==1?-30:20);pr=d;}}final mem={};int f(int r,int i,int e,int q){if(r==m)return 0;final key='$r,$i,$e,$q';if(mem.containsKey(key))return mem[key]!;var best=0;for(var c=0;c0&&d>0)s+=(u==1?-30:20)+(d==1?-30:20);}final v=h[c]+s+f(r+1,i-ii[c],e-ee[c],c);if(v>best)best=v;}mem[key]=best;return best;}return f(0,I,E,0);}} diff --git a/tests/1501-2000/1659. maximize-grid-happiness/sol.go b/tests/1501-2000/1659. maximize-grid-happiness/sol.go new file mode 100644 index 00000000..5364dee5 --- /dev/null +++ b/tests/1501-2000/1659. maximize-grid-happiness/sol.go @@ -0,0 +1 @@ +func getMaxGridHappiness(m int,n int,introvertsCount int,extrovertsCount int)int{I,E:=introvertsCount,extrovertsCount;if n>m{m,n=n,m};k:=1;for j:=0;j0&&p>0{if d==1{h[x]-=30}else{h[x]+=20};if p==1{h[x]-=30}else{h[x]+=20}};p=d}};mem:=map[[4]int]int{};var f func(int,int,int,int)int;f=func(r,i,e,p int)int{if r==m{return 0};q:=[4]int{r,i,e,p};if v,ok:=mem[q];ok{return v};z:=0;for c:=0;c0&&d>0{if u==1{s-=30}else{s+=20};if d==1{s-=30}else{s+=20}}};v:=h[c]+s+f(r+1,i-ii[c],e-ee[c],c);if v>z{z=v}}};mem[q]=z;return z};return f(0,I,E,0)} diff --git a/tests/1501-2000/1659. maximize-grid-happiness/sol.java b/tests/1501-2000/1659. maximize-grid-happiness/sol.java new file mode 100644 index 00000000..a92e0b9e --- /dev/null +++ b/tests/1501-2000/1659. maximize-grid-happiness/sol.java @@ -0,0 +1 @@ +class Solution{public int getMaxGridHappiness(int m,int n,int introvertsCount,int extrovertsCount){int I=introvertsCount,E=extrovertsCount;if(n>m){int t=m;m=n;n=t;}int k=1;for(int j=0;j0&&p>0)h[x]+=(d==1?-30:20)+(p==1?-30:20);p=d;}}MapM=new HashMap<>();return f(0,m,n,I,E,0,h,a,b,M,k);}int f(int r,int m,int n,int i,int e,int p,int[]h,int[]a,int[]b,MapM,int k){if(r==m)return 0;String z=r+","+i+","+e+","+p;if(M.containsKey(z))return M.get(z);int v=0;for(int c=0;c0&&d>0)s+=(u==1?-30:20)+(d==1?-30:20);}v=Math.max(v,h[c]+s+f(r+1,m,n,i-a[c],e-b[c],c,h,a,b,M,k));}M.put(z,v);return v;}} diff --git a/tests/1501-2000/1659. maximize-grid-happiness/sol.kt b/tests/1501-2000/1659. maximize-grid-happiness/sol.kt new file mode 100644 index 00000000..bf67fe10 --- /dev/null +++ b/tests/1501-2000/1659. maximize-grid-happiness/sol.kt @@ -0,0 +1 @@ +class Solution{fun getMaxGridHappiness(m:Int,n:Int,introvertsCount:Int,extrovertsCount:Int):Int{val I=introvertsCount;val E=extrovertsCount;var rows=m;var cols=n;if(cols>rows){val t=rows;rows=cols;cols=t};var k=1;repeat(cols){k*=3};val h=IntArray(k);val a=IntArray(k);val b=IntArray(k);for(x in 0 until k){var q=x;var p=0;repeat(cols){val d=q%3;q/=3;if(d==1){h[x]+=120;a[x]++}else if(d==2){h[x]+=40;b[x]++};if(d>0&&p>0)h[x]+=(if(d==1)-30 else 20)+(if(p==1)-30 else 20);p=d}};val M=HashMap();fun f(r:Int,i:Int,e:Int,p:Int):Int{if(r==rows)return 0;val z="$r,$i,$e,$p";M[z]?.let{return it};var v=0;for(c in 0 until k)if(a[c]<=i&&b[c]<=e){var x=p;var y=c;var s=0;repeat(cols){val u=x%3;val d=y%3;x/=3;y/=3;if(u>0&&d>0)s+=(if(u==1)-30 else 20)+(if(d==1)-30 else 20)};v=maxOf(v,h[c]+s+f(r+1,i-a[c],e-b[c],c))};M[z]=v;return v};return f(0,I,E,0)}} diff --git a/tests/1501-2000/1659. maximize-grid-happiness/sol.py b/tests/1501-2000/1659. maximize-grid-happiness/sol.py new file mode 100644 index 00000000..846f972f --- /dev/null +++ b/tests/1501-2000/1659. maximize-grid-happiness/sol.py @@ -0,0 +1,79 @@ +from functools import lru_cache + + +class Solution: + def getMaxGridHappiness( + self, m: int, n: int, introvertsCount: int, extrovertsCount: int + ) -> int: + # To optimize, ensure n is the smaller dimension + if n > m: + m, n = n, m + + # Precompute row-internal happiness and neighbor-external interactions + # 0: Empty, 1: Introvert, 2: Extrovert + + @lru_cache(None) + def get_row_stats(row_tuple): + # Returns (internal_happiness, intro_used, extro_used) + h = 0 + intro, extro = 0, 0 + for i in range(n): + if row_tuple[i] == 1: + h += 120 + intro += 1 + if i > 0 and row_tuple[i - 1] != 0: + h -= 30 + if i < n - 1 and row_tuple[i + 1] != 0: + h -= 30 + elif row_tuple[i] == 2: + h += 40 + extro += 1 + if i > 0 and row_tuple[i - 1] != 0: + h += 20 + if i < n - 1 and row_tuple[i + 1] != 0: + h += 20 + return h, intro, extro + + @lru_cache(None) + def get_inter_row_score(row_up, row_down): + # Interaction score between two adjacent rows + score = 0 + for i in range(n): + u, d = row_up[i], row_down[i] + if u == 0 or d == 0: + continue + # Adjustment for both cells based on their types + if u == 1: + score -= 30 + else: + score += 20 + if d == 1: + score -= 30 + else: + score += 20 + return score + + # All possible row configurations as tuples (3^n) + import itertools + + possible_rows = list(itertools.product([0, 1, 2], repeat=n)) + + @lru_cache(None) + def dp(row_idx, in_rem, ex_rem, prev_row): + if row_idx == m: + return 0 + + res = 0 + for curr_row in possible_rows: + h_internal, i_used, e_used = get_row_stats(curr_row) + if i_used <= in_rem and e_used <= ex_rem: + inter_score = get_inter_row_score(prev_row, curr_row) + total_gain = h_internal + inter_score + res = max( + res, + total_gain + + dp(row_idx + 1, in_rem - i_used, ex_rem - e_used, curr_row), + ) + return res + + return dp(0, introvertsCount, extrovertsCount, (0,) * n) diff --git a/tests/1501-2000/1659. maximize-grid-happiness/sol.py2 b/tests/1501-2000/1659. maximize-grid-happiness/sol.py2 new file mode 100644 index 00000000..c296cd15 --- /dev/null +++ b/tests/1501-2000/1659. maximize-grid-happiness/sol.py2 @@ -0,0 +1,28 @@ +class Solution(object): + def getMaxGridHappiness(self,m,n,introvertsCount,extrovertsCount): + I,E=introvertsCount,extrovertsCount + if n>m:m,n=n,m + rows=range(3**n); st=[] + for x in rows: + a=x;h=ii=ee=prev=0 + for j in range(n): + d=a%3;a//=3 + if d==1:h+=120;ii+=1 + elif d==2:h+=40;ee+=1 + if d and prev:h+=(-30 if d==1 else 20)+(-30 if prev==1 else 20) + prev=d + st.append((h,ii,ee)) + def inter(a,b): + s=0 + for _ in range(n): + u=a%3;d=b%3;a//=3;b//=3 + if u and d:s+=(-30 if u==1 else 20)+(-30 if d==1 else 20) + return s + memo={} + def f(r,i,e,p): + if r==m:return 0 + key=(r,i,e,p) + if key not in memo: + memo[key]=max(st[c][0]+inter(p,c)+f(r+1,i-st[c][1],e-st[c][2],c) for c in rows if st[c][1]<=i and st[c][2]<=e) + return memo[key] + return f(0,I,E,0) diff --git a/tests/1501-2000/1659. maximize-grid-happiness/sol.rb b/tests/1501-2000/1659. maximize-grid-happiness/sol.rb new file mode 100644 index 00000000..339fc790 --- /dev/null +++ b/tests/1501-2000/1659. maximize-grid-happiness/sol.rb @@ -0,0 +1,6 @@ +def get_max_grid_happiness(m,n,introverts_count,extroverts_count) + i,e=introverts_count,extroverts_count + m,n=n,m if n>m; k=3**n; st=[] + k.times{|x|a=x;h=ii=ee=prev=0;n.times{|j|d=a%3;a/=3;if d==1;h+=120;ii+=1;elsif d==2;h+=40;ee+=1;end;h+=(d==1 ? -30:20)+(prev==1 ? -30:20) if d>0&&prev>0;prev=d};st<<[h,ii,ee]} + mem={}; f=->(r,ii,ee,p){return 0 if r==m;key=[r,ii,ee,p];return mem[key] if mem[key];mem[key]=(0...k).select{|c|st[c][1]<=ii&&st[c][2]<=ee}.map{|c|a=p;b=c;s=0;n.times{u=a%3;d=b%3;a/=3;b/=3;s+=(u==1 ? -30:20)+(d==1 ? -30:20) if u>0&&d>0};st[c][0]+s+f.call(r+1,ii-st[c][1],ee-st[c][2],c)}.max};f.call(0,i,e,0) +end diff --git a/tests/1501-2000/1659. maximize-grid-happiness/sol.rs b/tests/1501-2000/1659. maximize-grid-happiness/sol.rs new file mode 100644 index 00000000..57c666b0 --- /dev/null +++ b/tests/1501-2000/1659. maximize-grid-happiness/sol.rs @@ -0,0 +1 @@ +impl Solution{pub fn get_max_grid_happiness(mut m:i32,mut n:i32,introverts_count:i32,extroverts_count:i32)->i32{let ic=introverts_count;let ec=extroverts_count;if n>m{std::mem::swap(&mut m,&mut n)};let k=3usize.pow(n as u32);let mut h=vec![0;k];let mut a=vec![0;k];let mut b=vec![0;k];for x in 0..k{let(mut q,mut p)=(x,0);for _ in 0..n{let d=q%3;q/=3;if d==1{h[x]+=120;a[x]+=1}else if d==2{h[x]+=40;b[x]+=1}if d>0&&p>0{h[x]+=if d==1{-30}else{20};h[x]+=if p==1{-30}else{20}};p=d}}fn f(r:i32,m:i32,n:i32,i:i32,e:i32,p:usize,h:&Vec,a:&Vec,b:&Vec,z:&mut HashMap<(i32,i32,i32,usize),i32>)->i32{if r==m{return 0}if let Some(v)=z.get(&(r,i,e,p)){return *v}let mut best=0;for c in 0..h.len(){if a[c]<=i&&b[c]<=e{let(mut x,mut y,mut s)=(p,c,0);for _ in 0..n{let u=x%3;let d=y%3;x/=3;y/=3;if u>0&&d>0{s+=if u==1{-30}else{20};s+=if d==1{-30}else{20}}}best=best.max(h[c]+s+f(r+1,m,n,i-a[c],e-b[c],c,h,a,b,z));}}z.insert((r,i,e,p),best);best}f(0,m,n,ic,ec,0,&h,&a,&b,&mut HashMap::new())}} diff --git a/tests/1501-2000/1659. maximize-grid-happiness/sol.swift b/tests/1501-2000/1659. maximize-grid-happiness/sol.swift new file mode 100644 index 00000000..6628232a --- /dev/null +++ b/tests/1501-2000/1659. maximize-grid-happiness/sol.swift @@ -0,0 +1 @@ +class Solution{func getMaxGridHappiness(_ m:Int,_ n:Int,_ introvertsCount:Int,_ extrovertsCount:Int)->Int{let I=introvertsCount,E=extrovertsCount;var rows=m,cols=n;if cols>rows{swap(&rows,&cols)};var k=1;for _ in 0..0&&p>0{h[x]+=(d==1 ? -30:20)+(p==1 ? -30:20)};p=d}};var M=[String:Int]();func f(_ r:Int,_ i:Int,_ e:Int,_ p:Int)->Int{if r==rows{return 0};let z="\(r),\(i),\(e),\(p)";if let v=M[z]{return v};var v=0;for c in 0..0&&d>0{s+=(u==1 ? -30:20)+(d==1 ? -30:20)}};v=max(v,h[c]+s+f(r+1,i-a[c],e-b[c],c))};M[z]=v;return v};return f(0,I,E,0)}} diff --git a/tests/1501-2000/1659. maximize-grid-happiness/sol.ts b/tests/1501-2000/1659. maximize-grid-happiness/sol.ts new file mode 100644 index 00000000..a61d23aa --- /dev/null +++ b/tests/1501-2000/1659. maximize-grid-happiness/sol.ts @@ -0,0 +1,55 @@ +function getMaxGridHappiness( + m: number, + n: number, + introvertsCount: number, + extrovertsCount: number, +): number { + const I = introvertsCount, + E = extrovertsCount; + if (n > m) [m, n] = [n, m]; + const k = 3 ** n, + h = Array(k).fill(0), + ii = Array(k).fill(0), + ee = Array(k).fill(0); + for (let x = 0; x < k; x++) { + let a = x, + p = 0; + for (let j = 0; j < n; j++) { + const d = a % 3; + a = Math.floor(a / 3); + if (d === 1) { + h[x] += 120; + ii[x]++; + } else if (d === 2) { + h[x] += 40; + ee[x]++; + } + if (d && p) h[x] += (d === 1 ? -30 : 20) + (p === 1 ? -30 : 20); + p = d; + } + } + const mem = new Map(); + function f(r: number, i: number, e: number, p: number): number { + if (r === m) return 0; + const key = `${r},${i},${e},${p}`; + if (mem.has(key)) return mem.get(key)!; + let best = 0; + for (let c = 0; c < k; c++) + if (ii[c] <= i && ee[c] <= e) { + let a = p, + b = c, + s = 0; + for (let j = 0; j < n; j++) { + const u = a % 3, + d = b % 3; + a = Math.floor(a / 3); + b = Math.floor(b / 3); + if (u && d) s += (u === 1 ? -30 : 20) + (d === 1 ? -30 : 20); + } + best = Math.max(best, h[c] + s + f(r + 1, i - ii[c], e - ee[c], c)); + } + mem.set(key, best); + return best; + } + return f(0, I, E, 0); +} diff --git a/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/manifest.yaml b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/manifest.yaml new file mode 100644 index 00000000..4539860b --- /dev/null +++ b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/manifest.yaml @@ -0,0 +1,368 @@ +entry: + id: 1662 + title: "check-if-two-string-arrays-are-equivalent" + params: + word1: + type: array + items: + type: string + word2: + type: array + items: + type: string + call: + cpp: "Solution().arrayStringsAreEqual({word1}, {word2})" + rust: "Solution::array_strings_are_equal({word1}, {word2})" + python3: "Solution().arrayStringsAreEqual({word1}, {word2})" + python2: "Solution().arrayStringsAreEqual({word1}, {word2})" + ruby: "array_strings_are_equal({word1}, {word2})" + java: "new Solution().arrayStringsAreEqual({word1}, {word2})" + csharp: "new Solution().ArrayStringsAreEqual({word1}, {word2})" + kotlin: "Solution().arrayStringsAreEqual({word1}, {word2})" + go: "arrayStringsAreEqual({word1}, {word2})" + dart: "Solution().arrayStringsAreEqual({word1}, {word2})" + swift: "Solution().arrayStringsAreEqual({word1}, {word2})" + typescript: "arrayStringsAreEqual({word1}, {word2})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(word1, word2, {result})" + checker: | + class Checker: + def check(self, word1, word2, result): + return isinstance(result, bool) and result == (''.join(word1) == ''.join(word2)) + +seed: 1662 + +tests: + - name: example-split + in: + word1: ["ab", "c"] + word2: ["a", "bc"] + out: true + - name: example-mismatch + in: + word1: ["a", "cb"] + word2: ["ab", "c"] + out: false + - name: example-single-joined + in: + word1: ["abc", "d", "defg"] + word2: ["abcddefg"] + out: true + - name: one-character-equal + in: + word1: ["a"] + word2: ["a"] + out: true + - name: one-character-different + in: + word1: ["a"] + word2: ["b"] + out: false + - name: two-character-split + in: + word1: ["a", "b"] + word2: ["ab"] + out: true + - name: reversed-order + in: + word1: ["ab", "c"] + word2: ["c", "ab"] + out: false + - name: repeated-letters + in: + word1: ["aa", "a"] + word2: ["a", "aa"] + out: true + - name: different-length-total + in: + word1: ["abc"] + word2: ["ab"] + out: false + - name: same-boundary-empty-not-allowed + in: + word1: ["hello"] + word2: ["he", "llo"] + out: true + - name: many-singletons + in: + word1: ["t", "e", "s", "t"] + word2: ["test"] + out: true + - name: many-singletons-mismatch + in: + word1: ["t", "e", "s", "t"] + word2: ["t", "e", "s", "x"] + out: false + - name: lowercase-extremes + in: + word1: ["a", "z", "az"] + word2: ["azaz"] + out: true + - name: internal-character-mismatch + in: + word1: ["abc", "def"] + word2: ["abx", "def"] + out: false + - name: boundary-character-mismatch + in: + word1: ["abc", "def"] + word2: ["abc", "deg"] + out: false + - name: different-segment-count + in: + word1: ["one", "two", "three"] + word2: ["o", "n", "etwothree"] + out: true + - name: alternating-segments + in: + word1: ["x", "yy", "zzz", "w"] + word2: ["xy", "yz", "zzw"] + out: true + - name: alternating-mismatch + in: + word1: ["x", "yy", "zzz", "w"] + word2: ["xy", "yz", "zzy"] + out: false + - name: long-single-segment + in: + word1: ["abcdefghijklmnopqrstuvwxyz"] + word2: ["abcdefghijklmnopqrstuvwxyz"] + out: true + - name: long-single-segment-mismatch + in: + word1: ["abcdefghijklmnopqrstuvwxyz"] + word2: ["abcdefghijklmnopqrstuvwxya"] + out: false + - name: nine-segment-equal + in: + word1: ["a", "bb", "ccc", "d", "ee", "fff", "g", "hh", "iii"] + word2: ["abbcccdeefffghhiii"] + out: true + - name: nine-segment-mismatch + in: + word1: ["a", "bb", "ccc", "d", "ee", "fff", "g", "hh", "iii"] + word2: ["abbcccdeefffghhiiix"] + out: false + - name: duplicate-segments + in: + word1: ["abc", "abc", "abc"] + word2: ["abcabc", "abc"] + out: true + - name: duplicate-order-mismatch + in: + word1: ["abc", "def", "abc"] + word2: ["abc", "abc", "def"] + out: false + - name: all-z + in: + word1: ["z", "zz", "zzz"] + word2: ["zzzzzz"] + out: true + - name: all-a-off-by-one + in: + word1: ["a", "aa", "aaa"] + word2: ["aaaaaa", "a"] + out: false + - name: prefix-only + in: + word1: ["prefix"] + word2: ["pre", "fix"] + out: true + - name: suffix-only-mismatch + in: + word1: ["prefix"] + word2: ["pre", "fi"] + out: false + - name: ten-segment-word + in: + word1: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] + word2: ["abcdefghij"] + out: true + - name: ten-segment-reordered + in: + word1: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] + word2: ["abcdefghji"] + out: false + - name: large-segments-different-layout + in: + word1: + [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + ] + word2: + [ + "ababababababababababababababababababababababababababababababababababababababababababababababababab", + ] + out: false + - name: large-long-mismatch + in: + word1: + [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + ] + word2: + [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "abbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + ] + out: false + - name: max-segment-count + in: + word1: + [ + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + ] + word2: ["aaaaaaaaaaaaaaaaaaaa"] + out: true + - name: max-segment-count-mismatch + in: + word1: + [ + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + "a", + ] + word2: ["aaaaaaaaaaaaaaaaaaab"] + out: false + - name: mixed-lowercase + in: + word1: ["leetcode", "is", "great"] + word2: ["leet", "codeis", "great"] + out: true + - name: mixed-lowercase-mismatch + in: + word1: ["leetcode", "is", "great"] + word2: ["leet", "codes", "great"] + out: false + - name: generated-max-single-segments-a + in: + word1: + gen: "array" + len: 1 + of: + gen: "str" + len: 1000 + alphabet: "abc" + word2: + gen: "array" + len: 1 + of: + gen: "str" + len: 1000 + alphabet: "abc" + seed: 166201 + - name: generated-max-single-segments-b + in: + word1: + gen: "array" + len: 1 + of: + gen: "str" + len: 1000 + alphabet: "xyz" + word2: + gen: "array" + len: 1 + of: + gen: "str" + len: 1000 + alphabet: "xyz" + seed: 166202 + - name: generated-max-single-segments-c + in: + word1: + gen: "array" + len: 1 + of: + gen: "str" + len: 1000 + alphabet: "az" + word2: + gen: "array" + len: 1 + of: + gen: "str" + len: 1000 + alphabet: "az" + seed: 166203 + - name: generated-max-single-segments-d + in: + word1: + gen: "array" + len: 1 + of: + gen: "str" + len: 1000 + alphabet: "mnop" + word2: + gen: "array" + len: 1 + of: + gen: "str" + len: 1000 + alphabet: "mnop" + seed: 166204 + - name: generated-max-single-segments-e + in: + word1: + gen: "array" + len: 1 + of: + gen: "str" + len: 1000 + alphabet: "aby" + word2: + gen: "array" + len: 1 + of: + gen: "str" + len: 1000 + alphabet: "aby" + seed: 166205 diff --git a/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.cpp b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.cpp new file mode 100644 index 00000000..f952ac4c --- /dev/null +++ b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + bool arrayStringsAreEqual(vector& word1, vector& word2) { + string s1 = ""; + for (const string& w : word1) { + s1 += w; + } + string s2 = ""; + for (const string& w : word2) { + s2 += w; + } + return s1 == s2; + } +}; diff --git a/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.cs b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.cs new file mode 100644 index 00000000..fb1192bc --- /dev/null +++ b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.cs @@ -0,0 +1,7 @@ +public class Solution { + public bool ArrayStringsAreEqual(string[] word1, string[] word2) { + string s1 = string.Concat(word1); + string s2 = string.Concat(word2); + return s1 == s2; + } +} diff --git a/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.dart b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.dart new file mode 100644 index 00000000..982d23dd --- /dev/null +++ b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.dart @@ -0,0 +1,7 @@ +class Solution { + bool arrayStringsAreEqual(List word1, List word2) { + String s1 = word1.join(); + String s2 = word2.join(); + return s1 == s2; + } +} diff --git a/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.go b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.go new file mode 100644 index 00000000..50ce5123 --- /dev/null +++ b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.go @@ -0,0 +1,11 @@ +func arrayStringsAreEqual(word1 []string, word2 []string) bool { + s1 := "" + for _, w := range word1 { + s1 += w + } + s2 := "" + for _, w := range word2 { + s2 += w + } + return s1 == s2 +} diff --git a/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.java b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.java new file mode 100644 index 00000000..b1cab456 --- /dev/null +++ b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.java @@ -0,0 +1,7 @@ +class Solution { + public boolean arrayStringsAreEqual(String[] word1, String[] word2) { + String s1 = String.join("", word1); + String s2 = String.join("", word2); + return s1.equals(s2); + } +} diff --git a/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.kt b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.kt new file mode 100644 index 00000000..3005c2b3 --- /dev/null +++ b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.kt @@ -0,0 +1,7 @@ +class Solution { + fun arrayStringsAreEqual(word1: Array, word2: Array): Boolean { + val s1 = word1.joinToString("") + val s2 = word2.joinToString("") + return s1 == s2 + } +} diff --git a/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.py b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.py new file mode 100644 index 00000000..5b00dc9e --- /dev/null +++ b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.py @@ -0,0 +1,9 @@ +from typing import List + + +class Solution: + def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: + s1 = "".join(word1) + s2 = "".join(word2) + + return s1 == s2 diff --git a/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.py2 b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.py2 new file mode 100644 index 00000000..f112f653 --- /dev/null +++ b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.py2 @@ -0,0 +1,10 @@ +class Solution(object): + def arrayStringsAreEqual(self, word1, word2): + """ + :type word1: List[str] + :type word2: List[str] + :rtype: bool + """ + s1 = ''.join(word1) + s2 = ''.join(word2) + return s1 == s2 diff --git a/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.rb b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.rb new file mode 100644 index 00000000..a460cc97 --- /dev/null +++ b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.rb @@ -0,0 +1,8 @@ +# @param {String[]} word1 +# @param {String[]} word2 +# @return {Boolean} +def array_strings_are_equal(word1, word2) + s1 = word1.join + s2 = word2.join + s1 == s2 +end diff --git a/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.rs b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.rs new file mode 100644 index 00000000..ee2578ec --- /dev/null +++ b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.rs @@ -0,0 +1,7 @@ +impl Solution { + pub fn array_strings_are_equal(word1: Vec, word2: Vec) -> bool { + let s1: String = word1.concat(); + let s2: String = word2.concat(); + s1 == s2 + } +} diff --git a/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.swift b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.swift new file mode 100644 index 00000000..6ca139b3 --- /dev/null +++ b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.swift @@ -0,0 +1,7 @@ +class Solution { + func arrayStringsAreEqual(_ word1: [String], _ word2: [String]) -> Bool { + let s1 = word1.joined() + let s2 = word2.joined() + return s1 == s2 + } +} diff --git a/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.ts b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.ts new file mode 100644 index 00000000..20dc0f10 --- /dev/null +++ b/tests/1501-2000/1662. check-if-two-string-arrays-are-equivalent/sol.ts @@ -0,0 +1,5 @@ +function arrayStringsAreEqual(word1: string[], word2: string[]): boolean { + const s1 = word1.join(""); + const s2 = word2.join(""); + return s1 === s2; +} diff --git a/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/manifest.yaml b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/manifest.yaml new file mode 100644 index 00000000..9b8fb3f1 --- /dev/null +++ b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/manifest.yaml @@ -0,0 +1,222 @@ +entry: + id: 1663 + title: "smallest-string-with-a-given-numeric-value" + params: + n: + type: int + k: + type: int + call: + cpp: "Solution().getSmallestString({n}, {k})" + rust: "Solution::get_smallest_string({n}, {k})" + python3: "Solution().getSmallestString({n}, {k})" + python2: "Solution().getSmallestString({n}, {k})" + ruby: "get_smallest_string({n}, {k})" + java: "new Solution().getSmallestString({n}, {k})" + csharp: "new Solution().GetSmallestString({n}, {k})" + kotlin: "Solution().getSmallestString({n}, {k})" + go: "getSmallestString({n}, {k})" + dart: "Solution().getSmallestString({n}, {k})" + swift: "Solution().getSmallestString({n}, {k})" + typescript: "getSmallestString({n}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().getSmallestString(n, k, {result})" + checker: | + class Checker: + def getSmallestString(self, n, k, result): + if not isinstance(result, str) or len(result) != n: + return False + if any(ch < 'a' or ch > 'z' for ch in result): + return False + extra = k - n + expected = ['a'] * n + i = n - 1 + while extra: + add = min(25, extra) + expected[i] = chr(ord('a') + add) + extra -= add + i -= 1 + return result == ''.join(expected) + +seed: 1663 + +tests: + - name: example-one + in: + n: 3 + k: 27 + out: "aay" + - name: example-two + in: + n: 5 + k: 73 + out: "aaszz" + - name: minimum-single + in: + n: 1 + k: 1 + out: "a" + - name: maximum-single + in: + n: 1 + k: 26 + out: "z" + - name: two-minimum + in: + n: 2 + k: 2 + out: "aa" + - name: two-maximum + in: + n: 2 + k: 52 + out: "zz" + - name: two-middle + in: + n: 2 + k: 27 + out: "az" + - name: three-low-extra + in: + n: 3 + k: 4 + out: "aab" + - name: three-middle + in: + n: 3 + k: 39 + out: "alz" + - name: three-maximum + in: + n: 3 + k: 78 + out: "zzz" + - name: four-one-extra + in: + n: 4 + k: 5 + out: "aaab" + - name: four-exact-boundary + in: + n: 4 + k: 29 + out: "aaaz" + - name: four-over-boundary + in: + n: 4 + k: 30 + out: "aabz" + - name: five-low + in: + n: 5 + k: 10 + out: "aaaaf" + - name: five-balanced + in: + n: 5 + k: 50 + out: "aaauz" + - name: five-maximum + in: + n: 5 + k: 130 + out: "zzzzz" + - name: six-one-z + in: + n: 6 + k: 31 + out: "aaaaaz" + - name: six-two-z + in: + n: 6 + k: 56 + out: "aaaazz" + - name: six-remainder + in: + n: 6 + k: 57 + out: "aaabzz" + - name: ten-minimum + in: + n: 10 + k: 10 + out: "aaaaaaaaaa" + - name: ten-near-minimum + in: + n: 10 + k: 11 + out: "aaaaaaaaab" + - name: ten-middle + in: + n: 10 + k: 100 + out: "aaaaaapzzz" + - name: ten-near-maximum + in: + n: 10 + k: 250 + out: "pzzzzzzzzz" + - name: ten-maximum + in: + n: 10 + k: 260 + out: "zzzzzzzzzz" + - name: seven-split + in: + n: 7 + k: 100 + out: "aaaszzz" + - name: eight-split + in: + n: 8 + k: 101 + out: "aaaaszzz" + - name: twenty-five-middle + in: + n: 25 + k: 100 + out: "aaaaaaaaaaaaaaaaaaaaaazzz" + - name: twenty-five-high + in: + n: 25 + k: 500 + out: "aaaaaazzzzzzzzzzzzzzzzzzz" + - name: fifty-low + in: + n: 50 + k: 51 + out: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" + - name: fifty-middle + in: + n: 50 + k: 650 + - name: hundred-minimum + in: + n: 100 + k: 100 + out: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + - name: hundred-one-extra + in: + n: 100 + k: 101 + - name: hundred-middle + in: + n: 100 + k: 1300 + - name: max-length-minimum + in: + n: 100000 + k: 100000 + - name: max-length-maximum + in: + n: 100000 + k: 2600000 diff --git a/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.cpp b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.cpp new file mode 100644 index 00000000..b6b513a0 --- /dev/null +++ b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + string getSmallestString(int n, int k) { + string res(n, 'a'); + k -= n; + + int i = n - 1; + while (k > 0) { + int add = min(25, k); + res[i] = 'a' + add; + k -= add; + i--; + } + + return res; + } +}; diff --git a/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.cs b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.cs new file mode 100644 index 00000000..7b91801c --- /dev/null +++ b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.cs @@ -0,0 +1,17 @@ +public class Solution { + public string GetSmallestString(int n, int k) { + char[] res = new char[n]; + Array.Fill(res, 'a'); + k -= n; + + int i = n - 1; + while (k > 0) { + int add = Math.Min(25, k); + res[i] = (char)('a' + add); + k -= add; + i--; + } + + return new string(res); + } +} diff --git a/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.dart b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.dart new file mode 100644 index 00000000..6480b945 --- /dev/null +++ b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.dart @@ -0,0 +1,16 @@ +class Solution { + String getSmallestString(int n, int k) { + List res = List.filled(n, 'a'); + k -= n; + + int i = n - 1; + while (k > 0) { + int add = k < 25 ? k : 25; + res[i] = String.fromCharCode('a'.codeUnitAt(0) + add); + k -= add; + i--; + } + + return res.join(); + } +} diff --git a/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.go b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.go new file mode 100644 index 00000000..c407eb1a --- /dev/null +++ b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.go @@ -0,0 +1,24 @@ +func getSmallestString(n int, k int) string { + res := make([]byte, n) + for i := range res { + res[i] = 'a' + } + k -= n + + i := n - 1 + for k > 0 { + add := min(25, k) + res[i] = byte('a' + add) + k -= add + i-- + } + + return string(res) +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} diff --git a/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.java b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.java new file mode 100644 index 00000000..085e5754 --- /dev/null +++ b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.java @@ -0,0 +1,17 @@ +class Solution { + public String getSmallestString(int n, int k) { + char[] res = new char[n]; + java.util.Arrays.fill(res, 'a'); + k -= n; + + int i = n - 1; + while (k > 0) { + int add = Math.min(25, k); + res[i] = (char) ('a' + add); + k -= add; + i--; + } + + return new String(res); + } +} diff --git a/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.kt b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.kt new file mode 100644 index 00000000..cd1eb7ab --- /dev/null +++ b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun getSmallestString(n: Int, k: Int): String { + val res = CharArray(n) { 'a' } + var kk = k - n + + var i = n - 1 + while (kk > 0) { + val add = minOf(25, kk) + res[i] = ('a'.code + add).toChar() + kk -= add + i-- + } + + return String(res) + } +} diff --git a/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.py b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.py new file mode 100644 index 00000000..109064ef --- /dev/null +++ b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.py @@ -0,0 +1,18 @@ +class Solution(object): + def getSmallestString(self, n, k): + """ + :type n: int + :type k: int + :rtype: str + """ + res = ["a"] * n + k -= n + + i = n - 1 + while k > 0: + add = min(25, k) + res[i] = chr(ord("a") + add) + k -= add + i -= 1 + + return "".join(res) diff --git a/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.py2 b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.py2 new file mode 100644 index 00000000..855ccb62 --- /dev/null +++ b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def getSmallestString(self, n, k): + """ + :type n: int + :type k: int + :rtype: str + """ + res = ['a'] * n + k -= n + + i = n - 1 + while k > 0: + add = min(25, k) + res[i] = chr(ord('a') + add) + k -= add + i -= 1 + + return ''.join(res) diff --git a/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.rb b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.rb new file mode 100644 index 00000000..f1190299 --- /dev/null +++ b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.rb @@ -0,0 +1,17 @@ +# @param {Integer} n +# @param {Integer} k +# @return {String} +def get_smallest_string(n, k) + res = Array.new(n, 'a') + k -= n + + i = n - 1 + while k > 0 + add = [25, k].min + res[i] = ('a'.ord + add).chr + k -= add + i -= 1 + end + + res.join +end diff --git a/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.rs b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.rs new file mode 100644 index 00000000..b9c06f57 --- /dev/null +++ b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn get_smallest_string(n: i32, k: i32) -> String { + let mut res: Vec = vec!['a'; n as usize]; + let mut kk = k - n; + + let mut i = (n - 1) as usize; + while kk > 0 { + let add = std::cmp::min(25, kk); + res[i] = (b'a' + add as u8) as char; + kk -= add; + i -= 1; + } + + res.into_iter().collect() + } +} diff --git a/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.swift b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.swift new file mode 100644 index 00000000..610af0b8 --- /dev/null +++ b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func getSmallestString(_ n: Int, _ k: Int) -> String { + var res = [Character](repeating: "a", count: n) + var kk = k - n + + var i = n - 1 + while kk > 0 { + let add = min(25, kk) + res[i] = Character(UnicodeScalar(Int(Character("a").asciiValue!) + add)!) + kk -= add + i -= 1 + } + + return String(res) + } +} diff --git a/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.ts b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.ts new file mode 100644 index 00000000..525d1893 --- /dev/null +++ b/tests/1501-2000/1663. smallest-string-with-a-given-numeric-value/sol.ts @@ -0,0 +1,14 @@ +function getSmallestString(n: number, k: number): string { + const res: string[] = new Array(n).fill("a"); + k -= n; + + let i = n - 1; + while (k > 0) { + const add = Math.min(25, k); + res[i] = String.fromCharCode("a".charCodeAt(0) + add); + k -= add; + i--; + } + + return res.join(""); +} diff --git a/tests/1501-2000/1664. ways-to-make-a-fair-array/manifest.yaml b/tests/1501-2000/1664. ways-to-make-a-fair-array/manifest.yaml new file mode 100644 index 00000000..981f4acf --- /dev/null +++ b/tests/1501-2000/1664. ways-to-make-a-fair-array/manifest.yaml @@ -0,0 +1,232 @@ +entry: + id: 1664 + title: "ways-to-make-a-fair-array" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().waysToMakeFair({nums})" + rust: "Solution::ways_to_make_fair({nums})" + python3: "Solution().waysToMakeFair({nums})" + python2: "Solution().waysToMakeFair({nums})" + ruby: "ways_to_make_fair({nums})" + java: "new Solution().waysToMakeFair({nums})" + csharp: "new Solution().WaysToMakeFair({nums})" + kotlin: "Solution().waysToMakeFair({nums})" + go: "waysToMakeFair({nums})" + dart: "Solution().waysToMakeFair({nums})" + swift: "Solution().waysToMakeFair({nums})" + typescript: "waysToMakeFair({nums})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().waysToMakeFair(nums, {result})" + checker: | + class Checker: + def waysToMakeFair(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + total_even = sum(nums[::2]) + total_odd = sum(nums[1::2]) + left_even = 0 + left_odd = 0 + expected = 0 + for index, value in enumerate(nums): + if index % 2 == 0: + total_even -= value + else: + total_odd -= value + if total_even + left_odd == total_odd + left_even: + expected += 1 + if index % 2 == 0: + left_even += value + else: + left_odd += value + return result == expected + +seed: 1664 + +tests: + - name: example-one + in: + nums: [2, 1, 6, 4] + out: 1 + - name: example-two + in: + nums: [1, 1, 1] + out: 3 + - name: example-three + in: + nums: [1, 2, 3] + out: 0 + - name: single-one + in: + nums: [1] + out: 1 + - name: two-equal + in: + nums: [7, 7] + out: 0 + - name: two-different + in: + nums: [1, 2] + out: 0 + - name: three-equal + in: + nums: [5, 5, 5] + out: 3 + - name: alternating-small + in: + nums: [1, 2, 1, 2, 1] + out: 1 + - name: all-ones-even + in: + nums: [1, 1, 1, 1] + out: 0 + - name: all-ones-five + in: + nums: [1, 1, 1, 1, 1] + out: 5 + - name: balanced-original + in: + nums: [4, 1, 2, 5, 3, 3] + out: 0 + - name: large-values + in: + nums: [10000, 9999, 10000, 9999, 10000] + out: 1 + - name: increasing-four + in: + nums: [1, 2, 3, 4] + out: 0 + - name: increasing-five + in: + nums: [1, 2, 3, 4, 5] + out: 0 + - name: decreasing-six + in: + nums: [6, 5, 4, 3, 2, 1] + out: 0 + - name: zero-not-allowed-values-one + in: + nums: [10, 1, 1, 10, 10, 1, 1] + out: 3 + - name: repeated-block + in: + nums: [3, 8, 3, 8, 3, 8, 3, 8] + out: 0 + - name: symmetric-seven + in: + nums: [2, 4, 6, 4, 2, 4, 6] + out: 1 + - name: one-large-middle + in: + nums: [1, 1, 100, 1, 1] + out: 1 + - name: cancellation + in: + nums: [8, 3, 5, 10, 2, 2, 7, 7] + out: 0 + - name: powers + in: + nums: [1, 2, 4, 8, 16, 32, 64] + out: 0 + - name: alternating-large + in: + nums: [10000, 1, 10000, 1, 10000, 1, 10000, 1, 10000] + out: 1 + - name: odd-length-mixed + in: + nums: [9, 2, 7, 4, 6, 8, 5, 3, 1] + out: 0 + - name: even-length-mixed + in: + nums: [9, 2, 7, 4, 6, 8, 5, 3] + out: 0 + - name: mostly-equal + in: + nums: [4, 4, 4, 4, 4, 4, 9] + out: 1 + - name: edge-value-pairs + in: + nums: [1, 10000, 10000, 1, 1, 10000, 10000] + out: 3 + - name: length-nine-ones + in: + nums: [1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 9 + - name: length-ten-ones + in: + nums: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 0 + - name: near-balanced + in: + nums: [2, 3, 4, 1, 5, 7, 6] + out: 1 + - name: singleton-large + in: + nums: [10000] + out: 1 + - name: alternating-two-values + in: + nums: [2, 9, 2, 9, 2, 9, 2] + out: 1 + - name: generated-small + in: + nums: + gen: "array" + len: 37 + of: + gen: "int" + min: 1 + max: 20 + elemType: "int" + - name: generated-medium + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 10000 + elemType: "int" + - name: generated-large + in: + nums: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 10000 + elemType: "int" + - name: generated-maximum + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 10000 + elemType: "int" + - name: generated-maximum-small-values + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 2 + elemType: "int" diff --git a/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.cpp b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.cpp new file mode 100644 index 00000000..d06c3a21 --- /dev/null +++ b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int waysToMakeFair(vector& nums) { + int even = 0; + int odd = 0; + int even_left = 0; + int odd_left = 0; + int result = 0; + for (int idx = 0; idx < nums.size(); idx++) { + if (idx % 2 == 0) { + even += nums[idx]; + } else { + odd += nums[idx]; + } + } + for (int idx = 0; idx < nums.size(); idx++) { + if (idx % 2 == 0) { + even -= nums[idx]; + } else { + odd -= nums[idx]; + } + if (even + odd_left == odd + even_left) { + result++; + } + if (idx % 2 == 0) { + even_left += nums[idx]; + } else { + odd_left += nums[idx]; + } + } + return result; + } +}; diff --git a/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.cs b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.cs new file mode 100644 index 00000000..3de7fb27 --- /dev/null +++ b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.cs @@ -0,0 +1,32 @@ +public class Solution { + public int WaysToMakeFair(int[] nums) { + int even = 0; + int odd = 0; + int even_left = 0; + int odd_left = 0; + int result = 0; + for (int idx = 0; idx < nums.Length; idx++) { + if (idx % 2 == 0) { + even += nums[idx]; + } else { + odd += nums[idx]; + } + } + for (int idx = 0; idx < nums.Length; idx++) { + if (idx % 2 == 0) { + even -= nums[idx]; + } else { + odd -= nums[idx]; + } + if (even + odd_left == odd + even_left) { + result++; + } + if (idx % 2 == 0) { + even_left += nums[idx]; + } else { + odd_left += nums[idx]; + } + } + return result; + } +} diff --git a/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.dart b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.dart new file mode 100644 index 00000000..4ce5ecc4 --- /dev/null +++ b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.dart @@ -0,0 +1,32 @@ +class Solution { + int waysToMakeFair(List nums) { + int even = 0; + int odd = 0; + int even_left = 0; + int odd_left = 0; + int result = 0; + for (int idx = 0; idx < nums.length; idx++) { + if (idx % 2 == 0) { + even += nums[idx]; + } else { + odd += nums[idx]; + } + } + for (int idx = 0; idx < nums.length; idx++) { + if (idx % 2 == 0) { + even -= nums[idx]; + } else { + odd -= nums[idx]; + } + if (even + odd_left == odd + even_left) { + result++; + } + if (idx % 2 == 0) { + even_left += nums[idx]; + } else { + odd_left += nums[idx]; + } + } + return result; + } +} diff --git a/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.go b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.go new file mode 100644 index 00000000..93bb462b --- /dev/null +++ b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.go @@ -0,0 +1,30 @@ +func waysToMakeFair(nums []int) int { + even := 0 + odd := 0 + even_left := 0 + odd_left := 0 + result := 0 + for idx, ele := range nums { + if idx%2 == 0 { + even += ele + } else { + odd += ele + } + } + for idx, ele := range nums { + if idx%2 == 0 { + even -= ele + } else { + odd -= ele + } + if even+odd_left == odd+even_left { + result++ + } + if idx%2 == 0 { + even_left += ele + } else { + odd_left += ele + } + } + return result +} diff --git a/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.java b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.java new file mode 100644 index 00000000..21b76d19 --- /dev/null +++ b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.java @@ -0,0 +1,32 @@ +class Solution { + public int waysToMakeFair(int[] nums) { + int even = 0; + int odd = 0; + int even_left = 0; + int odd_left = 0; + int result = 0; + for (int idx = 0; idx < nums.length; idx++) { + if (idx % 2 == 0) { + even += nums[idx]; + } else { + odd += nums[idx]; + } + } + for (int idx = 0; idx < nums.length; idx++) { + if (idx % 2 == 0) { + even -= nums[idx]; + } else { + odd -= nums[idx]; + } + if (even + odd_left == odd + even_left) { + result++; + } + if (idx % 2 == 0) { + even_left += nums[idx]; + } else { + odd_left += nums[idx]; + } + } + return result; + } +} diff --git a/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.kt b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.kt new file mode 100644 index 00000000..a580cc47 --- /dev/null +++ b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.kt @@ -0,0 +1,32 @@ +class Solution { + fun waysToMakeFair(nums: IntArray): Int { + var even = 0 + var odd = 0 + var even_left = 0 + var odd_left = 0 + var result = 0 + for (idx in nums.indices) { + if (idx % 2 == 0) { + even += nums[idx] + } else { + odd += nums[idx] + } + } + for (idx in nums.indices) { + if (idx % 2 == 0) { + even -= nums[idx] + } else { + odd -= nums[idx] + } + if (even + odd_left == odd + even_left) { + result++ + } + if (idx % 2 == 0) { + even_left += nums[idx] + } else { + odd_left += nums[idx] + } + } + return result + } +} diff --git a/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.py b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.py new file mode 100644 index 00000000..8f64c7a3 --- /dev/null +++ b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.py @@ -0,0 +1,24 @@ +class Solution: + def waysToMakeFair(self, nums: List[int]) -> int: + even = 0 + odd = 0 + even_left = 0 + odd_left = 0 + result = 0 + for idx, ele in enumerate(nums): + if idx % 2 == 0: + even += ele + else: + odd += ele + for idx, ele in enumerate(nums): + if idx % 2 == 0: + even -= ele + else: + odd -= ele + if even + odd_left == odd + even_left: + result += 1 + if idx % 2 == 0: + even_left += ele + else: + odd_left += ele + return result diff --git a/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.py2 b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.py2 new file mode 100644 index 00000000..8f101b49 --- /dev/null +++ b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.py2 @@ -0,0 +1,28 @@ +class Solution(object): + def waysToMakeFair(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + even = 0 + odd = 0 + even_left = 0 + odd_left = 0 + result = 0 + for idx, ele in enumerate(nums): + if idx % 2 == 0: + even += ele + else: + odd += ele + for idx, ele in enumerate(nums): + if idx % 2 == 0: + even -= ele + else: + odd -= ele + if even + odd_left == odd + even_left: + result += 1 + if idx % 2 == 0: + even_left += ele + else: + odd_left += ele + return result diff --git a/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.rb b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.rb new file mode 100644 index 00000000..fc45a005 --- /dev/null +++ b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.rb @@ -0,0 +1,32 @@ +# @param {Integer[]} nums +# @return {Integer} +def ways_to_make_fair(nums) + even = 0 + odd = 0 + even_left = 0 + odd_left = 0 + result = 0 + nums.each_with_index do |ele, idx| + if idx % 2 == 0 + even += ele + else + odd += ele + end + end + nums.each_with_index do |ele, idx| + if idx % 2 == 0 + even -= ele + else + odd -= ele + end + if even + odd_left == odd + even_left + result += 1 + end + if idx % 2 == 0 + even_left += ele + else + odd_left += ele + end + end + result +end diff --git a/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.rs b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.rs new file mode 100644 index 00000000..89dd0015 --- /dev/null +++ b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.rs @@ -0,0 +1,32 @@ +impl Solution { + pub fn ways_to_make_fair(nums: Vec) -> i32 { + let mut even = 0; + let mut odd = 0; + let mut even_left = 0; + let mut odd_left = 0; + let mut result = 0; + for (idx, &ele) in nums.iter().enumerate() { + if idx % 2 == 0 { + even += ele; + } else { + odd += ele; + } + } + for (idx, &ele) in nums.iter().enumerate() { + if idx % 2 == 0 { + even -= ele; + } else { + odd -= ele; + } + if even + odd_left == odd + even_left { + result += 1; + } + if idx % 2 == 0 { + even_left += ele; + } else { + odd_left += ele; + } + } + result + } +} diff --git a/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.swift b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.swift new file mode 100644 index 00000000..607be497 --- /dev/null +++ b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.swift @@ -0,0 +1,32 @@ +class Solution { + func waysToMakeFair(_ nums: [Int]) -> Int { + var even = 0 + var odd = 0 + var even_left = 0 + var odd_left = 0 + var result = 0 + for (idx, ele) in nums.enumerated() { + if idx % 2 == 0 { + even += ele + } else { + odd += ele + } + } + for (idx, ele) in nums.enumerated() { + if idx % 2 == 0 { + even -= ele + } else { + odd -= ele + } + if even + odd_left == odd + even_left { + result += 1 + } + if idx % 2 == 0 { + even_left += ele + } else { + odd_left += ele + } + } + return result + } +} diff --git a/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.ts b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.ts new file mode 100644 index 00000000..5e8a6117 --- /dev/null +++ b/tests/1501-2000/1664. ways-to-make-a-fair-array/sol.ts @@ -0,0 +1,30 @@ +function waysToMakeFair(nums: number[]): number { + let even = 0; + let odd = 0; + let even_left = 0; + let odd_left = 0; + let result = 0; + for (let idx = 0; idx < nums.length; idx++) { + if (idx % 2 === 0) { + even += nums[idx]; + } else { + odd += nums[idx]; + } + } + for (let idx = 0; idx < nums.length; idx++) { + if (idx % 2 === 0) { + even -= nums[idx]; + } else { + odd -= nums[idx]; + } + if (even + odd_left === odd + even_left) { + result++; + } + if (idx % 2 === 0) { + even_left += nums[idx]; + } else { + odd_left += nums[idx]; + } + } + return result; +} diff --git a/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/manifest.yaml b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/manifest.yaml new file mode 100644 index 00000000..a36f62af --- /dev/null +++ b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/manifest.yaml @@ -0,0 +1,337 @@ +entry: + id: 1665 + title: "minimum-initial-energy-to-finish-tasks" + params: + tasks: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().minimumEffort({tasks})" + rust: "Solution::minimum_effort({tasks})" + python3: "Solution().minimumEffort({tasks})" + python2: "Solution().minimumEffort({tasks})" + ruby: "minimum_effort({tasks})" + java: "new Solution().minimumEffort({tasks})" + csharp: "new Solution().MinimumEffort({tasks})" + kotlin: "Solution().minimumEffort({tasks})" + go: "minimumEffort({tasks})" + dart: "Solution().minimumEffort({tasks})" + swift: "Solution().minimumEffort({tasks})" + typescript: "minimumEffort({tasks})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().minimumEffort(tasks, {result})" + checker: | + class Checker: + def minimumEffort(self, tasks, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + ordered = sorted(tasks, key=lambda x: x[1] - x[0], reverse=True) + spent = 0 + need = 0 + for actual, minimum in ordered: + need = max(need, spent + minimum) + spent += actual + return result == need +seed: 1665 +tests: + - name: example-one + in: + tasks: + - [1, 2] + - [2, 4] + - [4, 8] + out: 8 + - name: example-two + in: + tasks: + - [1, 3] + - [2, 4] + - [10, 11] + - [10, 12] + - [8, 9] + out: 32 + - name: example-three + in: + tasks: + - [1, 7] + - [2, 8] + - [3, 9] + - [4, 10] + - [5, 11] + - [6, 12] + out: 27 + - name: one-task-equal + in: + tasks: + - [7, 7] + out: 7 + - name: one-task-max-threshold + in: + tasks: + - [1, 10000] + out: 10000 + - name: all-minimum-one + in: + tasks: + - [1, 1] + - [1, 1] + - [1, 1] + - [1, 1] + out: 4 + - name: equal-gaps + in: + tasks: + - [2, 5] + - [3, 6] + - [4, 7] + out: 12 + - name: equal-tasks + in: + tasks: + - [10, 20] + - [10, 20] + - [10, 20] + - [10, 20] + - [10, 20] + out: 60 + - name: zero-gap + in: + tasks: + - [5, 5] + - [4, 4] + - [3, 3] + out: 12 + - name: high-thresholds + in: + tasks: + - [1, 100] + - [1, 101] + - [1, 102] + out: 102 + - name: high-costs + in: + tasks: + - [100, 100] + - [99, 99] + - [98, 98] + out: 297 + - name: mixed-small + in: + tasks: + - [3, 5] + - [1, 4] + - [2, 2] + - [4, 8] + out: 10 + - name: reorder-required + in: + tasks: + - [5, 6] + - [1, 10] + - [2, 3] + out: 10 + - name: powers-of-two + in: + tasks: + - [1, 2] + - [2, 4] + - [4, 8] + - [8, 16] + - [16, 32] + out: 32 + - name: maximum-actuals + in: + tasks: + - [10000, 10000] + - [10000, 10000] + out: 20000 + - name: maximum-thresholds + in: + tasks: + - [1, 10000] + - [2, 10000] + - [3, 10000] + out: 10003 + - name: threshold-after-spend + in: + tasks: + - [8, 9] + - [1, 10] + - [1, 11] + out: 11 + - name: four-staged + in: + tasks: + - [2, 9] + - [7, 8] + - [3, 10] + - [1, 5] + out: 14 + - name: varied-gaps + in: + tasks: + - [9, 20] + - [1, 2] + - [4, 10] + - [2, 9] + out: 21 + - name: increasing-actuals + in: + tasks: + - [1, 5] + - [2, 6] + - [3, 7] + - [4, 8] + - [5, 9] + out: 19 + - name: decreasing-actuals + in: + tasks: + - [5, 5] + - [4, 6] + - [3, 7] + - [2, 8] + - [1, 9] + out: 15 + - name: alternating-gaps + in: + tasks: + - [1, 10] + - [9, 9] + - [1, 8] + - [8, 8] + - [1, 7] + out: 20 + - name: large-balanced + in: + tasks: + - [4000, 7000] + - [3000, 6000] + - [2000, 5000] + - [1000, 4000] + out: 13000 + - name: large-unbalanced + in: + tasks: + - [9999, 10000] + - [1, 10000] + - [1, 10000] + out: 10002 + - name: ten-unit-chain + in: + tasks: + - [10, 11] + - [10, 12] + - [10, 13] + - [10, 14] + - [10, 15] + - [10, 16] + out: 61 + - name: sparse-threshold + in: + tasks: + - [2, 2] + - [2, 50] + - [2, 2] + - [2, 2] + - [2, 2] + out: 50 + - name: near-limit-single + in: + tasks: + - [9999, 10000] + out: 10000 + - name: near-limit-multiple + in: + tasks: + - [9999, 10000] + - [9998, 9999] + - [9997, 9998] + out: 29995 + - name: many-small-varied + in: + tasks: + - [1, 3] + - [2, 5] + - [3, 7] + - [4, 9] + - [5, 11] + - [6, 13] + - [7, 15] + - [8, 17] + out: 38 + - name: high-cost-staircase + in: + tasks: + - [1000, 2000] + - [900, 1900] + - [800, 1800] + - [700, 1700] + - [600, 1600] + out: 5000 + - name: all-minimum-two + in: + tasks: + - [1, 2] + - [1, 2] + - [1, 2] + - [1, 2] + - [1, 2] + - [1, 2] + - [1, 2] + - [1, 2] + out: 9 + - name: alternating-cost-threshold + in: + tasks: + - [1, 100] + - [50, 51] + - [1, 100] + - [50, 51] + - [1, 100] + out: 104 + - name: repeated-max-threshold + in: + tasks: + - [1, 10000] + - [1, 10000] + - [1, 10000] + - [1, 10000] + - [1, 10000] + - [1, 10000] + - [1, 10000] + - [1, 10000] + - [1, 10000] + - [1, 10000] + out: 10009 + - name: descending-gap-chain + in: + tasks: + - [9, 10] + - [8, 12] + - [7, 14] + - [6, 16] + - [5, 18] + - [4, 20] + - [3, 22] + - [2, 24] + - [1, 26] + out: 46 + - name: near-limit-total-energy + in: + tasks: + - [10000, 10000] + - [10000, 10000] + - [10000, 10000] + - [9999, 10000] + - [9998, 9999] + out: 49997 diff --git a/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.cpp b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.cpp new file mode 100644 index 00000000..cd934a01 --- /dev/null +++ b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int minimumEffort(vector>& tasks) { + sort(tasks.begin(), tasks.end(), [](const vector& a, const vector& b) { + return (a[1] - a[0]) > (b[1] - b[0]); + }); + auto test = [&](int bal) { + for (auto& t : tasks) { + if (bal < t[1]) return false; + bal -= t[0]; + } + return true; + }; + int lo = 0, hi = 1000000001; + while (lo < hi) { + int mid = (lo + hi) / 2; + if (test(mid)) hi = mid; + else lo = mid + 1; + } + return lo; + } +}; diff --git a/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.cs b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.cs new file mode 100644 index 00000000..b80faa29 --- /dev/null +++ b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public int MinimumEffort(int[][] tasks) { + Array.Sort(tasks, (a, b) => (b[1] - b[0]).CompareTo(a[1] - a[0])); + bool test(int bal) { + foreach (var t in tasks) { + if (bal < t[1]) return false; + bal -= t[0]; + } + return true; + } + int lo = 0, hi = 1000000001; + while (lo < hi) { + int mid = (lo + hi) / 2; + if (test(mid)) hi = mid; + else lo = mid + 1; + } + return lo; + } +} diff --git a/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.dart b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.dart new file mode 100644 index 00000000..b04fddaf --- /dev/null +++ b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.dart @@ -0,0 +1,22 @@ +class Solution { + int minimumEffort(List> tasks) { + tasks.sort((a, b) => (b[1] - b[0]).compareTo(a[1] - a[0])); + bool test(int bal) { + for (var t in tasks) { + if (bal < t[1]) return false; + bal -= t[0]; + } + return true; + } + int lo = 0, hi = 1000000001; + while (lo < hi) { + int mid = (lo + hi) ~/ 2; + if (test(mid)) { + hi = mid; + } else { + lo = mid + 1; + } + } + return lo; + } +} diff --git a/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.go b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.go new file mode 100644 index 00000000..875cedaf --- /dev/null +++ b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.go @@ -0,0 +1,24 @@ +func minimumEffort(tasks [][]int) int { + sort.Slice(tasks, func(i, j int) bool { + return (tasks[i][1]-tasks[i][0]) > (tasks[j][1]-tasks[j][0]) + }) + test := func(bal int) bool { + for _, t := range tasks { + if bal < t[1] { + return false + } + bal -= t[0] + } + return true + } + lo, hi := 0, 1000000001 + for lo < hi { + mid := (lo + hi) / 2 + if test(mid) { + hi = mid + } else { + lo = mid + 1 + } + } + return lo +} diff --git a/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.java b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.java new file mode 100644 index 00000000..9c6f5e78 --- /dev/null +++ b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.java @@ -0,0 +1,22 @@ +class Solution { + public int minimumEffort(int[][] tasks) { + java.util.Arrays.sort(tasks, (a, b) -> Integer.compare((b[1] - b[0]), (a[1] - a[0]))); + int lo = 0, hi = 1000000001; + while (lo < hi) { + int mid = (lo + hi) / 2; + if (can(mid, tasks)) { + hi = mid; + } else { + lo = mid + 1; + } + } + return lo; + } + private boolean can(int bal, int[][] tasks) { + for (int[] t : tasks) { + if (bal < t[1]) return false; + bal -= t[0]; + } + return true; + } +} diff --git a/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.kt b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.kt new file mode 100644 index 00000000..b00fc808 --- /dev/null +++ b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun minimumEffort(tasks: Array): Int { + tasks.sortByDescending { it[1] - it[0] } + fun test(bal: Int): Boolean { + var b = bal + for ((cost, thresh) in tasks) { + if (b < thresh) return false + b -= cost + } + return true + } + var lo = 0 + var hi = 1000000001 + while (lo < hi) { + val mid = (lo + hi) / 2 + if (test(mid)) hi = mid else lo = mid + 1 + } + return lo + } +} diff --git a/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.py b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.py new file mode 100644 index 00000000..22283e94 --- /dev/null +++ b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.py @@ -0,0 +1,15 @@ +import bisect + + +class Solution: + def minimumEffort(self, tasks: list[list[int]]) -> int: + tasks.sort(key=lambda x: x[1] - x[0], reverse=True) + + def test(bal): + for cost, thresh in tasks: + if bal < thresh: + return False + bal -= cost + return True + + return bisect.bisect_left(range(10**9 + 1), True, key=test) diff --git a/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.py2 b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.py2 new file mode 100644 index 00000000..bb988f42 --- /dev/null +++ b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def minimumEffort(self, tasks): + """ + :type tasks: List[List[int]] + :rtype: int + """ + tasks.sort(key=lambda x: x[1] - x[0], reverse=True) + def test(bal): + for cost, thresh in tasks: + if bal < thresh: + return False + bal -= cost + return True + lo, hi = 0, 10**9 + 1 + while lo < hi: + mid = (lo + hi) // 2 + if test(mid): + hi = mid + else: + lo = mid + 1 + return lo diff --git a/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.rb b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.rb new file mode 100644 index 00000000..83e1d8e7 --- /dev/null +++ b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.rb @@ -0,0 +1,22 @@ +# @param {Integer[][]} tasks +# @return {Integer} +def minimum_effort(tasks) + tasks.sort_by! { |cost, thresh| -(thresh - cost) } + test = ->(bal) { + tasks.each do |cost, thresh| + return false if bal < thresh + bal -= cost + end + true + } + lo, hi = 0, 10**9 + 1 + while lo < hi + mid = (lo + hi) / 2 + if test.call(mid) + hi = mid + else + lo = mid + 1 + end + end + lo +end diff --git a/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.rs b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.rs new file mode 100644 index 00000000..70f28b99 --- /dev/null +++ b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn minimum_effort(tasks: Vec>) -> i32 { + let mut tasks = tasks; + tasks.sort_by(|a, b| (b[1] - b[0]).cmp(&(a[1] - a[0]))); + let test = |bal: i32| -> bool { + let mut b = bal; + for t in &tasks { + if b < t[1] { return false; } + b -= t[0]; + } + true + }; + let (mut lo, mut hi) = (0, 1_000_000_001); + while lo < hi { + let mid = (lo + hi) / 2; + if test(mid) { + hi = mid; + } else { + lo = mid + 1; + } + } + lo + } +} diff --git a/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.swift b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.swift new file mode 100644 index 00000000..dd71469b --- /dev/null +++ b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func minimumEffort(_ tasks: [[Int]]) -> Int { + let sorted = tasks.sorted { ($0[1] - $0[0]) > ($1[1] - $1[0]) } + func test(_ bal: Int) -> Bool { + var b = bal + for t in sorted { + if b < t[1] { return false } + b -= t[0] + } + return true + } + var lo = 0, hi = 1000000001 + while lo < hi { + let mid = (lo + hi) / 2 + if test(mid) { + hi = mid + } else { + lo = mid + 1 + } + } + return lo + } +} diff --git a/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.ts b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.ts new file mode 100644 index 00000000..344c2901 --- /dev/null +++ b/tests/1501-2000/1665. minimum-initial-energy-to-finish-tasks/sol.ts @@ -0,0 +1,18 @@ +function minimumEffort(tasks: number[][]): number { + tasks.sort((a, b) => b[1] - b[0] - (a[1] - a[0])); + const test = (bal: number): boolean => { + for (const [cost, thresh] of tasks) { + if (bal < thresh) return false; + bal -= cost; + } + return true; + }; + let lo = 0, + hi = 1000000001; + while (lo < hi) { + const mid = Math.floor((lo + hi) / 2); + if (test(mid)) hi = mid; + else lo = mid + 1; + } + return lo; +} diff --git a/tests/1501-2000/1668. maximum-repeating-substring/manifest.yaml b/tests/1501-2000/1668. maximum-repeating-substring/manifest.yaml new file mode 100644 index 00000000..cd864e5d --- /dev/null +++ b/tests/1501-2000/1668. maximum-repeating-substring/manifest.yaml @@ -0,0 +1,250 @@ +entry: + id: 1668 + title: "maximum-repeating-substring" + params: + sequence: + type: string + word: + type: string + call: + cpp: "Solution().maxRepeating({sequence}, {word})" + rust: "Solution::max_repeating({sequence}, {word})" + python3: "Solution().maxRepeating({sequence}, {word})" + python2: "Solution().maxRepeating({sequence}, {word})" + ruby: "max_repeating({sequence}, {word})" + java: "new Solution().maxRepeating({sequence}, {word})" + csharp: "new Solution().MaxRepeating({sequence}, {word})" + kotlin: "Solution().maxRepeating({sequence}, {word})" + go: "maxRepeating({sequence}, {word})" + dart: "Solution().maxRepeating({sequence}, {word})" + swift: "Solution().maxRepeating({sequence}, {word})" + typescript: "maxRepeating({sequence}, {word})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().maxRepeating(sequence, word, {result})" + checker: | + class Checker: + def maxRepeating(self, sequence, word, result): + expected = 0 + repeated = word + while repeated in sequence: + expected += 1 + repeated += word + return result == expected +seed: 1668 +tests: + - name: example-ab + in: + sequence: "ababc" + word: "ab" + out: 2 + - name: example-ba + in: + sequence: "ababc" + word: "ba" + out: 1 + - name: example-missing + in: + sequence: "ababc" + word: "ac" + out: 0 + - name: exact-one + in: + sequence: "abc" + word: "abc" + out: 1 + - name: empty-repeat + in: + sequence: "aaaaa" + word: "a" + out: 5 + - name: repeated-pair + in: + sequence: "abababab" + word: "ab" + out: 4 + - name: repeated-triple + in: + sequence: "abcabcabcabc" + word: "abc" + out: 4 + - name: word-longer + in: + sequence: "abc" + word: "abcd" + out: 0 + - name: prefix-only + in: + sequence: "ababx" + word: "ab" + out: 2 + - name: suffix-only + in: + sequence: "xabab" + word: "ab" + out: 2 + - name: separated-occurrences + in: + sequence: "abxabab" + word: "ab" + out: 2 + - name: overlap-not-repeat + in: + sequence: "aaaa" + word: "aa" + out: 2 + - name: overlap-single + in: + sequence: "aaaa" + word: "aaa" + out: 1 + - name: alternating + in: + sequence: "bababab" + word: "bab" + out: 1 + - name: repeated-with-tail + in: + sequence: "xyzxyzxyzq" + word: "xyz" + out: 3 + - name: internal-run + in: + sequence: "qabcabcabcr" + word: "abc" + out: 3 + - name: one-character-miss + in: + sequence: "aaaaaaaaab" + word: "aaab" + out: 1 + - name: all-different + in: + sequence: "abcdefghijklmnopqrstuvwxyz" + word: "z" + out: 1 + - name: absent-single + in: + sequence: "bbbbbbbb" + word: "a" + out: 0 + - name: word-inside-longer + in: + sequence: "zzhellozz" + word: "hello" + out: 1 + - name: repeated-long-word + in: + sequence: "abcdefghijklmnopabcdefghijklmnop" + word: "abcdefghijklmnop" + out: 2 + - name: partial-tail + in: + sequence: "abababa" + word: "ab" + out: 3 + - name: repeated-single-tail + in: + sequence: "cccccccd" + word: "c" + out: 7 + - name: embedded-two + in: + sequence: "mmnomnomnp" + word: "mn" + out: 1 + - name: exact-long-single + in: + sequence: "thequickbrownfox" + word: "thequickbrownfox" + out: 1 + - name: repeated-with-prefix + in: + sequence: "rstrstrsts" + word: "rst" + out: 3 + - name: repeated-with-suffix + in: + sequence: "strstrstrs" + word: "str" + out: 3 + - name: short-word-in-long-run + in: + sequence: "abababababababab" + word: "a" + out: 1 + - name: multi-character-zero + in: + sequence: "abcdefgh" + word: "bcdebcde" + out: 0 + - name: case-lowercase + in: + sequence: "zzzzzz" + word: "zz" + out: 3 + - name: long-periodic + in: + sequence: "abcabcabcabcabcabcabcabcabcabc" + word: "abcabc" + out: 5 + - name: long-nonperiodic + in: + sequence: "abcdefghijklmnopqrstuvwxyza" + word: "abc" + out: 1 + - name: generator-small + in: + sequence: + gen: "str" + len: 7 + alphabet: "abc" + word: + gen: "str" + len: 2 + alphabet: "abc" + - name: generator-medium + in: + sequence: + gen: "str" + len: 40 + alphabet: "abcd" + word: + gen: "str" + len: 5 + alphabet: "abcd" + - name: generator-long + in: + sequence: + gen: "str" + len: 100 + alphabet: "ab" + word: + gen: "str" + len: 10 + alphabet: "ab" + - name: generator-single-word + in: + sequence: + gen: "str" + len: 80 + alphabet: "abcde" + word: + gen: "str" + len: 1 + alphabet: "abcde" + - name: generator-max-word + in: + sequence: + gen: "str" + len: 100 + alphabet: "abc" + word: + gen: "str" + len: 100 + alphabet: "abc" diff --git a/tests/1501-2000/1668. maximum-repeating-substring/sol.cpp b/tests/1501-2000/1668. maximum-repeating-substring/sol.cpp new file mode 100644 index 00000000..bf5e6c07 --- /dev/null +++ b/tests/1501-2000/1668. maximum-repeating-substring/sol.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int maxRepeating(string sequence, string word) { + string temp = word; + int res = 0; + while (sequence.find(temp) != string::npos) { + res++; + temp += word; + } + return res; + } +}; diff --git a/tests/1501-2000/1668. maximum-repeating-substring/sol.cs b/tests/1501-2000/1668. maximum-repeating-substring/sol.cs new file mode 100644 index 00000000..8a7b35b1 --- /dev/null +++ b/tests/1501-2000/1668. maximum-repeating-substring/sol.cs @@ -0,0 +1,11 @@ +public class Solution { + public int MaxRepeating(string sequence, string word) { + string temp = word; + int res = 0; + while (sequence.Contains(temp)) { + res++; + temp += word; + } + return res; + } +} diff --git a/tests/1501-2000/1668. maximum-repeating-substring/sol.dart b/tests/1501-2000/1668. maximum-repeating-substring/sol.dart new file mode 100644 index 00000000..9f592bf8 --- /dev/null +++ b/tests/1501-2000/1668. maximum-repeating-substring/sol.dart @@ -0,0 +1,11 @@ +class Solution { + int maxRepeating(String sequence, String word) { + String temp = word; + int res = 0; + while (sequence.contains(temp)) { + res++; + temp += word; + } + return res; + } +} diff --git a/tests/1501-2000/1668. maximum-repeating-substring/sol.go b/tests/1501-2000/1668. maximum-repeating-substring/sol.go new file mode 100644 index 00000000..7f4b9247 --- /dev/null +++ b/tests/1501-2000/1668. maximum-repeating-substring/sol.go @@ -0,0 +1,9 @@ +func maxRepeating(sequence string, word string) int { + temp := word + res := 0 + for strings.Contains(sequence, temp) { + res++ + temp += word + } + return res +} diff --git a/tests/1501-2000/1668. maximum-repeating-substring/sol.java b/tests/1501-2000/1668. maximum-repeating-substring/sol.java new file mode 100644 index 00000000..33b6f707 --- /dev/null +++ b/tests/1501-2000/1668. maximum-repeating-substring/sol.java @@ -0,0 +1,11 @@ +class Solution { + public int maxRepeating(String sequence, String word) { + String temp = word; + int res = 0; + while (sequence.contains(temp)) { + res++; + temp += word; + } + return res; + } +} diff --git a/tests/1501-2000/1668. maximum-repeating-substring/sol.kt b/tests/1501-2000/1668. maximum-repeating-substring/sol.kt new file mode 100644 index 00000000..e05fc4a6 --- /dev/null +++ b/tests/1501-2000/1668. maximum-repeating-substring/sol.kt @@ -0,0 +1,11 @@ +class Solution { + fun maxRepeating(sequence: String, word: String): Int { + var temp = word + var res = 0 + while (sequence.contains(temp)) { + res++ + temp += word + } + return res + } +} diff --git a/tests/1501-2000/1668. maximum-repeating-substring/sol.py b/tests/1501-2000/1668. maximum-repeating-substring/sol.py new file mode 100644 index 00000000..2085a989 --- /dev/null +++ b/tests/1501-2000/1668. maximum-repeating-substring/sol.py @@ -0,0 +1,7 @@ +class Solution: + def maxRepeating(self, sequence: str, word: str) -> int: + temp, res = word, 0 + while temp in sequence: + res += 1 + temp += word + return res diff --git a/tests/1501-2000/1668. maximum-repeating-substring/sol.py2 b/tests/1501-2000/1668. maximum-repeating-substring/sol.py2 new file mode 100644 index 00000000..44e27fa0 --- /dev/null +++ b/tests/1501-2000/1668. maximum-repeating-substring/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def maxRepeating(self, sequence, word): + """ + :type sequence: str + :type word: str + :rtype: int + """ + temp, res = word, 0 + while temp in sequence: + res += 1 + temp += word + return res diff --git a/tests/1501-2000/1668. maximum-repeating-substring/sol.rb b/tests/1501-2000/1668. maximum-repeating-substring/sol.rb new file mode 100644 index 00000000..aa4bb24a --- /dev/null +++ b/tests/1501-2000/1668. maximum-repeating-substring/sol.rb @@ -0,0 +1,11 @@ +# @param {String} sequence +# @param {String} word +# @return {Integer} +def max_repeating(sequence, word) + temp, res = word, 0 + while sequence.include?(temp) + res += 1 + temp += word + end + res +end diff --git a/tests/1501-2000/1668. maximum-repeating-substring/sol.rs b/tests/1501-2000/1668. maximum-repeating-substring/sol.rs new file mode 100644 index 00000000..d6d7d67d --- /dev/null +++ b/tests/1501-2000/1668. maximum-repeating-substring/sol.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn max_repeating(sequence: String, word: String) -> i32 { + let mut temp = word.clone(); + let mut res = 0; + while sequence.contains(&temp) { + res += 1; + temp.push_str(&word); + } + res + } +} diff --git a/tests/1501-2000/1668. maximum-repeating-substring/sol.swift b/tests/1501-2000/1668. maximum-repeating-substring/sol.swift new file mode 100644 index 00000000..7bcf71e3 --- /dev/null +++ b/tests/1501-2000/1668. maximum-repeating-substring/sol.swift @@ -0,0 +1,11 @@ +class Solution { + func maxRepeating(_ sequence: String, _ word: String) -> Int { + var temp = word + var res = 0 + while sequence.contains(temp) { + res += 1 + temp += word + } + return res + } +} diff --git a/tests/1501-2000/1668. maximum-repeating-substring/sol.ts b/tests/1501-2000/1668. maximum-repeating-substring/sol.ts new file mode 100644 index 00000000..48abfa04 --- /dev/null +++ b/tests/1501-2000/1668. maximum-repeating-substring/sol.ts @@ -0,0 +1,9 @@ +function maxRepeating(sequence: string, word: string): number { + let temp = word; + let res = 0; + while (sequence.includes(temp)) { + res++; + temp += word; + } + return res; +} diff --git a/tests/1501-2000/1669. merge-in-between-linked-lists/manifest.yaml b/tests/1501-2000/1669. merge-in-between-linked-lists/manifest.yaml new file mode 100644 index 00000000..147ae84f --- /dev/null +++ b/tests/1501-2000/1669. merge-in-between-linked-lists/manifest.yaml @@ -0,0 +1,294 @@ +entry: + id: 1669 + title: "merge-in-between-linked-lists" + params: + list1: + type: list_node + a: + type: int + b: + type: int + list2: + type: list_node + call: + cpp: "listNodeToArray(Solution().mergeInBetween({list1}, {a}, {b}, {list2}))" + rust: "ListNode::list_node_to_array(Solution::merge_in_between({list1}, {a}, {b}, {list2}))" + python3: "list_node_to_array(Solution().mergeInBetween({list1}, {a}, {b}, {list2}))" + python2: "list_node_to_array(Solution().mergeInBetween({list1}, {a}, {b}, {list2}))" + ruby: "list_node_to_array(merge_in_between({list1}, {a}, {b}, {list2}))" + java: "ListNode.listNodeToArray(new Solution().mergeInBetween({list1}, {a}, {b}, {list2}))" + csharp: "ListNode.ListNodeToArray(new Solution().MergeInBetween({list1}, {a}, {b}, {list2}))" + kotlin: "listNodeToArray(Solution().mergeInBetween({list1}, {a}, {b}, {list2}))" + go: "listNodeToArray(mergeInBetween({list1}, {a}, {b}, {list2}))" + dart: "list_node_to_array(Solution().mergeInBetween({list1}, {a}, {b}, {list2}))" + swift: "list_node_to_array(Solution().mergeInBetween({list1}, {a}, {b}, {list2}))" + typescript: "listNodeToArray(mergeInBetween({list1}, {a}, {b}, {list2}))" +judge: + type: "exact" +limits: + time_ms: 500 + memory_mb: 300 +oracle: + python3: + call: "Checker().mergeInBetween(list1, a, b, list2, {result})" + checker: | + class Checker: + def mergeInBetween(self, list1, a, b, list2, result): + if not isinstance(result, list): + return False + expected = list1[:a] + list2 + list1[b + 1:] + return result == expected +seed: 1669 +tests: + - name: "example_one" + in: + list1: [10, 1, 13, 6, 9, 5] + a: 3 + b: 4 + list2: [1000000, 1000001, 1000002] + out: [10, 1, 13, 1000000, 1000001, 1000002, 5] + - name: "example_two" + in: + list1: [0, 1, 2, 3, 4, 5, 6] + a: 2 + b: 5 + list2: [1000000, 1000001, 1000002, 1000003, 1000004] + out: [0, 1, 1000000, 1000001, 1000002, 1000003, 1000004, 6] + - name: "replace_single_middle" + in: + list1: [1, 2, 3, 4, 5] + a: 2 + b: 2 + list2: [9] + out: [1, 2, 9, 4, 5] + - name: "replace_single_with_many" + in: + list1: [1, 2, 3, 4, 5] + a: 2 + b: 2 + list2: [8, 9, 10] + out: [1, 2, 8, 9, 10, 4, 5] + - name: "remove_two" + in: + list1: [1, 2, 3, 4, 5, 6] + a: 2 + b: 3 + list2: [7] + out: [1, 2, 7, 5, 6] + - name: "replace_prefix_allowed" + in: + list1: [1, 2, 3, 4] + a: 1 + b: 1 + list2: [8, 9] + out: [1, 8, 9, 3, 4] + - name: "replace_near_end" + in: + list1: [1, 2, 3, 4, 5, 6] + a: 4 + b: 4 + list2: [8, 9] + out: [1, 2, 3, 4, 8, 9, 6] + - name: "negative_values" + in: + list1: [-5, -4, -3, -2, -1, 0] + a: 2 + b: 4 + list2: [-9, -8] + out: [-5, -4, -9, -8, 0] + - name: "zero_values" + in: + list1: [0, 0, 0, 0, 0] + a: 1 + b: 3 + list2: [1, 2] + out: [0, 1, 2, 0] + - name: "duplicate_values" + in: + list1: [2, 2, 2, 3, 3, 3] + a: 2 + b: 4 + list2: [2, 3] + out: [2, 2, 2, 3, 3] + - name: "large_values" + in: + list1: [100000, 99999, -100000, 42, 7] + a: 1 + b: 3 + list2: [-100000, 100000] + out: [100000, -100000, 100000, 7] + - name: "list2_longer_than_removed" + in: + list1: [1, 2, 3, 4, 5, 6, 7] + a: 3 + b: 3 + list2: [10, 11, 12, 13, 14] + out: [1, 2, 3, 10, 11, 12, 13, 14, 5, 6, 7] + - name: "list2_same_length" + in: + list1: [1, 2, 3, 4, 5, 6] + a: 2 + b: 4 + list2: [8, 9, 10] + out: [1, 2, 8, 9, 10, 6] + - name: "list2_shorter" + in: + list1: [1, 2, 3, 4, 5, 6, 7] + a: 1 + b: 5 + list2: [9] + out: [1, 9, 7] + - name: "alternating_values" + in: + list1: [1, -1, 1, -1, 1, -1, 1] + a: 2 + b: 5 + list2: [4, -4, 4] + out: [1, -1, 4, -4, 4, 1] + - name: "ascending" + in: + list1: [1, 2, 3, 4, 5, 6, 7, 8] + a: 3 + b: 6 + list2: [20, 21] + out: [1, 2, 3, 20, 21, 8] + - name: "descending" + in: + list1: [8, 7, 6, 5, 4, 3, 2, 1] + a: 2 + b: 5 + list2: [0, -1, -2] + out: [8, 7, 0, -1, -2, 2, 1] + - name: "six_nodes" + in: + list1: [4, 5, 6, 7, 8, 9] + a: 1 + b: 4 + list2: [1, 2] + out: [4, 1, 2, 9] + - name: "seven_nodes" + in: + list1: [4, 5, 6, 7, 8, 9, 10] + a: 3 + b: 5 + list2: [1, 2, 3, 4] + out: [4, 5, 6, 1, 2, 3, 4, 10] + - name: "eight_nodes" + in: + list1: [0, 1, 2, 3, 4, 5, 6, 7] + a: 1 + b: 6 + list2: [99] + out: [0, 99, 7] + - name: "nine_nodes" + in: + list1: [9, 8, 7, 6, 5, 4, 3, 2, 1] + a: 4 + b: 7 + list2: [0, 0, 0] + out: [9, 8, 7, 6, 0, 0, 0, 1] + - name: "ten_nodes" + in: + list1: [1, 1, 2, 2, 3, 3, 4, 4, 5, 5] + a: 2 + b: 7 + list2: [6, 7] + out: [1, 1, 6, 7, 5, 5] + - name: "values_at_limits" + in: + list1: [-100000, -1, 0, 1, 100000] + a: 1 + b: 3 + list2: [100000, -100000] + out: [-100000, 100000, -100000, 100000] + - name: "repeated_insert_values" + in: + list1: [1, 2, 3, 4, 5, 6] + a: 1 + b: 4 + list2: [7, 7, 7] + out: [1, 7, 7, 7, 6] + - name: "single_insert_at_a_two" + in: + list1: [10, 20, 30, 40, 50] + a: 2 + b: 2 + list2: [60, 70] + out: [10, 20, 60, 70, 40, 50] + - name: "single_insert_at_b_four" + in: + list1: [10, 20, 30, 40, 50, 60] + a: 4 + b: 4 + list2: [70] + out: [10, 20, 30, 40, 70, 60] + - name: "removed_middle_long" + in: + list1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + a: 2 + b: 7 + list2: [100, 101, 102] + out: [0, 1, 100, 101, 102, 8, 9] + - name: "mixed_large_signed" + in: + list1: [100000, -99999, 500, -500, 0, 42, -42, 99999] + a: 1 + b: 6 + list2: [-1, 1] + out: [100000, -1, 1, 99999] + - name: "alternating_insert" + in: + list1: [0, 1, 0, 1, 0, 1, 0] + a: 2 + b: 4 + list2: [1, 0, 1, 0] + out: [0, 1, 1, 0, 1, 0, 1, 0] + - name: "long_insert_values" + in: + list1: [1, 2, 3, 4, 5, 6] + a: 2 + b: 3 + list2: [10, 20, 30, 40, 50, 60, 70] + out: [1, 2, 10, 20, 30, 40, 50, 60, 70, 5, 6] + - name: "constant_list1" + in: + list1: [5, 5, 5, 5, 5, 5, 5] + a: 1 + b: 5 + list2: [1, 2, 3, 4] + out: [5, 1, 2, 3, 4, 5] + - name: "constant_list2" + in: + list1: [1, 2, 3, 4, 5, 6, 7] + a: 2 + b: 6 + list2: [8, 8] + out: [1, 2, 8, 8] + - name: "near_full_replacement" + in: + list1: [1, 2, 3, 4, 5, 6, 7, 8] + a: 1 + b: 6 + list2: [9, 10, 11, 12, 13] + out: [1, 9, 10, 11, 12, 13, 8] + - name: "tail_preserved" + in: + list1: [1, 2, 3, 4, 5, 6, 7, 8, 9] + a: 5 + b: 7 + list2: [0] + out: [1, 2, 3, 4, 5, 0, 9] + - name: "distinct_extremes" + in: + list1: [-100000, -2, 3, 17, 99999, 100000] + a: 2 + b: 4 + list2: [0, 100000] + out: [-100000, -2, 0, 100000, 100000] + - name: "final_case" + in: + list1: [3, 1, 4, 1, 5, 9, 2, 6] + a: 3 + b: 5 + list2: [10, 20, 30, 40] + out: [3, 1, 4, 10, 20, 30, 40, 2, 6] diff --git a/tests/1501-2000/1669. merge-in-between-linked-lists/sol.cpp b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.cpp new file mode 100644 index 00000000..e4dbf847 --- /dev/null +++ b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.cpp @@ -0,0 +1,30 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) { + ListNode* curr = list1; + for (int i = 0; i < a-1; i++) { + curr = curr->next; + } + ListNode* prev = curr; + for (int i = 0; i < b-a+2; i++) { + curr = curr->next; + } + prev->next = list2; + prev = prev->next; + while (prev->next != nullptr) { + prev = prev->next; + } + prev->next = curr; + return list1; + } +}; diff --git a/tests/1501-2000/1669. merge-in-between-linked-lists/sol.cs b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.cs new file mode 100644 index 00000000..6c7b54df --- /dev/null +++ b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.cs @@ -0,0 +1,30 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode MergeInBetween(ListNode list1, int a, int b, ListNode list2) { + ListNode curr = list1; + for (int i = 0; i < a-1; i++) { + curr = curr.next; + } + ListNode prev = curr; + for (int i = 0; i < b-a+2; i++) { + curr = curr.next; + } + prev.next = list2; + prev = prev.next; + while (prev.next != null) { + prev = prev.next; + } + prev.next = curr; + return list1; + } +} diff --git a/tests/1501-2000/1669. merge-in-between-linked-lists/sol.dart b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.dart new file mode 100644 index 00000000..05fa1099 --- /dev/null +++ b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.dart @@ -0,0 +1,13 @@ +class Solution { + ListNode? mergeInBetween(ListNode? list1, int a, int b, ListNode? list2) { + ListNode? before = list1; + for (int i = 0; i < a - 1; i++) before = before!.next; + ListNode? after = before!.next; + for (int i = 0; i <= b - a; i++) after = after!.next; + before.next = list2; + ListNode? tail = list2; + while (tail!.next != null) tail = tail.next; + tail.next = after; + return list1; + } +} diff --git a/tests/1501-2000/1669. merge-in-between-linked-lists/sol.go b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.go new file mode 100644 index 00000000..61fc76c0 --- /dev/null +++ b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.go @@ -0,0 +1,24 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func mergeInBetween(list1 *ListNode, a int, b int, list2 *ListNode) *ListNode { + curr := list1 + for i := 0; i < a-1; i++ { + curr = curr.Next + } + prev := curr + for i := 0; i < b-a+2; i++ { + curr = curr.Next + } + prev.Next = list2 + prev = prev.Next + for prev.Next != nil { + prev = prev.Next + } + prev.Next = curr + return list1 +} diff --git a/tests/1501-2000/1669. merge-in-between-linked-lists/sol.java b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.java new file mode 100644 index 00000000..a4dc86b3 --- /dev/null +++ b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.java @@ -0,0 +1,29 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) { + ListNode curr = list1; + for (int i = 0; i < a-1; i++) { + curr = curr.next; + } + ListNode prev = curr; + for (int i = 0; i < b-a+2; i++) { + curr = curr.next; + } + prev.next = list2; + prev = prev.next; + while (prev.next != null) { + prev = prev.next; + } + prev.next = curr; + return list1; + } +} diff --git a/tests/1501-2000/1669. merge-in-between-linked-lists/sol.kt b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.kt new file mode 100644 index 00000000..7fcce606 --- /dev/null +++ b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.kt @@ -0,0 +1,28 @@ +/** + * Example: + * var li = ListNode(5) + * var v = li.`val` + * Definition for singly-linked list. + * class ListNode(var `val`: Int) { + * var next: ListNode? = null + * } + */ +class Solution { + fun mergeInBetween(list1: ListNode?, a: Int, b: Int, list2: ListNode?): ListNode? { + var curr = list1 + for (i in 0 until a-1) { + curr = curr?.next + } + var prev = curr + for (i in 0 until b-a+2) { + curr = curr?.next + } + prev?.next = list2 + prev = prev?.next + while (prev?.next != null) { + prev = prev.next + } + prev?.next = curr + return list1 + } +} diff --git a/tests/1501-2000/1669. merge-in-between-linked-lists/sol.py b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.py new file mode 100644 index 00000000..d68117f0 --- /dev/null +++ b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.py @@ -0,0 +1,27 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def mergeInBetween( + self, list1: ListNode, a: int, b: int, list2: ListNode + ) -> ListNode: + curr = list1 + + for i in range(a - 1): + curr = curr.next + + prev = curr + + for i in range(b - a + 2): + curr = curr.next + + prev.next = list2 + prev = prev.next + + while prev.next: + prev = prev.next + prev.next = curr + + return list1 diff --git a/tests/1501-2000/1669. merge-in-between-linked-lists/sol.py2 b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.py2 new file mode 100644 index 00000000..2214a764 --- /dev/null +++ b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.py2 @@ -0,0 +1,26 @@ +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution(object): + def mergeInBetween(self, list1, a, b, list2): + """ + :type list1: ListNode + :type a: int + :type b: int + :type list2: ListNode + :rtype: ListNode + """ + curr = list1 + for _ in range(a-1): + curr = curr.next + prev = curr + for _ in range(b-a+2): + curr = curr.next + prev.next = list2 + prev = prev.next + while prev.next: + prev = prev.next + prev.next = curr + return list1 diff --git a/tests/1501-2000/1669. merge-in-between-linked-lists/sol.rb b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.rb new file mode 100644 index 00000000..f5fca760 --- /dev/null +++ b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.rb @@ -0,0 +1,26 @@ +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# @param {ListNode} list1 +# @param {Integer} a +# @param {Integer} b +# @param {ListNode} list2 +# @return {ListNode} +def merge_in_between(list1, a, b, list2) + curr = list1 + (a-1).times { curr = curr.next } + prev = curr + (b-a+2).times { curr = curr.next } + prev.next = list2 + prev = prev.next + while prev.next + prev = prev.next + end + prev.next = curr + list1 +end diff --git a/tests/1501-2000/1669. merge-in-between-linked-lists/sol.rs b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.rs new file mode 100644 index 00000000..529cc121 --- /dev/null +++ b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.rs @@ -0,0 +1,44 @@ +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn merge_in_between(list1: Option>, a: i32, b: i32, list2: Option>) -> Option> { + let mut first = Vec::new(); + let mut cur = list1; + while let Some(mut node) = cur { + cur = node.next.take(); + first.push(node); + } + let mut middle = Vec::new(); + let mut cur = list2; + while let Some(mut node) = cur { + cur = node.next.take(); + middle.push(node); + } + let suffix = first.split_off((b + 1) as usize); + first.truncate(a as usize); + let mut result = Vec::new(); + result.extend(first); + result.extend(middle); + result.extend(suffix); + let mut head = None; + for mut node in result.into_iter().rev() { + node.next = head; + head = Some(node); + } + head + } +} diff --git a/tests/1501-2000/1669. merge-in-between-linked-lists/sol.swift b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.swift new file mode 100644 index 00000000..aa0dda8e --- /dev/null +++ b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.swift @@ -0,0 +1,29 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public var val: Int + * public var next: ListNode? + * public init() { self.val = 0; self.next = nil; } + * public init(_ val: Int) { self.val = val; self.next = nil; } + * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } + * } + */ +class Solution { + func mergeInBetween(_ list1: ListNode?, _ a: Int, _ b: Int, _ list2: ListNode?) -> ListNode? { + var curr = list1 + for _ in 0..<(a-1) { + curr = curr?.next + } + let prev = curr + for _ in 0..<(b-a+2) { + curr = curr?.next + } + prev?.next = list2 + var tail = prev?.next + while tail?.next != nil { + tail = tail?.next + } + tail?.next = curr + return list1 + } +} diff --git a/tests/1501-2000/1669. merge-in-between-linked-lists/sol.ts b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.ts new file mode 100644 index 00000000..3c7a7c7d --- /dev/null +++ b/tests/1501-2000/1669. merge-in-between-linked-lists/sol.ts @@ -0,0 +1,34 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function mergeInBetween( + list1: ListNode | null, + a: number, + b: number, + list2: ListNode | null, +): ListNode | null { + let curr = list1; + for (let i = 0; i < a - 1; i++) { + curr = curr!.next; + } + const prev = curr; + for (let i = 0; i < b - a + 2; i++) { + curr = curr!.next; + } + prev!.next = list2; + let tail = prev!.next; + while (tail!.next !== null) { + tail = tail!.next; + } + tail!.next = curr; + return list1; +} diff --git a/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/manifest.yaml b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/manifest.yaml new file mode 100644 index 00000000..cb3f1801 --- /dev/null +++ b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/manifest.yaml @@ -0,0 +1,197 @@ +entry: + id: 1671 + title: "minimum-number-of-removals-to-make-mountain-array" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().minimumMountainRemovals({nums})" + rust: "Solution::minimum_mountain_removals({nums})" + python3: "Solution().minimumMountainRemovals({nums})" + python2: "Solution().minimumMountainRemovals({nums})" + ruby: "minimum_mountain_removals({nums})" + java: "new Solution().minimumMountainRemovals({nums})" + csharp: "new Solution().MinimumMountainRemovals({nums})" + kotlin: "Solution().minimumMountainRemovals({nums})" + go: "minimumMountainRemovals({nums})" + dart: "Solution().minimumMountainRemovals({nums})" + swift: "Solution().minimumMountainRemovals({nums})" + typescript: "minimumMountainRemovals({nums})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minimumMountainRemovals(nums, {result})" + checker: | + class Checker: + def minimumMountainRemovals(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + n = len(nums) + inc = [1] * n + dec = [1] * n + for i in range(n): + for j in range(i): + if nums[j] < nums[i]: + inc[i] = max(inc[i], inc[j] + 1) + for i in range(n - 1, -1, -1): + for j in range(n - 1, i, -1): + if nums[j] < nums[i]: + dec[i] = max(dec[i], dec[j] + 1) + best = 0 + for i in range(1, n - 1): + if inc[i] > 1 and dec[i] > 1: + best = max(best, inc[i] + dec[i] - 1) + return result == n - best + +seed: 1671 + +tests: + - name: example-one + in: + nums: [1, 3, 1] + out: 0 + - name: example-two + in: + nums: [2, 1, 1, 5, 6, 2, 3, 1] + out: 3 + - name: perfect-seven + in: + nums: [1, 2, 3, 4, 3, 2, 1] + out: 0 + - name: perfect-nine + in: + nums: [1, 2, 3, 4, 5, 4, 3, 2, 1] + out: 0 + - name: descending-prefix + in: + nums: [5, 4, 3, 2, 1, 2, 3] + out: 7 + - name: duplicate-prefix + in: + nums: [1, 1, 2, 3, 2, 1] + out: 1 + - name: duplicate-peak-side + in: + nums: [1, 2, 2, 3, 2, 1] + out: 1 + - name: leading-outlier + in: + nums: [10, 1, 2, 3, 4, 5, 4, 3, 2, 1] + out: 1 + - name: short-perfect + in: + nums: [1, 3, 5, 4, 2] + out: 0 + - name: wrong-middle + in: + nums: [1, 4, 2, 3, 1] + out: 1 + - name: low-left-outlier + in: + nums: [7, 1, 2, 3, 4, 3, 2] + out: 1 + - name: high-center + in: + nums: [1, 2, 10, 3, 4, 2, 1] + out: 1 + - name: late-peak + in: + nums: [1, 5, 4, 3, 2, 6, 1] + out: 1 + - name: two-candidate-peaks + in: + nums: [4, 1, 2, 3, 2, 5, 1] + out: 2 + - name: interrupted-ramp + in: + nums: [1, 2, 3, 2, 4, 3, 2, 1] + out: 1 + - name: two-mountains + in: + nums: [1, 2, 3, 4, 5, 1, 2, 3, 4, 2, 1] + out: 3 + - name: descending-then-rising + in: + nums: [9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3] + out: 11 + - name: small-zigzag + in: + nums: [1, 3, 2, 4, 3, 2, 1] + out: 1 + - name: high-middle-candidate + in: + nums: [1, 2, 4, 3, 5, 4, 3, 2, 1] + out: 1 + - name: uneven-descent + in: + nums: [1, 2, 3, 5, 4, 2, 3, 1] + out: 1 + - name: separated-rises + in: + nums: [2, 3, 4, 1, 2, 3, 4, 3, 2, 1] + out: 3 + - name: competing-peak + in: + nums: [1, 4, 3, 2, 5, 4, 3, 2] + out: 2 + - name: valley-before-mountain + in: + nums: [1, 2, 1, 2, 3, 4, 3, 2, 1] + out: 2 + - name: late-ramp + in: + nums: [1, 2, 3, 4, 3, 2, 5, 4, 3, 2, 1] + out: 2 + - name: six-element-mix + in: + nums: [1, 5, 3, 4, 2, 1] + out: 1 + - name: delayed-start + in: + nums: [3, 1, 2, 4, 3, 2, 1] + out: 1 + - name: alternate-peak + in: + nums: [1, 2, 3, 4, 2, 3, 1] + out: 1 + - name: double-zigzag + in: + nums: [1, 2, 3, 2, 1, 2, 3, 2, 1] + out: 4 + - name: descending-long + in: + nums: [1, 10, 9, 8, 7, 6, 5, 4, 3] + out: 0 + - name: billion-values + in: + nums: [1000000000, 1, 2, 3, 4, 999999999, 5, 4, 3, 2, 1] + out: 1 + - name: alternating-large + in: + nums: [1, 1000000000, 2, 999999999, 3, 999999998, 1] + out: 2 + - name: perfect-eleven + in: + nums: [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1] + out: 0 + - name: long-descending-ramp + in: + nums: [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3] + out: 13 + - name: powers-and-descent + in: + nums: [1, 2, 4, 8, 7, 6, 5, 4, 3, 2, 1] + out: 0 + - name: broad-mountain + in: + nums: [1, 3, 6, 10, 9, 8, 7, 5, 4, 2, 1] + out: 0 diff --git a/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.cpp b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.cpp new file mode 100644 index 00000000..e927dca8 --- /dev/null +++ b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int minimumMountainRemovals(vector& nums) { + int n = nums.size(); + vector lis(n, 1); + vector lds(n, 1); + + for (int i = 0; i < n; i++) { + for (int j = 0; j < i; j++) { + if (nums[i] > nums[j]) { + lis[i] = max(lis[i], lis[j] + 1); + } + } + } + + for (int i = n - 1; i >= 0; i--) { + for (int j = n - 1; j > i; j--) { + if (nums[i] > nums[j]) { + lds[i] = max(lds[i], lds[j] + 1); + } + } + } + + int maxLen = 0; + for (int i = 1; i < n - 1; i++) { + if (lis[i] > 1 && lds[i] > 1) { + maxLen = max(maxLen, lis[i] + lds[i] - 1); + } + } + + return n - maxLen; + } +}; diff --git a/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.cs b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.cs new file mode 100644 index 00000000..13ef7cb5 --- /dev/null +++ b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.cs @@ -0,0 +1,34 @@ +public class Solution { + public int MinimumMountainRemovals(int[] nums) { + int n = nums.Length; + int[] lis = new int[n]; + int[] lds = new int[n]; + Array.Fill(lis, 1); + Array.Fill(lds, 1); + + for (int i = 0; i < n; i++) { + for (int j = 0; j < i; j++) { + if (nums[i] > nums[j]) { + lis[i] = Math.Max(lis[i], lis[j] + 1); + } + } + } + + for (int i = n - 1; i >= 0; i--) { + for (int j = n - 1; j > i; j--) { + if (nums[i] > nums[j]) { + lds[i] = Math.Max(lds[i], lds[j] + 1); + } + } + } + + int maxLen = 0; + for (int i = 1; i < n - 1; i++) { + if (lis[i] > 1 && lds[i] > 1) { + maxLen = Math.Max(maxLen, lis[i] + lds[i] - 1); + } + } + + return n - maxLen; + } +} diff --git a/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.dart b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.dart new file mode 100644 index 00000000..2f5f2e5b --- /dev/null +++ b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.dart @@ -0,0 +1,39 @@ +class Solution { + int minimumMountainRemovals(List nums) { + int n = nums.length; + List lis = List.filled(n, 1); + List lds = List.filled(n, 1); + + for (int i = 0; i < n; i++) { + for (int j = 0; j < i; j++) { + if (nums[i] > nums[j]) { + if (lis[j] + 1 > lis[i]) { + lis[i] = lis[j] + 1; + } + } + } + } + + for (int i = n - 1; i >= 0; i--) { + for (int j = n - 1; j > i; j--) { + if (nums[i] > nums[j]) { + if (lds[j] + 1 > lds[i]) { + lds[i] = lds[j] + 1; + } + } + } + } + + int maxLen = 0; + for (int i = 1; i < n - 1; i++) { + if (lis[i] > 1 && lds[i] > 1) { + int len = lis[i] + lds[i] - 1; + if (len > maxLen) { + maxLen = len; + } + } + } + + return n - maxLen; + } +} diff --git a/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.go b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.go new file mode 100644 index 00000000..a311c9cf --- /dev/null +++ b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.go @@ -0,0 +1,40 @@ +func minimumMountainRemovals(nums []int) int { + n := len(nums) + lis := make([]int, n) + lds := make([]int, n) + for i := range lis { + lis[i] = 1 + lds[i] = 1 + } + + for i := 0; i < n; i++ { + for j := 0; j < i; j++ { + if nums[i] > nums[j] { + if lis[j] + 1 > lis[i] { + lis[i] = lis[j] + 1 + } + } + } + } + + for i := n - 1; i >= 0; i-- { + for j := n - 1; j > i; j-- { + if nums[i] > nums[j] { + if lds[j] + 1 > lds[i] { + lds[i] = lds[j] + 1 + } + } + } + } + + maxLen := 0 + for i := 1; i < n-1; i++ { + if lis[i] > 1 && lds[i] > 1 { + if lis[i] + lds[i] - 1 > maxLen { + maxLen = lis[i] + lds[i] - 1 + } + } + } + + return n - maxLen +} diff --git a/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.java b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.java new file mode 100644 index 00000000..1ab71992 --- /dev/null +++ b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.java @@ -0,0 +1,34 @@ +class Solution { + public int minimumMountainRemovals(int[] nums) { + int n = nums.length; + int[] lis = new int[n]; + int[] lds = new int[n]; + Arrays.fill(lis, 1); + Arrays.fill(lds, 1); + + for (int i = 0; i < n; i++) { + for (int j = 0; j < i; j++) { + if (nums[i] > nums[j]) { + lis[i] = Math.max(lis[i], lis[j] + 1); + } + } + } + + for (int i = n - 1; i >= 0; i--) { + for (int j = n - 1; j > i; j--) { + if (nums[i] > nums[j]) { + lds[i] = Math.max(lds[i], lds[j] + 1); + } + } + } + + int maxLen = 0; + for (int i = 1; i < n - 1; i++) { + if (lis[i] > 1 && lds[i] > 1) { + maxLen = Math.max(maxLen, lis[i] + lds[i] - 1); + } + } + + return n - maxLen; + } +} diff --git a/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.kt b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.kt new file mode 100644 index 00000000..84c9152d --- /dev/null +++ b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.kt @@ -0,0 +1,32 @@ +class Solution { + fun minimumMountainRemovals(nums: IntArray): Int { + val n = nums.size + val lis = IntArray(n) { 1 } + val lds = IntArray(n) { 1 } + + for (i in 0 until n) { + for (j in 0 until i) { + if (nums[i] > nums[j]) { + lis[i] = maxOf(lis[i], lis[j] + 1) + } + } + } + + for (i in n - 1 downTo 0) { + for (j in n - 1 downTo i + 1) { + if (nums[i] > nums[j]) { + lds[i] = maxOf(lds[i], lds[j] + 1) + } + } + } + + var maxLen = 0 + for (i in 1 until n - 1) { + if (lis[i] > 1 && lds[i] > 1) { + maxLen = maxOf(maxLen, lis[i] + lds[i] - 1) + } + } + + return n - maxLen + } +} diff --git a/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.py b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.py new file mode 100644 index 00000000..f11b9169 --- /dev/null +++ b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.py @@ -0,0 +1,26 @@ +class Solution: + def minimumMountainRemovals(self, nums: List[int]) -> int: + n = len(nums) + LIS = [1] * n + LDS = [1] * n + + # Compute LIS for each index + for i in range(n): + for j in range(i): + if nums[i] > nums[j]: + LIS[i] = max(LIS[i], LIS[j] + 1) + + # Compute LDS from each index + for i in range(n - 1, -1, -1): + for j in range(n - 1, i, -1): + if nums[i] > nums[j]: + LDS[i] = max(LDS[i], LDS[j] + 1) + + maxMountainLength = 0 + + # Find the maximum mountain length + for i in range(1, n - 1): + if LIS[i] > 1 and LDS[i] > 1: # Valid peak + maxMountainLength = max(maxMountainLength, LIS[i] + LDS[i] - 1) + + return n - maxMountainLength diff --git a/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.py2 b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.py2 new file mode 100644 index 00000000..a1164ee6 --- /dev/null +++ b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.py2 @@ -0,0 +1,26 @@ +class Solution(object): + def minimumMountainRemovals(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + n = len(nums) + LIS = [1] * n + LDS = [1] * n + + for i in range(n): + for j in range(i): + if nums[i] > nums[j]: + LIS[i] = max(LIS[i], LIS[j] + 1) + + for i in range(n - 1, -1, -1): + for j in range(n - 1, i, -1): + if nums[i] > nums[j]: + LDS[i] = max(LDS[i], LDS[j] + 1) + + maxMountainLength = 0 + for i in range(1, n - 1): + if LIS[i] > 1 and LDS[i] > 1: + maxMountainLength = max(maxMountainLength, LIS[i] + LDS[i] - 1) + + return n - maxMountainLength diff --git a/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.rb b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.rb new file mode 100644 index 00000000..2af1a443 --- /dev/null +++ b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.rb @@ -0,0 +1,32 @@ +# @param {Integer[]} nums +# @return {Integer} +def minimum_mountain_removals(nums) + n = nums.length + lis = Array.new(n, 1) + lds = Array.new(n, 1) + + (0...n).each do |i| + (0...i).each do |j| + if nums[i] > nums[j] + lis[i] = [lis[i], lis[j] + 1].max + end + end + end + + (0...n).reverse_each do |i| + (i+1...n).each do |j| + if nums[i] > nums[j] + lds[i] = [lds[i], lds[j] + 1].max + end + end + end + + max_len = 0 + (1...n-1).each do |i| + if lis[i] > 1 && lds[i] > 1 + max_len = [max_len, lis[i] + lds[i] - 1].max + end + end + + n - max_len +end diff --git a/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.rs b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.rs new file mode 100644 index 00000000..4d12de15 --- /dev/null +++ b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.rs @@ -0,0 +1,32 @@ +impl Solution { + pub fn minimum_mountain_removals(nums: Vec) -> i32 { + let n = nums.len(); + let mut lis = vec![1; n]; + let mut lds = vec![1; n]; + + for i in 0..n { + for j in 0..i { + if nums[i] > nums[j] { + lis[i] = lis[i].max(lis[j] + 1); + } + } + } + + for i in (0..n).rev() { + for j in ((i+1)..n).rev() { + if nums[i] > nums[j] { + lds[i] = lds[i].max(lds[j] + 1); + } + } + } + + let mut max_len = 0; + for i in 1..(n-1) { + if lis[i] > 1 && lds[i] > 1 { + max_len = max_len.max(lis[i] + lds[i] - 1); + } + } + + (n - max_len) as i32 + } +} diff --git a/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.swift b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.swift new file mode 100644 index 00000000..a40a8904 --- /dev/null +++ b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.swift @@ -0,0 +1,32 @@ +class Solution { + func minimumMountainRemovals(_ nums: [Int]) -> Int { + let n = nums.count + var lis = [Int](repeating: 1, count: n) + var lds = [Int](repeating: 1, count: n) + + for i in 0.. nums[j] { + lis[i] = max(lis[i], lis[j] + 1) + } + } + } + + for i in stride(from: n-1, through: 0, by: -1) { + for j in stride(from: n-1, through: i+1, by: -1) { + if nums[i] > nums[j] { + lds[i] = max(lds[i], lds[j] + 1) + } + } + } + + var maxLen = 0 + for i in 1..<(n-1) { + if lis[i] > 1 && lds[i] > 1 { + maxLen = max(maxLen, lis[i] + lds[i] - 1) + } + } + + return n - maxLen + } +} diff --git a/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.ts b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.ts new file mode 100644 index 00000000..1e104061 --- /dev/null +++ b/tests/1501-2000/1671. minimum-number-of-removals-to-make-mountain-array/sol.ts @@ -0,0 +1,30 @@ +function minimumMountainRemovals(nums: number[]): number { + const n = nums.length; + const lis = new Array(n).fill(1); + const lds = new Array(n).fill(1); + + for (let i = 0; i < n; i++) { + for (let j = 0; j < i; j++) { + if (nums[i] > nums[j]) { + lis[i] = Math.max(lis[i], lis[j] + 1); + } + } + } + + for (let i = n - 1; i >= 0; i--) { + for (let j = n - 1; j > i; j--) { + if (nums[i] > nums[j]) { + lds[i] = Math.max(lds[i], lds[j] + 1); + } + } + } + + let maxLen = 0; + for (let i = 1; i < n - 1; i++) { + if (lis[i] > 1 && lds[i] > 1) { + maxLen = Math.max(maxLen, lis[i] + lds[i] - 1); + } + } + + return n - maxLen; +} diff --git a/tests/1501-2000/1672. richest-customer-wealth/manifest.yaml b/tests/1501-2000/1672. richest-customer-wealth/manifest.yaml new file mode 100644 index 00000000..0a88d832 --- /dev/null +++ b/tests/1501-2000/1672. richest-customer-wealth/manifest.yaml @@ -0,0 +1,423 @@ +entry: + id: 1672 + title: richest-customer-wealth + params: + accounts: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().maximumWealth({accounts})" + rust: "Solution::maximum_wealth({accounts})" + python3: "Solution().maximumWealth({accounts})" + python2: "Solution().maximumWealth({accounts})" + ruby: "maximum_wealth({accounts})" + java: "new Solution().maximumWealth({accounts})" + csharp: "new Solution().MaximumWealth({accounts})" + kotlin: "Solution().maximumWealth({accounts})" + go: "maximumWealth({accounts})" + dart: "Solution().maximumWealth({accounts})" + swift: "Solution().maximumWealth({accounts})" + typescript: "maximumWealth({accounts})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maximumWealth(accounts, {result})" + checker: | + class Checker: + def maximumWealth(self, accounts, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not isinstance(accounts, list) or not accounts: + return False + if any(not isinstance(row, list) or not row for row in accounts): + return False + if any(any(not isinstance(value, int) or isinstance(value, bool) or value < 1 or value > 100 for value in row) for row in accounts): + return False + width = len(accounts[0]) + if any(len(row) != width for row in accounts): + return False + return result == max(sum(row) for row in accounts) + +seed: 1672 + +tests: + - name: example-balanced + in: + accounts: + - [1, 2, 3] + - [3, 2, 1] + out: 6 + - name: example-middle-richest + in: + accounts: + - [1, 5] + - [7, 3] + - [3, 5] + out: 10 + - name: example-three-banks + in: + accounts: + - [2, 8, 7] + - [7, 1, 3] + - [1, 9, 5] + out: 17 + - name: one-customer-one-bank + in: + accounts: + - [42] + out: 42 + - name: all-minimum + in: + accounts: + - [1, 1] + - [1, 1] + - [1, 1] + out: 2 + - name: all-maximum + in: + accounts: + - [100, 100, 100, 100] + - [100, 100, 100, 100] + out: 400 + - name: single-row-five + in: + accounts: + - [4, 8, 15, 16, 23] + out: 66 + - name: single-column + in: + accounts: + - [9] + - [1] + - [77] + - [34] + out: 77 + - name: negative-not-allowed-boundary + in: + accounts: + - [1, 100] + - [100, 1] + - [50, 50] + out: 101 + - name: unequal-wealth-close + in: + accounts: + - [10, 10, 10] + - [9, 10, 10] + - [10, 9, 10] + out: 30 + - name: largest-first + in: + accounts: + - [100, 99, 98] + - [1, 2, 3] + - [50, 50, 50] + out: 297 + - name: largest-last + in: + accounts: + - [1, 2, 3] + - [50, 50, 50] + - [100, 99, 98] + out: 297 + - name: tie-at-maximum + in: + accounts: + - [12, 4, 8] + - [1, 22, 1] + - [20, 2, 2] + out: 24 + - name: repeated-pattern + in: + accounts: + - [5, 10, 5, 10] + - [10, 5, 10, 5] + - [6, 6, 6, 6] + out: 30 + - name: varied-width-six + in: + accounts: + - [3, 14, 15, 9, 2, 6] + - [5, 3, 5, 8, 9, 7] + - [9, 3, 2, 3, 8, 4] + out: 49 + - name: two-customers-extremes + in: + accounts: + - [1, 1, 1, 1, 1, 1, 1, 1] + - [100, 100, 100, 100, 100, 100, 100, 100] + out: 800 + - name: sparse-looking-values + in: + accounts: + - [1, 100, 1, 100] + - [50, 50, 50, 50] + - [99, 1, 99, 1] + out: 202 + - name: four-by-four + in: + accounts: + - [1, 2, 3, 4] + - [4, 3, 2, 1] + - [10, 10, 10, 10] + - [9, 8, 7, 6] + out: 40 + - name: max-sum-nine + in: + accounts: + - [100, 100, 100, 100, 100, 100, 100, 100, 100] + - [99, 99, 99, 99, 99, 99, 99, 99, 99] + out: 900 + - name: twenty-banks + in: + accounts: + - [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + ] + - [ + 20, + 19, + 18, + 17, + 16, + 15, + 14, + 13, + 12, + 11, + 10, + 9, + 8, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + ] + - [100, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 210 + - name: five-by-five-balanced + in: + accounts: + - [5, 5, 5, 5, 5] + - [6, 6, 6, 6, 6] + - [7, 7, 7, 7, 7] + - [8, 8, 8, 8, 8] + - [9, 9, 9, 9, 9] + out: 45 + - name: alternating-extremes + in: + accounts: + - [100, 1, 100, 1, 100] + - [1, 100, 1, 100, 1] + - [50, 50, 50, 50, 50] + out: 302 + - name: twelve-customers + in: + accounts: + - [1, 2, 3] + - [2, 3, 4] + - [3, 4, 5] + - [4, 5, 6] + - [5, 6, 7] + - [6, 7, 8] + - [7, 8, 9] + - [8, 9, 10] + - [9, 10, 11] + - [10, 11, 12] + - [11, 12, 13] + - [12, 13, 14] + out: 39 + - name: high-values-mixed + in: + accounts: + - [98, 97, 96, 95] + - [100, 100, 1, 1] + - [75, 75, 75, 75] + - [99, 98, 97, 96] + out: 390 + - name: one-hundred-banks + in: + accounts: + - [100, 100, 100, 100, 100, 100, 100, 100, 100, 100] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [99, 99, 99, 99, 99, 99, 99, 99, 99, 99] + out: 1000 + - name: seven-by-seven + in: + accounts: + - [1, 4, 9, 16, 25, 36, 49] + - [49, 36, 25, 16, 9, 4, 1] + - [7, 7, 7, 7, 7, 7, 7] + - [8, 8, 8, 8, 8, 8, 8] + out: 140 + - name: two-row-near-limit + in: + accounts: + - [100, 100, 100, 99, 99, 99, 98, 98, 98, 97] + - [100, 100, 100, 100, 100, 100, 100, 100, 100, 100] + out: 1000 + - name: equal-wealth-many + in: + accounts: + - [2, 4, 6, 8] + - [8, 6, 4, 2] + - [5, 5, 5, 5] + - [1, 9, 7, 3] + out: 20 + - name: three-by-eight-boundary + in: + accounts: + - [1, 1, 1, 1, 1, 1, 1, 1] + - [10, 10, 10, 10, 10, 10, 10, 10] + - [9, 9, 9, 9, 9, 9, 9, 9] + out: 80 + - name: forty-nine-customers + in: + accounts: + - [1, 1] + - [2, 2] + - [3, 3] + - [4, 4] + - [5, 5] + - [6, 6] + - [7, 7] + - [8, 8] + - [9, 9] + - [10, 10] + - [11, 11] + - [12, 12] + - [13, 13] + - [14, 14] + - [15, 15] + - [16, 16] + - [17, 17] + - [18, 18] + - [19, 19] + - [20, 20] + - [21, 21] + - [22, 22] + - [23, 23] + - [24, 24] + - [25, 25] + - [26, 26] + - [27, 27] + - [28, 28] + - [29, 29] + - [30, 30] + - [31, 31] + - [32, 32] + - [33, 33] + - [34, 34] + - [35, 35] + - [36, 36] + - [37, 37] + - [38, 38] + - [39, 39] + - [40, 40] + - [41, 41] + - [42, 42] + - [43, 43] + - [44, 44] + - [45, 45] + - [46, 46] + - [47, 47] + - [48, 48] + - [49, 49] + out: 98 + - name: generated-one-by-one + in: + accounts: + gen: "array" + len: 1 + of: + gen: "array" + len: 1 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + - name: generated-single-customer + in: + accounts: + gen: "array" + len: 1 + of: + gen: "array" + len: 50 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + - name: generated-single-bank + in: + accounts: + gen: "array" + len: 50 + of: + gen: "array" + len: 1 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + - name: generated-max-grid + in: + accounts: + gen: "array" + len: 50 + of: + gen: "array" + len: 50 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + - name: generated-wide-grid + in: + accounts: + gen: "array" + len: 37 + of: + gen: "array" + len: 23 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" diff --git a/tests/1501-2000/1672. richest-customer-wealth/sol.cpp b/tests/1501-2000/1672. richest-customer-wealth/sol.cpp new file mode 100644 index 00000000..3fbbaf46 --- /dev/null +++ b/tests/1501-2000/1672. richest-customer-wealth/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int maximumWealth(vector>& accounts) { + int rich = 0; + for (auto& i : accounts) { + int sum = 0; + for (int j : i) { + sum += j; + } + rich = max(rich, sum); + } + return rich; + } +}; diff --git a/tests/1501-2000/1672. richest-customer-wealth/sol.cs b/tests/1501-2000/1672. richest-customer-wealth/sol.cs new file mode 100644 index 00000000..cb7be860 --- /dev/null +++ b/tests/1501-2000/1672. richest-customer-wealth/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public int MaximumWealth(int[][] accounts) { + int rich = 0; + foreach (var i in accounts) { + int sum = 0; + foreach (int j in i) { + sum += j; + } + rich = Math.Max(rich, sum); + } + return rich; + } +} diff --git a/tests/1501-2000/1672. richest-customer-wealth/sol.dart b/tests/1501-2000/1672. richest-customer-wealth/sol.dart new file mode 100644 index 00000000..2fe0e9c8 --- /dev/null +++ b/tests/1501-2000/1672. richest-customer-wealth/sol.dart @@ -0,0 +1,10 @@ +class Solution { + int maximumWealth(List> accounts) { + int rich = 0; + for (var i in accounts) { + int sum = i.reduce((a, b) => a + b); + if (sum > rich) rich = sum; + } + return rich; + } +} diff --git a/tests/1501-2000/1672. richest-customer-wealth/sol.go b/tests/1501-2000/1672. richest-customer-wealth/sol.go new file mode 100644 index 00000000..c8c3bbf5 --- /dev/null +++ b/tests/1501-2000/1672. richest-customer-wealth/sol.go @@ -0,0 +1,13 @@ +func maximumWealth(accounts [][]int) int { + rich := 0 + for _, i := range accounts { + sum := 0 + for _, j := range i { + sum += j + } + if sum > rich { + rich = sum + } + } + return rich +} diff --git a/tests/1501-2000/1672. richest-customer-wealth/sol.java b/tests/1501-2000/1672. richest-customer-wealth/sol.java new file mode 100644 index 00000000..da1bc571 --- /dev/null +++ b/tests/1501-2000/1672. richest-customer-wealth/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int maximumWealth(int[][] accounts) { + int rich = 0; + for (int[] i : accounts) { + int sum = 0; + for (int j : i) { + sum += j; + } + rich = Math.max(rich, sum); + } + return rich; + } +} diff --git a/tests/1501-2000/1672. richest-customer-wealth/sol.kt b/tests/1501-2000/1672. richest-customer-wealth/sol.kt new file mode 100644 index 00000000..5f0f5477 --- /dev/null +++ b/tests/1501-2000/1672. richest-customer-wealth/sol.kt @@ -0,0 +1,9 @@ +class Solution { + fun maximumWealth(accounts: Array): Int { + var rich = 0 + for (i in accounts) { + rich = maxOf(rich, i.sum()) + } + return rich + } +} diff --git a/tests/1501-2000/1672. richest-customer-wealth/sol.py b/tests/1501-2000/1672. richest-customer-wealth/sol.py new file mode 100644 index 00000000..2b17ab1b --- /dev/null +++ b/tests/1501-2000/1672. richest-customer-wealth/sol.py @@ -0,0 +1,6 @@ +class Solution(object): + def maximumWealth(self, accounts: List[List[int]]) -> int: + rich = 0 + for i in accounts: + rich = max(rich, sum(i)) + return rich diff --git a/tests/1501-2000/1672. richest-customer-wealth/sol.py2 b/tests/1501-2000/1672. richest-customer-wealth/sol.py2 new file mode 100644 index 00000000..e77584f0 --- /dev/null +++ b/tests/1501-2000/1672. richest-customer-wealth/sol.py2 @@ -0,0 +1,10 @@ +class Solution(object): + def maximumWealth(self, accounts): + """ + :type accounts: List[List[int]] + :rtype: int + """ + rich = 0 + for i in accounts: + rich = max(rich, sum(i)) + return rich diff --git a/tests/1501-2000/1672. richest-customer-wealth/sol.rb b/tests/1501-2000/1672. richest-customer-wealth/sol.rb new file mode 100644 index 00000000..77d91839 --- /dev/null +++ b/tests/1501-2000/1672. richest-customer-wealth/sol.rb @@ -0,0 +1,9 @@ +# @param {Integer[][]} accounts +# @return {Integer} +def maximum_wealth(accounts) + rich = 0 + accounts.each do |i| + rich = [rich, i.sum].max + end + rich +end diff --git a/tests/1501-2000/1672. richest-customer-wealth/sol.rs b/tests/1501-2000/1672. richest-customer-wealth/sol.rs new file mode 100644 index 00000000..d1138a4e --- /dev/null +++ b/tests/1501-2000/1672. richest-customer-wealth/sol.rs @@ -0,0 +1,9 @@ +impl Solution { + pub fn maximum_wealth(accounts: Vec>) -> i32 { + let mut rich = 0; + for i in accounts { + rich = rich.max(i.iter().sum()); + } + rich + } +} diff --git a/tests/1501-2000/1672. richest-customer-wealth/sol.swift b/tests/1501-2000/1672. richest-customer-wealth/sol.swift new file mode 100644 index 00000000..0a01f1b2 --- /dev/null +++ b/tests/1501-2000/1672. richest-customer-wealth/sol.swift @@ -0,0 +1,9 @@ +class Solution { + func maximumWealth(_ accounts: [[Int]]) -> Int { + var rich = 0 + for i in accounts { + rich = max(rich, i.reduce(0, +)) + } + return rich + } +} diff --git a/tests/1501-2000/1672. richest-customer-wealth/sol.ts b/tests/1501-2000/1672. richest-customer-wealth/sol.ts new file mode 100644 index 00000000..2b324e56 --- /dev/null +++ b/tests/1501-2000/1672. richest-customer-wealth/sol.ts @@ -0,0 +1,10 @@ +function maximumWealth(accounts: number[][]): number { + let rich = 0; + for (let i of accounts) { + rich = Math.max( + rich, + i.reduce((a, b) => a + b, 0), + ); + } + return rich; +} diff --git a/tests/1501-2000/1673. find-the-most-competitive-subsequence/manifest.yaml b/tests/1501-2000/1673. find-the-most-competitive-subsequence/manifest.yaml new file mode 100644 index 00000000..f5fd7dbc --- /dev/null +++ b/tests/1501-2000/1673. find-the-most-competitive-subsequence/manifest.yaml @@ -0,0 +1,321 @@ +entry: + id: 1673 + title: "find-the-most-competitive-subsequence" + params: + nums: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().mostCompetitive({nums}, {k})" + rust: "Solution::most_competitive({nums}, {k})" + python3: "Solution().mostCompetitive({nums}, {k})" + python2: "Solution().mostCompetitive({nums}, {k})" + ruby: "most_competitive({nums}, {k})" + java: "new Solution().mostCompetitive({nums}, {k})" + csharp: "new Solution().MostCompetitive({nums}, {k})" + kotlin: "Solution().mostCompetitive({nums}, {k})" + go: "mostCompetitive({nums}, {k})" + dart: "Solution().mostCompetitive({nums}, {k})" + swift: "Solution().mostCompetitive({nums}, {k})" + typescript: "mostCompetitive({nums}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().mostCompetitive(nums, k, {result})" + checker: | + class Checker: + def mostCompetitive(self, nums, k, result): + if not isinstance(result, list) or len(result) != k: + return False + stack = [] + n = len(nums) + for i, value in enumerate(nums): + while stack and stack[-1] > value and n - i - 1 >= k - len(stack): + stack.pop() + stack.append(value) + return result == stack[:k] + +seed: 1673 + +tests: + - name: example-one + in: + nums: [3, 5, 2, 6] + k: 2 + out: [2, 6] + judge: + type: "exact" + - name: example-two + in: + nums: [2, 4, 3, 3, 5, 4, 9, 6] + k: 4 + out: [2, 3, 3, 4] + judge: + type: "exact" + - name: keep-all + in: + nums: [1, 2, 3, 4] + k: 4 + out: [1, 2, 3, 4] + judge: + type: "exact" + - name: one-element + in: + nums: [9] + k: 1 + out: [9] + judge: + type: "exact" + - name: choose-global-minimum + in: + nums: [8, 7, 6, 5, 4] + k: 1 + out: [4] + judge: + type: "exact" + - name: descending-half + in: + nums: [9, 8, 7, 6, 5, 4] + k: 3 + out: [6, 5, 4] + judge: + type: "exact" + - name: ascending + in: + nums: [0, 1, 2, 3, 4, 5] + k: 3 + out: [0, 1, 2] + judge: + type: "exact" + - name: duplicates + in: + nums: [2, 2, 1, 2, 1, 2] + k: 4 + out: [1, 2, 1, 2] + judge: + type: "exact" + - name: zeros + in: + nums: [0, 0, 0, 1, 0] + k: 3 + out: [0, 0, 0] + judge: + type: "exact" + - name: late-drop + in: + nums: [4, 5, 6, 1, 2, 3] + k: 3 + out: [1, 2, 3] + judge: + type: "exact" + - name: early-drop-limited + in: + nums: [1, 9, 8, 7, 6] + k: 4 + out: [1, 8, 7, 6] + judge: + type: "exact" + - name: alternating + in: + nums: [5, 1, 5, 1, 5, 1, 5] + k: 4 + out: [1, 1, 1, 5] + judge: + type: "exact" + - name: equal-boundary + in: + nums: [3, 1, 1, 1, 2] + k: 3 + out: [1, 1, 1] + judge: + type: "exact" + - name: large-values + in: + nums: [1000000000, 999999999, 1, 999999998, 0] + k: 2 + out: [1, 0] + judge: + type: "exact" + - name: negative-not-allowed-boundary + in: + nums: [0, 1000000000, 0, 1000000000] + k: 2 + out: [0, 0] + judge: + type: "exact" + - name: k-near-n + in: + nums: [5, 1, 4, 2, 3] + k: 4 + out: [1, 4, 2, 3] + judge: + type: "exact" + - name: first-minimum + in: + nums: [1, 5, 4, 3, 2] + k: 2 + out: [1, 2] + judge: + type: "exact" + - name: min-at-cutoff + in: + nums: [4, 3, 2, 1, 0] + k: 4 + out: [3, 2, 1, 0] + judge: + type: "exact" + - name: repeated-valleys + in: + nums: [6, 2, 5, 2, 4, 2, 3] + k: 4 + out: [2, 2, 2, 3] + judge: + type: "exact" + - name: all-max + in: + nums: [1000000000, 1000000000, 1000000000] + k: 2 + out: [1000000000, 1000000000] + judge: + type: "exact" + - name: mixed-small + in: + nums: [7, 3, 9, 2, 8, 1, 6] + k: 5 + out: [3, 2, 8, 1, 6] + judge: + type: "exact" + - name: isolated-zero + in: + nums: [9, 8, 7, 0, 6, 5] + k: 2 + out: [0, 5] + judge: + type: "exact" + - name: zero-k-choice + in: + nums: [5, 0, 4, 0, 3] + k: 1 + out: [0] + judge: + type: "exact" + - name: preserve-prefix + in: + nums: [1, 2, 9, 0, 8, 7] + k: 4 + out: [1, 0, 8, 7] + judge: + type: "exact" + - name: last-element-required + in: + nums: [2, 3, 1, 4] + k: 3 + out: [2, 1, 4] + judge: + type: "exact" + - name: two-elements + in: + nums: [2, 1] + k: 1 + out: [1] + judge: + type: "exact" + - name: tie-order + in: + nums: [2, 1, 1, 2, 1] + k: 3 + out: [1, 1, 1] + judge: + type: "exact" + - name: plateau + in: + nums: [4, 4, 3, 3, 2, 2] + k: 3 + out: [3, 2, 2] + judge: + type: "exact" + - name: bounded-drop + in: + nums: [3, 2, 1, 4, 0, 5] + k: 4 + out: [1, 4, 0, 5] + judge: + type: "exact" + - name: large-static + in: + nums: [1000000000, 1, 999999999, 2, 999999998, 3, 0, 4, 5, 6] + k: 5 + out: [1, 0, 4, 5, 6] + judge: + type: "exact" + - name: generated-random-100k-k1 + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 0 + max: 1000000000 + distinct: false + elemType: "int" + k: 1 + - name: generated-random-100k-k50k + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 0 + max: 1000000000 + distinct: false + elemType: "int" + k: 50000 + - name: generated-small-values + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 0 + max: 3 + distinct: false + elemType: "int" + k: 25000 + - name: generated-descending-range + in: + nums: + gen: "array" + len: 75000 + of: + gen: "int" + min: 0 + max: 1000000000 + distinct: false + elemType: "int" + sorted: true + k: 37500 + - name: generated-large-k-near-n + in: + nums: + gen: "array" + len: 60000 + of: + gen: "int" + min: 0 + max: 1000000000 + distinct: false + elemType: "int" + k: 59999 diff --git a/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.cpp b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.cpp new file mode 100644 index 00000000..6f1f1d3c --- /dev/null +++ b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + vector mostCompetitive(vector& nums, int k) { + vector stack; + int n = nums.size(); + for (int i = 0; i < n; i++) { + while (!stack.empty() && stack.back() > nums[i]) { + if (n - 1 - i >= k - (int)stack.size()) { + stack.pop_back(); + } else { + break; + } + } + stack.push_back(nums[i]); + } + return vector(stack.begin(), stack.begin() + k); + } +}; diff --git a/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.cs b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.cs new file mode 100644 index 00000000..8b9d5caa --- /dev/null +++ b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.cs @@ -0,0 +1,17 @@ +public class Solution { + public int[] MostCompetitive(int[] nums, int k) { + var stack = new List(); + int n = nums.Length; + for (int i = 0; i < n; i++) { + while (stack.Count > 0 && stack[stack.Count - 1] > nums[i]) { + if (n - 1 - i >= k - stack.Count) { + stack.RemoveAt(stack.Count - 1); + } else { + break; + } + } + stack.Add(nums[i]); + } + return stack.Take(k).ToArray(); + } +} diff --git a/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.dart b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.dart new file mode 100644 index 00000000..ecad8346 --- /dev/null +++ b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.dart @@ -0,0 +1,17 @@ +class Solution { + List mostCompetitive(List nums, int k) { + List stack = []; + int n = nums.length; + for (int i = 0; i < n; i++) { + while (stack.isNotEmpty && stack.last > nums[i]) { + if (n - 1 - i >= k - stack.length) { + stack.removeLast(); + } else { + break; + } + } + stack.add(nums[i]); + } + return stack.sublist(0, k); + } +} diff --git a/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.go b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.go new file mode 100644 index 00000000..25628b71 --- /dev/null +++ b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.go @@ -0,0 +1,15 @@ +func mostCompetitive(nums []int, k int) []int { + stack := make([]int, 0, k) + n := len(nums) + for i := 0; i < n; i++ { + for len(stack) > 0 && stack[len(stack)-1] > nums[i] { + if n-1-i >= k-len(stack) { + stack = stack[:len(stack)-1] + } else { + break + } + } + stack = append(stack, nums[i]) + } + return stack[:k] +} diff --git a/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.java b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.java new file mode 100644 index 00000000..ad83a97d --- /dev/null +++ b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.java @@ -0,0 +1,21 @@ +class Solution { + public int[] mostCompetitive(int[] nums, int k) { + Deque stack = new ArrayDeque<>(); + int n = nums.length; + for (int i = 0; i < n; i++) { + while (!stack.isEmpty() && stack.peekLast() > nums[i]) { + if (n - 1 - i >= k - stack.size()) { + stack.pollLast(); + } else { + break; + } + } + stack.addLast(nums[i]); + } + int[] res = new int[k]; + for (int i = 0; i < k; i++) { + res[i] = stack.pollFirst(); + } + return res; + } +} diff --git a/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.kt b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.kt new file mode 100644 index 00000000..0b7f47ed --- /dev/null +++ b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.kt @@ -0,0 +1,17 @@ +class Solution { + fun mostCompetitive(nums: IntArray, k: Int): IntArray { + val stack = mutableListOf() + val n = nums.size + for (i in 0 until n) { + while (stack.isNotEmpty() && stack.last() > nums[i]) { + if (n - 1 - i >= k - stack.size) { + stack.removeAt(stack.size - 1) + } else { + break + } + } + stack.add(nums[i]) + } + return stack.take(k).toIntArray() + } +} diff --git a/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.py b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.py new file mode 100644 index 00000000..094ab5a5 --- /dev/null +++ b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.py @@ -0,0 +1,15 @@ +class Solution: + def mostCompetitive(self, nums: List[int], k: int) -> List[int]: + # lexographically smallest subsequence of size k + stack = [] + n = len(nums) + for i in range(n): + while len(stack) and stack[-1] > nums[i]: + # pop only if future suffices + if (n - 1 - i) >= k - len(stack): + stack.pop() + else: + break + stack.append(nums[i]) + # print(stack[:k]) + return stack[:k] diff --git a/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.py2 b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.py2 new file mode 100644 index 00000000..6d81240b --- /dev/null +++ b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.py2 @@ -0,0 +1,17 @@ +class Solution(object): + def mostCompetitive(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: List[int] + """ + stack = [] + n = len(nums) + for i in range(n): + while len(stack) and stack[-1] > nums[i]: + if (n - 1 - i) >= k - len(stack): + stack.pop() + else: + break + stack.append(nums[i]) + return stack[:k] diff --git a/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.rb b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.rb new file mode 100644 index 00000000..5c02fe78 --- /dev/null +++ b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.rb @@ -0,0 +1,18 @@ +# @param {Integer[]} nums +# @param {Integer} k +# @return {Integer[]} +def most_competitive(nums, k) + stack = [] + n = nums.length + (0...n).each do |i| + while !stack.empty? && stack[-1] > nums[i] + if (n - 1 - i) >= k - stack.length + stack.pop + else + break + end + end + stack << nums[i] + end + stack[0...k] +end diff --git a/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.rs b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.rs new file mode 100644 index 00000000..2900d4a8 --- /dev/null +++ b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn most_competitive(nums: Vec, k: i32) -> Vec { + let k = k as usize; + let mut stack: Vec = Vec::with_capacity(k); + let n = nums.len(); + for (i, &num) in nums.iter().enumerate() { + while let Some(&top) = stack.last() { + if top > num && stack.len() + (n - i) > k { + stack.pop(); + } else { + break; + } + } + stack.push(num); + } + stack.truncate(k); + stack + } +} diff --git a/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.swift b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.swift new file mode 100644 index 00000000..3389c0e5 --- /dev/null +++ b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.swift @@ -0,0 +1,17 @@ +class Solution { + func mostCompetitive(_ nums: [Int], _ k: Int) -> [Int] { + var stack: [Int] = [] + let n = nums.count + for i in 0.. nums[i] { + if n - 1 - i >= k - stack.count { + stack.removeLast() + } else { + break + } + } + stack.append(nums[i]) + } + return Array(stack.prefix(k)) + } +} diff --git a/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.ts b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.ts new file mode 100644 index 00000000..12124c29 --- /dev/null +++ b/tests/1501-2000/1673. find-the-most-competitive-subsequence/sol.ts @@ -0,0 +1,15 @@ +function mostCompetitive(nums: number[], k: number): number[] { + const stack: number[] = []; + const n = nums.length; + for (let i = 0; i < n; i++) { + while (stack.length > 0 && stack[stack.length - 1] > nums[i]) { + if (n - 1 - i >= k - stack.length) { + stack.pop(); + } else { + break; + } + } + stack.push(nums[i]); + } + return stack.slice(0, k); +} diff --git a/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/manifest.yaml b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/manifest.yaml new file mode 100644 index 00000000..98153762 --- /dev/null +++ b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/manifest.yaml @@ -0,0 +1,316 @@ +entry: + id: 1674 + title: "minimum-moves-to-make-array-complementary" + params: + nums: + type: array + items: + type: int + limit: + type: int + call: + cpp: "Solution().minMoves({nums}, {limit})" + rust: "Solution::min_moves({nums}, {limit})" + python3: "Solution().minMoves({nums}, {limit})" + python2: "Solution().minMoves({nums}, {limit})" + ruby: "min_moves({nums}, {limit})" + java: "new Solution().minMoves({nums}, {limit})" + csharp: "new Solution().MinMoves({nums}, {limit})" + kotlin: "Solution().minMoves({nums}, {limit})" + go: "minMoves({nums}, {limit})" + dart: "Solution().minMoves({nums}, {limit})" + swift: "Solution().minMoves({nums}, {limit})" + typescript: "minMoves({nums}, {limit})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minMoves(nums, limit, {result})" + checker: | + class Checker: + def minMoves(self, nums, limit, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + diff = [0] * (2 * limit + 2) + for i in range(len(nums) // 2): + a = nums[i] + b = nums[-1 - i] + diff[2] += 2 + diff[2 * limit + 1] -= 2 + diff[min(a, b) + 1] -= 1 + diff[max(a, b) + limit + 1] += 1 + diff[a + b] -= 1 + diff[a + b + 1] += 1 + cur = 0 + expected = len(nums) + for s in range(2, 2 * limit + 1): + cur += diff[s] + expected = min(expected, cur) + return result == expected + +seed: 1674 + +tests: + - name: example-one + in: + nums: [1, 2, 4, 3] + limit: 4 + out: 1 + - name: example-two + in: + nums: [1, 2, 2, 1] + limit: 2 + out: 2 + - name: example-three + in: + nums: [1, 2, 1, 2] + limit: 2 + out: 0 + - name: two-equal + in: + nums: [5, 5] + limit: 5 + out: 0 + - name: two-extremes + in: + nums: [1, 10] + limit: 10 + out: 0 + - name: two-low + in: + nums: [1, 1] + limit: 10 + out: 0 + - name: two-high + in: + nums: [10, 10] + limit: 10 + out: 0 + - name: two-different-limit-two + in: + nums: [1, 2] + limit: 2 + out: 0 + - name: four-already + in: + nums: [1, 3, 3, 1] + limit: 3 + out: 2 + - name: four-mixed + in: + nums: [1, 1, 4, 4] + limit: 4 + out: 0 + - name: four-two-sums + in: + nums: [1, 4, 2, 3] + limit: 4 + out: 1 + - name: four-all-low + in: + nums: [1, 1, 1, 1] + limit: 4 + out: 0 + - name: four-opposite + in: + nums: [1, 4, 4, 1] + limit: 4 + out: 2 + - name: six-already + in: + nums: [1, 2, 3, 3, 2, 1] + limit: 3 + out: 2 + - name: six-varied + in: + nums: [1, 1, 2, 3, 4, 4] + limit: 4 + out: 0 + - name: six-conflicting + in: + nums: [1, 2, 1, 4, 3, 4] + limit: 4 + out: 0 + - name: eight-small + in: + nums: [1, 1, 1, 2, 2, 1, 1, 1] + limit: 2 + out: 2 + - name: eight-balanced + in: + nums: [1, 2, 3, 4, 4, 3, 2, 1] + limit: 4 + out: 4 + - name: eight-repeated + in: + nums: [2, 2, 2, 2, 3, 3, 3, 3] + limit: 3 + out: 0 + - name: ten-boundary + in: + nums: [1, 10, 1, 10, 10, 1, 10, 1, 10, 1] + limit: 10 + out: 4 + - name: ten-mixed + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + limit: 10 + out: 0 + - name: ten-ones + in: + nums: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + limit: 10 + out: 0 + - name: twelve-low-limit + in: + nums: [1, 2, 1, 2, 2, 1, 2, 1, 2, 1, 1, 2] + limit: 2 + out: 2 + - name: twelve-varied + in: + nums: [1, 6, 2, 5, 3, 4, 4, 3, 5, 2, 6, 1] + limit: 6 + out: 6 + - name: twenty-three + in: + nums: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 12, + 11, + 10, + 9, + 8, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + ] + limit: 12 + out: 12 + - name: twenty-four-conflict + in: + nums: + [ + 1, + 1, + 1, + 1, + 1, + 1, + 12, + 12, + 12, + 12, + 12, + 12, + 1, + 1, + 1, + 1, + 1, + 1, + 12, + 12, + 12, + 12, + 12, + 12, + ] + limit: 12 + out: 0 + - name: max-values-small-n + in: + nums: [100000, 99999] + limit: 100000 + out: 0 + - name: max-limit-four + in: + nums: [99999, 1, 50000, 100000] + limit: 100000 + out: 2 + - name: large-regular + in: + nums: [1, 100000, 1, 100000, 1, 100000, 100000, 1, 100000, 1, 100000, 1] + limit: 100000 + out: 6 + - name: large-noncomplementary + in: + nums: [1, 1, 1, 1, 100000, 100000, 100000, 100000] + limit: 100000 + out: 0 + - name: generated-small + in: + nums: + gen: "array" + len: 20 + of: + gen: "int" + min: 1 + max: 20 + elemType: "int" + limit: 20 + - name: generated-medium + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 50 + elemType: "int" + limit: 50 + - name: generated-large-one + in: + nums: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + limit: 100000 + - name: generated-large-two + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + limit: 100000 + - name: generated-large-three + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + limit: 100000 diff --git a/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.cpp b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.cpp new file mode 100644 index 00000000..679e02a6 --- /dev/null +++ b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int minMoves(vector& nums, int limit) { + int n = nums.size(); + vector diff(2 * limit + 2, 0); + + for (int i = 0; i < n / 2; i++) { + int a = nums[i]; + int b = nums[n - 1 - i]; + int low = min(a, b) + 1; + int high = max(a, b) + limit; + int total = a + b; + + diff[2] += 2; + diff[2 * limit + 1] -= 2; + + diff[low] -= 1; + diff[high + 1] += 1; + + diff[total] -= 1; + diff[total + 1] += 1; + } + + int ans = INT_MAX; + int moves = 0; + for (int target = 2; target <= 2 * limit; target++) { + moves += diff[target]; + ans = min(ans, moves); + } + + return ans; + } +}; diff --git a/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.cs b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.cs new file mode 100644 index 00000000..2b2e9199 --- /dev/null +++ b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.cs @@ -0,0 +1,32 @@ +public class Solution { + public int MinMoves(int[] nums, int limit) { + int n = nums.Length; + int[] diff = new int[2 * limit + 2]; + + for (int i = 0; i < n / 2; i++) { + int a = nums[i]; + int b = nums[n - 1 - i]; + int low = Math.Min(a, b) + 1; + int high = Math.Max(a, b) + limit; + int total = a + b; + + diff[2] += 2; + diff[2 * limit + 1] -= 2; + + diff[low] -= 1; + diff[high + 1] += 1; + + diff[total] -= 1; + diff[total + 1] += 1; + } + + int ans = int.MaxValue; + int moves = 0; + for (int target = 2; target <= 2 * limit; target++) { + moves += diff[target]; + ans = Math.Min(ans, moves); + } + + return ans; + } +} diff --git a/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.dart b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.dart new file mode 100644 index 00000000..63da3b99 --- /dev/null +++ b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.dart @@ -0,0 +1,32 @@ +class Solution { + int minMoves(List nums, int limit) { + int n = nums.length; + List diff = List.filled(2 * limit + 2, 0); + + for (int i = 0; i < n ~/ 2; i++) { + int a = nums[i]; + int b = nums[n - 1 - i]; + int low = (a < b ? a : b) + 1; + int high = (a > b ? a : b) + limit; + int total = a + b; + + diff[2] += 2; + diff[2 * limit + 1] -= 2; + + diff[low] -= 1; + diff[high + 1] += 1; + + diff[total] -= 1; + diff[total + 1] += 1; + } + + int ans = 1 << 31 - 1; // MaxInt + int moves = 0; + for (int target = 2; target <= 2 * limit; target++) { + moves += diff[target]; + if (moves < ans) ans = moves; + } + + return ans; + } +} diff --git a/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.go b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.go new file mode 100644 index 00000000..b61ee75d --- /dev/null +++ b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.go @@ -0,0 +1,46 @@ +func minMoves(nums []int, limit int) int { + n := len(nums) + diff := make([]int, 2*limit+2) + + for i := 0; i < n/2; i++ { + a := nums[i] + b := nums[n-1-i] + low := min(a, b) + 1 + high := max(a, b) + limit + total := a + b + + diff[2] += 2 + diff[2*limit+1] -= 2 + + diff[low] -= 1 + diff[high+1] += 1 + + diff[total] -= 1 + diff[total+1] += 1 + } + + ans := int(^uint(0) >> 1) // MaxInt + moves := 0 + for target := 2; target <= 2*limit; target++ { + moves += diff[target] + if moves < ans { + ans = moves + } + } + + return ans +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} diff --git a/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.java b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.java new file mode 100644 index 00000000..1741cebf --- /dev/null +++ b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.java @@ -0,0 +1,32 @@ +class Solution { + public int minMoves(int[] nums, int limit) { + int n = nums.length; + int[] diff = new int[2 * limit + 2]; + + for (int i = 0; i < n / 2; i++) { + int a = nums[i]; + int b = nums[n - 1 - i]; + int low = Math.min(a, b) + 1; + int high = Math.max(a, b) + limit; + int total = a + b; + + diff[2] += 2; + diff[2 * limit + 1] -= 2; + + diff[low] -= 1; + diff[high + 1] += 1; + + diff[total] -= 1; + diff[total + 1] += 1; + } + + int ans = Integer.MAX_VALUE; + int moves = 0; + for (int target = 2; target <= 2 * limit; target++) { + moves += diff[target]; + ans = Math.min(ans, moves); + } + + return ans; + } +} diff --git a/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.kt b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.kt new file mode 100644 index 00000000..b1682ddb --- /dev/null +++ b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.kt @@ -0,0 +1,32 @@ +class Solution { + fun minMoves(nums: IntArray, limit: Int): Int { + val n = nums.size + val diff = IntArray(2 * limit + 2) + + for (i in 0 until n / 2) { + val a = nums[i] + val b = nums[n - 1 - i] + val low = minOf(a, b) + 1 + val high = maxOf(a, b) + limit + val total = a + b + + diff[2] += 2 + diff[2 * limit + 1] -= 2 + + diff[low] -= 1 + diff[high + 1] += 1 + + diff[total] -= 1 + diff[total + 1] += 1 + } + + var ans = Int.MAX_VALUE + var moves = 0 + for (target in 2..2 * limit) { + moves += diff[target] + ans = minOf(ans, moves) + } + + return ans + } +} diff --git a/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.py b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.py new file mode 100644 index 00000000..be4a4096 --- /dev/null +++ b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.py @@ -0,0 +1,37 @@ +class Solution: + def minMoves(self, nums: List[int], limit: int) -> int: + n = len(nums) + + # difference array + diff = [0] * (2 * limit + 2) + + for i in range(n // 2): + a = nums[i] + b = nums[n - 1 - i] + + low = min(a, b) + 1 + high = max(a, b) + limit + + total = a + b + + # initially all sums need 2 moves + diff[2] += 2 + diff[2 * limit + 1] -= 2 + + # one move range + diff[low] -= 1 + diff[high + 1] += 1 + + # exact sum needs 0 move + diff[total] -= 1 + diff[total + 1] += 1 + + ans = float("inf") + moves = 0 + + # calculate prefix sum + for target in range(2, 2 * limit + 1): + moves += diff[target] + ans = min(ans, moves) + + return ans diff --git a/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.py2 b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.py2 new file mode 100644 index 00000000..461821bb --- /dev/null +++ b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.py2 @@ -0,0 +1,33 @@ +class Solution(object): + def minMoves(self, nums, limit): + """ + :type nums: List[int] + :type limit: int + :rtype: int + """ + n = len(nums) + diff = [0] * (2 * limit + 2) + + for i in range(n // 2): + a = nums[i] + b = nums[n - 1 - i] + low = min(a, b) + 1 + high = max(a, b) + limit + total = a + b + + diff[2] += 2 + diff[2 * limit + 1] -= 2 + + diff[low] -= 1 + diff[high + 1] += 1 + + diff[total] -= 1 + diff[total + 1] += 1 + + ans = float('inf') + moves = 0 + for target in range(2, 2 * limit + 1): + moves += diff[target] + ans = min(ans, moves) + + return ans diff --git a/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.rb b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.rb new file mode 100644 index 00000000..f8b9a0fb --- /dev/null +++ b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.rb @@ -0,0 +1,33 @@ +# @param {Integer[]} nums +# @param {Integer} limit +# @return {Integer} +def min_moves(nums, limit) + n = nums.length + diff = Array.new(2 * limit + 2, 0) + + (0...(n / 2)).each do |i| + a = nums[i] + b = nums[n - 1 - i] + low = [a, b].min + 1 + high = [a, b].max + limit + total = a + b + + diff[2] += 2 + diff[2 * limit + 1] -= 2 + + diff[low] -= 1 + diff[high + 1] += 1 + + diff[total] -= 1 + diff[total + 1] += 1 + end + + ans = Float::INFINITY + moves = 0 + (2..(2 * limit)).each do |target| + moves += diff[target] + ans = [ans, moves].min + end + + ans +end diff --git a/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.rs b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.rs new file mode 100644 index 00000000..d34d9127 --- /dev/null +++ b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.rs @@ -0,0 +1,32 @@ +impl Solution { + pub fn min_moves(nums: Vec, limit: i32) -> i32 { + let n = nums.len(); + let mut diff = vec![0; (2 * limit + 2) as usize]; + + for i in 0..n / 2 { + let a = nums[i]; + let b = nums[n - 1 - i]; + let low = a.min(b) + 1; + let high = a.max(b) + limit; + let total = a + b; + + diff[2] += 2; + diff[(2 * limit + 1) as usize] -= 2; + + diff[low as usize] -= 1; + diff[(high + 1) as usize] += 1; + + diff[total as usize] -= 1; + diff[(total + 1) as usize] += 1; + } + + let mut ans = i32::MAX; + let mut moves = 0; + for target in 2..=(2 * limit) { + moves += diff[target as usize]; + ans = ans.min(moves); + } + + ans + } +} diff --git a/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.swift b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.swift new file mode 100644 index 00000000..87929fa8 --- /dev/null +++ b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.swift @@ -0,0 +1,32 @@ +class Solution { + func minMoves(_ nums: [Int], _ limit: Int) -> Int { + let n = nums.count + var diff = [Int](repeating: 0, count: 2 * limit + 2) + + for i in 0..<(n / 2) { + let a = nums[i] + let b = nums[n - 1 - i] + let low = min(a, b) + 1 + let high = max(a, b) + limit + let total = a + b + + diff[2] += 2 + diff[2 * limit + 1] -= 2 + + diff[low] -= 1 + diff[high + 1] += 1 + + diff[total] -= 1 + diff[total + 1] += 1 + } + + var ans = Int.max + var moves = 0 + for target in 2...(2 * limit) { + moves += diff[target] + ans = min(ans, moves) + } + + return ans + } +} diff --git a/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.ts b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.ts new file mode 100644 index 00000000..67d99f71 --- /dev/null +++ b/tests/1501-2000/1674. minimum-moves-to-make-array-complementary/sol.ts @@ -0,0 +1,30 @@ +function minMoves(nums: number[], limit: number): number { + const n = nums.length; + const diff = new Array(2 * limit + 2).fill(0); + + for (let i = 0; i < n / 2; i++) { + const a = nums[i]; + const b = nums[n - 1 - i]; + const low = Math.min(a, b) + 1; + const high = Math.max(a, b) + limit; + const total = a + b; + + diff[2] += 2; + diff[2 * limit + 1] -= 2; + + diff[low] -= 1; + diff[high + 1] += 1; + + diff[total] -= 1; + diff[total + 1] += 1; + } + + let ans = Number.MAX_SAFE_INTEGER; + let moves = 0; + for (let target = 2; target <= 2 * limit; target++) { + moves += diff[target]; + ans = Math.min(ans, moves); + } + + return ans; +} diff --git a/tests/1501-2000/1675. minimize-deviation-in-array/manifest.yaml b/tests/1501-2000/1675. minimize-deviation-in-array/manifest.yaml new file mode 100644 index 00000000..f9920bf5 --- /dev/null +++ b/tests/1501-2000/1675. minimize-deviation-in-array/manifest.yaml @@ -0,0 +1,238 @@ +entry: + id: 1675 + title: "minimize-deviation-in-array" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().minimumDeviation({nums})" + rust: "Solution::minimum_deviation({nums})" + python3: "Solution().minimumDeviation({nums})" + python2: "Solution().minimumDeviation({nums})" + ruby: "minimum_deviation({nums})" + java: "new Solution().minimumDeviation({nums})" + csharp: "new Solution().MinimumDeviation({nums})" + kotlin: "Solution().minimumDeviation({nums})" + go: "minimumDeviation({nums})" + dart: "Solution().minimumDeviation({nums})" + swift: "Solution().minimumDeviation({nums})" + typescript: "minimumDeviation({nums})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().minimumDeviation(nums, {result})" + checker: | + import heapq + + class Checker: + def minimumDeviation(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + heap = [] + low = 10**30 + for value in nums: + value = value if value % 2 == 0 else value * 2 + heapq.heappush(heap, -value) + low = min(low, value) + best = 10**30 + while heap and (-heap[0]) % 2 == 0: + high = -heapq.heappop(heap) + best = min(best, high - low) + lowered = high // 2 + heapq.heappush(heap, -lowered) + low = min(low, lowered) + best = min(best, -heap[0] - low) + return result == best + +seed: 1675 + +tests: + - name: example-one + in: + nums: [1, 2, 3, 4] + out: 1 + - name: example-two + in: + nums: [4, 1, 5, 20, 3] + out: 3 + - name: example-three + in: + nums: [2, 10, 8] + out: 3 + - name: all-equal-odd + in: + nums: [7, 7, 7] + out: 0 + - name: all-equal-even + in: + nums: [8, 8, 8, 8] + out: 0 + - name: powers-of-two + in: + nums: [1, 2, 4, 8, 16] + out: 0 + - name: two-values + in: + nums: [3, 10] + out: 1 + - name: adjacent-odds + in: + nums: [3, 5, 7, 9] + out: 4 + - name: mixed-small + in: + nums: [1, 6, 11] + out: 9 + - name: minimum-values + in: + nums: [1, 1, 2] + out: 0 + - name: one-large-even + in: + nums: [1, 2, 1000000000] + out: 1953123 + - name: max-odd + in: + nums: [999999999, 1000000000, 999999997] + out: 3 + - name: repeated-mixed + in: + nums: [4, 4, 5, 5, 10, 10] + out: 1 + - name: powers-and-odd + in: + nums: [2, 8, 32, 63] + out: 61 + - name: broad-range + in: + nums: [6, 13, 24, 41, 100] + out: 35 + - name: odd-heavy + in: + nums: [9, 15, 21, 27, 33] + out: 15 + - name: even-heavy + in: + nums: [12, 20, 28, 36, 44] + out: 5 + - name: duplicate-extremes + in: + nums: [1, 1, 1, 1000000000, 1000000000] + out: 1953123 + - name: balanced-small + in: + nums: [2, 3, 4, 5, 6] + out: 3 + - name: values-near-billion + in: + nums: [536870911, 536870912, 805306367, 805306368] + out: 268435457 + - name: alternating + in: + nums: [1, 16, 3, 64, 5, 256] + out: 3 + - name: prime-values + in: + nums: [2, 3, 5, 7, 11, 13] + out: 11 + - name: sparse-powers + in: + nums: [17, 34, 68, 272] + out: 0 + - name: three-large + in: + nums: [700000000, 800000001, 900000000] + out: 200000000 + - name: six-values + in: + nums: [14, 18, 22, 26, 30, 34] + out: 7 + - name: one-outlier + in: + nums: [31, 32, 32, 32] + out: 1 + - name: odd-and-double + in: + nums: [25, 50, 100, 200] + out: 0 + - name: low-and-high + in: + nums: [2, 999999999, 4] + out: 999999997 + - name: mixed-powers + in: + nums: [7, 14, 28, 56, 112] + out: 0 + - name: varied-small + in: + nums: [2, 7, 12, 19, 26, 31] + out: 29 + - name: stress-randomish + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + elemType: "int" + seed: 101 + - name: stress-small-values + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 1024 + distinct: false + elemType: "int" + seed: 102 + - name: stress-large-values + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 999000000 + max: 1000000000 + distinct: false + elemType: "int" + seed: 103 + - name: stress-powers-range + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 536870912 + distinct: false + elemType: "int" + seed: 104 + - name: stress-max-length + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + elemType: "int" + seed: 105 diff --git a/tests/1501-2000/1675. minimize-deviation-in-array/sol.cpp b/tests/1501-2000/1675. minimize-deviation-in-array/sol.cpp new file mode 100644 index 00000000..77faad5c --- /dev/null +++ b/tests/1501-2000/1675. minimize-deviation-in-array/sol.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int minimumDeviation(vector& nums) { + if (nums.empty()) return INT_MAX; + + priority_queue maxHeap; + int minVal = INT_MAX; + + for (int num : nums) { + if (num % 2 == 0) { + maxHeap.push(num); + minVal = min(num, minVal); + } else { + maxHeap.push(num * 2); + minVal = min(num * 2, minVal); + } + } + + int res = INT_MAX; + while (maxHeap.top() % 2 == 0) { + int maxVal = maxHeap.top(); + maxHeap.pop(); + res = min(res, maxVal - minVal); + int newNum = maxVal / 2; + maxHeap.push(newNum); + minVal = min(newNum, minVal); + } + + res = min(maxHeap.top() - minVal, res); + return res; + } +}; diff --git a/tests/1501-2000/1675. minimize-deviation-in-array/sol.cs b/tests/1501-2000/1675. minimize-deviation-in-array/sol.cs new file mode 100644 index 00000000..3ff463d7 --- /dev/null +++ b/tests/1501-2000/1675. minimize-deviation-in-array/sol.cs @@ -0,0 +1,31 @@ +public class Solution { + public int MinimumDeviation(int[] nums) { + if (nums.Length == 0) return int.MaxValue; + + var maxHeap = new SortedSet(Comparer.Create((a, b) => b.CompareTo(a))); + int minVal = int.MaxValue; + + foreach (int num in nums) { + if (num % 2 == 0) { + maxHeap.Add(num); + minVal = Math.Min(num, minVal); + } else { + maxHeap.Add(num * 2); + minVal = Math.Min(num * 2, minVal); + } + } + + int res = int.MaxValue; + while (maxHeap.Min % 2 == 0) { + int maxVal = maxHeap.Min; + maxHeap.Remove(maxVal); + res = Math.Min(res, maxVal - minVal); + int newNum = maxVal / 2; + maxHeap.Add(newNum); + minVal = Math.Min(newNum, minVal); + } + + res = Math.Min(maxHeap.Min - minVal, res); + return res; + } +} diff --git a/tests/1501-2000/1675. minimize-deviation-in-array/sol.dart b/tests/1501-2000/1675. minimize-deviation-in-array/sol.dart new file mode 100644 index 00000000..04815787 --- /dev/null +++ b/tests/1501-2000/1675. minimize-deviation-in-array/sol.dart @@ -0,0 +1,30 @@ +class Solution { + int minimumDeviation(List nums) { + if (nums.isEmpty) return 1 << 31 - 1; + + final maxHeap = PriorityQueue((a, b) => b.compareTo(a)); + var minVal = 1 << 31 - 1; + + for (var num in nums) { + if (num % 2 == 0) { + maxHeap.add(num); + minVal = num < minVal ? num : minVal; + } else { + maxHeap.add(num * 2); + minVal = num * 2 < minVal ? num * 2 : minVal; + } + } + + var res = 1 << 31 - 1; + while (maxHeap.first % 2 == 0) { + var maxVal = maxHeap.removeFirst(); + res = (maxVal - minVal) < res ? maxVal - minVal : res; + var newNum = maxVal ~/ 2; + maxHeap.add(newNum); + minVal = newNum < minVal ? newNum : minVal; + } + + res = (maxHeap.first - minVal) < res ? maxHeap.first - minVal : res; + return res; + } +} diff --git a/tests/1501-2000/1675. minimize-deviation-in-array/sol.go b/tests/1501-2000/1675. minimize-deviation-in-array/sol.go new file mode 100644 index 00000000..cdc148e9 --- /dev/null +++ b/tests/1501-2000/1675. minimize-deviation-in-array/sol.go @@ -0,0 +1,42 @@ +func minimumDeviation(nums []int) int { + if len(nums) == 0 { + return int(^uint(0) >> 1) // MaxInt + } + + h := []int{} + push := func(x int) { h = append(h, x); i := len(h)-1; for i > 0 { p := (i-1)/2; if h[p] >= h[i] { break }; h[p],h[i]=h[i],h[p]; i=p } } + minVal := int(^uint(0) >> 1) + + for _, num := range nums { + if num%2 == 0 { + push(num) + if num < minVal { + minVal = num + } + } else { + push(num*2) + if num*2 < minVal { + minVal = num * 2 + } + } + } + + res := int(^uint(0) >> 1) + for h[0]%2 == 0 { + maxVal := h[0]; h[0] = h[len(h)-1]; h = h[:len(h)-1] + for i:=0;; { l:=2*i+1; if l>=len(h){break}; r:=l+1; j:=l; if rh[l]{j=r}; if h[i]>=h[j]{break}; h[i],h[j]=h[j],h[i]; i=j } + if maxVal-minVal < res { + res = maxVal - minVal + } + newNum := maxVal / 2 + push(newNum) + if newNum < minVal { + minVal = newNum + } + } + + if h[0]-minVal < res { + res = h[0] - minVal + } + return res +} diff --git a/tests/1501-2000/1675. minimize-deviation-in-array/sol.java b/tests/1501-2000/1675. minimize-deviation-in-array/sol.java new file mode 100644 index 00000000..c7308961 --- /dev/null +++ b/tests/1501-2000/1675. minimize-deviation-in-array/sol.java @@ -0,0 +1,32 @@ +import java.util.*; + +class Solution { + public int minimumDeviation(int[] nums) { + if (nums.length == 0) return Integer.MAX_VALUE; + + PriorityQueue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + int minVal = Integer.MAX_VALUE; + + for (int num : nums) { + if (num % 2 == 0) { + maxHeap.add(num); + minVal = Math.min(num, minVal); + } else { + maxHeap.add(num * 2); + minVal = Math.min(num * 2, minVal); + } + } + + int res = Integer.MAX_VALUE; + while (maxHeap.peek() % 2 == 0) { + int maxVal = maxHeap.poll(); + res = Math.min(res, maxVal - minVal); + int newNum = maxVal / 2; + maxHeap.add(newNum); + minVal = Math.min(newNum, minVal); + } + + res = Math.min(maxHeap.peek() - minVal, res); + return res; + } +} diff --git a/tests/1501-2000/1675. minimize-deviation-in-array/sol.kt b/tests/1501-2000/1675. minimize-deviation-in-array/sol.kt new file mode 100644 index 00000000..9ebb1499 --- /dev/null +++ b/tests/1501-2000/1675. minimize-deviation-in-array/sol.kt @@ -0,0 +1,30 @@ +class Solution { + fun minimumDeviation(nums: IntArray): Int { + if (nums.isEmpty()) return Int.MAX_VALUE + + val maxHeap = PriorityQueue(Collections.reverseOrder()) + var minVal = Int.MAX_VALUE + + for (num in nums) { + if (num % 2 == 0) { + maxHeap.add(num) + minVal = minOf(num, minVal) + } else { + maxHeap.add(num * 2) + minVal = minOf(num * 2, minVal) + } + } + + var res = Int.MAX_VALUE + while (maxHeap.peek() % 2 == 0) { + val maxVal = maxHeap.poll() + res = minOf(res, maxVal - minVal) + val newNum = maxVal / 2 + maxHeap.add(newNum) + minVal = minOf(newNum, minVal) + } + + res = minOf(maxHeap.peek() - minVal, res) + return res + } +} diff --git a/tests/1501-2000/1675. minimize-deviation-in-array/sol.py b/tests/1501-2000/1675. minimize-deviation-in-array/sol.py new file mode 100644 index 00000000..5a7bd52c --- /dev/null +++ b/tests/1501-2000/1675. minimize-deviation-in-array/sol.py @@ -0,0 +1,29 @@ +import heapq + + +class Solution: + def minimumDeviation(self, nums: List[int]) -> int: + if not nums: + return float("inf") + + evens = [] + min_val = float("inf") + + for num in nums: + if num % 2 == 0: + heapq.heappush(evens, -num) + min_val = min(num, min_val) + else: + heapq.heappush(evens, -num * 2) + min_val = min(num * 2, min_val) + + res = float("inf") + while evens[0] % 2 == 0: + max_val = -heapq.heappop(evens) + res = min(res, max_val - min_val) + new_num = max_val // 2 + heapq.heappush(evens, -new_num) + min_val = min(new_num, min_val) + + res = min(-evens[0] - min_val, res) + return res diff --git a/tests/1501-2000/1675. minimize-deviation-in-array/sol.py2 b/tests/1501-2000/1675. minimize-deviation-in-array/sol.py2 new file mode 100644 index 00000000..7712d8dd --- /dev/null +++ b/tests/1501-2000/1675. minimize-deviation-in-array/sol.py2 @@ -0,0 +1,32 @@ +class Solution(object): + def minimumDeviation(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + import heapq + + if not nums: + return float('inf') + + evens = [] + min_val = float('inf') + + for num in nums: + if num % 2 == 0: + heapq.heappush(evens, -num) + min_val = min(num, min_val) + else: + heapq.heappush(evens, -num * 2) + min_val = min(num * 2, min_val) + + res = float('inf') + while evens[0] % 2 == 0: + max_val = -heapq.heappop(evens) + res = min(res, max_val - min_val) + new_num = max_val // 2 + heapq.heappush(evens, -new_num) + min_val = min(new_num, min_val) + + res = min(-evens[0] - min_val, res) + return res diff --git a/tests/1501-2000/1675. minimize-deviation-in-array/sol.rb b/tests/1501-2000/1675. minimize-deviation-in-array/sol.rb new file mode 100644 index 00000000..6893e60a --- /dev/null +++ b/tests/1501-2000/1675. minimize-deviation-in-array/sol.rb @@ -0,0 +1,49 @@ +# @param {Integer[]} nums +# @return {Integer} +def minimum_deviation(nums) + return Float::INFINITY if nums.empty? + + evens = [] + min_val = Float::INFINITY + + nums.each do |num| + if num.even? + evens << -num + min_val = [num, min_val].min + else + evens << -num * 2 + min_val = [num * 2, min_val].min + end + end + + evens.sort! + res = Float::INFINITY + + while evens[0].even? + max_val = -evens[0] + evens[0] = evens[-1] + evens.pop + i = 0 + while (left = i * 2 + 1) < evens.length + right = left + 1 + child = right < evens.length && evens[right] < evens[left] ? right : left + break if evens[i] <= evens[child] + evens[i], evens[child] = evens[child], evens[i] + i = child + end + res = [res, max_val - min_val].min + new_num = max_val / 2 + evens << -new_num + i = evens.length - 1 + while i > 0 + p = (i - 1) / 2 + break if evens[p] <= evens[i] + evens[p], evens[i] = evens[i], evens[p] + i = p + end + min_val = [new_num, min_val].min + end + + res = [-evens[0] - min_val, res].min + res +end diff --git a/tests/1501-2000/1675. minimize-deviation-in-array/sol.rs b/tests/1501-2000/1675. minimize-deviation-in-array/sol.rs new file mode 100644 index 00000000..6a0cdb0f --- /dev/null +++ b/tests/1501-2000/1675. minimize-deviation-in-array/sol.rs @@ -0,0 +1,35 @@ +use std::collections::BinaryHeap; +use std::cmp::Reverse; + +impl Solution { + pub fn minimum_deviation(nums: Vec) -> i32 { + if nums.is_empty() { + return i32::MAX; + } + + let mut max_heap = BinaryHeap::new(); + let mut min_val = i32::MAX; + + for &num in &nums { + if num % 2 == 0 { + max_heap.push(num); + min_val = min_val.min(num); + } else { + max_heap.push(num * 2); + min_val = min_val.min(num * 2); + } + } + + let mut res = i32::MAX; + while max_heap.peek().unwrap() % 2 == 0 { + let max_val = max_heap.pop().unwrap(); + res = res.min(max_val - min_val); + let new_num = max_val / 2; + max_heap.push(new_num); + min_val = min_val.min(new_num); + } + + res = res.min(max_heap.peek().unwrap() - min_val); + res + } +} diff --git a/tests/1501-2000/1675. minimize-deviation-in-array/sol.swift b/tests/1501-2000/1675. minimize-deviation-in-array/sol.swift new file mode 100644 index 00000000..4391c61c --- /dev/null +++ b/tests/1501-2000/1675. minimize-deviation-in-array/sol.swift @@ -0,0 +1,31 @@ +class Solution { + func minimumDeviation(_ nums: [Int]) -> Int { + if nums.isEmpty { return Int.max } + + var maxHeap: [Int] = [] + func push(_ value: Int) { maxHeap.append(value); var i = maxHeap.count - 1; while i > 0 { let p = (i - 1) / 2; if maxHeap[p] >= maxHeap[i] { break }; maxHeap.swapAt(p, i); i = p } } + var minVal = Int.max + + for num in nums { + if num % 2 == 0 { + push(num) + minVal = min(num, minVal) + } else { + push(num * 2) + minVal = min(num * 2, minVal) + } + } + + var res = Int.max + while maxHeap[0] % 2 == 0 { + let maxVal = maxHeap[0]; maxHeap[0] = maxHeap[maxHeap.count - 1]; maxHeap.removeLast(); var i = 0; while true { let l = i * 2 + 1; if l >= maxHeap.count { break }; let r = l + 1; var j = l; if r < maxHeap.count && maxHeap[r] > maxHeap[l] { j = r }; if maxHeap[i] >= maxHeap[j] { break }; maxHeap.swapAt(i, j); i = j } + res = min(res, maxVal - minVal) + let newNum = maxVal / 2 + push(newNum) + minVal = min(newNum, minVal) + } + + res = min(maxHeap[0] - minVal, res) + return res + } +} diff --git a/tests/1501-2000/1675. minimize-deviation-in-array/sol.ts b/tests/1501-2000/1675. minimize-deviation-in-array/sol.ts new file mode 100644 index 00000000..b0f12248 --- /dev/null +++ b/tests/1501-2000/1675. minimize-deviation-in-array/sol.ts @@ -0,0 +1,51 @@ +function minimumDeviation(nums: number[]): number { + if (nums.length === 0) return Infinity; + + const maxHeap: number[] = []; + const push = (value: number) => { + maxHeap.push(value); + let i = maxHeap.length - 1; + while (i > 0) { + const p = Math.floor((i - 1) / 2); + if (maxHeap[p] >= maxHeap[i]) break; + [maxHeap[p], maxHeap[i]] = [maxHeap[i], maxHeap[p]]; + i = p; + } + }; + let minVal = Infinity; + + for (const num of nums) { + if (num % 2 === 0) { + push(num); + minVal = Math.min(num, minVal); + } else { + push(num * 2); + minVal = Math.min(num * 2, minVal); + } + } + + let res = Infinity; + while (maxHeap[0] % 2 === 0) { + const maxVal = maxHeap[0]; + maxHeap[0] = maxHeap[maxHeap.length - 1]; + maxHeap.pop(); + let i = 0; + while (true) { + const l = i * 2 + 1; + if (l >= maxHeap.length) break; + const r = l + 1; + let j = l; + if (r < maxHeap.length && maxHeap[r] > maxHeap[l]) j = r; + if (maxHeap[i] >= maxHeap[j]) break; + [maxHeap[i], maxHeap[j]] = [maxHeap[j], maxHeap[i]]; + i = j; + } + res = Math.min(res, maxVal - minVal); + const newNum = maxVal / 2; + push(newNum); + minVal = Math.min(newNum, minVal); + } + + res = Math.min(maxHeap[0] - minVal, res); + return res; +} diff --git a/tests/1501-2000/1678. goal-parser-interpretation/manifest.yaml b/tests/1501-2000/1678. goal-parser-interpretation/manifest.yaml new file mode 100644 index 00000000..f7a80caf --- /dev/null +++ b/tests/1501-2000/1678. goal-parser-interpretation/manifest.yaml @@ -0,0 +1,190 @@ +entry: + id: 1678 + title: "goal-parser-interpretation" + params: + command: + type: string + call: + cpp: "Solution().interpret({command})" + rust: "Solution::interpret({command})" + python3: "Solution().interpret({command})" + python2: "Solution().interpret({command})" + ruby: "interpret({command})" + java: "new Solution().interpret({command})" + csharp: "new Solution().Interpret({command})" + kotlin: "Solution().interpret({command})" + go: "interpret({command})" + dart: "Solution().interpret({command})" + swift: "Solution().interpret({command})" + typescript: "interpret({command})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(command, {result})" + checker: | + class Checker: + def check(self, command, result): + expected = [] + i = 0 + while i < len(command): + if command[i] == "G": + expected.append("G") + i += 1 + elif command[i:i + 2] == "()": + expected.append("o") + i += 2 + else: + expected.append("al") + i += 4 + return result == "".join(expected) + +seed: 1678 + +tests: + - name: example-one + in: + command: "G()(al)" + out: "Goal" + - name: example-two + in: + command: "G()()()()(al)" + out: "Gooooal" + - name: example-three + in: + command: "(al)G(al)()()G" + out: "alGalooG" + - name: single-g + in: + command: "G" + out: "G" + - name: single-empty-token + in: + command: "()" + out: "o" + - name: single-al-token + in: + command: "(al)" + out: "al" + - name: repeated-g + in: + command: "GGGGG" + out: "GGGGG" + - name: repeated-empty + in: + command: "()()()()()" + out: "ooooo" + - name: repeated-al + in: + command: "(al)(al)(al)" + out: "alalal" + - name: alternating-g-empty + in: + command: "G()G()G()" + out: "GoGoGo" + - name: alternating-g-al + in: + command: "G(al)G(al)G(al)" + out: "GalGalGal" + - name: alternating-empty-al + in: + command: "()(al)()(al)" + out: "oaloal" + - name: g-prefix + in: + command: "GGG(al)()" + out: "GGGalo" + - name: g-suffix + in: + command: "()(al)GGG" + out: "oalGGG" + - name: al-prefix + in: + command: "(al)(al)G()" + out: "alalGo" + - name: mixed-short + in: + command: "G()(al)G()" + out: "GoalGo" + - name: mixed-long-one + in: + command: "G(al)()G(al)()G" + out: "GaloGaloG" + - name: twenty-g + in: + command: "GGGGGGGGGGGGGGGGGGGG" + out: "GGGGGGGGGGGGGGGGGGGG" + - name: twenty-empty + in: + command: "()()()()()()()()()()" + out: "oooooooooo" + - name: ten-al + in: + command: "(al)(al)(al)(al)(al)(al)(al)(al)(al)(al)" + out: "alalalalalalalalalal" + - name: max-g + in: + command: "GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG" + out: "GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG" + - name: max-empty + in: + command: "()()()()()()()()()()()()()()()()()()()()()()()()()()" + out: "oooooooooooooooooooooooooo" + - name: max-al + in: + command: "(al)(al)(al)(al)(al)(al)(al)(al)(al)(al)(al)(al)(al)(al)(al)(al)(al)(al)(al)(al)(al)(al)(al)(al)(al)" + out: "alalalalalalalalalalalalalalalalalalalalalalalalal" + - name: pattern-one + in: + command: "G()G(al)()G(al)G()" + out: "GoGaloGalGo" + - name: pattern-two + in: + command: "(al)()G(al)G()G(al)" + out: "aloGalGoGal" + - name: pattern-three + in: + command: "G(al)(al)()()G" + out: "GalalooG" + - name: pattern-four + in: + command: "()G()(al)G(al)()" + out: "oGoalGalo" + - name: pattern-five + in: + command: "(al)G()G()G(al)(al)" + out: "alGoGoGalal" + - name: long-mixed-one + in: + command: "G()G()G()G()G()G(al)G(al)G(al)" + out: "GoGoGoGoGoGalGalGal" + - name: long-mixed-two + in: + command: "(al)()(al)G(al)()G()G(al)" + out: "aloalGaloGoGal" + - name: long-mixed-three + in: + command: "G(al)G()()(al)G()G(al)()" + out: "GalGooalGoGalo" + - name: long-mixed-four + in: + command: "()(al)G()(al)G(al)G()()" + out: "oalGoalGalGoo" + - name: long-mixed-five + in: + command: "G()()G(al)(al)G()G(al)()G" + out: "GooGalalGoGaloG" + - name: boundary-mix + in: + command: "GG(al)()G(al)()()G(al)GG" + out: "GGaloGalooGalGG" + - name: full-length-mix + in: + command: "G()G(al)()G()G(al)G()()G(al)G()G(al)()G" + out: "GoGaloGoGalGooGalGoGaloG" diff --git a/tests/1501-2000/1678. goal-parser-interpretation/sol.cpp b/tests/1501-2000/1678. goal-parser-interpretation/sol.cpp new file mode 100644 index 00000000..da866611 --- /dev/null +++ b/tests/1501-2000/1678. goal-parser-interpretation/sol.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + string interpret(string command) { + string result; + int i = 0; + while (i < command.length()) { + if (command[i] == 'G') { + result += "G"; + i++; + } else if (i + 1 < command.length() && command[i] == '(' && command[i+1] == ')') { + result += "o"; + i += 2; + } else { + result += "al"; + i += 4; + } + } + return result; + } +}; diff --git a/tests/1501-2000/1678. goal-parser-interpretation/sol.cs b/tests/1501-2000/1678. goal-parser-interpretation/sol.cs new file mode 100644 index 00000000..6006a0cf --- /dev/null +++ b/tests/1501-2000/1678. goal-parser-interpretation/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public string Interpret(string command) { + var result = new StringBuilder(); + int i = 0; + while (i < command.Length) { + if (command[i] == 'G') { + result.Append("G"); + i++; + } else if (i + 1 < command.Length && command[i] == '(' && command[i+1] == ')') { + result.Append("o"); + i += 2; + } else { + result.Append("al"); + i += 4; + } + } + return result.ToString(); + } +} diff --git a/tests/1501-2000/1678. goal-parser-interpretation/sol.dart b/tests/1501-2000/1678. goal-parser-interpretation/sol.dart new file mode 100644 index 00000000..b4293875 --- /dev/null +++ b/tests/1501-2000/1678. goal-parser-interpretation/sol.dart @@ -0,0 +1,19 @@ +class Solution { + String interpret(String command) { + final result = StringBuffer(); + var i = 0; + while (i < command.length) { + if (command[i] == 'G') { + result.write('G'); + i++; + } else if (command.substring(i, i + 2) == '()') { + result.write('o'); + i += 2; + } else { + result.write('al'); + i += 4; + } + } + return result.toString(); + } +} diff --git a/tests/1501-2000/1678. goal-parser-interpretation/sol.go b/tests/1501-2000/1678. goal-parser-interpretation/sol.go new file mode 100644 index 00000000..db76b217 --- /dev/null +++ b/tests/1501-2000/1678. goal-parser-interpretation/sol.go @@ -0,0 +1,17 @@ +func interpret(command string) string { + result := []byte{} + i := 0 + for i < len(command) { + if command[i] == 'G' { + result = append(result, 'G') + i++ + } else if i+1 < len(command) && command[i:i+2] == "()" { + result = append(result, 'o') + i += 2 + } else { + result = append(result, []byte("al")...) + i += 4 + } + } + return string(result) +} diff --git a/tests/1501-2000/1678. goal-parser-interpretation/sol.java b/tests/1501-2000/1678. goal-parser-interpretation/sol.java new file mode 100644 index 00000000..7f9d43a5 --- /dev/null +++ b/tests/1501-2000/1678. goal-parser-interpretation/sol.java @@ -0,0 +1,19 @@ +class Solution { + public String interpret(String command) { + StringBuilder result = new StringBuilder(); + int i = 0; + while (i < command.length()) { + if (command.charAt(i) == 'G') { + result.append("G"); + i++; + } else if (command.startsWith("()", i)) { + result.append("o"); + i += 2; + } else { + result.append("al"); + i += 4; + } + } + return result.toString(); + } +} diff --git a/tests/1501-2000/1678. goal-parser-interpretation/sol.kt b/tests/1501-2000/1678. goal-parser-interpretation/sol.kt new file mode 100644 index 00000000..b189a66a --- /dev/null +++ b/tests/1501-2000/1678. goal-parser-interpretation/sol.kt @@ -0,0 +1,19 @@ +class Solution { + fun interpret(command: String): String { + val result = StringBuilder() + var i = 0 + while (i < command.length) { + if (command[i] == 'G') { + result.append("G") + i++ + } else if (command.startsWith("()", i)) { + result.append("o") + i += 2 + } else { + result.append("al") + i += 4 + } + } + return result.toString() + } +} diff --git a/tests/1501-2000/1678. goal-parser-interpretation/sol.py b/tests/1501-2000/1678. goal-parser-interpretation/sol.py new file mode 100644 index 00000000..9484fbb3 --- /dev/null +++ b/tests/1501-2000/1678. goal-parser-interpretation/sol.py @@ -0,0 +1,20 @@ +class Solution: + def interpret(self, command): + + result = [] + i = 0 + + while i < len(command): + if command[i] == "G": + result.append("G") + i += 1 + + elif command[i : i + 2] == "()": + result.append("o") + i += 2 + + else: + result.append("al") + i += 4 + + return "".join(result) diff --git a/tests/1501-2000/1678. goal-parser-interpretation/sol.py2 b/tests/1501-2000/1678. goal-parser-interpretation/sol.py2 new file mode 100644 index 00000000..e132644e --- /dev/null +++ b/tests/1501-2000/1678. goal-parser-interpretation/sol.py2 @@ -0,0 +1,19 @@ +class Solution(object): + def interpret(self, command): + """ + :type command: str + :rtype: str + """ + result = [] + i = 0 + while i < len(command): + if command[i] == 'G': + result.append("G") + i += 1 + elif command[i:i+2] == "()": + result.append("o") + i += 2 + else: + result.append("al") + i += 4 + return "".join(result) diff --git a/tests/1501-2000/1678. goal-parser-interpretation/sol.rb b/tests/1501-2000/1678. goal-parser-interpretation/sol.rb new file mode 100644 index 00000000..019b6889 --- /dev/null +++ b/tests/1501-2000/1678. goal-parser-interpretation/sol.rb @@ -0,0 +1,19 @@ +# @param {String} command +# @return {String} +def interpret(command) + result = [] + i = 0 + while i < command.length + if command[i] == 'G' + result << "G" + i += 1 + elsif command[i, 2] == "()" + result << "o" + i += 2 + else + result << "al" + i += 4 + end + end + result.join +end diff --git a/tests/1501-2000/1678. goal-parser-interpretation/sol.rs b/tests/1501-2000/1678. goal-parser-interpretation/sol.rs new file mode 100644 index 00000000..7bfa3025 --- /dev/null +++ b/tests/1501-2000/1678. goal-parser-interpretation/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn interpret(command: String) -> String { + let mut result = String::new(); + let chars: Vec = command.chars().collect(); + let mut i = 0; + while i < chars.len() { + if chars[i] == 'G' { + result.push('G'); + i += 1; + } else if i + 1 < chars.len() && chars[i] == '(' && chars[i+1] == ')' { + result.push('o'); + i += 2; + } else { + result.push_str("al"); + i += 4; + } + } + result + } +} diff --git a/tests/1501-2000/1678. goal-parser-interpretation/sol.swift b/tests/1501-2000/1678. goal-parser-interpretation/sol.swift new file mode 100644 index 00000000..7ccf3839 --- /dev/null +++ b/tests/1501-2000/1678. goal-parser-interpretation/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func interpret(_ command: String) -> String { + var result = "" + var i = 0 + let chars = Array(command) + while i < chars.count { + if chars[i] == "G" { + result += "G" + i += 1 + } else if i + 1 < chars.count && String(chars[i...i+1]) == "()" { + result += "o" + i += 2 + } else { + result += "al" + i += 4 + } + } + return result + } +} diff --git a/tests/1501-2000/1678. goal-parser-interpretation/sol.ts b/tests/1501-2000/1678. goal-parser-interpretation/sol.ts new file mode 100644 index 00000000..0a6f9a0c --- /dev/null +++ b/tests/1501-2000/1678. goal-parser-interpretation/sol.ts @@ -0,0 +1,17 @@ +function interpret(command: string): string { + let result = ""; + let i = 0; + while (i < command.length) { + if (command[i] === "G") { + result += "G"; + i++; + } else if (command.substring(i, i + 2) === "()") { + result += "o"; + i += 2; + } else { + result += "al"; + i += 4; + } + } + return result; +} diff --git a/tests/1501-2000/1679. max-number-of-k-sum-pairs/manifest.yaml b/tests/1501-2000/1679. max-number-of-k-sum-pairs/manifest.yaml new file mode 100644 index 00000000..30f4aab2 --- /dev/null +++ b/tests/1501-2000/1679. max-number-of-k-sum-pairs/manifest.yaml @@ -0,0 +1,325 @@ +entry: + id: 1679 + title: "max-number-of-k-sum-pairs" + params: + nums: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().maxOperations({nums}, {k})" + rust: "Solution::max_operations({nums}, {k})" + python3: "Solution().maxOperations({nums}, {k})" + python2: "Solution().maxOperations({nums}, {k})" + ruby: "max_operations({nums}, {k})" + java: "new Solution().maxOperations({nums}, {k})" + csharp: "new Solution().MaxOperations({nums}, {k})" + kotlin: "Solution().maxOperations({nums}, {k})" + go: "maxOperations({nums}, {k})" + dart: "Solution().maxOperations({nums}, {k})" + swift: "Solution().maxOperations({nums}, {k})" + typescript: "maxOperations({nums}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxOperations(nums, k, {result})" + checker: | + from collections import Counter + + class Checker: + def maxOperations(self, nums, k, result): + counts = Counter(nums) + expected = 0 + for value in list(counts): + other = k - value + if other not in counts: + continue + if value == other: + expected += counts[value] // 2 + counts[value] = 0 + elif counts[value] > 0 and counts[other] > 0: + pairs = min(counts[value], counts[other]) + expected += pairs + counts[value] -= pairs + counts[other] -= pairs + return result == expected + +seed: 1679 + +tests: + - name: example-balanced + in: + nums: [1, 2, 3, 4] + k: 5 + out: 2 + - name: example-duplicate-threes + in: + nums: [3, 1, 3, 4, 3] + k: 6 + out: 1 + - name: single-element + in: + nums: [5] + k: 5 + out: 0 + - name: two-elements-match + in: + nums: [4, 7] + k: 11 + out: 1 + - name: two-elements-miss + in: + nums: [4, 7] + k: 10 + out: 0 + - name: all-identical-even + in: + nums: [5, 5, 5, 5, 5, 5] + k: 10 + out: 3 + - name: all-identical-odd + in: + nums: [5, 5, 5, 5, 5] + k: 10 + out: 2 + - name: no-complements + in: + nums: [1, 1, 1, 1] + k: 100 + out: 0 + - name: complement-shortage + in: + nums: [1, 1, 1, 9, 9] + k: 10 + out: 2 + - name: unsorted-input + in: + nums: [4, 1, 3, 2] + k: 5 + out: 2 + - name: negatives-not-allowed-boundary + in: + nums: [1, 2, 999999999, 1000000000] + k: 1000000000 + out: 1 + - name: minimum-values + in: + nums: [1, 1, 2, 2, 3, 3] + k: 3 + out: 2 + - name: maximum-values + in: + nums: [1000000000, 999999999, 1, 2] + k: 1000000000 + out: 1 + - name: several-value-groups + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8] + k: 9 + out: 4 + - name: extra-unmatched-large + in: + nums: [1, 8, 2, 7, 3, 6, 4, 5, 100] + k: 9 + out: 4 + - name: repeated-low-side + in: + nums: [2, 2, 2, 2, 8] + k: 10 + out: 1 + - name: repeated-high-side + in: + nums: [2, 8, 8, 8, 8] + k: 10 + out: 1 + - name: target-one-billion + in: + nums: [1, 999999999, 2, 999999998, 500000000] + k: 1000000000 + out: 2 + - name: alternating-pairs + in: + nums: [10, 1, 9, 2, 8, 3, 7, 4, 6, 5] + k: 11 + out: 5 + - name: one-valid-pair + in: + nums: [1, 2, 2, 2, 9, 10] + k: 11 + out: 2 + - name: pair-with-self-and-other + in: + nums: [5, 5, 5, 5, 4, 6] + k: 10 + out: 3 + - name: four-pairs-with-noise + in: + nums: [12, 88, 13, 87, 14, 86, 15, 85, 1, 2, 3] + k: 100 + out: 4 + - name: target-two + in: + nums: [1, 1, 1, 1, 1, 1, 2] + k: 2 + out: 3 + - name: target-three + in: + nums: [1, 1, 1, 2, 2, 3] + k: 3 + out: 2 + - name: target-two-billion + in: + nums: [1000000000, 1000000000, 999999999, 999999999] + k: 1000000000 + out: 0 + - name: sorted-ascending + in: + nums: [1, 2, 3, 4, 5, 6, 7] + k: 8 + out: 3 + - name: sorted-descending + in: + nums: [7, 6, 5, 4, 3, 2, 1] + k: 8 + out: 3 + - name: many-duplicates + in: + nums: [1, 1, 1, 1, 4, 4, 4, 4, 4] + k: 5 + out: 4 + - name: disjoint-complements + in: + nums: [2, 3, 4, 5, 6, 7, 8] + k: 20 + out: 0 + - name: mixed-boundaries + in: + nums: [1, 1000000000, 500000000, 500000000, 999999999, 1] + k: 1000000001 + out: 1 + - name: odd-length-perfect-prefix + in: + nums: [1, 9, 2, 8, 3, 7, 100] + k: 10 + out: 3 + - name: value-duplicates-and-noise + in: + nums: [6, 6, 4, 4, 4, 4, 1, 2, 9] + k: 10 + out: 3 + - name: large-static-structured + in: + nums: + [ + 1, + 999999999, + 2, + 999999998, + 3, + 999999997, + 4, + 999999996, + 5, + 999999995, + 6, + 999999994, + 7, + 999999993, + 8, + 999999992, + 9, + 999999991, + 10, + 999999990, + ] + k: 1000000000 + out: 10 + - name: generator-random-small + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + elemType: "int" + k: + gen: "int" + min: 2 + max: 2000 + seed: 101 + - name: generator-random-medium + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + elemType: "int" + k: + gen: "int" + min: 2 + max: 200000 + seed: 202 + - name: generator-maximum-range + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 1000000000 + seed: 303 + - name: generator-many-duplicates + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 20 + distinct: false + elemType: "int" + k: + gen: "int" + min: 2 + max: 40 + seed: 404 + - name: generator-upper-values + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 999900000 + max: 1000000000 + distinct: false + elemType: "int" + k: + gen: "int" + min: 999900000 + max: 1000000000 + seed: 505 diff --git a/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.cpp b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.cpp new file mode 100644 index 00000000..49a14144 --- /dev/null +++ b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int maxOperations(vector& nums, int k) { + sort(nums.begin(), nums.end()); + int i = 0, j = nums.size() - 1; + int count = 0; + + while (i < j) { + int total = nums[i] + nums[j]; + if (total == k) { + count++; + i++; + j--; + } else if (total > k) { + j--; + } else { + i++; + } + } + + return count; + } +}; diff --git a/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.cs b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.cs new file mode 100644 index 00000000..2990b0fc --- /dev/null +++ b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public int MaxOperations(int[] nums, int k) { + Array.Sort(nums); + int i = 0, j = nums.Length - 1; + int count = 0; + + while (i < j) { + int total = nums[i] + nums[j]; + if (total == k) { + count++; + i++; + j--; + } else if (total > k) { + j--; + } else { + i++; + } + } + + return count; + } +} diff --git a/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.dart b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.dart new file mode 100644 index 00000000..1777b169 --- /dev/null +++ b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.dart @@ -0,0 +1,21 @@ +class Solution { + int maxOperations(List nums, int k) { + nums.sort(); + var left = 0; + var right = nums.length - 1; + var result = 0; + while (left < right) { + final sum = nums[left] + nums[right]; + if (sum == k) { + result++; + left++; + right--; + } else if (sum < k) { + left++; + } else { + right--; + } + } + return result; + } +} diff --git a/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.go b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.go new file mode 100644 index 00000000..3f5ea93e --- /dev/null +++ b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.go @@ -0,0 +1,20 @@ +func maxOperations(nums []int, k int) int { + sort.Ints(nums) + i, j := 0, len(nums)-1 + count := 0 + + for i < j { + total := nums[i] + nums[j] + if total == k { + count++ + i++ + j-- + } else if total > k { + j-- + } else { + i++ + } + } + + return count +} diff --git a/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.java b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.java new file mode 100644 index 00000000..2494de7b --- /dev/null +++ b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.java @@ -0,0 +1,22 @@ +class Solution { + public int maxOperations(int[] nums, int k) { + Arrays.sort(nums); + int i = 0, j = nums.length - 1; + int count = 0; + + while (i < j) { + int total = nums[i] + nums[j]; + if (total == k) { + count++; + i++; + j--; + } else if (total > k) { + j--; + } else { + i++; + } + } + + return count; + } +} diff --git a/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.kt b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.kt new file mode 100644 index 00000000..6a60dbc0 --- /dev/null +++ b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.kt @@ -0,0 +1,23 @@ +class Solution { + fun maxOperations(nums: IntArray, k: Int): Int { + nums.sort() + var i = 0 + var j = nums.size - 1 + var count = 0 + + while (i < j) { + val total = nums[i] + nums[j] + if (total == k) { + count++ + i++ + j-- + } else if (total > k) { + j-- + } else { + i++ + } + } + + return count + } +} diff --git a/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.py b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.py new file mode 100644 index 00000000..2c3acfb3 --- /dev/null +++ b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.py @@ -0,0 +1,18 @@ +class Solution: + def maxOperations(self, nums: List[int], k: int) -> int: + nums.sort() + i, j = 0, len(nums) - 1 + count = 0 + + while i < j: + total = nums[i] + nums[j] + if total == k: + count += 1 + i += 1 + j -= 1 + elif total > k: + j -= 1 + else: + i += 1 + + return count diff --git a/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.py2 b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.py2 new file mode 100644 index 00000000..0d997686 --- /dev/null +++ b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def maxOperations(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + nums.sort() + i, j = 0, len(nums) - 1 + count = 0 + + while i < j: + total = nums[i] + nums[j] + if total == k: + count += 1 + i += 1 + j -= 1 + elif total > k: + j -= 1 + else: + i += 1 + + return count diff --git a/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.rb b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.rb new file mode 100644 index 00000000..8ff635f0 --- /dev/null +++ b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.rb @@ -0,0 +1,23 @@ +# @param {Integer[]} nums +# @param {Integer} k +# @return {Integer} +def max_operations(nums, k) + nums.sort! + i, j = 0, nums.length - 1 + count = 0 + + while i < j + total = nums[i] + nums[j] + if total == k + count += 1 + i += 1 + j -= 1 + elsif total > k + j -= 1 + else + i += 1 + end + end + + count +end diff --git a/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.rs b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.rs new file mode 100644 index 00000000..250a33f1 --- /dev/null +++ b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.rs @@ -0,0 +1,23 @@ +impl Solution { + pub fn max_operations(nums: Vec, k: i32) -> i32 { + let mut nums = nums; + nums.sort(); + let (mut i, mut j) = (0, nums.len() - 1); + let mut count = 0; + + while i < j { + let total = nums[i] + nums[j]; + if total == k { + count += 1; + i += 1; + j -= 1; + } else if total > k { + j -= 1; + } else { + i += 1; + } + } + + count + } +} diff --git a/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.swift b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.swift new file mode 100644 index 00000000..8a13bfac --- /dev/null +++ b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func maxOperations(_ nums: [Int], _ k: Int) -> Int { + var nums = nums.sorted() + var i = 0 + var j = nums.count - 1 + var count = 0 + + while i < j { + let total = nums[i] + nums[j] + if total == k { + count += 1 + i += 1 + j -= 1 + } else if total > k { + j -= 1 + } else { + i += 1 + } + } + + return count + } +} diff --git a/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.ts b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.ts new file mode 100644 index 00000000..6006b4ed --- /dev/null +++ b/tests/1501-2000/1679. max-number-of-k-sum-pairs/sol.ts @@ -0,0 +1,21 @@ +function maxOperations(nums: number[], k: number): number { + nums.sort((a, b) => a - b); + let i = 0, + j = nums.length - 1; + let count = 0; + + while (i < j) { + const total = nums[i] + nums[j]; + if (total === k) { + count++; + i++; + j--; + } else if (total > k) { + j--; + } else { + i++; + } + } + + return count; +} diff --git a/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/manifest.yaml b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/manifest.yaml new file mode 100644 index 00000000..cc4cfbc5 --- /dev/null +++ b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/manifest.yaml @@ -0,0 +1,197 @@ +entry: + id: 1680 + title: "concatenation-of-consecutive-binary-numbers" + params: + n: + type: int + call: + cpp: "Solution().concatenatedBinary({n})" + rust: "Solution::concatenated_binary({n})" + python3: "Solution().concatenatedBinary({n})" + python2: "Solution().concatenatedBinary({n})" + ruby: "concatenated_binary({n})" + java: "new Solution().concatenatedBinary({n})" + csharp: "new Solution().ConcatenatedBinary({n})" + kotlin: "Solution().concatenatedBinary({n})" + go: "concatenatedBinary({n})" + dart: "Solution().concatenatedBinary({n})" + swift: "Solution().concatenatedBinary({n})" + typescript: "concatenatedBinary({n})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().concatenatedBinary(n, {result})" + checker: | + class Checker: + def concatenatedBinary(self, n, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + mod = 1000000007 + value = 0 + width = 0 + for number in range(1, n + 1): + if number & (number - 1) == 0: + width += 1 + value = ((value << width) | number) % mod + return result == value + +seed: 1680 + +tests: + - name: minimum + in: + n: 1 + out: 1 + - name: two + in: + n: 2 + out: 6 + - name: example-three + in: + n: 3 + out: 27 + - name: first-power-of-two + in: + n: 4 + out: 220 + - name: after-four + in: + n: 5 + out: 1765 + - name: small-six + in: + n: 6 + out: 14126 + - name: small-seven + in: + n: 7 + out: 113015 + - name: eight + in: + n: 8 + out: 1808248 + - name: stated-example + in: + n: 12 + out: 505379714 + - name: sixteen + in: + n: 16 + out: 129523881 + - name: just-after-sixteen + in: + n: 17 + out: 144764181 + - name: thirty-one + in: + n: 31 + out: 144699479 + - name: thirty-two + in: + n: 32 + out: 260766625 + - name: thirty-three + in: + n: 33 + out: 689063921 + - name: forty-two + in: + n: 42 + out: 727837408 + - name: fifty + in: + n: 50 + out: 875059690 + - name: sixty-four + in: + n: 64 + out: 644325427 + - name: sixty-five + in: + n: 65 + out: 473654147 + - name: ninety-nine + in: + n: 99 + out: 627428348 + - name: one-hundred + in: + n: 100 + out: 310828084 + - name: one-twenty-seven + in: + n: 127 + out: 5842299 + - name: one-twenty-eight + in: + n: 128 + out: 495628665 + - name: one-twenty-nine + in: + n: 129 + out: 880937487 + - name: two-fifty-five + in: + n: 255 + out: 313471718 + - name: two-fifty-six + in: + n: 256 + out: 497518752 + - name: two-fifty-seven + in: + n: 257 + out: 729599503 + - name: five-hundred + in: + n: 500 + out: 715412131 + - name: one-thousand + in: + n: 1000 + out: 499361981 + - name: power-boundary + in: + n: 4096 + out: 861688679 + - name: ten-thousand + in: + n: 10000 + out: 356435599 + - name: generated-small + in: + n: + gen: "int" + min: 1 + max: 64 + - name: generated-medium + in: + n: + gen: "int" + min: 65 + max: 4096 + - name: generated-large + in: + n: + gen: "int" + min: 4097 + max: 50000 + - name: generated-near-maximum + in: + n: + gen: "int" + min: 50001 + max: 99999 + - name: generated-maximum + in: + n: + gen: "int" + min: 100000 + max: 100000 diff --git a/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.cpp b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.cpp new file mode 100644 index 00000000..580ff345 --- /dev/null +++ b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int concatenatedBinary(int n) { + const long long MOD = 1'000'000'007; + long long res = 0; + int bits = 0; + + for (int i = 1; i <= n; i++) { + if ((i & (i - 1)) == 0) { + bits++; + } + res = ((res << bits) | i) % MOD; + } + + return (int)res; + } +}; diff --git a/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.cs b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.cs new file mode 100644 index 00000000..625f6390 --- /dev/null +++ b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public int ConcatenatedBinary(int n) { + const long MOD = 1_000_000_007; + long res = 0; + int bits = 0; + + for (int i = 1; i <= n; i++) { + if ((i & (i - 1)) == 0) { + bits++; + } + res = ((res << bits) | i) % MOD; + } + + return (int)res; + } +} diff --git a/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.dart b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.dart new file mode 100644 index 00000000..04ea71e3 --- /dev/null +++ b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.dart @@ -0,0 +1,12 @@ +class Solution { + int concatenatedBinary(int n) { + const mod = 1000000007; + var result = 0; + var bits = 0; + for (var i = 1; i <= n; i++) { + if ((i & (i - 1)) == 0) bits++; + result = (result * (1 << bits) + i) % mod; + } + return result; + } +} diff --git a/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.go b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.go new file mode 100644 index 00000000..0a38ea20 --- /dev/null +++ b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.go @@ -0,0 +1,14 @@ +func concatenatedBinary(n int) int { + const MOD = 1000000007 + res := 0 + bits := 0 + + for i := 1; i <= n; i++ { + if (i & (i - 1)) == 0 { + bits++ + } + res = ((res << bits) | i) % MOD + } + + return res +} diff --git a/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.java b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.java new file mode 100644 index 00000000..f10619ca --- /dev/null +++ b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.java @@ -0,0 +1,16 @@ +class Solution { + public int concatenatedBinary(int n) { + final int MOD = 1_000_000_007; + long res = 0; + int bits = 0; + + for (int i = 1; i <= n; i++) { + if ((i & (i - 1)) == 0) { + bits++; + } + res = ((res << bits) | i) % MOD; + } + + return (int) res; + } +} diff --git a/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.kt b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.kt new file mode 100644 index 00000000..f2151154 --- /dev/null +++ b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun concatenatedBinary(n: Int): Int { + val MOD = 1_000_000_007 + var res = 0L + var bits = 0 + + for (i in 1..n) { + if ((i and (i - 1)) == 0) { + bits++ + } + res = ((res shl bits) or i.toLong()) % MOD + } + + return res.toInt() + } +} diff --git a/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.py b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.py new file mode 100644 index 00000000..f9bfeee2 --- /dev/null +++ b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.py @@ -0,0 +1,12 @@ +class Solution: + def concatenatedBinary(self, n: int) -> int: + MOD = 10**9 + 7 + res = 0 + bits = 0 + + for i in range(1, n + 1): + if (i & (i - 1)) == 0: + bits += 1 + res = ((res << bits) | i) % MOD + + return res diff --git a/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.py2 b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.py2 new file mode 100644 index 00000000..31cc7d17 --- /dev/null +++ b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def concatenatedBinary(self, n): + """ + :type n: int + :rtype: int + """ + MOD = 10**9 + 7 + res = 0 + bits = 0 + + for i in range(1, n+1): + if (i & (i-1)) == 0: + bits += 1 + res = ((res << bits) | i) % MOD + + return res diff --git a/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.rb b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.rb new file mode 100644 index 00000000..50b918fa --- /dev/null +++ b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.rb @@ -0,0 +1,16 @@ +# @param {Integer} n +# @return {Integer} +def concatenated_binary(n) + mod = 10**9 + 7 + res = 0 + bits = 0 + + (1..n).each do |i| + if (i & (i-1)) == 0 + bits += 1 + end + res = ((res << bits) | i) % mod + end + + res +end diff --git a/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.rs b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.rs new file mode 100644 index 00000000..e801fa51 --- /dev/null +++ b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn concatenated_binary(n: i32) -> i32 { + const MOD: i64 = 1_000_000_007; + let mut res: i64 = 0; + let mut bits: i64 = 0; + + for i in 1..=n as i64 { + if (i & (i - 1)) == 0 { + bits += 1; + } + res = ((res << bits) | i) % MOD; + } + + res as i32 + } +} diff --git a/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.swift b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.swift new file mode 100644 index 00000000..504bf6c4 --- /dev/null +++ b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func concatenatedBinary(_ n: Int) -> Int { + let MOD = 1_000_000_007 + var res = 0 + var bits = 0 + + for i in 1...n { + if (i & (i - 1)) == 0 { + bits += 1 + } + res = ((res << bits) | i) % MOD + } + + return res + } +} diff --git a/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.ts b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.ts new file mode 100644 index 00000000..832b9e28 --- /dev/null +++ b/tests/1501-2000/1680. concatenation-of-consecutive-binary-numbers/sol.ts @@ -0,0 +1,14 @@ +function concatenatedBinary(n: number): number { + const MOD = 1_000_000_007; + let res = 0; + let bits = 0; + + for (let i = 1; i <= n; i++) { + if ((i & (i - 1)) === 0) { + bits++; + } + res = (res * Math.pow(2, bits) + i) % MOD; + } + + return res; +} diff --git a/tests/1501-2000/1681. minimum-incompatibility/manifest.yaml b/tests/1501-2000/1681. minimum-incompatibility/manifest.yaml new file mode 100644 index 00000000..62997d43 --- /dev/null +++ b/tests/1501-2000/1681. minimum-incompatibility/manifest.yaml @@ -0,0 +1,270 @@ +entry: + id: 1681 + title: minimum-incompatibility + params: + nums: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().minimumIncompatibility({nums}, {k})" + rust: "Solution::minimum_incompatibility({nums}, {k})" + python3: "Solution().minimumIncompatibility({nums}, {k})" + python2: "Solution().minimumIncompatibility({nums}, {k})" + ruby: "minimum_incompatibility({nums}, {k})" + java: "new Solution().minimumIncompatibility({nums}, {k})" + csharp: "new Solution().MinimumIncompatibility({nums}, {k})" + kotlin: "Solution().minimumIncompatibility({nums}, {k})" + go: "minimumIncompatibility({nums}, {k})" + dart: "Solution().minimumIncompatibility({nums}, {k})" + swift: "Solution().minimumIncompatibility({nums}, {k})" + typescript: "minimumIncompatibility({nums}, {k})" + +judge: + type: exact + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().check(nums, k, {result})" + checker: | + from functools import lru_cache + class Checker: + def check(self, nums, k, result): + n = len(nums) + size = n // k + valid = {} + for mask in range(1 << n): + if mask.bit_count() != size: + continue + values = [nums[i] for i in range(n) if (mask >> i) & 1] + if len(set(values)) == size: + valid[mask] = max(values) - min(values) + inf = 10 ** 9 + @lru_cache(None) + def solve(rem): + if rem == 0: + return 0 + first = (rem & -rem).bit_length() - 1 + best = inf + for mask, cost in valid.items(): + if (mask & rem) == mask and ((mask >> first) & 1): + best = min(best, cost + solve(rem ^ mask)) + return best + expected = solve((1 << n) - 1) + expected = -1 if expected == inf else expected + return isinstance(result, int) and result == expected + +seed: 1681 + +tests: + - name: example-one + in: + nums: [1, 2, 1, 4] + k: 2 + out: 4 + - name: example-two + in: + nums: [6, 3, 8, 1, 3, 1, 2, 2] + k: 4 + out: 6 + - name: example-three-impossible + in: + nums: [5, 3, 3, 6, 3, 3] + k: 3 + out: -1 + - name: duplicate-single-group + in: + nums: [1, 1] + k: 1 + out: -1 + - name: one-group-distinct + in: + nums: [1, 2] + k: 1 + out: 1 + - name: singleton-groups + in: + nums: [1, 2] + k: 2 + out: 0 + - name: paired-duplicates + in: + nums: [1, 1, 2, 2] + k: 2 + out: 2 + - name: four-two-groups + in: + nums: [1, 2, 3, 4] + k: 2 + out: 2 + - name: all-singletons + in: + nums: [1, 2, 3, 4] + k: 4 + out: 0 + - name: impossible-many-duplicates + in: + nums: [1, 1, 1, 1] + k: 2 + out: -1 + - name: duplicate-four-singletons + in: + nums: [1, 1, 1, 1] + k: 4 + out: 0 + - name: mixed-six + in: + nums: [1, 2, 1, 2, 3, 3] + k: 3 + out: 4 + - name: six-two-groups + in: + nums: [1, 2, 3, 4, 5, 6] + k: 2 + out: 4 + - name: six-three-groups + in: + nums: [1, 2, 3, 4, 5, 6] + k: 3 + out: 3 + - name: six-singletons + in: + nums: [1, 2, 3, 4, 5, 6] + k: 6 + out: 0 + - name: shuffled-eight + in: + nums: [1, 4, 2, 7, 3, 6, 5, 8] + k: 4 + out: 4 + - name: one-duplicate-six + in: + nums: [1, 1, 2, 3, 4, 5] + k: 2 + out: 6 + - name: paired-values-six + in: + nums: [2, 2, 3, 3, 4, 4] + k: 3 + out: 4 + - name: repeated-eight + in: + nums: [1, 2, 2, 3, 3, 4, 4, 5] + k: 4 + out: 4 + - name: repeated-middle-eight + in: + nums: [1, 2, 3, 3, 4, 5, 5, 6] + k: 4 + out: 5 + - name: pairs-eight + in: + nums: [1, 1, 2, 2, 3, 3, 4, 4] + k: 4 + out: 4 + - name: gap-eight + in: + nums: [1, 2, 3, 4, 4, 5, 6, 7] + k: 4 + out: 4 + - name: one-repeat-eight + in: + nums: [1, 2, 2, 3, 4, 5, 6, 7] + k: 4 + out: 4 + - name: low-repeat-eight + in: + nums: [1, 1, 2, 3, 4, 5, 6, 7] + k: 4 + out: 5 + - name: high-repeat-eight + in: + nums: [1, 2, 3, 4, 5, 5, 6, 7] + k: 4 + out: 5 + - name: eight-two-groups + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8] + k: 2 + out: 6 + - name: spaced-eight + in: + nums: [1, 3, 5, 7, 9, 11, 13, 15] + k: 4 + out: 8 + - name: duplicate-low-eight + in: + nums: [4, 4, 5, 6, 7, 8, 9, 10] + k: 4 + out: 5 + - name: nine-three-groups + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9] + k: 3 + out: 6 + - name: triple-pairs + in: + nums: [1, 1, 1, 2, 2, 2, 3, 3, 3] + k: 3 + out: 6 + - name: generated-sixteen-k-four + in: + nums: + gen: array + len: 16 + of: + gen: int + min: 1 + max: 16 + elemType: int + k: 4 + - name: generated-sixteen-k-two + in: + nums: + gen: array + len: 16 + of: + gen: int + min: 1 + max: 16 + elemType: int + k: 2 + - name: generated-twelve-k-three + in: + nums: + gen: array + len: 12 + of: + gen: int + min: 1 + max: 12 + elemType: int + k: 3 + - name: generated-fifteen-k-five + in: + nums: + gen: array + len: 15 + of: + gen: int + min: 1 + max: 15 + elemType: int + k: 5 + - name: generated-sixteen-k-eight + in: + nums: + gen: array + len: 16 + of: + gen: int + min: 1 + max: 16 + elemType: int + k: 8 diff --git a/tests/1501-2000/1681. minimum-incompatibility/sol.cpp b/tests/1501-2000/1681. minimum-incompatibility/sol.cpp new file mode 100644 index 00000000..6c9daac2 --- /dev/null +++ b/tests/1501-2000/1681. minimum-incompatibility/sol.cpp @@ -0,0 +1,59 @@ +class Solution { +public: + int minimumIncompatibility(vector& nums, int k) { + int n = nums.size(); + int sz = n / k; + + unordered_map counts; + for (int num : nums) { + counts[num]++; + } + for (auto& [num, v] : counts) { + if (v > k) return -1; + } + + sort(nums.begin(), nums.end()); + + unordered_map valid_subsets; + for (int mask = 0; mask < (1 << n); mask++) { + if (__builtin_popcount(mask) == sz) { + vector subset; + for (int i = 0; i < n; i++) { + if ((mask >> i) & 1) { + subset.push_back(nums[i]); + } + } + unordered_set set(subset.begin(), subset.end()); + if (set.size() == sz) { + int max_val = *max_element(subset.begin(), subset.end()); + int min_val = *min_element(subset.begin(), subset.end()); + valid_subsets[mask] = max_val - min_val; + } + } + } + + unordered_map memo; + function solve = [&](int remaining_mask) -> int { + if (remaining_mask == 0) return 0; + if (memo.count(remaining_mask)) return memo[remaining_mask]; + + int first_element = __builtin_ctz(remaining_mask & -remaining_mask); + int res = INT_MAX; + + for (auto& [mask, cost] : valid_subsets) { + if ((mask & remaining_mask) == mask && ((mask >> first_element) & 1)) { + int next = solve(remaining_mask ^ mask); + if (next != INT_MAX) { + res = min(res, cost + next); + } + } + } + + memo[remaining_mask] = res; + return res; + }; + + int ans = solve((1 << n) - 1); + return ans == INT_MAX ? -1 : ans; + } +}; diff --git a/tests/1501-2000/1681. minimum-incompatibility/sol.cs b/tests/1501-2000/1681. minimum-incompatibility/sol.cs new file mode 100644 index 00000000..127ef6b2 --- /dev/null +++ b/tests/1501-2000/1681. minimum-incompatibility/sol.cs @@ -0,0 +1,70 @@ +public class Solution { + public int MinimumIncompatibility(int[] nums, int k) { + int n = nums.Length; + int sz = n / k; + + var counts = new Dictionary(); + foreach (int num in nums) { + counts[num] = counts.GetValueOrDefault(num, 0) + 1; + } + foreach (var v in counts.Values) { + if (v > k) return -1; + } + + Array.Sort(nums); + + var validSubsets = new Dictionary(); + for (int mask = 0; mask < (1 << n); mask++) { + if (BitCount(mask) == sz) { + var subset = new List(); + for (int i = 0; i < n; i++) { + if (((mask >> i) & 1) == 1) { + subset.Add(nums[i]); + } + } + if (subset.Distinct().Count() == sz) { + int max = subset.Max(); + int min = subset.Min(); + validSubsets[mask] = max - min; + } + } + } + + var memo = new Dictionary(); + int Solve(int remainingMask) { + if (remainingMask == 0) return 0; + if (memo.ContainsKey(remainingMask)) return memo[remainingMask]; + + int firstElement = 0; + int bit = remainingMask & -remainingMask; + while ((bit >> firstElement) != 1) firstElement++; + int res = int.MaxValue; + + foreach (var kvp in validSubsets) { + int mask = kvp.Key; + int cost = kvp.Value; + if ((mask & remainingMask) == mask && ((mask >> firstElement) & 1) == 1) { + int next = Solve(remainingMask ^ mask); + if (next != int.MaxValue) { + res = Math.Min(res, cost + next); + } + } + } + + memo[remainingMask] = res; + return res; + } + + int ans = Solve((1 << n) - 1); + return ans == int.MaxValue ? -1 : ans; + } + + private int BitCount(int x) { + int count = 0; + while (x > 0) { + count += x & 1; + x >>= 1; + } + return count; + } +} diff --git a/tests/1501-2000/1681. minimum-incompatibility/sol.dart b/tests/1501-2000/1681. minimum-incompatibility/sol.dart new file mode 100644 index 00000000..eadedcfe --- /dev/null +++ b/tests/1501-2000/1681. minimum-incompatibility/sol.dart @@ -0,0 +1,58 @@ +class Solution { + int minimumIncompatibility(List nums, int k) { + int n = nums.length; + int sz = n ~/ k; + + Map counts = {}; + for (int num in nums) { + counts[num] = (counts[num] ?? 0) + 1; + } + for (int v in counts.values) { + if (v > k) return -1; + } + + nums.sort(); + + Map validSubsets = {}; + for (int mask = 0; mask < (1 << n); mask++) { + if (mask.toRadixString(2).split('1').length - 1 == sz) { + List subset = []; + for (int i = 0; i < n; i++) { + if (((mask >> i) & 1) == 1) { + subset.add(nums[i]); + } + } + Set set = subset.toSet(); + if (set.length == sz) { + int maxVal = subset.reduce((a, b) => a > b ? a : b); + int minVal = subset.reduce((a, b) => a < b ? a : b); + validSubsets[mask] = maxVal - minVal; + } + } + } + + Map memo = {}; + int solve(int remainingMask) { + if (remainingMask == 0) return 0; + if (memo.containsKey(remainingMask)) return memo[remainingMask]!; + + int firstElement = (remainingMask & -remainingMask).bitLength - 1; + int res = 1 << 30; + + validSubsets.forEach((mask, cost) { + if ((mask & remainingMask) == mask && ((mask >> firstElement) & 1) == 1) { + int next = solve(remainingMask ^ mask); + if (next != 1 << 30) { + res = res < cost + next ? res : cost + next; + } + } + }); + + memo[remainingMask] = res; + return res; + } + + int ans = solve((1 << n) - 1); + return ans == 1 << 30 ? -1 : ans; + } +} diff --git a/tests/1501-2000/1681. minimum-incompatibility/sol.go b/tests/1501-2000/1681. minimum-incompatibility/sol.go new file mode 100644 index 00000000..99f8d71d --- /dev/null +++ b/tests/1501-2000/1681. minimum-incompatibility/sol.go @@ -0,0 +1,79 @@ +func minimumIncompatibility(nums []int, k int) int { + n := len(nums) + sz := n / k + + counts := make(map[int]int) + for _, num := range nums { + counts[num]++ + } + for _, v := range counts { + if v > k { + return -1 + } + } + + sort.Ints(nums) + + validSubsets := make(map[int]int) + for mask := 0; mask < (1 << n); mask++ { + if bits.OnesCount(uint(mask)) == sz { + subset := []int{} + for i := 0; i < n; i++ { + if (mask>>i)&1 == 1 { + subset = append(subset, nums[i]) + } + } + set := make(map[int]bool) + for _, val := range subset { + set[val] = true + } + if len(set) == sz { + minVal := subset[0] + maxVal := subset[0] + for _, val := range subset { + if val < minVal { + minVal = val + } + if val > maxVal { + maxVal = val + } + } + validSubsets[mask] = maxVal - minVal + } + } + } + + memo := make(map[int]int) + var solve func(int) int + solve = func(remainingMask int) int { + if remainingMask == 0 { + return 0 + } + if val, ok := memo[remainingMask]; ok { + return val + } + + firstElement := bits.TrailingZeros(uint(remainingMask & -remainingMask)) + res := math.MaxInt32 + + for mask, cost := range validSubsets { + if mask&remainingMask == mask && (mask>>firstElement)&1 == 1 { + next := solve(remainingMask ^ mask) + if next != math.MaxInt32 { + if cost+next < res { + res = cost + next + } + } + } + } + + memo[remainingMask] = res + return res + } + + ans := solve((1 << n) - 1) + if ans == math.MaxInt32 { + return -1 + } + return ans +} diff --git a/tests/1501-2000/1681. minimum-incompatibility/sol.java b/tests/1501-2000/1681. minimum-incompatibility/sol.java new file mode 100644 index 00000000..5b1c0963 --- /dev/null +++ b/tests/1501-2000/1681. minimum-incompatibility/sol.java @@ -0,0 +1,59 @@ +class Solution { + public int minimumIncompatibility(int[] nums, int k) { + int n = nums.length; + int sz = n / k; + + Map counts = new HashMap<>(); + for (int num : nums) { + counts.put(num, counts.getOrDefault(num, 0) + 1); + } + for (int v : counts.values()) { + if (v > k) return -1; + } + + Arrays.sort(nums); + + Map validSubsets = new HashMap<>(); + for (int mask = 0; mask < (1 << n); mask++) { + if (Integer.bitCount(mask) == sz) { + List subset = new ArrayList<>(); + for (int i = 0; i < n; i++) { + if (((mask >> i) & 1) == 1) { + subset.add(nums[i]); + } + } + Set set = new HashSet<>(subset); + if (set.size() == sz) { + int max = Collections.max(subset); + int min = Collections.min(subset); + validSubsets.put(mask, max - min); + } + } + } + + Map memo = new HashMap<>(); + return solve((1 << n) - 1, validSubsets, memo); + } + + private int solve(int remainingMask, Map validSubsets, Map memo) { + if (remainingMask == 0) return 0; + if (memo.containsKey(remainingMask)) return memo.get(remainingMask); + + int firstElement = Integer.numberOfTrailingZeros(remainingMask & -remainingMask); + int res = Integer.MAX_VALUE; + + for (Map.Entry entry : validSubsets.entrySet()) { + int mask = entry.getKey(); + int cost = entry.getValue(); + if ((mask & remainingMask) == mask && ((mask >> firstElement) & 1) == 1) { + int next = solve(remainingMask ^ mask, validSubsets, memo); + if (next != Integer.MAX_VALUE) { + res = Math.min(res, cost + next); + } + } + } + + memo.put(remainingMask, res); + return res; + } +} diff --git a/tests/1501-2000/1681. minimum-incompatibility/sol.kt b/tests/1501-2000/1681. minimum-incompatibility/sol.kt new file mode 100644 index 00000000..a97a8d7b --- /dev/null +++ b/tests/1501-2000/1681. minimum-incompatibility/sol.kt @@ -0,0 +1,51 @@ +class Solution { + fun minimumIncompatibility(nums: IntArray, k: Int): Int { + val n = nums.size + val sz = n / k + + val counts = mutableMapOf() + for (value in nums) counts[value] = (counts[value] ?: 0) + 1 + if (counts.values.any { it > k }) return -1 + + nums.sort() + + val validSubsets = mutableMapOf() + for (mask in 0 until (1 shl n)) { + if (Integer.bitCount(mask) == sz) { + val subset = mutableListOf() + for (i in 0 until n) { + if (((mask shr i) and 1) == 1) { + subset.add(nums[i]) + } + } + if (subset.toSet().size == sz) { + validSubsets[mask] = subset.max()!! - subset.min()!! + } + } + } + + val memo = mutableMapOf() + fun solve(remainingMask: Int): Int { + if (remainingMask == 0) return 0 + memo[remainingMask]?.let { return it } + + val firstElement = Integer.numberOfTrailingZeros(remainingMask and -remainingMask) + var res = Int.MAX_VALUE + + for ((mask, cost) in validSubsets) { + if ((mask and remainingMask) == mask && ((mask shr firstElement) and 1) == 1) { + val next = solve(remainingMask xor mask) + if (next != Int.MAX_VALUE) { + res = minOf(res, cost + next) + } + } + } + + memo[remainingMask] = res + return res + } + + val ans = solve((1 shl n) - 1) + return if (ans == Int.MAX_VALUE) -1 else ans + } +} diff --git a/tests/1501-2000/1681. minimum-incompatibility/sol.py b/tests/1501-2000/1681. minimum-incompatibility/sol.py new file mode 100644 index 00000000..eb4aed68 --- /dev/null +++ b/tests/1501-2000/1681. minimum-incompatibility/sol.py @@ -0,0 +1,46 @@ +from functools import lru_cache + + +class Solution: + def minimumIncompatibility(self, nums: List[int], k: int) -> int: + n = len(nums) + sz = n // k + + # 1. Feasibility Constraint: Pigeonhole Principle + # If any element appears more than k times, partitioning is impossible + from collections import Counter + + counts = Counter(nums) + if any(v > k for v in counts.values()): + return -1 + + nums.sort() + + # 2. Candidate Generation (Pre-calculating valid subset costs) + # We only care about subsets of size 'sz' with unique elements + valid_subsets = {} + for mask in range(1 << n): + if bin(mask).count("1") == sz: + subset = [nums[i] for i in range(n) if (mask >> i) & 1] + if len(set(subset)) == sz: + valid_subsets[mask] = max(subset) - min(subset) + + # 3. Recursive Set Partitioning (The Optimization Manifold) + @lru_cache(None) + def solve(remaining_mask): + if remaining_mask == 0: + return 0 + + res = float("inf") + # To avoid redundant permutations, always include the first available element + first_element = (remaining_mask & -remaining_mask).bit_length() - 1 + + # Search for candidates that contain the 'first_element' + for mask, cost in valid_subsets.items(): + if (mask & remaining_mask) == mask and (mask >> first_element) & 1: + res = min(res, cost + solve(remaining_mask ^ mask)) + + return res + + ans = solve((1 << n) - 1) + return int(ans) if ans != float("inf") else -1 diff --git a/tests/1501-2000/1681. minimum-incompatibility/sol.py2 b/tests/1501-2000/1681. minimum-incompatibility/sol.py2 new file mode 100644 index 00000000..167a82f0 --- /dev/null +++ b/tests/1501-2000/1681. minimum-incompatibility/sol.py2 @@ -0,0 +1,40 @@ +class Solution(object): + def minimumIncompatibility(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + n = len(nums) + sz = n // k + + from collections import Counter + counts = Counter(nums) + if any(v > k for v in counts.values()): + return -1 + + nums.sort() + + valid_subsets = {} + for mask in range(1 << n): + if bin(mask).count('1') == sz: + subset = [nums[i] for i in range(n) if (mask >> i) & 1] + if len(set(subset)) == sz: + valid_subsets[mask] = max(subset) - min(subset) + + memo = {} + def solve(remaining_mask): + if remaining_mask == 0: + return 0 + if remaining_mask in memo: + return memo[remaining_mask] + res = float('inf') + first_element = (remaining_mask & -remaining_mask).bit_length() - 1 + for mask, cost in valid_subsets.items(): + if (mask & remaining_mask) == mask and (mask >> first_element) & 1: + res = min(res, cost + solve(remaining_mask ^ mask)) + memo[remaining_mask] = res + return res + + ans = solve((1 << n) - 1) + return int(ans) if ans != float('inf') else -1 diff --git a/tests/1501-2000/1681. minimum-incompatibility/sol.rb b/tests/1501-2000/1681. minimum-incompatibility/sol.rb new file mode 100644 index 00000000..e9cbf1cf --- /dev/null +++ b/tests/1501-2000/1681. minimum-incompatibility/sol.rb @@ -0,0 +1,46 @@ +# @param {Integer[]} nums +# @param {Integer} k +# @return {Integer} +def minimum_incompatibility(nums, k) + n = nums.length + sz = n / k + + counts = nums.tally + return -1 if counts.any? { |_, v| v > k } + + nums.sort! + + valid_subsets = {} + (0...(1 << n)).each do |mask| + if mask.to_s(2).count('1') == sz + subset = [] + (0...n).each do |i| + subset << nums[i] if (mask >> i) & 1 == 1 + end + if subset.uniq.length == sz + valid_subsets[mask] = subset.max - subset.min + end + end + end + + memo = {} + solve = lambda do |remaining_mask| + return 0 if remaining_mask == 0 + return memo[remaining_mask] if memo.key?(remaining_mask) + + res = Float::INFINITY + first_element = (remaining_mask & -remaining_mask).bit_length - 1 + + valid_subsets.each do |mask, cost| + if (mask & remaining_mask) == mask && ((mask >> first_element) & 1) == 1 + res = [res, cost + solve.call(remaining_mask ^ mask)].min + end + end + + memo[remaining_mask] = res + res + end + + ans = solve.call((1 << n) - 1) + ans == Float::INFINITY ? -1 : ans +end diff --git a/tests/1501-2000/1681. minimum-incompatibility/sol.rs b/tests/1501-2000/1681. minimum-incompatibility/sol.rs new file mode 100644 index 00000000..93842df2 --- /dev/null +++ b/tests/1501-2000/1681. minimum-incompatibility/sol.rs @@ -0,0 +1,62 @@ +impl Solution { + pub fn minimum_incompatibility(nums: Vec, k: i32) -> i32 { + let n = nums.len(); + let sz = n / k as usize; + + let mut counts = std::collections::HashMap::new(); + for &num in &nums { + *counts.entry(num).or_insert(0) += 1; + } + if counts.values().any(|&v| v > k) { + return -1; + } + + let mut nums = nums; + nums.sort(); + + let mut valid_subsets = std::collections::HashMap::new(); + for mask in 0i32..(1i32 << n) { + if mask.count_ones() as usize == sz { + let mut subset = Vec::new(); + for i in 0..n { + if (mask >> i) & 1 == 1 { + subset.push(nums[i]); + } + } + if subset.iter().collect::>().len() == sz { + let max = *subset.iter().max().unwrap(); + let min = *subset.iter().min().unwrap(); + valid_subsets.insert(mask, max - min); + } + } + } + + let mut memo = std::collections::HashMap::new(); + fn solve(remaining_mask: i32, valid_subsets: &std::collections::HashMap, memo: &mut std::collections::HashMap) -> i32 { + if remaining_mask == 0 { + return 0; + } + if let Some(&val) = memo.get(&remaining_mask) { + return val; + } + + let first_element = (remaining_mask & -remaining_mask).trailing_zeros() as usize; + let mut res = i32::MAX; + + for (&mask, &cost) in valid_subsets { + if (mask & remaining_mask) == mask && ((mask >> first_element) & 1) == 1 { + let next = solve(remaining_mask ^ mask, valid_subsets, memo); + if next != i32::MAX { + res = res.min(cost + next); + } + } + } + + memo.insert(remaining_mask, res); + res + } + + let ans = solve((1 << n) - 1, &valid_subsets, &mut memo); + if ans == i32::MAX { -1 } else { ans } + } +} diff --git a/tests/1501-2000/1681. minimum-incompatibility/sol.swift b/tests/1501-2000/1681. minimum-incompatibility/sol.swift new file mode 100644 index 00000000..c4d0d8e0 --- /dev/null +++ b/tests/1501-2000/1681. minimum-incompatibility/sol.swift @@ -0,0 +1,61 @@ +class Solution { + func minimumIncompatibility(_ nums: [Int], _ k: Int) -> Int { + let n = nums.count + let sz = n / k + + var counts: [Int: Int] = [:] + for num in nums { + counts[num, default: 0] += 1 + } + for v in counts.values { + if v > k { + return -1 + } + } + + let sortedNums = nums.sorted() + + var validSubsets: [Int: Int] = [:] + for mask in 0..<(1 << n) { + if mask.nonzeroBitCount == sz { + var subset: [Int] = [] + for i in 0..> i) & 1 == 1 { + subset.append(sortedNums[i]) + } + } + if Set(subset).count == sz { + validSubsets[mask] = subset.max()! - subset.min()! + } + } + } + + var memo: [Int: Int] = [:] + func solve(_ remainingMask: Int) -> Int { + if remainingMask == 0 { + return 0 + } + if let val = memo[remainingMask] { + return val + } + + let firstElement = (remainingMask & -remainingMask).trailingZeroBitCount + var res = Int.max + + for (mask, cost) in validSubsets { + if (mask & remainingMask) == mask && ((mask >> firstElement) & 1) == 1 { + let next = solve(remainingMask ^ mask) + if next != Int.max { + res = min(res, cost + next) + } + } + } + + memo[remainingMask] = res + return res + } + + let ans = solve((1 << n) - 1) + return ans == Int.max ? -1 : ans + } +} diff --git a/tests/1501-2000/1681. minimum-incompatibility/sol.ts b/tests/1501-2000/1681. minimum-incompatibility/sol.ts new file mode 100644 index 00000000..45b1160a --- /dev/null +++ b/tests/1501-2000/1681. minimum-incompatibility/sol.ts @@ -0,0 +1,66 @@ +function minimumIncompatibility(nums: number[], k: number): number { + const n = nums.length; + const sz = n / k; + + const counts = new Map(); + for (const num of nums) { + counts.set(num, (counts.get(num) || 0) + 1); + } + for (const v of counts.values()) { + if (v > k) return -1; + } + + nums.sort((a, b) => a - b); + + const validSubsets = new Map(); + for (let mask = 0; mask < 1 << n; mask++) { + if (bitCount(mask) === sz) { + const subset: number[] = []; + for (let i = 0; i < n; i++) { + if ((mask >> i) & 1) { + subset.push(nums[i]); + } + } + if (new Set(subset).size === sz) { + validSubsets.set(mask, Math.max(...subset) - Math.min(...subset)); + } + } + } + + const memo = new Map(); + function solve(remainingMask: number): number { + if (remainingMask === 0) return 0; + if (memo.has(remainingMask)) return memo.get(remainingMask)!; + + const firstElement = + (remainingMask & -remainingMask).toString(2).length - 1; + let res = Number.MAX_SAFE_INTEGER; + + for (const [mask, cost] of validSubsets) { + if ( + (mask & remainingMask) === mask && + ((mask >> firstElement) & 1) === 1 + ) { + const next = solve(remainingMask ^ mask); + if (next !== Number.MAX_SAFE_INTEGER) { + res = Math.min(res, cost + next); + } + } + } + + memo.set(remainingMask, res); + return res; + } + + const ans = solve((1 << n) - 1); + return ans === Number.MAX_SAFE_INTEGER ? -1 : ans; +} + +function bitCount(x: number): number { + let count = 0; + while (x > 0) { + count += x & 1; + x >>= 1; + } + return count; +} diff --git a/tests/1501-2000/1684. count-the-number-of-consistent-strings/manifest.yaml b/tests/1501-2000/1684. count-the-number-of-consistent-strings/manifest.yaml new file mode 100644 index 00000000..3418cd02 --- /dev/null +++ b/tests/1501-2000/1684. count-the-number-of-consistent-strings/manifest.yaml @@ -0,0 +1,283 @@ +entry: + id: 1684 + title: count-the-number-of-consistent-strings + params: + allowed: + type: string + words: + type: array + items: + type: string + call: + cpp: "Solution().countConsistentStrings({allowed}, {words})" + rust: "Solution::count_consistent_strings({allowed}, {words})" + python3: "Solution().countConsistentStrings({allowed}, {words})" + python2: "Solution().countConsistentStrings({allowed}, {words})" + ruby: "count_consistent_strings({allowed}, {words})" + java: "new Solution().countConsistentStrings({allowed}, {words})" + csharp: "new Solution().CountConsistentStrings({allowed}, {words})" + kotlin: "Solution().countConsistentStrings({allowed}, {words})" + go: "countConsistentStrings({allowed}, {words})" + dart: "Solution().countConsistentStrings({allowed}, {words})" + swift: "Solution().countConsistentStrings({allowed}, {words})" + typescript: "countConsistentStrings({allowed}, {words})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().countConsistentStrings(allowed, words, {result})" + checker: | + class Checker: + def countConsistentStrings(self, allowed, words, result): + if not isinstance(allowed, str) or not isinstance(words, list): + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + if len(allowed) < 1 or len(allowed) > 26 or len(set(allowed)) != len(allowed): + return False + if any(c < 'a' or c > 'z' for c in allowed): + return False + if len(words) < 1 or len(words) > 10000: + return False + if any(not isinstance(word, str) or len(word) < 1 or len(word) > 10 for word in words): + return False + if any(any(c < 'a' or c > 'z' for c in word) for word in words): + return False + expected = sum(1 for word in words if all(c in allowed for c in word)) + return result == expected + +seed: 1684 + +tests: + - name: example-one + in: + allowed: "ab" + words: ["ad", "bd", "aaab", "baa", "badab"] + out: 2 + - name: example-two-all-consistent + in: + allowed: "abc" + words: ["a", "b", "c", "ab", "ac", "bc", "abc"] + out: 7 + - name: example-three + in: + allowed: "cad" + words: ["cc", "acd", "b", "ba", "bac", "bad", "ac", "d"] + out: 4 + - name: one-letter-allowed + in: + allowed: "a" + words: ["a", "aa", "b", "ab", "aaa"] + out: 3 + - name: all-letters-allowed + in: + allowed: "abcdefghijklmnopqrstuvwxyz" + words: ["a", "z", "hello", "leetcode", "abcxyz"] + out: 5 + - name: no-word-consistent + in: + allowed: "xyz" + words: ["a", "ab", "hello", "world"] + out: 0 + - name: all-words-identical + in: + allowed: "abc" + words: ["abc", "abc", "abc", "abc"] + out: 4 + - name: repeated-characters + in: + allowed: "ab" + words: ["aaaa", "bbbb", "ababab", "cccc", "baac"] + out: 3 + - name: allowed-singleton-mixed + in: + allowed: "m" + words: ["m", "mmmmm", "n", "mn", "mmm"] + out: 3 + - name: one-invalid-character + in: + allowed: "abcdef" + words: ["abc", "abcdef", "abcg", "f", "z", "de"] + out: 4 + - name: disjoint-alphabet + in: + allowed: "abc" + words: ["x", "y", "z", "xy", "xyz"] + out: 0 + - name: alternating-valid-invalid + in: + allowed: "aeiou" + words: ["a", "b", "e", "f", "io", "jk", "ou", "xyz"] + out: 4 + - name: forbidden-lowercase-not-allowed + in: + allowed: "abc" + words: ["abc", "abx", "axc", "cab"] + out: 2 + - name: max-word-length + in: + allowed: "abc" + words: ["abcabcabca", "cccccccccc", "abcabcdefg", "aaaaaaaaaa"] + out: 3 + - name: single-word-valid + in: + allowed: "qwerty" + words: ["type"] + out: 0 + - name: single-word-invalid + in: + allowed: "qwerty" + words: ["python"] + out: 0 + - name: boundary-alphabet-prefix + in: + allowed: "abcdefghijklm" + words: ["abcdefghijklm", "nop", "abc", "mn", "z", "ghijk"] + out: 3 + - name: boundary-alphabet-suffix + in: + allowed: "nopqrstuvwxyz" + words: ["nop", "xyz", "abc", "mnop", "qrst", "lm"] + out: 3 + - name: empty-not-permitted-word-replacement + in: + allowed: "d" + words: ["d", "dd", "ddd", "c", "dc", "cd"] + out: 3 + - name: every-word-has-one-forbidden + in: + allowed: "ab" + words: ["ac", "bd", "ca", "db", "abc", "babd"] + out: 0 + - name: one-forbidden-at-end + in: + allowed: "abc" + words: ["a", "ab", "abc", "abcz", "zz", "cab"] + out: 4 + - name: one-forbidden-at-start + in: + allowed: "abc" + words: ["za", "zab", "zabc", "a", "bc", "cba"] + out: 3 + - name: two-character-alphabet + in: + allowed: "az" + words: ["a", "z", "az", "za", "aaazzz", "b", "zab"] + out: 5 + - name: vowel-only + in: + allowed: "aeiou" + words: ["aeiou", "uoiea", "queue", "sequoia", "ai", "b"] + out: 3 + - name: consonant-only + in: + allowed: "bcdfg" + words: ["bcdfg", "big", "dog", "gfd", "abc", "cf"] + out: 3 + - name: duplicates-in-words + in: + allowed: "xyz" + words: ["xxyyzz", "xyzxyz", "xxx", "xyza", "yy"] + out: 4 + - name: long-valid-and-invalid + in: + allowed: "abcdefghij" + words: + ["abcdefghij", "jihgfedcba", "abcdefghik", "aaaaaaaaaa", "klmnopqrst"] + out: 3 + - name: near-complete-alphabet + in: + allowed: "abcdefghijklmnopqrstuvwxy" + words: ["abcdefghijklmnopqrstuvwxy", "z", "xy", "yz", "mnopqrst"] + out: 3 + - name: all-single-character-words + in: + allowed: "ace" + words: ["a", "b", "c", "d", "e", "f", "a", "c"] + out: 5 + - name: valid-prefixes + in: + allowed: "leetcode" + words: ["leet", "code", "leetcode", "leetx", "cool", "to", "e"] + out: 6 + - name: forbidden-middle + in: + allowed: "abc" + words: ["a", "abc", "axbc", "abxc", "abcx", "bac"] + out: 3 + - name: alternating-allowed + in: + allowed: "bd" + words: ["bd", "dbdb", "bbbb", "dddd", "abcd", "dcb"] + out: 4 + - name: maximal-count-small-list + in: + allowed: "a" + words: ["a", "a", "a", "a", "a", "b", "b", "aa", "aaa"] + out: 7 + - name: maximal-count-large-alphabet + in: + allowed: "abcdefghijklmnopqrstuvwxyz" + words: ["zxy", "abc", "leetcode", "zzzzzzzzzz", "qwertyuiop"] + out: 5 + - name: generated-small + in: + allowed: "abc" + words: + gen: "array" + len: 20 + of: + gen: "str" + len: 5 + alphabet: "abcde" + elemType: "string" + - name: generated-single-character + in: + allowed: "m" + words: + gen: "array" + len: 100 + of: + gen: "str" + len: 1 + alphabet: "mno" + elemType: "string" + - name: generated-medium + in: + allowed: "abcdefghijklm" + words: + gen: "array" + len: 1000 + of: + gen: "str" + len: 10 + alphabet: "abcmnz" + elemType: "string" + - name: generated-near-max + in: + allowed: "aeiou" + words: + gen: "array" + len: 10000 + of: + gen: "str" + len: 10 + alphabet: "aeioub" + elemType: "string" + - name: generated-maximal-alphabet + in: + allowed: "abcdefghijklmnopqrstuvwxyz" + words: + gen: "array" + len: 10000 + of: + gen: "str" + len: 10 + alphabet: "abcdefghijklmnopqrstuvwxyz" + elemType: "string" diff --git a/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.cpp b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.cpp new file mode 100644 index 00000000..a33e2aed --- /dev/null +++ b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int countConsistentStrings(string allowed, vector& words) { + int result = 0; + unordered_set allowedSet(allowed.begin(), allowed.end()); + for (const string& word : words) { + bool allIn = true; + for (char c : word) { + if (allowedSet.find(c) == allowedSet.end()) { + allIn = false; + break; + } + } + if (allIn) result++; + } + return result; + } +}; diff --git a/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.cs b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.cs new file mode 100644 index 00000000..a8767359 --- /dev/null +++ b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.cs @@ -0,0 +1,17 @@ +public class Solution { + public int CountConsistentStrings(string allowed, string[] words) { + int result = 0; + var allowedSet = new HashSet(allowed); + foreach (string word in words) { + bool allIn = true; + foreach (char c in word) { + if (!allowedSet.Contains(c)) { + allIn = false; + break; + } + } + if (allIn) result++; + } + return result; + } +} diff --git a/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.dart b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.dart new file mode 100644 index 00000000..0bba8151 --- /dev/null +++ b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.dart @@ -0,0 +1,10 @@ +class Solution { + int countConsistentStrings(String allowed, List words) { + final allowedSet = allowed.split('').toSet(); + var result = 0; + for (final word in words) { + if (word.split('').every(allowedSet.contains)) result++; + } + return result; + } +} diff --git a/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.go b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.go new file mode 100644 index 00000000..d3c064db --- /dev/null +++ b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.go @@ -0,0 +1,20 @@ +func countConsistentStrings(allowed string, words []string) int { + result := 0 + allowedSet := make(map[rune]bool) + for _, c := range allowed { + allowedSet[c] = true + } + for _, word := range words { + allIn := true + for _, c := range word { + if !allowedSet[c] { + allIn = false + break + } + } + if allIn { + result++ + } + } + return result +} diff --git a/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.java b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.java new file mode 100644 index 00000000..0537829e --- /dev/null +++ b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.java @@ -0,0 +1,22 @@ +class Solution { + public int countConsistentStrings(String allowed, String[] words) { + int result = 0; + java.util.Set allowedSet = new java.util.HashSet<>(); + for (char c : allowed.toCharArray()) { + allowedSet.add(c); + } + for (String word : words) { + boolean allIn = true; + for (char c : word.toCharArray()) { + if (!allowedSet.contains(c)) { + allIn = false; + break; + } + } + if (allIn) { + result++; + } + } + return result; + } +} diff --git a/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.kt b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.kt new file mode 100644 index 00000000..0f0abe68 --- /dev/null +++ b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.kt @@ -0,0 +1,17 @@ +class Solution { + fun countConsistentStrings(allowed: String, words: Array): Int { + var result = 0 + val allowedSet = allowed.toSet() + for (word in words) { + var allIn = true + for (c in word) { + if (c !in allowedSet) { + allIn = false + break + } + } + if (allIn) result++ + } + return result + } +} diff --git a/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.py b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.py new file mode 100644 index 00000000..50ade4b4 --- /dev/null +++ b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.py @@ -0,0 +1,13 @@ +class Solution: + def countConsistentStrings(self, allowed: str, words: List[str]) -> int: + result = 0 + allowed = set(allowed) + for word in words: + all_in = True + for c in word: + if c not in allowed: + all_in = False + break + if all_in is True: + result += 1 + return result diff --git a/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.py2 b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.py2 new file mode 100644 index 00000000..2288f9fd --- /dev/null +++ b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def countConsistentStrings(self, allowed, words): + """ + :type allowed: str + :type words: List[str] + :rtype: int + """ + result = 0 + allowed_set = set(allowed) + for word in words: + all_in = True + for c in word: + if c not in allowed_set: + all_in = False + break + if all_in: + result += 1 + return result diff --git a/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.rb b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.rb new file mode 100644 index 00000000..1876ea64 --- /dev/null +++ b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.rb @@ -0,0 +1,18 @@ +# @param {String} allowed +# @param {String[]} words +# @return {Integer} +def count_consistent_strings(allowed, words) + result = 0 + allowed_set = allowed.chars.to_set + words.each do |word| + all_in = true + word.each_char do |c| + unless allowed_set.include?(c) + all_in = false + break + end + end + result += 1 if all_in + end + result +end diff --git a/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.rs b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.rs new file mode 100644 index 00000000..3301be5d --- /dev/null +++ b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn count_consistent_strings(allowed: String, words: Vec) -> i32 { + let mut result = 0; + let allowed_set: std::collections::HashSet = allowed.chars().collect(); + for word in words { + let mut all_in = true; + for c in word.chars() { + if !allowed_set.contains(&c) { + all_in = false; + break; + } + } + if all_in { + result += 1; + } + } + result + } +} diff --git a/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.swift b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.swift new file mode 100644 index 00000000..cb0cd3f5 --- /dev/null +++ b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.swift @@ -0,0 +1,19 @@ +class Solution { + func countConsistentStrings(_ allowed: String, _ words: [String]) -> Int { + var result = 0 + let allowedSet = Set(allowed) + for word in words { + var allIn = true + for c in word { + if !allowedSet.contains(c) { + allIn = false + break + } + } + if allIn { + result += 1 + } + } + return result + } +} diff --git a/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.ts b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.ts new file mode 100644 index 00000000..4813357a --- /dev/null +++ b/tests/1501-2000/1684. count-the-number-of-consistent-strings/sol.ts @@ -0,0 +1,15 @@ +function countConsistentStrings(allowed: string, words: string[]): number { + let result = 0; + const allowedSet = new Set(allowed); + for (const word of words) { + let allIn = true; + for (const c of word) { + if (!allowedSet.has(c)) { + allIn = false; + break; + } + } + if (allIn) result++; + } + return result; +} diff --git a/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/manifest.yaml b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/manifest.yaml new file mode 100644 index 00000000..ed4dab47 --- /dev/null +++ b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/manifest.yaml @@ -0,0 +1,298 @@ +entry: + id: 1685 + title: "sum-of-absolute-differences-in-a-sorted-array" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().getSumAbsoluteDifferences({nums})" + rust: "Solution::get_sum_absolute_differences({nums})" + python3: "Solution().getSumAbsoluteDifferences({nums})" + python2: "Solution().getSumAbsoluteDifferences({nums})" + ruby: "get_sum_absolute_differences({nums})" + java: "new Solution().getSumAbsoluteDifferences({nums})" + csharp: "new Solution().GetSumAbsoluteDifferences({nums})" + kotlin: "Solution().getSumAbsoluteDifferences({nums})" + go: "getSumAbsoluteDifferences({nums})" + dart: "Solution().getSumAbsoluteDifferences({nums})" + swift: "Solution().getSumAbsoluteDifferences({nums})" + typescript: "getSumAbsoluteDifferences({nums})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().getSumAbsoluteDifferences(nums, {result})" + checker: | + class Checker: + def getSumAbsoluteDifferences(self, nums, result): + if not isinstance(nums, list) or not isinstance(result, list): + return False + if len(nums) != len(result) or len(nums) < 2: + return False + if any(not isinstance(x, int) or isinstance(x, bool) for x in nums): + return False + if any(nums[i] > nums[i + 1] for i in range(len(nums) - 1)): + return False + prefix = 0 + total = sum(nums) + expected = [] + n = len(nums) + for i, value in enumerate(nums): + left = value * i - prefix + right = (total - prefix - value) - value * (n - i - 1) + expected.append(left + right) + prefix += value + return result == expected + +seed: 1685001 + +tests: + - name: "example_one" + in: + nums: [2, 3, 5] + out: [4, 3, 5] + - name: "example_two" + in: + nums: [1, 4, 6, 8, 10] + out: [24, 15, 13, 15, 21] + - name: "minimum_length" + in: + nums: [1, 2] + out: [1, 1] + - name: "equal_pair" + in: + nums: [7, 7] + out: [0, 0] + - name: "all_equal" + in: + nums: [5, 5, 5, 5, 5, 5] + out: [0, 0, 0, 0, 0, 0] + - name: "three_duplicates" + in: + nums: [1, 1, 3] + out: [2, 2, 4] + - name: "negative_not_allowed_boundary" + in: + nums: [1, 1, 2, 2, 3] + out: [4, 4, 3, 3, 6] + - name: "consecutive_small" + in: + nums: [1, 2, 3, 4, 5] + out: [10, 7, 6, 7, 10] + - name: "large_gap" + in: + nums: [1, 10000] + out: [9999, 9999] + - name: "extreme_endpoints" + in: + nums: [1, 1, 1, 10000, 10000] + out: [19998, 19998, 19998, 29997, 29997] + - name: "repeated_blocks" + in: + nums: [2, 2, 2, 8, 8, 8] + out: [18, 18, 18, 18, 18, 18] + - name: "uneven_duplicates" + in: + nums: [1, 2, 2, 2, 10] + out: [12, 9, 9, 9, 33] + - name: "near_max_values" + in: + nums: [9996, 9997, 9998, 9999, 10000] + out: [10, 7, 6, 7, 10] + - name: "wide_progression" + in: + nums: [1, 100, 200, 500, 1000] + out: [1796, 1499, 1399, 1699, 3199] + - name: "seven_values" + in: + nums: [1, 3, 3, 6, 9, 9, 10] + out: [34, 24, 24, 21, 24, 24, 29] + - name: "alternating_gaps" + in: + nums: [1, 2, 10, 11, 100, 101] + out: [219, 215, 199, 199, 377, 381] + - name: "ten_consecutive" + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + out: [45, 37, 31, 27, 25, 25, 27, 31, 37, 45] + - name: "ten_equal" + in: + nums: [42, 42, 42, 42, 42, 42, 42, 42, 42, 42] + out: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: "powers_and_gaps" + in: + nums: [1, 2, 4, 8, 16, 32] + out: [57, 53, 49, 49, 65, 129] + - name: "one_low_many_high" + in: + nums: [1, 9000, 9000, 9000, 9000, 10000] + out: [45995, 9999, 9999, 9999, 9999, 13999] + - name: "three_clusters" + in: + nums: [10, 10, 10, 20, 20, 30, 30, 30] + out: [80, 80, 80, 60, 60, 80, 80, 80] + - name: "dense_low_range" + in: + nums: [1, 1, 2, 3, 3, 4, 5, 5, 5] + out: [20, 20, 15, 12, 12, 13, 16, 16, 16] + - name: "large_duplicate_middle" + in: + nums: [1, 2, 50, 50, 50, 50, 99] + out: [295, 290, 146, 146, 146, 146, 391] + - name: "boundary_minimum_repeated" + in: + nums: [1, 1, 1, 1, 2, 3] + out: [3, 3, 3, 3, 5, 9] + - name: "boundary_maximum_repeated" + in: + nums: [9998, 9999, 10000, 10000, 10000, 10000] + out: [9, 5, 3, 3, 3, 3] + - name: "balanced_values" + in: + nums: [2, 4, 6, 8, 10, 12, 14] + out: [42, 32, 26, 24, 26, 32, 42] + - name: "irregular_eight" + in: + nums: [1, 4, 4, 7, 12, 12, 20, 25] + out: [77, 59, 59, 53, 53, 53, 85, 115] + - name: "fourteen_consecutive" + in: + nums: + [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113] + out: [91, 79, 69, 61, 55, 51, 49, 49, 51, 55, 61, 69, 79, 91] + - name: "very_sparse" + in: + nums: [1, 10, 100, 1000, 5000, 10000] + out: [16105, 16069, 15889, 15889, 23889, 43889] + - name: "twenty_mixed" + in: + nums: + [ + 1, + 1, + 2, + 2, + 3, + 5, + 8, + 13, + 21, + 34, + 55, + 89, + 144, + 233, + 377, + 610, + 987, + 1597, + 2584, + 4181, + ] + out: + [ + 10927, + 10927, + 10911, + 10911, + 10899, + 10879, + 10855, + 10825, + 10793, + 10767, + 10767, + 10835, + 11055, + 11589, + 12741, + 15071, + 19595, + 28135, + 43927, + 72673, + ] + - name: "generated_small_sorted" + seed: 168501 + in: + nums: + gen: "array" + len: + gen: "int" + min: 2 + max: 30 + of: + gen: "int" + min: 1 + max: 10000 + sorted: true + distinct: false + + - name: "generated_medium_sorted" + seed: 168502 + in: + nums: + gen: "array" + len: + gen: "int" + min: 100 + max: 500 + of: + gen: "int" + min: 1 + max: 10000 + sorted: true + distinct: false + + - name: "generated_duplicate_heavy" + seed: 168503 + in: + nums: + gen: "array" + len: + gen: "int" + min: 1000 + max: 3000 + of: + gen: "int" + min: 1 + max: 10 + sorted: true + distinct: false + + - name: "generated_large_full_range" + seed: 168504 + in: + nums: + gen: "array" + len: + gen: "int" + min: 80000 + max: 100000 + of: + gen: "int" + min: 1 + max: 10000 + sorted: true + distinct: false + + - name: "generated_large_constant" + seed: 168505 + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 5000 + max: 5000 + sorted: true + distinct: false diff --git a/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.cpp b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.cpp new file mode 100644 index 00000000..5350a212 --- /dev/null +++ b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector getSumAbsoluteDifferences(vector& nums) { + int n = nums.size(); + vector pref(n); + pref[0] = nums[0]; + for (int i = 1; i < n; i++) pref[i] = pref[i-1] + nums[i]; + vector ans(n); + for (int i = 0; i < n; i++) { + int left = i > 0 ? pref[i-1] : 0; + int right = pref[n-1] - pref[i]; + ans[i] = right - left + (2*i - n + 1) * nums[i]; + } + return ans; + } +}; diff --git a/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.cs b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.cs new file mode 100644 index 00000000..05bbe9b6 --- /dev/null +++ b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int[] GetSumAbsoluteDifferences(int[] nums) { + int n = nums.Length; + int[] pref = new int[n]; + pref[0] = nums[0]; + for (int i = 1; i < n; i++) pref[i] = pref[i-1] + nums[i]; + int[] ans = new int[n]; + for (int i = 0; i < n; i++) { + int left = i > 0 ? pref[i-1] : 0; + int right = pref[n-1] - pref[i]; + ans[i] = right - left + (2*i - n + 1) * nums[i]; + } + return ans; + } +} diff --git a/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.dart b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.dart new file mode 100644 index 00000000..e0ffedea --- /dev/null +++ b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.dart @@ -0,0 +1,17 @@ +class Solution { + List getSumAbsoluteDifferences(List nums) { + final n = nums.length; + final prefix = List.filled(n, 0); + prefix[0] = nums[0]; + for (var i = 1; i < n; i++) { + prefix[i] = prefix[i - 1] + nums[i]; + } + final result = []; + for (var i = 0; i < n; i++) { + final left = i == 0 ? 0 : prefix[i - 1]; + final right = prefix[n - 1] - prefix[i]; + result.add(right - left + (2 * i - n + 1) * nums[i]); + } + return result; + } +} diff --git a/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.go b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.go new file mode 100644 index 00000000..64d2b8d1 --- /dev/null +++ b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.go @@ -0,0 +1,16 @@ +func getSumAbsoluteDifferences(nums []int) []int { + n := len(nums) + pref := make([]int, n) + pref[0] = nums[0] + for i := 1; i < n; i++ { + pref[i] = pref[i-1] + nums[i] + } + ans := make([]int, n) + for i := 0; i < n; i++ { + left := 0 + if i > 0 { left = pref[i-1] } + right := pref[n-1] - pref[i] + ans[i] = right - left + (2*i - n + 1) * nums[i] + } + return ans +} diff --git a/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.java b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.java new file mode 100644 index 00000000..f8a1326e --- /dev/null +++ b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.java @@ -0,0 +1,15 @@ +class Solution { + public int[] getSumAbsoluteDifferences(int[] nums) { + int n = nums.length; + int[] pref = new int[n]; + pref[0] = nums[0]; + for (int i = 1; i < n; i++) pref[i] = pref[i-1] + nums[i]; + int[] ans = new int[n]; + for (int i = 0; i < n; i++) { + int left = i > 0 ? pref[i-1] : 0; + int right = pref[n-1] - pref[i]; + ans[i] = right - left + (2*i - n + 1) * nums[i]; + } + return ans; + } +} diff --git a/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.kt b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.kt new file mode 100644 index 00000000..55881ed2 --- /dev/null +++ b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun getSumAbsoluteDifferences(nums: IntArray): IntArray { + val n = nums.size + val pref = IntArray(n) + pref[0] = nums[0] + for (i in 1 until n) pref[i] = pref[i-1] + nums[i] + val ans = IntArray(n) + for (i in 0 until n) { + val left = if (i > 0) pref[i-1] else 0 + val right = pref[n-1] - pref[i] + ans[i] = right - left + (2*i - n + 1) * nums[i] + } + return ans + } +} diff --git a/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.py b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.py new file mode 100644 index 00000000..d1b2b013 --- /dev/null +++ b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.py @@ -0,0 +1,18 @@ +class Solution: + def getSumAbsoluteDifferences(self, nums: List[int]) -> List[int]: + n = len(nums) + pref = [0] * n + pref[0] = nums[0] + + for i in range(1, n): + pref[i] = pref[i - 1] + nums[i] + + ans = [] + for i in range(n): + left = 0 + if i > 0: + left = pref[i - 1] + right = pref[n - 1] - pref[i] + ans.append(right - left + (2 * i - n + 1) * nums[i]) + + return ans diff --git a/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.py2 b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.py2 new file mode 100644 index 00000000..2a16a79a --- /dev/null +++ b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.py2 @@ -0,0 +1,17 @@ +class Solution(object): + def getSumAbsoluteDifferences(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + n = len(nums) + pref = [0] * n + pref[0] = nums[0] + for i in range(1, n): + pref[i] = pref[i-1] + nums[i] + ans = [] + for i in range(n): + left = pref[i-1] if i > 0 else 0 + right = pref[n-1] - pref[i] + ans.append(right - left + (2*i - n + 1) * nums[i]) + return ans diff --git a/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.rb b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.rb new file mode 100644 index 00000000..88fad27a --- /dev/null +++ b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.rb @@ -0,0 +1,15 @@ +# @param {Integer[]} nums +# @return {Integer[]} +def get_sum_absolute_differences(nums) + n = nums.length + pref = Array.new(n) + pref[0] = nums[0] + (1...n).each { |i| pref[i] = pref[i-1] + nums[i] } + ans = [] + (0...n).each do |i| + left = i > 0 ? pref[i-1] : 0 + right = pref[n-1] - pref[i] + ans << (right - left + (2*i - n + 1) * nums[i]) + end + ans +end diff --git a/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.rs b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.rs new file mode 100644 index 00000000..c6d72f75 --- /dev/null +++ b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn get_sum_absolute_differences(nums: Vec) -> Vec { + let n = nums.len(); + let mut pref = vec![0; n]; + pref[0] = nums[0]; + for i in 1..n { + pref[i] = pref[i-1] + nums[i]; + } + let mut ans = Vec::with_capacity(n); + for i in 0..n { + let left = if i > 0 { pref[i-1] } else { 0 }; + let right = pref[n-1] - pref[i]; + ans.push(right - left + (2*i as i32 - n as i32 + 1) * nums[i]); + } + ans + } +} diff --git a/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.swift b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.swift new file mode 100644 index 00000000..0c1c4e62 --- /dev/null +++ b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func getSumAbsoluteDifferences(_ nums: [Int]) -> [Int] { + let n = nums.count + var pref = Array(repeating: 0, count: n) + pref[0] = nums[0] + for i in 1.. 0 ? pref[i-1] : 0 + let right = pref[n-1] - pref[i] + ans.append(right - left + (2*i - n + 1) * nums[i]) + } + return ans + } +} diff --git a/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.ts b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.ts new file mode 100644 index 00000000..a251bded --- /dev/null +++ b/tests/1501-2000/1685. sum-of-absolute-differences-in-a-sorted-array/sol.ts @@ -0,0 +1,13 @@ +function getSumAbsoluteDifferences(nums: number[]): number[] { + const n = nums.length; + const pref: number[] = new Array(n); + pref[0] = nums[0]; + for (let i = 1; i < n; i++) pref[i] = pref[i - 1] + nums[i]; + const ans: number[] = []; + for (let i = 0; i < n; i++) { + const left = i > 0 ? pref[i - 1] : 0; + const right = pref[n - 1] - pref[i]; + ans.push(right - left + (2 * i - n + 1) * nums[i]); + } + return ans; +} diff --git a/tests/1501-2000/1686. stone-game-vi/manifest.yaml b/tests/1501-2000/1686. stone-game-vi/manifest.yaml new file mode 100644 index 00000000..88821af9 --- /dev/null +++ b/tests/1501-2000/1686. stone-game-vi/manifest.yaml @@ -0,0 +1,356 @@ +entry: + id: 1686 + title: "stone-game-vi" + params: + aliceValues: + type: array + items: + type: int + bobValues: + type: array + items: + type: int + call: + cpp: "Solution().stoneGameVI({aliceValues}, {bobValues})" + rust: "Solution::stone_game_vi({aliceValues}, {bobValues})" + python3: "Solution().stoneGameVI({aliceValues}, {bobValues})" + python2: "Solution().stoneGameVI({aliceValues}, {bobValues})" + ruby: "stone_game_vi({aliceValues}, {bobValues})" + java: "new Solution().stoneGameVI({aliceValues}, {bobValues})" + csharp: "new Solution().StoneGameVI({aliceValues}, {bobValues})" + kotlin: "Solution().stoneGameVI({aliceValues}, {bobValues})" + go: "stoneGameVI({aliceValues}, {bobValues})" + dart: "Solution().stoneGameVI({aliceValues}, {bobValues})" + swift: "Solution().stoneGameVI({aliceValues}, {bobValues})" + typescript: "stoneGameVI({aliceValues}, {bobValues})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().stoneGameVI(aliceValues, bobValues, {result})" + checker: | + class Checker: + def stoneGameVI(self, aliceValues, bobValues, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + order = sorted(zip(aliceValues, bobValues), key=lambda p: p[0] + p[1], reverse=True) + alice = sum(a for i, (a, b) in enumerate(order) if i % 2 == 0) + bob = sum(b for i, (a, b) in enumerate(order) if i % 2 == 1) + expected = 1 if alice > bob else (-1 if alice < bob else 0) + return result == expected +seed: 1686 +tests: + - name: example-one + in: + aliceValues: [1, 3] + bobValues: [2, 1] + out: 1 + - name: example-two + in: + aliceValues: [1, 2] + bobValues: [3, 1] + out: 0 + - name: example-three + in: + aliceValues: [2, 4, 3] + bobValues: [1, 6, 7] + out: -1 + - name: one-stone-alice + in: + aliceValues: [100] + bobValues: [1] + out: 1 + - name: one-stone-bob + in: + aliceValues: [1] + bobValues: [100] + out: 1 + - name: one-stone-tie + in: + aliceValues: [7] + bobValues: [7] + out: 1 + - name: two-clear-alice + in: + aliceValues: [9, 1] + bobValues: [1, 1] + out: 1 + - name: two-clear-bob + in: + aliceValues: [1, 1] + bobValues: [9, 1] + out: 0 + - name: two-tie + in: + aliceValues: [5, 5] + bobValues: [5, 5] + out: 0 + - name: descending-total + in: + aliceValues: [10, 1, 1, 1] + bobValues: [10, 1, 1, 1] + out: 1 + - name: equal-total-different-values + in: + aliceValues: [9, 8, 7, 6] + bobValues: [1, 2, 3, 4] + out: 1 + - name: reverse-equal-total + in: + aliceValues: [1, 2, 3, 4] + bobValues: [9, 8, 7, 6] + out: -1 + - name: all-ones-odd + in: + aliceValues: [1, 1, 1, 1, 1] + bobValues: [1, 1, 1, 1, 1] + out: 1 + - name: all-ones-even + in: + aliceValues: [1, 1, 1, 1, 1, 1] + bobValues: [1, 1, 1, 1, 1, 1] + out: 0 + - name: max-values-odd + in: + aliceValues: [100, 100, 100, 100, 100] + bobValues: [100, 100, 100, 100, 100] + out: 1 + - name: max-values-even + in: + aliceValues: [100, 100, 100, 100] + bobValues: [100, 100, 100, 100] + out: 0 + - name: alternating-high-alice + in: + aliceValues: [100, 1, 100, 1, 100, 1] + bobValues: [1, 100, 1, 100, 1, 100] + out: 0 + - name: alternating-high-bob + in: + aliceValues: [1, 100, 1, 100, 1, 100] + bobValues: [100, 1, 100, 1, 100, 1] + out: 0 + - name: tie-breaking-order + in: + aliceValues: [4, 3, 2] + bobValues: [3, 4, 5] + out: 1 + - name: late-high-total + in: + aliceValues: [1, 1, 1, 50] + bobValues: [1, 1, 1, 50] + out: 1 + - name: many-equal-totals + in: + aliceValues: [6, 5, 4, 3, 2, 1] + bobValues: [4, 5, 6, 7, 8, 9] + out: -1 + - name: asymmetric-small + in: + aliceValues: [2, 2, 2, 2, 2, 2, 2] + bobValues: [1, 1, 1, 1, 1, 1, 1] + out: 1 + - name: asymmetric-bob + in: + aliceValues: [1, 1, 1, 1, 1, 1, 1] + bobValues: [2, 2, 2, 2, 2, 2, 2] + out: -1 + - name: mixed-nine + in: + aliceValues: [8, 1, 7, 2, 6, 3, 5, 4, 9] + bobValues: [2, 9, 3, 8, 4, 7, 5, 6, 1] + out: 1 + - name: mixed-ten + in: + aliceValues: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] + bobValues: [100, 90, 80, 70, 60, 50, 40, 30, 20, 10] + out: 0 + - name: repeated-high-totals + in: + aliceValues: [50, 50, 49, 49, 1, 1] + bobValues: [50, 49, 50, 49, 1, 1] + out: 1 + - name: skewed-values + in: + aliceValues: [100, 2, 2, 2, 2] + bobValues: [1, 99, 99, 99, 99] + out: -1 + - name: alternating-totals + in: + aliceValues: [40, 1, 30, 2, 20, 3, 10, 4] + bobValues: [1, 40, 2, 30, 3, 20, 4, 10] + out: 0 + - name: fifteen-balanced + in: + aliceValues: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + bobValues: [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + out: 1 + - name: fifteen-reversed + in: + aliceValues: [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + bobValues: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + out: 1 + - name: thirty-one-ones + in: + aliceValues: + [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + ] + bobValues: + [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + ] + out: 1 + - name: generated-small + in: + aliceValues: + gen: "array" + len: 25 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + bobValues: + gen: "array" + len: 25 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + - name: generated-medium + in: + aliceValues: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + bobValues: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + - name: generated-large + in: + aliceValues: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + bobValues: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + - name: generated-large-low + in: + aliceValues: + gen: "array" + len: 99999 + of: + gen: "int" + min: 1 + max: 3 + elemType: "int" + bobValues: + gen: "array" + len: 99999 + of: + gen: "int" + min: 1 + max: 3 + elemType: "int" + - name: generated-large-high + in: + aliceValues: + gen: "array" + len: 100000 + of: + gen: "int" + min: 98 + max: 100 + elemType: "int" + bobValues: + gen: "array" + len: 100000 + of: + gen: "int" + min: 98 + max: 100 + elemType: "int" diff --git a/tests/1501-2000/1686. stone-game-vi/sol.cpp b/tests/1501-2000/1686. stone-game-vi/sol.cpp new file mode 100644 index 00000000..eb10ea3b --- /dev/null +++ b/tests/1501-2000/1686. stone-game-vi/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int stoneGameVI(vector& aliceValues, vector& bobValues) { + int n = aliceValues.size(); + vector> combined(n, vector(3)); + for (int i = 0; i < n; i++) { + combined[i][0] = aliceValues[i] + bobValues[i]; + combined[i][1] = aliceValues[i]; + combined[i][2] = bobValues[i]; + } + sort(combined.begin(), combined.end(), [](const vector& a, const vector& b) { + return a[0] > b[0]; + }); + + int alice = 0, bob = 0; + for (int i = 0; i < n; i++) { + if (i % 2 == 0) { + alice += combined[i][1]; + } else { + bob += combined[i][2]; + } + } + + if (alice > bob) return 1; + else if (alice < bob) return -1; + else return 0; + } +}; diff --git a/tests/1501-2000/1686. stone-game-vi/sol.cs b/tests/1501-2000/1686. stone-game-vi/sol.cs new file mode 100644 index 00000000..594d983d --- /dev/null +++ b/tests/1501-2000/1686. stone-game-vi/sol.cs @@ -0,0 +1,23 @@ +public class Solution { + public int StoneGameVI(int[] aliceValues, int[] bobValues) { + int n = aliceValues.Length; + var combined = new List<(int, int, int)>(); + for (int i = 0; i < n; i++) { + combined.Add((aliceValues[i] + bobValues[i], aliceValues[i], bobValues[i])); + } + combined.Sort((a, b) => b.Item1.CompareTo(a.Item1)); + + int alice = 0, bob = 0; + for (int i = 0; i < n; i++) { + if (i % 2 == 0) { + alice += combined[i].Item2; + } else { + bob += combined[i].Item3; + } + } + + if (alice > bob) return 1; + else if (alice < bob) return -1; + else return 0; + } +} diff --git a/tests/1501-2000/1686. stone-game-vi/sol.dart b/tests/1501-2000/1686. stone-game-vi/sol.dart new file mode 100644 index 00000000..fc90d6f2 --- /dev/null +++ b/tests/1501-2000/1686. stone-game-vi/sol.dart @@ -0,0 +1,20 @@ +class Solution { + int stoneGameVI(List aliceValues, List bobValues) { + int n = aliceValues.length; + List> combined = List.generate(n, (i) => [aliceValues[i] + bobValues[i], aliceValues[i], bobValues[i]]); + combined.sort((a, b) => b[0].compareTo(a[0])); + + int alice = 0, bob = 0; + for (int i = 0; i < n; i++) { + if (i % 2 == 0) { + alice += combined[i][1]; + } else { + bob += combined[i][2]; + } + } + + if (alice > bob) return 1; + else if (alice < bob) return -1; + else return 0; + } +} diff --git a/tests/1501-2000/1686. stone-game-vi/sol.go b/tests/1501-2000/1686. stone-game-vi/sol.go new file mode 100644 index 00000000..11691726 --- /dev/null +++ b/tests/1501-2000/1686. stone-game-vi/sol.go @@ -0,0 +1,31 @@ +func stoneGameVI(aliceValues []int, bobValues []int) int { + n := len(aliceValues) + type item struct { + total int + a int + b int + } + combined := make([]item, n) + for i := 0; i < n; i++ { + combined[i] = item{aliceValues[i] + bobValues[i], aliceValues[i], bobValues[i]} + } + sort.Slice(combined, func(i, j int) bool { + return combined[i].total > combined[j].total + }) + + alice, bob := 0, 0 + for i, it := range combined { + if i%2 == 0 { + alice += it.a + } else { + bob += it.b + } + } + + if alice > bob { + return 1 + } else if alice < bob { + return -1 + } + return 0 +} diff --git a/tests/1501-2000/1686. stone-game-vi/sol.java b/tests/1501-2000/1686. stone-game-vi/sol.java new file mode 100644 index 00000000..94d776cb --- /dev/null +++ b/tests/1501-2000/1686. stone-game-vi/sol.java @@ -0,0 +1,25 @@ +class Solution { + public int stoneGameVI(int[] aliceValues, int[] bobValues) { + int n = aliceValues.length; + int[][] combined = new int[n][3]; + for (int i = 0; i < n; i++) { + combined[i][0] = aliceValues[i] + bobValues[i]; + combined[i][1] = aliceValues[i]; + combined[i][2] = bobValues[i]; + } + Arrays.sort(combined, (a, b) -> b[0] - a[0]); + + int alice = 0, bob = 0; + for (int i = 0; i < n; i++) { + if (i % 2 == 0) { + alice += combined[i][1]; + } else { + bob += combined[i][2]; + } + } + + if (alice > bob) return 1; + else if (alice < bob) return -1; + else return 0; + } +} diff --git a/tests/1501-2000/1686. stone-game-vi/sol.kt b/tests/1501-2000/1686. stone-game-vi/sol.kt new file mode 100644 index 00000000..853d15f3 --- /dev/null +++ b/tests/1501-2000/1686. stone-game-vi/sol.kt @@ -0,0 +1,28 @@ +class Solution { + fun stoneGameVI(aliceValues: IntArray, bobValues: IntArray): Int { + val n = aliceValues.size + val combined = Array(n) { IntArray(3) } + for (i in 0 until n) { + combined[i][0] = aliceValues[i] + bobValues[i] + combined[i][1] = aliceValues[i] + combined[i][2] = bobValues[i] + } + combined.sortByDescending { it[0] } + + var alice = 0 + var bob = 0 + for (i in 0 until n) { + if (i % 2 == 0) { + alice += combined[i][1] + } else { + bob += combined[i][2] + } + } + + return when { + alice > bob -> 1 + alice < bob -> -1 + else -> 0 + } + } +} diff --git a/tests/1501-2000/1686. stone-game-vi/sol.py b/tests/1501-2000/1686. stone-game-vi/sol.py new file mode 100644 index 00000000..9c6e4848 --- /dev/null +++ b/tests/1501-2000/1686. stone-game-vi/sol.py @@ -0,0 +1,24 @@ +class Solution: + """My Greedy Solution!!!""" + + def stoneGameVI(self, aliceValues: list[int], bobValues: list[int]) -> int: + n = len(aliceValues) + combined = [ + (aliceValues[i] + bobValues[i], aliceValues[i], bobValues[i]) + for i in range(n) + ] + combined.sort(key=lambda x: x[0], reverse=True) + + alice = bob = 0 + for i, (total, a_val, b_val) in enumerate(combined): + if i % 2 == 0: + alice += a_val + else: + bob += b_val + + if alice > bob: + return 1 + elif alice < bob: + return -1 + else: + return 0 diff --git a/tests/1501-2000/1686. stone-game-vi/sol.py2 b/tests/1501-2000/1686. stone-game-vi/sol.py2 new file mode 100644 index 00000000..2cd18c86 --- /dev/null +++ b/tests/1501-2000/1686. stone-game-vi/sol.py2 @@ -0,0 +1,24 @@ +class Solution(object): + def stoneGameVI(self, aliceValues, bobValues): + """ + :type aliceValues: List[int] + :type bobValues: List[int] + :rtype: int + """ + n = len(aliceValues) + combined = [(aliceValues[i] + bobValues[i], aliceValues[i], bobValues[i]) for i in range(n)] + combined.sort(key=lambda x: x[0], reverse=True) + + alice = bob = 0 + for i, (total, a_val, b_val) in enumerate(combined): + if i % 2 == 0: + alice += a_val + else: + bob += b_val + + if alice > bob: + return 1 + elif alice < bob: + return -1 + else: + return 0 diff --git a/tests/1501-2000/1686. stone-game-vi/sol.rb b/tests/1501-2000/1686. stone-game-vi/sol.rb new file mode 100644 index 00000000..f4cc934b --- /dev/null +++ b/tests/1501-2000/1686. stone-game-vi/sol.rb @@ -0,0 +1,25 @@ +# @param {Integer[]} alice_values +# @param {Integer[]} bob_values +# @return {Integer} +def stone_game_vi(alice_values, bob_values) + n = alice_values.length + combined = (0...n).map { |i| [alice_values[i] + bob_values[i], alice_values[i], bob_values[i]] } + combined.sort_by! { |x| -x[0] } + + alice = bob = 0 + combined.each_with_index do |(total, a_val, b_val), i| + if i.even? + alice += a_val + else + bob += b_val + end + end + + if alice > bob + return 1 + elsif alice < bob + return -1 + else + return 0 + end +end diff --git a/tests/1501-2000/1686. stone-game-vi/sol.rs b/tests/1501-2000/1686. stone-game-vi/sol.rs new file mode 100644 index 00000000..0da1228d --- /dev/null +++ b/tests/1501-2000/1686. stone-game-vi/sol.rs @@ -0,0 +1,27 @@ +impl Solution { + pub fn stone_game_vi(alice_values: Vec, bob_values: Vec) -> i32 { + let n = alice_values.len(); + let mut combined: Vec<(i32, i32, i32)> = (0..n).map(|i| { + (alice_values[i] + bob_values[i], alice_values[i], bob_values[i]) + }).collect(); + combined.sort_by(|a, b| b.0.cmp(&a.0)); + + let mut alice = 0; + let mut bob = 0; + for (i, &(_, a, b)) in combined.iter().enumerate() { + if i % 2 == 0 { + alice += a; + } else { + bob += b; + } + } + + if alice > bob { + 1 + } else if alice < bob { + -1 + } else { + 0 + } + } +} diff --git a/tests/1501-2000/1686. stone-game-vi/sol.swift b/tests/1501-2000/1686. stone-game-vi/sol.swift new file mode 100644 index 00000000..53865d96 --- /dev/null +++ b/tests/1501-2000/1686. stone-game-vi/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func stoneGameVI(_ aliceValues: [Int], _ bobValues: [Int]) -> Int { + let n = aliceValues.count + var combined = [(total: Int, a: Int, b: Int)]() + for i in 0.. $1.total } + + var alice = 0, bob = 0 + for (i, item) in combined.enumerated() { + if i % 2 == 0 { + alice += item.a + } else { + bob += item.b + } + } + + if alice > bob { return 1 } + else if alice < bob { return -1 } + else { return 0 } + } +} diff --git a/tests/1501-2000/1686. stone-game-vi/sol.ts b/tests/1501-2000/1686. stone-game-vi/sol.ts new file mode 100644 index 00000000..c621e2a4 --- /dev/null +++ b/tests/1501-2000/1686. stone-game-vi/sol.ts @@ -0,0 +1,26 @@ +function stoneGameVI(aliceValues: number[], bobValues: number[]): number { + const n = aliceValues.length; + const combined: number[][] = []; + for (let i = 0; i < n; i++) { + combined.push([ + aliceValues[i] + bobValues[i], + aliceValues[i], + bobValues[i], + ]); + } + combined.sort((a, b) => b[0] - a[0]); + + let alice = 0, + bob = 0; + for (let i = 0; i < n; i++) { + if (i % 2 === 0) { + alice += combined[i][1]; + } else { + bob += combined[i][2]; + } + } + + if (alice > bob) return 1; + else if (alice < bob) return -1; + else return 0; +} diff --git a/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/manifest.yaml b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/manifest.yaml new file mode 100644 index 00000000..c1762b23 --- /dev/null +++ b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/manifest.yaml @@ -0,0 +1,517 @@ +entry: + id: 1687 + title: "delivering-boxes-from-storage-to-ports" + params: + boxes: + type: array + items: + type: array + items: + type: int + portsCount: + type: int + maxBoxes: + type: int + maxWeight: + type: int + call: + cpp: "Solution().boxDelivering({boxes}, {portsCount}, {maxBoxes}, {maxWeight})" + rust: "Solution::box_delivering({boxes}, {portsCount}, {maxBoxes}, {maxWeight})" + python3: "Solution().boxDelivering({boxes}, {portsCount}, {maxBoxes}, {maxWeight})" + python2: "Solution().boxDelivering({boxes}, {portsCount}, {maxBoxes}, {maxWeight})" + ruby: "box_delivering({boxes}, {portsCount}, {maxBoxes}, {maxWeight})" + java: "new Solution().boxDelivering({boxes}, {portsCount}, {maxBoxes}, {maxWeight})" + csharp: "new Solution().BoxDelivering({boxes}, {portsCount}, {maxBoxes}, {maxWeight})" + kotlin: "Solution().boxDelivering({boxes}, {portsCount}, {maxBoxes}, {maxWeight})" + go: "boxDelivering({boxes}, {portsCount}, {maxBoxes}, {maxWeight})" + dart: "Solution().boxDelivering({boxes}, {portsCount}, {maxBoxes}, {maxWeight})" + swift: "Solution().boxDelivering({boxes}, {portsCount}, {maxBoxes}, {maxWeight})" + typescript: "boxDelivering({boxes}, {portsCount}, {maxBoxes}, {maxWeight})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().boxDelivering(boxes, portsCount, maxBoxes, maxWeight, {result})" + checker: | + from collections import deque + + class Checker: + def boxDelivering(self, boxes, portsCount, maxBoxes, maxWeight, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + n = len(boxes) + prefix_weight = [0] * (n + 1) + ports_changes = [0] * (n + 2) + for i, (port, weight) in enumerate(boxes, 1): + prefix_weight[i] = prefix_weight[i - 1] + weight + if i > 1 and port != boxes[i - 2][0]: + ports_changes[i] = ports_changes[i - 1] + 1 + else: + ports_changes[i] = ports_changes[i - 1] + ports_changes[n + 1] = ports_changes[n] + + dp = [0] * (n + 1) + candidates = deque([0]) + left = 0 + for right in range(1, n + 1): + while (right - left > maxBoxes or + prefix_weight[right] - prefix_weight[left] > maxWeight): + if candidates and candidates[0] == left: + candidates.popleft() + left += 1 + best = candidates[0] + dp[right] = (2 + ports_changes[right] + + dp[best] - ports_changes[best + 1]) + value = dp[right] - ports_changes[right + 1] + while candidates: + tail = candidates[-1] + if dp[tail] - ports_changes[tail + 1] < value: + break + candidates.pop() + candidates.append(right) + return result == dp[n] + +seed: 1687 + +tests: + - name: one-box + in: + boxes: + - [1, 1] + portsCount: 1 + maxBoxes: 1 + maxWeight: 1 + out: 2 + - name: stated-example-one + in: + boxes: + - [1, 1] + - [2, 1] + - [1, 1] + portsCount: 2 + maxBoxes: 3 + maxWeight: 3 + out: 4 + - name: stated-example-two + in: + boxes: + - [1, 2] + - [3, 3] + - [3, 1] + - [3, 1] + - [2, 4] + portsCount: 3 + maxBoxes: 3 + maxWeight: 6 + out: 6 + - name: stated-example-three + in: + boxes: + - [1, 4] + - [1, 2] + - [2, 1] + - [2, 1] + - [3, 2] + - [3, 4] + portsCount: 3 + maxBoxes: 6 + maxWeight: 7 + out: 6 + - name: same-port-full-load + in: + boxes: + - [2, 5] + - [2, 5] + - [2, 5] + - [2, 5] + portsCount: 3 + maxBoxes: 4 + maxWeight: 20 + out: 2 + - name: single-box-capacity + in: + boxes: + - [1, 3] + - [2, 3] + - [1, 3] + portsCount: 2 + maxBoxes: 1 + maxWeight: 3 + out: 6 + - name: weight-splits-load + in: + boxes: + - [1, 4] + - [1, 4] + - [2, 4] + portsCount: 2 + maxBoxes: 3 + maxWeight: 5 + out: 6 + - name: alternating-three + in: + boxes: + - [1, 1] + - [2, 1] + - [3, 1] + portsCount: 3 + maxBoxes: 3 + maxWeight: 3 + out: 4 + - name: alternating-five + in: + boxes: + - [1, 1] + - [2, 1] + - [3, 1] + - [1, 1] + - [2, 1] + portsCount: 3 + maxBoxes: 5 + maxWeight: 5 + out: 6 + - name: two-ports-capacity-two + in: + boxes: + - [1, 1] + - [2, 1] + - [1, 1] + - [2, 1] + portsCount: 2 + maxBoxes: 2 + maxWeight: 2 + out: 6 + - name: port-runs + in: + boxes: + - [1, 1] + - [1, 1] + - [2, 1] + - [2, 1] + - [3, 1] + - [3, 1] + portsCount: 3 + maxBoxes: 6 + maxWeight: 6 + out: 4 + - name: max-weight-one + in: + boxes: + - [1, 1] + - [1, 1] + - [1, 1] + portsCount: 1 + maxBoxes: 3 + maxWeight: 1 + out: 6 + - name: max-boxes-one + in: + boxes: + - [2, 1] + - [2, 1] + - [2, 1] + portsCount: 2 + maxBoxes: 1 + maxWeight: 3 + out: 6 + - name: capacity-by-both + in: + boxes: + - [1, 2] + - [1, 2] + - [2, 2] + - [2, 2] + portsCount: 2 + maxBoxes: 3 + maxWeight: 5 + out: 4 + - name: ten-boxes + in: + boxes: + - [1, 1] + - [2, 1] + - [3, 1] + - [4, 1] + - [1, 1] + - [2, 1] + - [3, 1] + - [4, 1] + - [1, 1] + - [2, 1] + portsCount: 4 + maxBoxes: 7 + maxWeight: 7 + out: 12 + - name: twenty-boxes + in: + boxes: + - [1, 1] + - [2, 1] + - [1, 1] + - [2, 1] + - [1, 1] + - [2, 1] + - [1, 1] + - [2, 1] + - [1, 1] + - [2, 1] + - [1, 1] + - [2, 1] + - [1, 1] + - [2, 1] + - [1, 1] + - [2, 1] + - [1, 1] + - [2, 1] + - [1, 1] + - [2, 1] + portsCount: 2 + maxBoxes: 2 + maxWeight: 2 + out: 30 + - name: one-box-high-capacity + in: + boxes: + - [1, 1] + portsCount: 1 + maxBoxes: 50 + maxWeight: 50 + out: 2 + - name: five-port-runs + in: + boxes: + - [1, 1] + - [2, 1] + - [3, 1] + - [4, 1] + - [5, 1] + portsCount: 100000 + maxBoxes: 50 + maxWeight: 50 + out: 6 + - name: one-box-high-capacity-weight + in: + boxes: + - [1, 1] + portsCount: 2 + maxBoxes: 100 + maxWeight: 100 + out: 2 + - name: port-count-larger-than-used + in: + boxes: + - [1, 2] + - [1, 2] + - [1, 2] + portsCount: 100 + maxBoxes: 3 + maxWeight: 6 + out: 2 + - name: max-weight-boundary + in: + boxes: + - [1, 5] + - [2, 5] + - [2, 5] + portsCount: 2 + maxBoxes: 3 + maxWeight: 10 + out: 4 + - name: max-box-boundary + in: + boxes: + - [1, 1] + - [2, 1] + - [2, 1] + - [1, 1] + portsCount: 2 + maxBoxes: 4 + maxWeight: 4 + out: 4 + - name: repeated-return-port + in: + boxes: + - [1, 1] + - [2, 1] + - [1, 1] + - [2, 1] + - [1, 1] + portsCount: 2 + maxBoxes: 5 + maxWeight: 5 + out: 6 + - name: eight-boxes + in: + boxes: + - [1, 1] + - [2, 1] + - [3, 1] + - [4, 1] + - [1, 1] + - [2, 1] + - [3, 1] + - [4, 1] + portsCount: 4 + maxBoxes: 42 + maxWeight: 42 + out: 9 + - name: two-large-runs + in: + boxes: + - [1, 9] + - [1, 9] + - [1, 9] + - [2, 9] + - [2, 9] + - [2, 9] + portsCount: 2 + maxBoxes: 6 + maxWeight: 54 + out: 3 + - name: alternating-weighted + in: + boxes: + - [1, 1] + - [2, 2] + - [3, 3] + - [1, 4] + - [2, 5] + portsCount: 3 + maxBoxes: 5 + maxWeight: 15 + out: 6 + - name: one-port-many + in: + boxes: + - [1, 7] + - [1, 7] + - [1, 7] + - [1, 7] + - [1, 7] + portsCount: 1 + maxBoxes: 3 + maxWeight: 21 + out: 4 + - name: mixed-boundary + in: + boxes: + - [1, 2] + - [1, 2] + - [2, 1] + - [3, 4] + - [3, 1] + - [1, 2] + portsCount: 3 + maxBoxes: 4 + maxWeight: 7 + out: 6 + - name: six-single-port-batches + in: + boxes: + - [1, 1] + - [2, 1] + - [3, 1] + - [1, 1] + - [2, 1] + - [3, 1] + portsCount: 3 + maxBoxes: 2 + maxWeight: 2 + out: 9 + - name: weight-forces-two-trips + in: + boxes: + - [1, 3] + - [1, 3] + - [2, 3] + - [2, 3] + portsCount: 2 + maxBoxes: 4 + maxWeight: 6 + out: 4 + - name: generated-small + in: + boxes: + gen: "array" + len: 20 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 5 + elemType: "int" + portsCount: 5 + maxBoxes: 5 + maxWeight: 15 + - name: generated-medium + in: + boxes: + gen: "array" + len: 100 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 20 + elemType: "int" + portsCount: 100000 + maxBoxes: 25 + maxWeight: 200 + - name: generated-heavy + in: + boxes: + gen: "array" + len: 1000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + portsCount: 100000 + maxBoxes: 100 + maxWeight: 5000 + - name: generated-large + in: + boxes: + gen: "array" + len: 10000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + portsCount: 100000 + maxBoxes: 1000 + maxWeight: 100000 + - name: generated-maximum + in: + boxes: + gen: "array" + len: 100000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + portsCount: 100000 + maxBoxes: 100000 + maxWeight: 100000 diff --git a/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.cpp b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.cpp new file mode 100644 index 00000000..194d886c --- /dev/null +++ b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + int boxDelivering(vector>& boxes, int portsCount, int maxBoxes, int maxWeight) { + int n = boxes.size(); + vector ports(n+1); + vector weights(n+1); + for (int i = 0; i < n; i++) { + ports[i+1] = boxes[i][0]; + weights[i+1] = boxes[i][1]; + } + vector prefixWeights(n+1); + for (int i = 1; i <= n; i++) { + prefixWeights[i] = prefixWeights[i-1] + weights[i]; + } + vector portsCnt(n+2); + for (int i = 2; i <= n; i++) { + portsCnt[i] = portsCnt[i-1] + (ports[i] != ports[i-1] ? 1 : 0); + } + portsCnt[n+1] = portsCnt[n]; + vector dp(n+1); + deque queue; + queue.push_back(0); + int left = 0; + for (int i = 1; i <= n; i++) { + while (i - left > maxBoxes || prefixWeights[i] - prefixWeights[left] > maxWeight) { + if (!queue.empty() && queue.front() == left) { + queue.pop_front(); + } + left++; + } + dp[i] = 2 + portsCnt[i] + (dp[queue.front()] - portsCnt[queue.front()+1]); + int idx = dp[i] - portsCnt[i+1]; + while (!queue.empty() && (dp[queue.back()] - portsCnt[queue.back()+1]) >= idx) { + queue.pop_back(); + } + queue.push_back(i); + } + return dp[n]; + } +}; diff --git a/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.cs b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.cs new file mode 100644 index 00000000..ba7f94b0 --- /dev/null +++ b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.cs @@ -0,0 +1,39 @@ +public class Solution { + public int BoxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) { + int n = boxes.Length; + int[] ports = new int[n+1]; + int[] weights = new int[n+1]; + for (int i = 0; i < n; i++) { + ports[i+1] = boxes[i][0]; + weights[i+1] = boxes[i][1]; + } + int[] prefixWeights = new int[n+1]; + for (int i = 1; i <= n; i++) { + prefixWeights[i] = prefixWeights[i-1] + weights[i]; + } + int[] portsCnt = new int[n+2]; + for (int i = 2; i <= n; i++) { + portsCnt[i] = portsCnt[i-1] + (ports[i] != ports[i-1] ? 1 : 0); + } + portsCnt[n+1] = portsCnt[n]; + int[] dp = new int[n+1]; + var queue = new System.Collections.Generic.LinkedList(); + queue.AddLast(0); + int left = 0; + for (int i = 1; i <= n; i++) { + while (i - left > maxBoxes || prefixWeights[i] - prefixWeights[left] > maxWeight) { + if (queue.Count > 0 && queue.First.Value == left) { + queue.RemoveFirst(); + } + left++; + } + dp[i] = 2 + portsCnt[i] + (dp[queue.First.Value] - portsCnt[queue.First.Value+1]); + int idx = dp[i] - portsCnt[i+1]; + while (queue.Count > 0 && (dp[queue.Last.Value] - portsCnt[queue.Last.Value+1]) >= idx) { + queue.RemoveLast(); + } + queue.AddLast(i); + } + return dp[n]; + } +} diff --git a/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.dart b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.dart new file mode 100644 index 00000000..68a7b3d8 --- /dev/null +++ b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.dart @@ -0,0 +1,38 @@ +class Solution { + int boxDelivering(List> boxes, int portsCount, int maxBoxes, int maxWeight) { + int n = boxes.length; + List ports = List.filled(n+1, 0); + List weights = List.filled(n+1, 0); + for (int i = 0; i < n; i++) { + ports[i+1] = boxes[i][0]; + weights[i+1] = boxes[i][1]; + } + List prefixWeights = List.filled(n+1, 0); + for (int i = 1; i <= n; i++) { + prefixWeights[i] = prefixWeights[i-1] + weights[i]; + } + List portsCnt = List.filled(n+2, 0); + for (int i = 2; i <= n; i++) { + portsCnt[i] = portsCnt[i-1] + (ports[i] != ports[i-1] ? 1 : 0); + } + portsCnt[n+1] = portsCnt[n]; + List dp = List.filled(n+1, 0); + List queue = [0]; + int left = 0; + for (int i = 1; i <= n; i++) { + while (i - left > maxBoxes || prefixWeights[i] - prefixWeights[left] > maxWeight) { + if (queue.isNotEmpty && queue.first == left) { + queue.removeAt(0); + } + left++; + } + dp[i] = 2 + portsCnt[i] + (dp[queue.first] - portsCnt[queue.first+1]); + int idx = dp[i] - portsCnt[i+1]; + while (queue.isNotEmpty && dp[queue.last] - portsCnt[queue.last+1] >= idx) { + queue.removeLast(); + } + queue.add(i); + } + return dp[n]; + } +} diff --git a/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.go b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.go new file mode 100644 index 00000000..25d5e432 --- /dev/null +++ b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.go @@ -0,0 +1,41 @@ +func boxDelivering(boxes [][]int, portsCount int, maxBoxes int, maxWeight int) int { + n := len(boxes) + ports := make([]int, n+1) + weights := make([]int, n+1) + for i, box := range boxes { + ports[i+1] = box[0] + weights[i+1] = box[1] + } + prefixWeights := make([]int, n+1) + for i := 1; i <= n; i++ { + prefixWeights[i] = prefixWeights[i-1] + weights[i] + } + portsCnt := make([]int, n+2) + for i := 2; i <= n; i++ { + if ports[i] != ports[i-1] { + portsCnt[i] = portsCnt[i-1] + 1 + } else { + portsCnt[i] = portsCnt[i-1] + } + } + portsCnt[n+1] = portsCnt[n] + dp := make([]int, n+1) + queue := make([]int, 0, n+1) + queue = append(queue, 0) + left := 0 + for i := 1; i <= n; i++ { + for i-left > maxBoxes || prefixWeights[i]-prefixWeights[left] > maxWeight { + if len(queue) > 0 && queue[0] == left { + queue = queue[1:] + } + left++ + } + dp[i] = 2 + portsCnt[i] + (dp[queue[0]] - portsCnt[queue[0]+1]) + idx := dp[i] - portsCnt[i+1] + for len(queue) > 0 && dp[queue[len(queue)-1]]-portsCnt[queue[len(queue)-1]+1] >= idx { + queue = queue[:len(queue)-1] + } + queue = append(queue, i) + } + return dp[n] +} diff --git a/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.java b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.java new file mode 100644 index 00000000..4d40b8be --- /dev/null +++ b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.java @@ -0,0 +1,39 @@ +class Solution { + public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) { + int n = boxes.length; + int[] ports = new int[n+1]; + int[] weights = new int[n+1]; + for (int i = 0; i < n; i++) { + ports[i+1] = boxes[i][0]; + weights[i+1] = boxes[i][1]; + } + int[] prefixWeights = new int[n+1]; + for (int i = 1; i <= n; i++) { + prefixWeights[i] = prefixWeights[i-1] + weights[i]; + } + int[] portsCnt = new int[n+2]; + for (int i = 2; i <= n; i++) { + portsCnt[i] = portsCnt[i-1] + (ports[i] != ports[i-1] ? 1 : 0); + } + portsCnt[n+1] = portsCnt[n]; + int[] dp = new int[n+1]; + java.util.Deque queue = new java.util.ArrayDeque<>(); + queue.add(0); + int left = 0; + for (int i = 1; i <= n; i++) { + while (i - left > maxBoxes || prefixWeights[i] - prefixWeights[left] > maxWeight) { + if (!queue.isEmpty() && queue.peekFirst() == left) { + queue.pollFirst(); + } + left++; + } + dp[i] = 2 + portsCnt[i] + (dp[queue.peekFirst()] - portsCnt[queue.peekFirst()+1]); + int idx = dp[i] - portsCnt[i+1]; + while (!queue.isEmpty() && (dp[queue.peekLast()] - portsCnt[queue.peekLast()+1]) >= idx) { + queue.pollLast(); + } + queue.addLast(i); + } + return dp[n]; + } +} diff --git a/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.kt b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.kt new file mode 100644 index 00000000..d030e1a3 --- /dev/null +++ b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.kt @@ -0,0 +1,39 @@ +class Solution { + fun boxDelivering(boxes: Array, portsCount: Int, maxBoxes: Int, maxWeight: Int): Int { + val n = boxes.size + val ports = IntArray(n+1) + val weights = IntArray(n+1) + for (i in 0 until n) { + ports[i+1] = boxes[i][0] + weights[i+1] = boxes[i][1] + } + val prefixWeights = IntArray(n+1) + for (i in 1..n) { + prefixWeights[i] = prefixWeights[i-1] + weights[i] + } + val portsCnt = IntArray(n+2) + for (i in 2..n) { + portsCnt[i] = portsCnt[i-1] + if (ports[i] != ports[i-1]) 1 else 0 + } + portsCnt[n+1] = portsCnt[n] + val dp = IntArray(n+1) + val queue = ArrayDeque() + queue.add(0) + var left = 0 + for (i in 1..n) { + while (i - left > maxBoxes || prefixWeights[i] - prefixWeights[left] > maxWeight) { + if (!queue.isEmpty() && queue.first == left) { + queue.removeFirst() + } + left++ + } + dp[i] = 2 + portsCnt[i] + (dp[queue.first] - portsCnt[queue.first+1]) + val idx = dp[i] - portsCnt[i+1] + while (!queue.isEmpty() && (dp[queue.last] - portsCnt[queue.last+1]) >= idx) { + queue.removeLast() + } + queue.addLast(i) + } + return dp[n] + } +} diff --git a/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.py b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.py new file mode 100644 index 00000000..32d1f710 --- /dev/null +++ b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.py @@ -0,0 +1,37 @@ +from collections import deque + + +class Solution: + def boxDelivering( + self, boxes: list[list[int]], portsCount: int, maxBoxes: int, maxWeight: int + ) -> int: + n = len(boxes) + ports = [0] * (n + 1) + weights = [0] * (n + 1) + for i, (p, w) in enumerate(boxes, 1): + ports[i] = p + weights[i] = w + prefixWeights = [0] * (n + 1) + for i in range(1, n + 1): + prefixWeights[i] = prefixWeights[i - 1] + weights[i] + portsCnt = [0] * (n + 2) + for i in range(2, n + 1): + portsCnt[i] = portsCnt[i - 1] + (ports[i] != ports[i - 1]) + portsCnt[n + 1] = portsCnt[n] + dp = [0] * (n + 1) + queue = deque([0]) + left = 0 + for i in range(1, n + 1): + while ( + i - left > maxBoxes + or prefixWeights[i] - prefixWeights[left] > maxWeight + ): + if queue and queue[0] == left: + queue.popleft() + left += 1 + dp[i] = 2 + portsCnt[i] + (dp[queue[0]] - portsCnt[queue[0] + 1]) + idx = dp[i] - portsCnt[i + 1] + while queue and (dp[queue[-1]] - portsCnt[queue[-1] + 1]) >= idx: + queue.pop() + queue.append(i) + return dp[n] diff --git a/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.py2 b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.py2 new file mode 100644 index 00000000..f4afb4cd --- /dev/null +++ b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.py2 @@ -0,0 +1,37 @@ +class Solution(object): + def boxDelivering(self, boxes, portsCount, maxBoxes, maxWeight): + """ + :type boxes: List[List[int]] + :type portsCount: int + :type maxBoxes: int + :type maxWeight: int + :rtype: int + """ + n = len(boxes) + ports = [0]*(n+1) + weights = [0]*(n+1) + for i,(p,w) in enumerate(boxes,1): + ports[i] = p + weights[i] = w + prefix_weights = [0]*(n+1) + for i in range(1,n+1): + prefix_weights[i] = prefix_weights[i-1] + weights[i] + ports_cnt = [0]*(n+2) + for i in range(2,n+1): + ports_cnt[i] = ports_cnt[i-1] + (1 if ports[i]!=ports[i-1] else 0) + ports_cnt[n+1] = ports_cnt[n] + dp = [0]*(n+1) + from collections import deque + queue = deque([0]) + left = 0 + for i in range(1,n+1): + while i - left > maxBoxes or prefix_weights[i] - prefix_weights[left] > maxWeight: + if queue and queue[0] == left: + queue.popleft() + left += 1 + dp[i] = 2 + ports_cnt[i] + (dp[queue[0]]-ports_cnt[queue[0]+1]) + idx = dp[i]-ports_cnt[i+1] + while queue and (dp[queue[-1]]-ports_cnt[queue[-1]+1]) >= idx: + queue.pop() + queue.append(i) + return dp[n] diff --git a/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.rb b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.rb new file mode 100644 index 00000000..dee5682a --- /dev/null +++ b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.rb @@ -0,0 +1,34 @@ +def box_delivering(boxes, ports_count, max_boxes, max_weight) + n = boxes.length + ports = [0]*(n+1) + weights = [0]*(n+1) + boxes.each_with_index do |(p,w), i| + ports[i+1] = p + weights[i+1] = w + end + prefix_weights = [0]*(n+1) + (1..n).each do |i| + prefix_weights[i] = prefix_weights[i-1] + weights[i] + end + ports_cnt = [0]*(n+2) + (2..n).each do |i| + ports_cnt[i] = ports_cnt[i-1] + (ports[i] != ports[i-1] ? 1 : 0) + end + ports_cnt[n+1] = ports_cnt[n] + dp = [0]*(n+1) + queue = [0] + left = 0 + (1..n).each do |i| + while i - left > max_boxes || prefix_weights[i] - prefix_weights[left] > max_weight + queue.shift if !queue.empty? && queue[0] == left + left += 1 + end + dp[i] = 2 + ports_cnt[i] + (dp[queue[0]]-ports_cnt[queue[0]+1]) + idx = dp[i]-ports_cnt[i+1] + while !queue.empty? && (dp[queue[-1]]-ports_cnt[queue[-1]+1]) >= idx + queue.pop + end + queue.push(i) + end + dp[n] +end diff --git a/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.rs b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.rs new file mode 100644 index 00000000..22f56cf9 --- /dev/null +++ b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.rs @@ -0,0 +1,39 @@ +impl Solution { + pub fn box_delivering(boxes: Vec>, ports_count: i32, max_boxes: i32, max_weight: i32) -> i32 { + let n = boxes.len(); + let mut ports = vec![0; n+1]; + let mut weights = vec![0; n+1]; + for (i, box_) in boxes.iter().enumerate() { + ports[i+1] = box_[0]; + weights[i+1] = box_[1]; + } + let mut prefix_weights = vec![0; n+1]; + for i in 1..=n { + prefix_weights[i] = prefix_weights[i-1] + weights[i]; + } + let mut ports_cnt = vec![0; n+2]; + for i in 2..=n { + ports_cnt[i] = ports_cnt[i-1] + if ports[i] != ports[i-1] {1} else {0}; + } + ports_cnt[n+1] = ports_cnt[n]; + let mut dp = vec![0; n+1]; + let mut queue = Vec::with_capacity(n+1); + queue.push(0); + let mut left = 0; + for i in 1..=n { + while (i as i32 - left as i32) > max_boxes || (prefix_weights[i] - prefix_weights[left]) > max_weight { + if !queue.is_empty() && queue[0] == left { + queue.remove(0); + } + left += 1; + } + dp[i] = 2 + ports_cnt[i] + (dp[queue[0]] - ports_cnt[queue[0]+1]); + let idx = dp[i] - ports_cnt[i+1]; + while !queue.is_empty() && (dp[*queue.last().unwrap()] - ports_cnt[*queue.last().unwrap()+1]) >= idx { + queue.pop(); + } + queue.push(i); + } + dp[n] + } +} diff --git a/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.swift b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.swift new file mode 100644 index 00000000..6fb31640 --- /dev/null +++ b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.swift @@ -0,0 +1,40 @@ +class Solution { + func boxDelivering(_ boxes: [[Int]], _ portsCount: Int, _ maxBoxes: Int, _ maxWeight: Int) -> Int { + let n = boxes.count + var ports = [Int](repeating: 0, count: n+1) + var weights = [Int](repeating: 0, count: n+1) + for i in 0..= 2 { + for i in 2...n { + portsCnt[i] = portsCnt[i-1] + (ports[i] != ports[i-1] ? 1 : 0) + } + } + portsCnt[n+1] = portsCnt[n] + var dp = [Int](repeating: 0, count: n+1) + var queue = [0] + var left = 0 + for i in 1...n { + while i - left > maxBoxes || prefixWeights[i] - prefixWeights[left] > maxWeight { + if !queue.isEmpty && queue[0] == left { + queue.removeFirst() + } + left += 1 + } + dp[i] = 2 + portsCnt[i] + (dp[queue[0]] - portsCnt[queue[0]+1]) + let idx = dp[i] - portsCnt[i+1] + while !queue.isEmpty && (dp[queue[queue.count-1]] - portsCnt[queue[queue.count-1]+1]) >= idx { + queue.removeLast() + } + queue.append(i) + } + return dp[n] + } +} diff --git a/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.ts b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.ts new file mode 100644 index 00000000..c9f5333b --- /dev/null +++ b/tests/1501-2000/1687. delivering-boxes-from-storage-to-ports/sol.ts @@ -0,0 +1,47 @@ +function boxDelivering( + boxes: number[][], + portsCount: number, + maxBoxes: number, + maxWeight: number, +): number { + const n = boxes.length; + const ports: number[] = new Array(n + 1).fill(0); + const weights: number[] = new Array(n + 1).fill(0); + for (let i = 0; i < n; i++) { + ports[i + 1] = boxes[i][0]; + weights[i + 1] = boxes[i][1]; + } + const prefixWeights: number[] = new Array(n + 1).fill(0); + for (let i = 1; i <= n; i++) { + prefixWeights[i] = prefixWeights[i - 1] + weights[i]; + } + const portsCnt: number[] = new Array(n + 2).fill(0); + for (let i = 2; i <= n; i++) { + portsCnt[i] = portsCnt[i - 1] + (ports[i] !== ports[i - 1] ? 1 : 0); + } + portsCnt[n + 1] = portsCnt[n]; + const dp: number[] = new Array(n + 1).fill(0); + const queue: number[] = [0]; + let left = 0; + for (let i = 1; i <= n; i++) { + while ( + i - left > maxBoxes || + prefixWeights[i] - prefixWeights[left] > maxWeight + ) { + if (queue.length > 0 && queue[0] === left) { + queue.shift(); + } + left++; + } + dp[i] = 2 + portsCnt[i] + (dp[queue[0]] - portsCnt[queue[0] + 1]); + const idx = dp[i] - portsCnt[i + 1]; + while ( + queue.length > 0 && + dp[queue[queue.length - 1]] - portsCnt[queue[queue.length - 1] + 1] >= idx + ) { + queue.pop(); + } + queue.push(i); + } + return dp[n]; +} diff --git a/tests/1501-2000/1688. count-of-matches-in-tournament/manifest.yaml b/tests/1501-2000/1688. count-of-matches-in-tournament/manifest.yaml new file mode 100644 index 00000000..dae9a6d6 --- /dev/null +++ b/tests/1501-2000/1688. count-of-matches-in-tournament/manifest.yaml @@ -0,0 +1,208 @@ +entry: + id: 1688 + title: "count-of-matches-in-tournament" + params: + n: + type: int + call: + cpp: "Solution().numberOfMatches({n})" + rust: "Solution::number_of_matches({n})" + python3: "Solution().numberOfMatches({n})" + python2: "Solution().numberOfMatches({n})" + ruby: "number_of_matches({n})" + java: "new Solution().numberOfMatches({n})" + csharp: "new Solution().NumberOfMatches({n})" + kotlin: "Solution().numberOfMatches({n})" + go: "numberOfMatches({n})" + dart: "Solution().numberOfMatches({n})" + swift: "Solution().numberOfMatches({n})" + typescript: "numberOfMatches({n})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(n, {result})" + checker: | + class Checker: + def check(self, n, result): + return result == n - 1 + +seed: 1688 + +tests: + - name: minimum + in: + n: 1 + out: 0 + - name: two-teams + in: + n: 2 + out: 1 + - name: three-teams + in: + n: 3 + out: 2 + - name: four-teams + in: + n: 4 + out: 3 + - name: five-teams + in: + n: 5 + out: 4 + - name: example-seven + in: + n: 7 + out: 6 + - name: eight-teams + in: + n: 8 + out: 7 + - name: nine-teams + in: + n: 9 + out: 8 + - name: ten-teams + in: + n: 10 + out: 9 + - name: eleven-teams + in: + n: 11 + out: 10 + - name: twelve-teams + in: + n: 12 + out: 11 + - name: thirteen-teams + in: + n: 13 + out: 12 + - name: example-fourteen + in: + n: 14 + out: 13 + - name: fifteen-teams + in: + n: 15 + out: 14 + - name: sixteen-teams + in: + n: 16 + out: 15 + - name: seventeen-teams + in: + n: 17 + out: 16 + - name: nineteen-teams + in: + n: 19 + out: 18 + - name: twenty-teams + in: + n: 20 + out: 19 + - name: twenty-three-teams + in: + n: 23 + out: 22 + - name: twenty-four-teams + in: + n: 24 + out: 23 + - name: twenty-five-teams + in: + n: 25 + out: 24 + - name: thirty-one-teams + in: + n: 31 + out: 30 + - name: thirty-two-teams + in: + n: 32 + out: 31 + - name: thirty-three-teams + in: + n: 33 + out: 32 + - name: forty-seven-teams + in: + n: 47 + out: 46 + - name: forty-eight-teams + in: + n: 48 + out: 47 + - name: sixty-four-teams + in: + n: 64 + out: 63 + - name: ninety-nine-teams + in: + n: 99 + out: 98 + - name: one-hundred-teams + in: + n: 100 + out: 99 + - name: one-hundred-one-teams + in: + n: 101 + out: 100 + - name: one-hundred-twenty-seven-teams + in: + n: 127 + out: 126 + - name: one-hundred-twenty-eight-teams + in: + n: 128 + out: 127 + - name: one-hundred-ninety-eight-teams + in: + n: 198 + out: 197 + - name: one-hundred-ninety-nine-teams + in: + n: 199 + out: 198 + - name: maximum + in: + n: 200 + out: 199 + - name: generated-minimum + in: + n: + gen: int + min: 1 + max: 1 + - name: generated-small + in: + n: + gen: int + min: 2 + max: 10 + - name: generated-middle + in: + n: + gen: int + min: 11 + max: 100 + - name: generated-upper + in: + n: + gen: int + min: 101 + max: 199 + - name: generated-maximum + in: + n: + gen: int + min: 200 + max: 200 diff --git a/tests/1501-2000/1688. count-of-matches-in-tournament/sol.cpp b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.cpp new file mode 100644 index 00000000..143a2e95 --- /dev/null +++ b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + int numberOfMatches(int n) { + return n-1; + } +}; diff --git a/tests/1501-2000/1688. count-of-matches-in-tournament/sol.cs b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.cs new file mode 100644 index 00000000..c01e6521 --- /dev/null +++ b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.cs @@ -0,0 +1,5 @@ +public class Solution { + public int NumberOfMatches(int n) { + return n-1; + } +} diff --git a/tests/1501-2000/1688. count-of-matches-in-tournament/sol.dart b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.dart new file mode 100644 index 00000000..2f070d24 --- /dev/null +++ b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.dart @@ -0,0 +1,5 @@ +class Solution { + int numberOfMatches(int n) { + return n - 1; + } +} diff --git a/tests/1501-2000/1688. count-of-matches-in-tournament/sol.go b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.go new file mode 100644 index 00000000..18caa821 --- /dev/null +++ b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.go @@ -0,0 +1,3 @@ +func numberOfMatches(n int) int { + return n-1 +} diff --git a/tests/1501-2000/1688. count-of-matches-in-tournament/sol.java b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.java new file mode 100644 index 00000000..5ef833c7 --- /dev/null +++ b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.java @@ -0,0 +1,5 @@ +class Solution { + public int numberOfMatches(int n) { + return n-1; + } +} diff --git a/tests/1501-2000/1688. count-of-matches-in-tournament/sol.kt b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.kt new file mode 100644 index 00000000..9b47c18a --- /dev/null +++ b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.kt @@ -0,0 +1,5 @@ +class Solution { + fun numberOfMatches(n: Int): Int { + return n-1 + } +} diff --git a/tests/1501-2000/1688. count-of-matches-in-tournament/sol.py b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.py new file mode 100644 index 00000000..85569207 --- /dev/null +++ b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.py @@ -0,0 +1,3 @@ +class Solution: + def numberOfMatches(self, n: int) -> int: + return n - 1 diff --git a/tests/1501-2000/1688. count-of-matches-in-tournament/sol.py2 b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.py2 new file mode 100644 index 00000000..1004883c --- /dev/null +++ b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.py2 @@ -0,0 +1,7 @@ +class Solution(object): + def numberOfMatches(self, n): + """ + :type n: int + :rtype: int + """ + return n-1 diff --git a/tests/1501-2000/1688. count-of-matches-in-tournament/sol.rb b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.rb new file mode 100644 index 00000000..45f89767 --- /dev/null +++ b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.rb @@ -0,0 +1,5 @@ +# @param {Integer} n +# @return {Integer} +def number_of_matches(n) + n-1 +end diff --git a/tests/1501-2000/1688. count-of-matches-in-tournament/sol.rs b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.rs new file mode 100644 index 00000000..83d07863 --- /dev/null +++ b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.rs @@ -0,0 +1,5 @@ +impl Solution { + pub fn number_of_matches(n: i32) -> i32 { + n-1 + } +} diff --git a/tests/1501-2000/1688. count-of-matches-in-tournament/sol.swift b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.swift new file mode 100644 index 00000000..34ccf7b3 --- /dev/null +++ b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.swift @@ -0,0 +1,5 @@ +class Solution { + func numberOfMatches(_ n: Int) -> Int { + return n-1 + } +} diff --git a/tests/1501-2000/1688. count-of-matches-in-tournament/sol.ts b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.ts new file mode 100644 index 00000000..1dcdaa1e --- /dev/null +++ b/tests/1501-2000/1688. count-of-matches-in-tournament/sol.ts @@ -0,0 +1,3 @@ +function numberOfMatches(n: number): number { + return n - 1; +} diff --git a/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/manifest.yaml b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/manifest.yaml new file mode 100644 index 00000000..f910f37a --- /dev/null +++ b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/manifest.yaml @@ -0,0 +1,192 @@ +entry: + id: 1689 + title: "partitioning-into-minimum-number-of-deci-binary-numbers" + params: + n: + type: string + call: + cpp: "Solution().minPartitions({n})" + rust: "Solution::min_partitions({n})" + python3: "Solution().minPartitions({n})" + python2: "Solution().minPartitions({n})" + ruby: "min_partitions({n})" + java: "new Solution().minPartitions({n})" + csharp: "new Solution().MinPartitions({n})" + kotlin: "Solution().minPartitions({n})" + go: "minPartitions({n})" + dart: "Solution().minPartitions({n})" + swift: "Solution().minPartitions({n})" + typescript: "minPartitions({n})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minPartitions(n, {result})" + checker: | + class Checker: + def minPartitions(self, n, result): + if not isinstance(n, str) or not n or n[0] == "0": + return False + if not n.isdigit() or not isinstance(result, int) or isinstance(result, bool): + return False + return result == max(int(ch) for ch in n) + +seed: 1689 + +tests: + - name: single-one + in: + n: "1" + out: 1 + - name: single-nine + in: + n: "9" + out: 9 + - name: single-five + in: + n: "5" + out: 5 + - name: all-zero-after-one + in: + n: "1000" + out: 1 + - name: binary-digits + in: + n: "1010101" + out: 1 + - name: all-nines + in: + n: "999999" + out: 9 + - name: max-at-start + in: + n: "900001" + out: 9 + - name: max-at-end + in: + n: "100009" + out: 9 + - name: max-in-middle + in: + n: "123456789" + out: 9 + - name: example-one + in: + n: "32" + out: 3 + - name: example-two + in: + n: "82734" + out: 8 + - name: example-three + in: + n: "27346209830709182346" + out: 9 + - name: only-zero-and-two + in: + n: "2020202020" + out: 2 + - name: only-zero-and-eight + in: + n: "8080808080" + out: 8 + - name: repeated-three + in: + n: "3333333333" + out: 3 + - name: increasing-digits + in: + n: "1234567890" + out: 9 + - name: decreasing-digits + in: + n: "9876543210" + out: 9 + - name: maximum-length-pattern + in: + n: "10000000000000000000000000000000000000000000000000" + out: 1 + - name: alternating-nine-one + in: + n: "9191919191919191" + out: 9 + - name: alternating-four-zero + in: + n: "4040404040404040" + out: 4 + - name: max-seven-near-end + in: + n: "1111111111111171" + out: 7 + - name: max-six-near-start + in: + n: "6111111111111111" + out: 6 + - name: max-two-long + in: + n: "22222222222222222222222222222222" + out: 2 + - name: sparse-eight + in: + n: "10000000800000001" + out: 8 + - name: mixed-five + in: + n: "5050505050505050505" + out: 5 + - name: max-four + in: + n: "4444444444444444444444444444" + out: 4 + - name: max-at-both-ends + in: + n: "90000000000000000000000000000000000000000000000009" + out: 9 + - name: mostly-zero-seven + in: + n: "70000000000000000000000000000000000000000000000001" + out: 7 + - name: mixed-six-and-eight + in: + n: "6080608060806080" + out: 8 + - name: long-nine-tail + in: + n: "1234000000000000000000000000000000000000000000999" + out: 9 + - name: generator-short + in: + n: + gen: "str" + len: 37 + alphabet: "123456789" + - name: generator-medium + in: + n: + gen: "str" + len: 1000 + alphabet: "123456789" + - name: generator-large-low-digits + in: + n: + gen: "str" + len: 10000 + alphabet: "123" + - name: generator-large-all-digits + in: + n: + gen: "str" + len: 50000 + alphabet: "123456789" + - name: generator-maximum-length + in: + n: + gen: "str" + len: 100000 + alphabet: "123456789" diff --git a/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.cpp b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.cpp new file mode 100644 index 00000000..6e64837a --- /dev/null +++ b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + int minPartitions(string n) { + int maxDigit = 0; + for (char c : n) { + maxDigit = max(maxDigit, c - '0'); + } + return maxDigit; + } +}; diff --git a/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.cs b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.cs new file mode 100644 index 00000000..1f772ef3 --- /dev/null +++ b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.cs @@ -0,0 +1,9 @@ +public class Solution { + public int MinPartitions(string n) { + int max = 0; + foreach (char c in n) { + max = Math.Max(max, c - '0'); + } + return max; + } +} diff --git a/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.dart b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.dart new file mode 100644 index 00000000..21e64fa6 --- /dev/null +++ b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.dart @@ -0,0 +1,10 @@ +class Solution { + int minPartitions(String n) { + int max = 0; + for (int i = 0; i < n.length; i++) { + int digit = n.codeUnitAt(i) - 48; + if (digit > max) max = digit; + } + return max; + } +} diff --git a/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.go b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.go new file mode 100644 index 00000000..58e1a1c9 --- /dev/null +++ b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.go @@ -0,0 +1,9 @@ +func minPartitions(n string) int { + max := 0 + for _, ch := range n { + if int(ch-'0') > max { + max = int(ch - '0') + } + } + return max +} diff --git a/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.java b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.java new file mode 100644 index 00000000..f4d80df1 --- /dev/null +++ b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.java @@ -0,0 +1,9 @@ +class Solution { + public int minPartitions(String n) { + int max = 0; + for (char c : n.toCharArray()) { + max = Math.max(max, c - '0'); + } + return max; + } +} diff --git a/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.kt b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.kt new file mode 100644 index 00000000..7076bad7 --- /dev/null +++ b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.kt @@ -0,0 +1,5 @@ +class Solution { + fun minPartitions(n: String): Int { + return n.maxOf { it - '0' } + } +} diff --git a/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.py b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.py new file mode 100644 index 00000000..aef0691d --- /dev/null +++ b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.py @@ -0,0 +1,3 @@ +class Solution: + def minPartitions(self, n: str) -> int: + return int(max(n)) diff --git a/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.py2 b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.py2 new file mode 100644 index 00000000..bf88f995 --- /dev/null +++ b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.py2 @@ -0,0 +1,7 @@ +class Solution(object): + def minPartitions(self, n): + """ + :type n: str + :rtype: int + """ + return int(max(n)) diff --git a/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.rb b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.rb new file mode 100644 index 00000000..297f5edf --- /dev/null +++ b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.rb @@ -0,0 +1,5 @@ +# @param {String} n +# @return {Integer} +def min_partitions(n) + n.chars.map(&:to_i).max +end diff --git a/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.rs b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.rs new file mode 100644 index 00000000..2ba733af --- /dev/null +++ b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.rs @@ -0,0 +1,5 @@ +impl Solution { + pub fn min_partitions(n: String) -> i32 { + n.chars().map(|c| c.to_digit(10).unwrap() as i32).max().unwrap() + } +} diff --git a/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.swift b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.swift new file mode 100644 index 00000000..686c1a43 --- /dev/null +++ b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.swift @@ -0,0 +1,5 @@ +class Solution { + func minPartitions(_ n: String) -> Int { + return n.compactMap { Int(String($0)) }.max() ?? 0 + } +} diff --git a/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.ts b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.ts new file mode 100644 index 00000000..16796eaf --- /dev/null +++ b/tests/1501-2000/1689. partitioning-into-minimum-number-of-deci-binary-numbers/sol.ts @@ -0,0 +1,3 @@ +function minPartitions(n: string): number { + return Math.max(...n.split("").map(Number)); +} diff --git a/tests/1501-2000/1690. stone-game-vii/manifest.yaml b/tests/1501-2000/1690. stone-game-vii/manifest.yaml new file mode 100644 index 00000000..00365687 --- /dev/null +++ b/tests/1501-2000/1690. stone-game-vii/manifest.yaml @@ -0,0 +1,235 @@ +entry: + id: 1690 + title: "stone-game-vii" + params: + stones: + type: array + items: + type: int + call: + cpp: "Solution().stoneGameVII({stones})" + rust: "Solution::stone_game_vii({stones})" + python3: "Solution().stoneGameVII({stones})" + python2: "Solution().stoneGameVII({stones})" + ruby: "stone_game_vii({stones})" + java: "new Solution().stoneGameVII({stones})" + csharp: "new Solution().StoneGameVII({stones})" + kotlin: "Solution().stoneGameVII({stones})" + go: "stoneGameVII({stones})" + dart: "Solution().stoneGameVII({stones})" + swift: "Solution().stoneGameVII({stones})" + typescript: "stoneGameVII({stones})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().stoneGameVII(stones, {result})" + checker: | + class Checker: + def stoneGameVII(self, stones, result): + n = len(stones) + if n < 2 or n > 1000 or any(x < 1 or x > 1000 for x in stones): + return False + prefix = [0] + for x in stones: + prefix.append(prefix[-1] + x) + dp = [0] * n + for length in range(2, n + 1): + for left in range(n - length + 1): + right = left + length - 1 + total = prefix[right + 1] - prefix[left] + dp[left] = max(total - stones[left] - dp[left + 1], + total - stones[right] - dp[left]) + return result == dp[0] + +seed: 1690 + +tests: + - name: example-one + in: + stones: [5, 3, 1, 4, 2] + out: 6 + - name: example-two + in: + stones: [7, 90, 5, 1, 100, 10, 10, 2] + out: 122 + - name: minimum-length + in: + stones: [2, 7] + out: 7 + - name: three-equal + in: + stones: [1, 1, 1] + out: 1 + - name: increasing-four + in: + stones: [1, 2, 3, 4] + out: 6 + - name: alternating-large + in: + stones: [10, 1, 10, 1] + out: 20 + - name: maximum-equal-four + in: + stones: [1000, 1000, 1000, 1000] + out: 2000 + - name: alternating-five + in: + stones: [1, 1000, 1, 1000, 1] + out: 2 + - name: skewed-three + in: + stones: [999, 1, 500] + out: 1 + - name: repeated-alternation + in: + stones: [1, 2, 1, 2, 1, 2] + out: 6 + - name: valley-then-peak + in: + stones: [8, 6, 4, 2, 10, 12] + out: 22 + - name: mixed-seven + in: + stones: [3, 9, 2, 8, 1, 7, 4] + out: 7 + - name: equal-seven + in: + stones: [5, 5, 5, 5, 5, 5, 5] + out: 15 + - name: increasing-eight + in: + stones: [1, 3, 5, 7, 9, 11, 13, 15] + out: 36 + - name: decreasing-eight + in: + stones: [15, 13, 11, 9, 7, 5, 3, 1] + out: 36 + - name: high-low-nine + in: + stones: [1, 1000, 999, 2, 998, 3, 997, 4, 996] + out: 1009 + - name: equal-ten + in: + stones: [42, 42, 42, 42, 42, 42, 42, 42, 42, 42] + out: 210 + - name: increasing-ten + in: + stones: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + out: 30 + - name: decreasing-eight-high + in: + stones: [1000, 999, 998, 997, 996, 995, 994, 993] + out: 3988 + - name: repeated-three-values + in: + stones: [250, 750, 500, 250, 750, 500] + out: 1750 + - name: mixed-nine + in: + stones: [4, 1, 7, 3, 9, 2, 8, 5, 6] + out: 11 + - name: paired-values + in: + stones: [1, 1, 2, 2, 3, 3, 4, 4] + out: 10 + - name: separated-peaks + in: + stones: [12, 1, 2, 20, 3, 4, 30] + out: 25 + - name: descending-seven + in: + stones: [6, 5, 4, 3, 2, 1, 1] + out: 9 + - name: arithmetic-five + in: + stones: [11, 22, 33, 44, 55] + out: 66 + - name: alternating-seven + in: + stones: [2, 100, 3, 99, 4, 98, 5] + out: 12 + - name: sparse-peaks + in: + stones: [17, 2, 23, 4, 19, 6, 13] + out: 12 + - name: alternating-nine + in: + stones: [1, 50, 2, 49, 3, 48, 4, 47, 5] + out: 14 + - name: irregular-six + in: + stones: [321, 123, 456, 234, 345, 111] + out: 1122 + - name: decreasing-nine + in: + stones: [9, 8, 7, 6, 5, 4, 3, 2, 1] + out: 20 + - name: permutation-eight + in: + stones: [1, 4, 2, 8, 3, 7, 5, 6] + out: 25 + - name: dominant-first + in: + stones: [100, 1, 2, 3, 4, 5, 6, 7, 8] + out: 16 + - name: repeated-blocks + in: + stones: [13, 13, 13, 1, 1, 1, 26, 26] + out: 53 + - name: generated-small + in: + stones: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + - name: generated-medium + in: + stones: + gen: "array" + len: 17 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + - name: generated-structured + in: + stones: + gen: "array" + len: 64 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + - name: generated-large + in: + stones: + gen: "array" + len: 500 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + - name: generated-maximum + in: + stones: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" diff --git a/tests/1501-2000/1690. stone-game-vii/sol.cpp b/tests/1501-2000/1690. stone-game-vii/sol.cpp new file mode 100644 index 00000000..548bf9e1 --- /dev/null +++ b/tests/1501-2000/1690. stone-game-vii/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int stoneGameVII(vector& stones) { + int n = stones.size(); + vector prefix(n + 1, 0); + + for (int i = 0; i < n; i++) { + prefix[i + 1] = prefix[i] + stones[i]; + } + + vector> dp(n, vector(n, 0)); + + for (int length = 2; length <= n; length++) { + for (int i = 0; i <= n - length; i++) { + int j = i + length - 1; + int total = prefix[j + 1] - prefix[i]; + dp[i][j] = max( + total - stones[i] - dp[i + 1][j], + total - stones[j] - dp[i][j - 1] + ); + } + } + + return dp[0][n - 1]; + } +}; diff --git a/tests/1501-2000/1690. stone-game-vii/sol.cs b/tests/1501-2000/1690. stone-game-vii/sol.cs new file mode 100644 index 00000000..ba3d853a --- /dev/null +++ b/tests/1501-2000/1690. stone-game-vii/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public int StoneGameVII(int[] stones) { + int n = stones.Length; + int[] prefix = new int[n + 1]; + + for (int i = 0; i < n; i++) { + prefix[i + 1] = prefix[i] + stones[i]; + } + + int[,] dp = new int[n, n]; + + for (int length = 2; length <= n; length++) { + for (int i = 0; i <= n - length; i++) { + int j = i + length - 1; + int total = prefix[j + 1] - prefix[i]; + dp[i, j] = Math.Max( + total - stones[i] - dp[i + 1, j], + total - stones[j] - dp[i, j - 1] + ); + } + } + + return dp[0, n - 1]; + } +} diff --git a/tests/1501-2000/1690. stone-game-vii/sol.dart b/tests/1501-2000/1690. stone-game-vii/sol.dart new file mode 100644 index 00000000..fddb4270 --- /dev/null +++ b/tests/1501-2000/1690. stone-game-vii/sol.dart @@ -0,0 +1,20 @@ +class Solution { + int stoneGameVII(List stones) { + final n = stones.length; + final prefix = List.filled(n + 1, 0); + for (var i = 0; i < n; i++) { + prefix[i + 1] = prefix[i] + stones[i]; + } + final dp = List.filled(n, 0); + for (var length = 2; length <= n; length++) { + for (var left = 0; left + length <= n; left++) { + final right = left + length - 1; + final total = prefix[right + 1] - prefix[left]; + final removeLeft = total - stones[left] - dp[left + 1]; + final removeRight = total - stones[right] - dp[left]; + dp[left] = removeLeft > removeRight ? removeLeft : removeRight; + } + } + return dp[0]; + } +} diff --git a/tests/1501-2000/1690. stone-game-vii/sol.go b/tests/1501-2000/1690. stone-game-vii/sol.go new file mode 100644 index 00000000..4066c06f --- /dev/null +++ b/tests/1501-2000/1690. stone-game-vii/sol.go @@ -0,0 +1,30 @@ +func stoneGameVII(stones []int) int { + n := len(stones) + prefix := make([]int, n+1) + + for i := 0; i < n; i++ { + prefix[i+1] = prefix[i] + stones[i] + } + + dp := make([][]int, n) + for i := range dp { + dp[i] = make([]int, n) + } + + for length := 2; length <= n; length++ { + for i := 0; i <= n - length; i++ { + j := i + length - 1 + total := prefix[j+1] - prefix[i] + dp[i][j] = max(total - stones[i] - dp[i+1][j], total - stones[j] - dp[i][j-1]) + } + } + + return dp[0][n-1] +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} diff --git a/tests/1501-2000/1690. stone-game-vii/sol.java b/tests/1501-2000/1690. stone-game-vii/sol.java new file mode 100644 index 00000000..c4c25510 --- /dev/null +++ b/tests/1501-2000/1690. stone-game-vii/sol.java @@ -0,0 +1,25 @@ +class Solution { + public int stoneGameVII(int[] stones) { + int n = stones.length; + int[] prefix = new int[n + 1]; + + for (int i = 0; i < n; i++) { + prefix[i + 1] = prefix[i] + stones[i]; + } + + int[][] dp = new int[n][n]; + + for (int length = 2; length <= n; length++) { + for (int i = 0; i <= n - length; i++) { + int j = i + length - 1; + int total = prefix[j + 1] - prefix[i]; + dp[i][j] = Math.max( + total - stones[i] - dp[i + 1][j], + total - stones[j] - dp[i][j - 1] + ); + } + } + + return dp[0][n - 1]; + } +} diff --git a/tests/1501-2000/1690. stone-game-vii/sol.kt b/tests/1501-2000/1690. stone-game-vii/sol.kt new file mode 100644 index 00000000..3e6c27a0 --- /dev/null +++ b/tests/1501-2000/1690. stone-game-vii/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun stoneGameVII(stones: IntArray): Int { + val n = stones.size + val prefix = IntArray(n + 1) + + for (i in 0 until n) { + prefix[i + 1] = prefix[i] + stones[i] + } + + val dp = Array(n) { IntArray(n) } + + for (length in 2..n) { + for (i in 0..(n - length)) { + val j = i + length - 1 + val total = prefix[j + 1] - prefix[i] + dp[i][j] = maxOf( + total - stones[i] - dp[i + 1][j], + total - stones[j] - dp[i][j - 1] + ) + } + } + + return dp[0][n - 1] + } +} diff --git a/tests/1501-2000/1690. stone-game-vii/sol.py b/tests/1501-2000/1690. stone-game-vii/sol.py new file mode 100644 index 00000000..1fc84455 --- /dev/null +++ b/tests/1501-2000/1690. stone-game-vii/sol.py @@ -0,0 +1,23 @@ +class Solution(object): + def stoneGameVII(self, stones): + """ + :type stones: List[int] + :rtype: int + """ + n = len(stones) + prefix = [0] * (n + 1) + + for i in range(n): + prefix[i + 1] = prefix[i] + stones[i] + + dp = [[0] * n for _ in range(n)] + + for length in range(2, n + 1): + for i in range(n - length + 1): + j = i + length - 1 + total = prefix[j + 1] - prefix[i] + dp[i][j] = max( + total - stones[i] - dp[i + 1][j], total - stones[j] - dp[i][j - 1] + ) + + return dp[0][n - 1] diff --git a/tests/1501-2000/1690. stone-game-vii/sol.py2 b/tests/1501-2000/1690. stone-game-vii/sol.py2 new file mode 100644 index 00000000..932429de --- /dev/null +++ b/tests/1501-2000/1690. stone-game-vii/sol.py2 @@ -0,0 +1,24 @@ +class Solution(object): + def stoneGameVII(self, stones): + """ + :type stones: List[int] + :rtype: int + """ + n = len(stones) + prefix = [0] * (n + 1) + + for i in range(n): + prefix[i + 1] = prefix[i] + stones[i] + + dp = [[0] * n for _ in range(n)] + + for length in range(2, n + 1): + for i in range(n - length + 1): + j = i + length - 1 + total = prefix[j + 1] - prefix[i] + dp[i][j] = max( + total - stones[i] - dp[i + 1][j], + total - stones[j] - dp[i][j - 1] + ) + + return dp[0][n - 1] diff --git a/tests/1501-2000/1690. stone-game-vii/sol.rb b/tests/1501-2000/1690. stone-game-vii/sol.rb new file mode 100644 index 00000000..b7ddeebb --- /dev/null +++ b/tests/1501-2000/1690. stone-game-vii/sol.rb @@ -0,0 +1,25 @@ +# @param {Integer[]} stones +# @return {Integer} +def stone_game_vii(stones) + n = stones.length + prefix = Array.new(n + 1, 0) + + (0...n).each do |i| + prefix[i + 1] = prefix[i] + stones[i] + end + + dp = Array.new(n) { Array.new(n, 0) } + + (2..n).each do |length| + (0..(n - length)).each do |i| + j = i + length - 1 + total = prefix[j + 1] - prefix[i] + dp[i][j] = [ + total - stones[i] - dp[i + 1][j], + total - stones[j] - dp[i][j - 1] + ].max + end + end + + dp[0][n - 1] +end diff --git a/tests/1501-2000/1690. stone-game-vii/sol.rs b/tests/1501-2000/1690. stone-game-vii/sol.rs new file mode 100644 index 00000000..d25acd2f --- /dev/null +++ b/tests/1501-2000/1690. stone-game-vii/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn stone_game_vii(stones: Vec) -> i32 { + let n = stones.len(); + let mut prefix = vec![0; n + 1]; + + for i in 0..n { + prefix[i + 1] = prefix[i] + stones[i]; + } + + let mut dp = vec![vec![0; n]; n]; + + for length in 2..=n { + for i in 0..=(n - length) { + let j = i + length - 1; + let total = prefix[j + 1] - prefix[i]; + dp[i][j] = std::cmp::max( + total - stones[i] - dp[i + 1][j], + total - stones[j] - dp[i][j - 1] + ); + } + } + + dp[0][n - 1] + } +} diff --git a/tests/1501-2000/1690. stone-game-vii/sol.swift b/tests/1501-2000/1690. stone-game-vii/sol.swift new file mode 100644 index 00000000..0144afa2 --- /dev/null +++ b/tests/1501-2000/1690. stone-game-vii/sol.swift @@ -0,0 +1,27 @@ +class Solution { + func stoneGameVII(_ stones: [Int]) -> Int { + let n = stones.count + var prefix = [Int](repeating: 0, count: n + 1) + + for i in 0..= 2 { + for length in 2...n { + for i in 0...(n - length) { + let j = i + length - 1 + let total = prefix[j + 1] - prefix[i] + dp[i][j] = max( + total - stones[i] - dp[i + 1][j], + total - stones[j] - dp[i][j - 1] + ) + } + } + } + + return dp[0][n - 1] + } +} diff --git a/tests/1501-2000/1690. stone-game-vii/sol.ts b/tests/1501-2000/1690. stone-game-vii/sol.ts new file mode 100644 index 00000000..b32d98f3 --- /dev/null +++ b/tests/1501-2000/1690. stone-game-vii/sol.ts @@ -0,0 +1,23 @@ +function stoneGameVII(stones: number[]): number { + const n = stones.length; + const prefix = new Array(n + 1).fill(0); + + for (let i = 0; i < n; i++) { + prefix[i + 1] = prefix[i] + stones[i]; + } + + const dp: number[][] = Array.from({ length: n }, () => new Array(n).fill(0)); + + for (let length = 2; length <= n; length++) { + for (let i = 0; i <= n - length; i++) { + const j = i + length - 1; + const total = prefix[j + 1] - prefix[i]; + dp[i][j] = Math.max( + total - stones[i] - dp[i + 1][j], + total - stones[j] - dp[i][j - 1], + ); + } + } + + return dp[0][n - 1]; +} diff --git a/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/manifest.yaml b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/manifest.yaml new file mode 100644 index 00000000..17e3619d --- /dev/null +++ b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/manifest.yaml @@ -0,0 +1,384 @@ +entry: + id: 1691 + title: "maximum-height-by-stacking-cuboids" + params: + cuboids: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().maxHeight({cuboids})" + rust: "Solution::max_height({cuboids})" + python3: "Solution().maxHeight({cuboids})" + python2: "Solution().maxHeight({cuboids})" + ruby: "max_height({cuboids})" + java: "new Solution().maxHeight({cuboids})" + csharp: "new Solution().MaxHeight({cuboids})" + kotlin: "Solution().maxHeight({cuboids})" + go: "maxHeight({cuboids})" + dart: "Solution().maxHeight({cuboids})" + swift: "Solution().maxHeight({cuboids})" + typescript: "maxHeight({cuboids})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxHeight(cuboids, {result})" + checker: | + class Checker: + def maxHeight(self, cuboids, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + normalized = sorted(sorted(int(x) for x in c) for c in cuboids) + dp = [0] * len(normalized) + for i, current in enumerate(normalized): + dp[i] = current[2] + for j in range(i): + previous = normalized[j] + if all(previous[k] <= current[k] for k in range(3)): + dp[i] = max(dp[i], dp[j] + current[2]) + return result == max(dp) + +seed: 1691 + +tests: + - name: example-1 + in: + cuboids: + - [50, 45, 20] + - [95, 37, 53] + - [45, 23, 12] + out: 190 + - name: example-2 + in: + cuboids: + - [38, 25, 45] + - [76, 35, 3] + out: 76 + - name: example-3 + in: + cuboids: + - [7, 11, 17] + - [7, 17, 11] + - [11, 7, 17] + - [11, 17, 7] + - [17, 7, 11] + - [17, 11, 7] + out: 102 + - name: single-cuboid + in: + cuboids: + - [1, 2, 3] + out: 3 + - name: all-equal + in: + cuboids: + - [5, 5, 5] + - [5, 5, 5] + - [5, 5, 5] + - [5, 5, 5] + out: 20 + - name: strict-chain + in: + cuboids: + - [1, 1, 1] + - [2, 2, 2] + - [3, 3, 3] + - [4, 4, 4] + - [5, 5, 5] + out: 15 + - name: incomparable-pairs + in: + cuboids: + - [1, 10, 10] + - [10, 1, 10] + - [10, 10, 1] + - [2, 9, 9] + out: 30 + - name: rotations-matter + in: + cuboids: + - [4, 2, 3] + - [3, 4, 2] + - [2, 3, 4] + out: 12 + - name: one-dimension-ties + in: + cuboids: + - [2, 3, 4] + - [2, 4, 5] + - [3, 4, 6] + - [3, 5, 7] + out: 22 + - name: descending-input + in: + cuboids: + - [9, 9, 9] + - [7, 7, 7] + - [5, 5, 5] + - [3, 3, 3] + - [1, 1, 1] + out: 25 + - name: duplicate-with-different-height + in: + cuboids: + - [2, 3, 4] + - [2, 3, 4] + - [2, 3, 5] + out: 13 + - name: zero-crossing-not-allowed + in: + cuboids: + - [1, 100, 1] + - [2, 99, 2] + - [3, 98, 3] + - [4, 97, 4] + out: 100 + - name: maximum-dimensions + in: + cuboids: + - [100, 100, 100] + - [99, 99, 99] + - [98, 98, 98] + - [97, 97, 97] + out: 394 + - name: thin-cuboids + in: + cuboids: + - [1, 1, 100] + - [1, 2, 99] + - [1, 3, 98] + - [1, 4, 97] + out: 100 + - name: sorted-already + in: + cuboids: + - [1, 2, 3] + - [2, 3, 4] + - [3, 4, 5] + - [4, 5, 6] + out: 18 + - name: mixed-orientations + in: + cuboids: + - [8, 6, 5] + - [7, 4, 3] + - [9, 2, 8] + - [6, 6, 6] + - [10, 1, 1] + out: 15 + - name: equal-base-chain + in: + cuboids: + - [4, 4, 1] + - [4, 4, 2] + - [4, 4, 3] + - [4, 4, 4] + out: 16 + - name: many-maximal + in: + cuboids: + - [6, 10, 2] + - [7, 9, 3] + - [8, 8, 4] + - [9, 7, 5] + - [10, 6, 6] + out: 20 + - name: staircase + in: + cuboids: + - [1, 5, 2] + - [2, 6, 3] + - [3, 7, 4] + - [4, 8, 5] + - [5, 9, 6] + - [6, 10, 7] + out: 45 + - name: two-useful-among-noise + in: + cuboids: + - [100, 1, 1] + - [1, 100, 1] + - [2, 2, 2] + - [3, 3, 3] + - [4, 4, 4] + - [1, 99, 2] + out: 200 + - name: nineties + in: + cuboids: + - [90, 91, 92] + - [91, 92, 93] + - [92, 93, 94] + out: 279 + - name: repeated-dimensions + in: + cuboids: + - [2, 2, 8] + - [2, 8, 2] + - [8, 2, 2] + - [3, 3, 7] + - [3, 7, 3] + out: 24 + - name: lower-bound-values + in: + cuboids: + - [1, 1, 1] + - [1, 1, 2] + - [1, 2, 1] + - [2, 1, 1] + out: 7 + - name: broad-chain + in: + cuboids: + - [10, 20, 30] + - [15, 25, 35] + - [20, 30, 40] + - [25, 35, 45] + - [30, 40, 50] + - [35, 45, 55] + out: 255 + - name: alternate-traps + in: + cuboids: + - [2, 100, 2] + - [3, 99, 3] + - [4, 98, 4] + - [5, 97, 5] + - [6, 6, 6] + - [7, 7, 7] + out: 100 + - name: equal-two-sides + in: + cuboids: + - [3, 3, 1] + - [3, 3, 2] + - [3, 3, 3] + - [4, 4, 4] + - [4, 4, 5] + out: 18 + - name: high-height-small-base + in: + cuboids: + - [1, 2, 100] + - [1, 3, 99] + - [2, 3, 98] + - [2, 4, 97] + out: 100 + - name: six-identical + in: + cuboids: + - [7, 11, 17] + - [7, 11, 17] + - [7, 11, 17] + - [7, 11, 17] + - [7, 11, 17] + - [7, 11, 17] + out: 102 + - name: nontrivial-choice + in: + cuboids: + - [4, 5, 6] + - [5, 6, 7] + - [6, 7, 8] + - [7, 8, 9] + - [8, 9, 10] + - [9, 10, 11] + - [10, 11, 12] + out: 63 + - name: max-count-small + in: + cuboids: + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + out: 8 + - name: max-count-varied + in: + cuboids: + - [2, 2, 2] + - [2, 2, 3] + - [2, 3, 3] + - [3, 3, 3] + - [3, 3, 4] + - [3, 4, 4] + - [4, 4, 4] + out: 23 + - name: generator-uniform + in: + cuboids: + gen: "array" + len: 100 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + - name: generator-small-values + in: + cuboids: + gen: "array" + len: 100 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 1 + max: 10 + elemType: "int" + - name: generator-wide-values + in: + cuboids: + gen: "array" + len: 100 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 90 + max: 100 + elemType: "int" + - name: generator-two-valued + in: + cuboids: + gen: "array" + len: 100 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 1 + max: 2 + elemType: "int" + - name: generator-mixed + in: + cuboids: + gen: "array" + len: 100 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" diff --git a/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.cpp b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.cpp new file mode 100644 index 00000000..deb7832c --- /dev/null +++ b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int maxHeight(vector>& cuboids) { + for (auto& c : cuboids) { + sort(c.begin(), c.end()); + } + sort(cuboids.begin(), cuboids.end()); + int n = cuboids.size(); + vector dp(n); + int ans = 0; + for (int i = 0; i < n; i++) { + dp[i] = cuboids[i][2]; + for (int j = 0; j < i; j++) { + if (cuboids[j][0] <= cuboids[i][0] && cuboids[j][1] <= cuboids[i][1] && cuboids[j][2] <= cuboids[i][2]) { + dp[i] = max(dp[i], dp[j] + cuboids[i][2]); + } + } + ans = max(ans, dp[i]); + } + return ans; + } +}; diff --git a/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.cs b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.cs new file mode 100644 index 00000000..86e3eb20 --- /dev/null +++ b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public int MaxHeight(int[][] cuboids) { + foreach (var c in cuboids) { + Array.Sort(c); + } + Array.Sort(cuboids, (a,b) => { + if (a[0] != b[0]) return a[0].CompareTo(b[0]); + if (a[1] != b[1]) return a[1].CompareTo(b[1]); + return a[2].CompareTo(b[2]); + }); + int n = cuboids.Length; + int[] dp = new int[n]; + int ans = 0; + for (int i = 0; i < n; i++) { + dp[i] = cuboids[i][2]; + for (int j = 0; j < i; j++) { + if (cuboids[j][0] <= cuboids[i][0] && cuboids[j][1] <= cuboids[i][1] && cuboids[j][2] <= cuboids[i][2]) { + dp[i] = Math.Max(dp[i], dp[j] + cuboids[i][2]); + } + } + ans = Math.Max(ans, dp[i]); + } + return ans; + } +} diff --git a/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.dart b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.dart new file mode 100644 index 00000000..b28c1fb3 --- /dev/null +++ b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.dart @@ -0,0 +1,29 @@ +class Solution { + int maxHeight(List> cuboids) { + for (final cuboid in cuboids) { + cuboid.sort(); + } + cuboids.sort((a, b) { + for (var i = 0; i < 3; i++) { + final comparison = a[i].compareTo(b[i]); + if (comparison != 0) return comparison; + } + return 0; + }); + final dp = List.filled(cuboids.length, 0); + var answer = 0; + for (var i = 0; i < cuboids.length; i++) { + dp[i] = cuboids[i][2]; + for (var j = 0; j < i; j++) { + if (cuboids[j][0] <= cuboids[i][0] && + cuboids[j][1] <= cuboids[i][1] && + cuboids[j][2] <= cuboids[i][2]) { + final candidate = dp[j] + cuboids[i][2]; + if (candidate > dp[i]) dp[i] = candidate; + } + } + if (dp[i] > answer) answer = dp[i]; + } + return answer; + } +} diff --git a/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.go b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.go new file mode 100644 index 00000000..79727e60 --- /dev/null +++ b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.go @@ -0,0 +1,31 @@ +func maxHeight(cuboids [][]int) int { + for _, c := range cuboids { + sort.Ints(c) + } + sort.Slice(cuboids, func(i, j int) bool { + if cuboids[i][0] != cuboids[j][0] { + return cuboids[i][0] < cuboids[j][0] + } + if cuboids[i][1] != cuboids[j][1] { + return cuboids[i][1] < cuboids[j][1] + } + return cuboids[i][2] < cuboids[j][2] + }) + n := len(cuboids) + dp := make([]int, n) + ans := 0 + for i := 0; i < n; i++ { + dp[i] = cuboids[i][2] + for j := 0; j < i; j++ { + if cuboids[j][0] <= cuboids[i][0] && cuboids[j][1] <= cuboids[i][1] && cuboids[j][2] <= cuboids[i][2] { + if dp[j]+cuboids[i][2] > dp[i] { + dp[i] = dp[j] + cuboids[i][2] + } + } + } + if dp[i] > ans { + ans = dp[i] + } + } + return ans +} diff --git a/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.java b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.java new file mode 100644 index 00000000..2e7de281 --- /dev/null +++ b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.java @@ -0,0 +1,25 @@ +class Solution { + public int maxHeight(int[][] cuboids) { + for (int[] c : cuboids) { + Arrays.sort(c); + } + Arrays.sort(cuboids, (a, b) -> { + if (a[0] != b[0]) return Integer.compare(a[0], b[0]); + if (a[1] != b[1]) return Integer.compare(a[1], b[1]); + return Integer.compare(a[2], b[2]); + }); + int n = cuboids.length; + int[] dp = new int[n]; + int ans = 0; + for (int i = 0; i < n; i++) { + dp[i] = cuboids[i][2]; + for (int j = 0; j < i; j++) { + if (cuboids[j][0] <= cuboids[i][0] && cuboids[j][1] <= cuboids[i][1] && cuboids[j][2] <= cuboids[i][2]) { + dp[i] = Math.max(dp[i], dp[j] + cuboids[i][2]); + } + } + ans = Math.max(ans, dp[i]); + } + return ans; + } +} diff --git a/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.kt b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.kt new file mode 100644 index 00000000..186ec9d9 --- /dev/null +++ b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.kt @@ -0,0 +1,19 @@ +class Solution { + fun maxHeight(cuboids: Array): Int { + cuboids.forEach { it.sort() } + cuboids.sortWith(compareBy { it[0] }.thenBy { it[1] }.thenBy { it[2] }) + val n = cuboids.size + val dp = IntArray(n) + var ans = 0 + for (i in 0 until n) { + dp[i] = cuboids[i][2] + for (j in 0 until i) { + if (cuboids[j][0] <= cuboids[i][0] && cuboids[j][1] <= cuboids[i][1] && cuboids[j][2] <= cuboids[i][2]) { + dp[i] = maxOf(dp[i], dp[j] + cuboids[i][2]) + } + } + ans = maxOf(ans, dp[i]) + } + return ans + } +} diff --git a/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.py b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.py new file mode 100644 index 00000000..3093a175 --- /dev/null +++ b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.py @@ -0,0 +1,17 @@ +class Solution: + def maxHeight(self, cuboids: list[list[int]]) -> int: + for c in cuboids: + c.sort() + cuboids.sort() + n = len(cuboids) + dp = [0] * n + for i in range(n): + dp[i] = cuboids[i][2] + for j in range(i): + if ( + cuboids[j][0] <= cuboids[i][0] + and cuboids[j][1] <= cuboids[i][1] + and cuboids[j][2] <= cuboids[i][2] + ): + dp[i] = max(dp[i], dp[j] + cuboids[i][2]) + return max(dp) diff --git a/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.py2 b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.py2 new file mode 100644 index 00000000..c1735457 --- /dev/null +++ b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.py2 @@ -0,0 +1,17 @@ +class Solution(object): + def maxHeight(self, cuboids): + """ + :type cuboids: List[List[int]] + :rtype: int + """ + for c in cuboids: + c.sort() + cuboids.sort() + n = len(cuboids) + dp = [0]*n + for i in range(n): + dp[i] = cuboids[i][2] + for j in range(i): + if cuboids[j][0] <= cuboids[i][0] and cuboids[j][1] <= cuboids[i][1] and cuboids[j][2] <= cuboids[i][2]: + dp[i]=max(dp[i], dp[j]+cuboids[i][2]) + return max(dp) diff --git a/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.rb b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.rb new file mode 100644 index 00000000..bcbb1f1f --- /dev/null +++ b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.rb @@ -0,0 +1,17 @@ +# @param {Integer[][]} cuboids +# @return {Integer} +def max_height(cuboids) + cuboids.each { |c| c.sort! } + cuboids.sort! + n = cuboids.length + dp = Array.new(n, 0) + (0...n).each do |i| + dp[i] = cuboids[i][2] + (0...i).each do |j| + if cuboids[j][0] <= cuboids[i][0] && cuboids[j][1] <= cuboids[i][1] && cuboids[j][2] <= cuboids[i][2] + dp[i] = [dp[i], dp[j] + cuboids[i][2]].max + end + end + end + dp.max +end diff --git a/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.rs b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.rs new file mode 100644 index 00000000..54bb53f1 --- /dev/null +++ b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn max_height(cuboids: Vec>) -> i32 { + let mut cubs = cuboids; + for c in cubs.iter_mut() { + c.sort(); + } + cubs.sort_by(|a, b| { + if a[0] != b[0] { return a[0].cmp(&b[0]); } + if a[1] != b[1] { return a[1].cmp(&b[1]); } + a[2].cmp(&b[2]) + }); + let n = cubs.len(); + let mut dp = vec![0; n]; + let mut ans = 0; + for i in 0..n { + dp[i] = cubs[i][2]; + for j in 0..i { + if cubs[j][0] <= cubs[i][0] && cubs[j][1] <= cubs[i][1] && cubs[j][2] <= cubs[i][2] { + dp[i] = dp[i].max(dp[j] + cubs[i][2]); + } + } + ans = ans.max(dp[i]); + } + ans + } +} diff --git a/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.swift b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.swift new file mode 100644 index 00000000..e45dc5ce --- /dev/null +++ b/tests/1501-2000/1691. maximum-height-by-stacking-cuboids/sol.swift @@ -0,0 +1,26 @@ +class Solution { + func maxHeight(_ cuboids: [[Int]]) -> Int { + var cubs = cuboids + for i in 0.. c.sort((a, b) => a - b)); + cuboids.sort((a, b) => { + if (a[0] !== b[0]) return a[0] - b[0]; + if (a[1] !== b[1]) return a[1] - b[1]; + return a[2] - b[2]; + }); + const n = cuboids.length; + const dp = new Array(n).fill(0); + let ans = 0; + for (let i = 0; i < n; i++) { + dp[i] = cuboids[i][2]; + for (let j = 0; j < i; j++) { + if ( + cuboids[j][0] <= cuboids[i][0] && + cuboids[j][1] <= cuboids[i][1] && + cuboids[j][2] <= cuboids[i][2] + ) { + dp[i] = Math.max(dp[i], dp[j] + cuboids[i][2]); + } + } + ans = Math.max(ans, dp[i]); + } + return ans; +} diff --git a/tests/1501-2000/1694. reformat-phone-number/manifest.yaml b/tests/1501-2000/1694. reformat-phone-number/manifest.yaml new file mode 100644 index 00000000..b3388552 --- /dev/null +++ b/tests/1501-2000/1694. reformat-phone-number/manifest.yaml @@ -0,0 +1,212 @@ +entry: + id: 1694 + title: reformat-phone-number + params: + number: + type: string + call: + cpp: "Solution().reformatNumber({number})" + rust: "Solution::reformat_number({number})" + python3: "Solution().reformatNumber({number})" + python2: "Solution().reformatNumber({number})" + ruby: "reformat_number({number})" + java: "new Solution().reformatNumber({number})" + csharp: "new Solution().ReformatNumber({number})" + kotlin: "Solution().reformatNumber({number})" + go: "reformatNumber({number})" + dart: "Solution().reformatNumber({number})" + swift: "Solution().reformatNumber({number})" + typescript: "reformatNumber({number})" + +judge: + type: exact + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(number, {result})" + checker: | + class Checker: + def check(self, number, result): + digits = ''.join(ch for ch in number if ch.isdigit()) + blocks = [] + while len(digits) > 4: + blocks.append(digits[:3]) + digits = digits[3:] + if len(digits) == 4: + blocks.extend([digits[:2], digits[2:]]) + elif digits: + blocks.append(digits) + return result == '-'.join(blocks) + +seed: 1694 + +tests: + - name: example-one + in: + number: "1-23-45 6" + out: "123-456" + - name: example-two + in: + number: "123 4-567" + out: "123-45-67" + - name: example-three + in: + number: "123 4-5678" + out: "123-456-78" + - name: two-digits-spaced + in: + number: "1 2" + - name: two-digits-dashed + in: + number: "1-2" + - name: three-digits + in: + number: "123" + - name: four-digits + in: + number: "12-34" + out: "12-34" + - name: five-digits + in: + number: "12345" + out: "123-45" + - name: six-digits + in: + number: "123456" + out: "123-456" + - name: seven-digits + in: + number: "1234567" + out: "123-45-67" + - name: eight-digits + in: + number: "12345678" + out: "123-456-78" + - name: nine-digits + in: + number: "123456789" + out: "123-456-789" + - name: ten-digits + in: + number: "1234567890" + out: "123-456-78-90" + - name: leading-zero + in: + number: "0-12 345" + out: "012-345" + - name: all-zeroes + in: + number: "0-0 0-0 0" + out: "000-00" + - name: repeated-separators + in: + number: "12-- 34 56" + out: "123-456" + - name: separators-at-edges + in: + number: " 123456 " + out: "123-456" + - name: alternating-separators + in: + number: "1 2-3 4-5 6-7 8" + out: "123-456-78" + - name: four-after-block + in: + number: "123-4567" + out: "123-45-67" + - name: five-after-block + in: + number: "123-45678" + out: "123-456-78" + - name: long-spaced + in: + number: "1 2 3 4 5 6 7 8 9 0 1 2" + out: "123-456-789-012" + - name: long-dashed + in: + number: "12-34-56-78-90-12-34-56" + - name: mixed-long + in: + number: "123 -45 6-789 0-12" + out: "123-456-789-012" + - name: zeros-and-separators + in: + number: "000-000 000-000" + out: "000-000-000-000" + - name: digits-one-through + in: + number: "1-2-3-4-5-6-7-8-9" + out: "123-456-789" + - name: twelve-digits + in: + number: "123456789012" + out: "123-456-789-012" + - name: thirteen-digits + in: + number: "1234567890123" + - name: fourteen-digits + in: + number: "12345678901234" + - name: thirty-digits + in: + number: "123456789012345678901234567890" + - name: separator-heavy + in: + number: "1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 0" + out: "123-456-78-90" + - name: grouped-input + in: + number: "123 456 789 012 345" + out: "123-456-789-012-345" + - name: leading-zero-long + in: + number: "0000000000000" + - name: alternating-zeroes + in: + number: "0-10 20-30 40-50" + out: "010-203-040-50" + - name: final-four-preserved + in: + number: "999-9999" + out: "999-99-99" + - name: final-two-preserved + in: + number: "999-999-99" + out: "999-999-99" + - name: max-length-digits + in: + number: "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" + - name: generated-short + in: + number: + gen: str + len: 20 + alphabet: "0123456789" + - name: generated-medium + in: + number: + gen: str + len: 50 + alphabet: "0123456789" + - name: generated-long + in: + number: + gen: str + len: 100 + alphabet: "0123456789" + - name: generated-digits-heavy + in: + number: + gen: str + len: 90 + alphabet: "0123456789" + - name: generated-maximal + in: + number: + gen: str + len: 100 + alphabet: "0123456789 -" diff --git a/tests/1501-2000/1694. reformat-phone-number/sol.cpp b/tests/1501-2000/1694. reformat-phone-number/sol.cpp new file mode 100644 index 00000000..d2d719b1 --- /dev/null +++ b/tests/1501-2000/1694. reformat-phone-number/sol.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + string reformatNumber(string number) { + string phoneCleared = ""; + for (char c : number) { + if (isdigit(c)) phoneCleared += c; + } + + vector result; + while (phoneCleared.length() > 4) { + result.push_back(phoneCleared.substr(0, 3)); + phoneCleared = phoneCleared.substr(3); + } + + if (phoneCleared.length() == 4) { + result.push_back(phoneCleared.substr(0, 2)); + result.push_back(phoneCleared.substr(2)); + } else if (!phoneCleared.empty()) { + result.push_back(phoneCleared); + } + + string output; + for (int i = 0; i < result.size(); i++) { + if (i > 0) output += '-'; + output += result[i]; + } + return output; + } +}; diff --git a/tests/1501-2000/1694. reformat-phone-number/sol.cs b/tests/1501-2000/1694. reformat-phone-number/sol.cs new file mode 100644 index 00000000..2a1f9f7f --- /dev/null +++ b/tests/1501-2000/1694. reformat-phone-number/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public string ReformatNumber(string number) { + string phoneCleared = new string(number.Where(char.IsDigit).ToArray()); + List result = new List(); + + while (phoneCleared.Length > 4) { + result.Add(phoneCleared.Substring(0, 3)); + phoneCleared = phoneCleared.Substring(3); + } + + if (phoneCleared.Length == 4) { + result.Add(phoneCleared.Substring(0, 2)); + result.Add(phoneCleared.Substring(2)); + } else if (phoneCleared.Length > 0) { + result.Add(phoneCleared); + } + + return string.Join("-", result); + } +} diff --git a/tests/1501-2000/1694. reformat-phone-number/sol.dart b/tests/1501-2000/1694. reformat-phone-number/sol.dart new file mode 100644 index 00000000..d90ec294 --- /dev/null +++ b/tests/1501-2000/1694. reformat-phone-number/sol.dart @@ -0,0 +1,20 @@ +class Solution { + String reformatNumber(String number) { + String phoneCleared = number.replaceAll(RegExp(r'\D'), ''); + List result = []; + + while (phoneCleared.length > 4) { + result.add(phoneCleared.substring(0, 3)); + phoneCleared = phoneCleared.substring(3); + } + + if (phoneCleared.length == 4) { + result.add(phoneCleared.substring(0, 2)); + result.add(phoneCleared.substring(2)); + } else if (phoneCleared.isNotEmpty) { + result.add(phoneCleared); + } + + return result.join('-'); + } +} diff --git a/tests/1501-2000/1694. reformat-phone-number/sol.go b/tests/1501-2000/1694. reformat-phone-number/sol.go new file mode 100644 index 00000000..04d0c429 --- /dev/null +++ b/tests/1501-2000/1694. reformat-phone-number/sol.go @@ -0,0 +1,22 @@ +func reformatNumber(number string) string { + phoneCleared := "" + for _, ch := range number { + if ch >= '0' && ch <= '9' { + phoneCleared += string(ch) + } + } + + result := []string{} + for len(phoneCleared) > 4 { + result = append(result, phoneCleared[:3]) + phoneCleared = phoneCleared[3:] + } + + if len(phoneCleared) == 4 { + result = append(result, phoneCleared[:2], phoneCleared[2:]) + } else if len(phoneCleared) > 0 { + result = append(result, phoneCleared) + } + + return strings.Join(result, "-") +} diff --git a/tests/1501-2000/1694. reformat-phone-number/sol.java b/tests/1501-2000/1694. reformat-phone-number/sol.java new file mode 100644 index 00000000..7ec8540f --- /dev/null +++ b/tests/1501-2000/1694. reformat-phone-number/sol.java @@ -0,0 +1,19 @@ +class Solution { + public String reformatNumber(String number) { + String phoneCleared = number.replaceAll("\\D", ""); + StringBuilder result = new StringBuilder(); + + while (phoneCleared.length() > 4) { + result.append(phoneCleared.substring(0, 3)).append('-'); + phoneCleared = phoneCleared.substring(3); + } + + if (phoneCleared.length() == 4) { + result.append(phoneCleared.substring(0, 2)).append('-').append(phoneCleared.substring(2)); + } else if (!phoneCleared.isEmpty()) { + result.append(phoneCleared); + } + + return result.toString(); + } +} diff --git a/tests/1501-2000/1694. reformat-phone-number/sol.kt b/tests/1501-2000/1694. reformat-phone-number/sol.kt new file mode 100644 index 00000000..cbebc926 --- /dev/null +++ b/tests/1501-2000/1694. reformat-phone-number/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun reformatNumber(number: String): String { + var phoneCleared = number.filter { it.isDigit() } + val result = mutableListOf() + + while (phoneCleared.length > 4) { + result.add(phoneCleared.substring(0, 3)) + phoneCleared = phoneCleared.substring(3) + } + + if (phoneCleared.length == 4) { + result.add(phoneCleared.substring(0, 2)) + result.add(phoneCleared.substring(2)) + } else if (phoneCleared.isNotEmpty()) { + result.add(phoneCleared) + } + + return result.joinToString("-") + } +} diff --git a/tests/1501-2000/1694. reformat-phone-number/sol.py b/tests/1501-2000/1694. reformat-phone-number/sol.py new file mode 100644 index 00000000..9bc02a52 --- /dev/null +++ b/tests/1501-2000/1694. reformat-phone-number/sol.py @@ -0,0 +1,14 @@ +class Solution(object): + def reformatNumber(self, number): + phone_cleared = "".join(char for char in number if char.isdigit()) + phone_result = [] + + while len(phone_cleared) > 4: + phone_result.append(phone_cleared[:3]) + phone_cleared = phone_cleared[3:] + if len(phone_cleared) == 4: + phone_result.append(phone_cleared[:2]) + phone_result.append(phone_cleared[2:]) + elif phone_cleared: + phone_result.append(phone_cleared) + return "-".join(phone_result) diff --git a/tests/1501-2000/1694. reformat-phone-number/sol.py2 b/tests/1501-2000/1694. reformat-phone-number/sol.py2 new file mode 100644 index 00000000..26ca7c0c --- /dev/null +++ b/tests/1501-2000/1694. reformat-phone-number/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def reformatNumber(self, number): + """ + :type number: str + :rtype: str + """ + phone_cleared = ''.join(char for char in number if char.isdigit()) + phone_result = [] + + while len(phone_cleared) > 4: + phone_result.append(phone_cleared[:3]) + phone_cleared = phone_cleared[3:] + if len(phone_cleared) == 4: + phone_result.append(phone_cleared[:2]) + phone_result.append(phone_cleared[2:]) + elif phone_cleared: + phone_result.append(phone_cleared) + return '-'.join(phone_result) diff --git a/tests/1501-2000/1694. reformat-phone-number/sol.rb b/tests/1501-2000/1694. reformat-phone-number/sol.rb new file mode 100644 index 00000000..98cebb3d --- /dev/null +++ b/tests/1501-2000/1694. reformat-phone-number/sol.rb @@ -0,0 +1,20 @@ +# @param {String} number +# @return {String} +def reformat_number(number) + phone_cleared = number.gsub(/\D/, '') + phone_result = [] + + while phone_cleared.length > 4 + phone_result << phone_cleared[0...3] + phone_cleared = phone_cleared[3..-1] || '' + end + + if phone_cleared.length == 4 + phone_result << phone_cleared[0...2] + phone_result << phone_cleared[2..-1] + elsif !phone_cleared.empty? + phone_result << phone_cleared + end + + phone_result.join('-') +end diff --git a/tests/1501-2000/1694. reformat-phone-number/sol.rs b/tests/1501-2000/1694. reformat-phone-number/sol.rs new file mode 100644 index 00000000..ffeb7b5b --- /dev/null +++ b/tests/1501-2000/1694. reformat-phone-number/sol.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn reformat_number(number: String) -> String { + let phone_cleared: String = number.chars().filter(|c| c.is_digit(10)).collect(); + let mut result: Vec = Vec::new(); + let mut phone = phone_cleared; + + while phone.len() > 4 { + result.push(phone[..3].to_string()); + phone = phone[3..].to_string(); + } + + if phone.len() == 4 { + result.push(phone[..2].to_string()); + result.push(phone[2..].to_string()); + } else if !phone.is_empty() { + result.push(phone); + } + + result.join("-") + } +} diff --git a/tests/1501-2000/1694. reformat-phone-number/sol.swift b/tests/1501-2000/1694. reformat-phone-number/sol.swift new file mode 100644 index 00000000..e3ab107e --- /dev/null +++ b/tests/1501-2000/1694. reformat-phone-number/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func reformatNumber(_ number: String) -> String { + var phoneCleared = number.filter { $0.isNumber } + var result: [String] = [] + + while phoneCleared.count > 4 { + result.append(String(phoneCleared.prefix(3))) + phoneCleared = String(phoneCleared.dropFirst(3)) + } + + if phoneCleared.count == 4 { + result.append(String(phoneCleared.prefix(2))) + result.append(String(phoneCleared.suffix(2))) + } else if !phoneCleared.isEmpty { + result.append(phoneCleared) + } + + return result.joined(separator: "-") + } +} diff --git a/tests/1501-2000/1694. reformat-phone-number/sol.ts b/tests/1501-2000/1694. reformat-phone-number/sol.ts new file mode 100644 index 00000000..2c1bad99 --- /dev/null +++ b/tests/1501-2000/1694. reformat-phone-number/sol.ts @@ -0,0 +1,18 @@ +function reformatNumber(number: string): string { + let phoneCleared = number.replace(/\D/g, ""); + const result: string[] = []; + + while (phoneCleared.length > 4) { + result.push(phoneCleared.slice(0, 3)); + phoneCleared = phoneCleared.slice(3); + } + + if (phoneCleared.length === 4) { + result.push(phoneCleared.slice(0, 2)); + result.push(phoneCleared.slice(2)); + } else if (phoneCleared.length > 0) { + result.push(phoneCleared); + } + + return result.join("-"); +} diff --git a/tests/1501-2000/1695. maximum-erasure-value/manifest.yaml b/tests/1501-2000/1695. maximum-erasure-value/manifest.yaml new file mode 100644 index 00000000..f49da793 --- /dev/null +++ b/tests/1501-2000/1695. maximum-erasure-value/manifest.yaml @@ -0,0 +1,234 @@ +entry: + id: 1695 + title: "maximum-erasure-value" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().maximumUniqueSubarray({nums})" + rust: "Solution::maximum_unique_subarray({nums})" + python3: "Solution().maximumUniqueSubarray({nums})" + python2: "Solution().maximumUniqueSubarray({nums})" + ruby: "maximum_unique_subarray({nums})" + java: "new Solution().maximumUniqueSubarray({nums})" + csharp: "new Solution().MaximumUniqueSubarray({nums})" + kotlin: "Solution().maximumUniqueSubarray({nums})" + go: "maximumUniqueSubarray({nums})" + dart: "Solution().maximumUniqueSubarray({nums})" + swift: "Solution().maximumUniqueSubarray({nums})" + typescript: "maximumUniqueSubarray({nums})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maximumUniqueSubarray(nums, {result})" + checker: | + class Checker: + def maximumUniqueSubarray(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + seen = set() + left = 0 + current = 0 + expected = 0 + for right, value in enumerate(nums): + while value in seen: + seen.remove(nums[left]) + current -= nums[left] + left += 1 + seen.add(value) + current += value + expected = max(expected, current) + return result == expected + +seed: 1695 + +tests: + - name: example-one + in: + nums: [4, 2, 4, 5, 6] + out: 17 + - name: example-two + in: + nums: [5, 2, 1, 2, 5, 2, 1, 2, 5] + out: 8 + - name: single-one + in: + nums: [1] + out: 1 + - name: single-maximum + in: + nums: [10000] + out: 10000 + - name: all-equal + in: + nums: [7, 7, 7, 7, 7] + out: 7 + - name: all-distinct-small + in: + nums: [1, 2, 3, 4, 5, 6] + out: 21 + - name: duplicate-at-end + in: + nums: [1, 2, 3, 4, 3] + out: 10 + - name: duplicate-at-start + in: + nums: [4, 1, 2, 3, 4] + out: 10 + - name: repeated-pattern + in: + nums: [1, 2, 1, 2, 1, 2] + out: 3 + - name: shrinking-window + in: + nums: [5, 4, 3, 2, 1, 5] + out: 15 + - name: high-values-distinct + in: + nums: [9998, 9999, 10000] + out: 29997 + - name: high-values-duplicate + in: + nums: [10000, 9999, 10000, 9998] + out: 29997 + - name: alternating + in: + nums: [10, 1, 10, 1, 10, 1, 10] + out: 11 + - name: long-unique-prefix + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 1, 9] + out: 45 + - name: zero-not-allowed-boundary-values + in: + nums: [1, 100, 2, 99, 3, 98] + out: 303 + - name: two-values + in: + nums: [2, 1] + out: 3 + - name: duplicate-forces-single + in: + nums: [9, 1, 9] + out: 10 + - name: best-middle-window + in: + nums: [100, 1, 2, 100, 3, 4] + out: 110 + - name: best-suffix + in: + nums: [8, 8, 1, 2, 3, 4] + out: 18 + - name: best-prefix + in: + nums: [1, 2, 3, 4, 1, 1] + out: 10 + - name: many-small-duplicates + in: + nums: [1, 2, 3, 1, 2, 3, 4, 5] + out: 15 + - name: duplicate-after-large-sum + in: + nums: [10000, 9999, 9998, 10000, 1] + out: 29998 + - name: alternating-high-low + in: + nums: [10000, 1, 9999, 2, 9998, 3] + out: 30003 + - name: descending-distinct + in: + nums: [9, 8, 7, 6, 5, 4, 3, 2, 1] + out: 45 + - name: duplicate-near-window-start + in: + nums: [1, 2, 3, 4, 5, 2, 6] + out: 20 + - name: duplicate-near-window-end + in: + nums: [2, 3, 4, 5, 2, 6, 7] + out: 27 + - name: nested-choice + in: + nums: [6, 7, 8, 6, 9, 10, 11] + out: 51 + - name: large-value-single-best + in: + nums: [1, 1, 1, 10000, 1, 1] + out: 10001 + - name: ten-distinct + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + out: 55 + - name: duplicate-crossing-best + in: + nums: [4, 5, 6, 4, 7, 8, 9, 10] + out: 49 + - name: gen-random-bounded + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" + - name: gen-many-duplicates + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 20 + distinct: false + sorted: false + elemType: "int" + - name: gen-all-distinct-range + in: + nums: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 10000 + distinct: true + sorted: false + elemType: "int" + - name: gen-small-alphabet + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + - name: gen-max-length-wide-values + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1695. maximum-erasure-value/sol.cpp b/tests/1501-2000/1695. maximum-erasure-value/sol.cpp new file mode 100644 index 00000000..1c9edab9 --- /dev/null +++ b/tests/1501-2000/1695. maximum-erasure-value/sol.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int maximumUniqueSubarray(vector& nums) { + int res = 0; + int cur_sum = 0; + int start = 0; + const int k = 10001; + vector is_present(k, false); + + for (int end = 0; end < nums.size(); end++) { + while (is_present[nums[end]]) { + is_present[nums[start]] = false; + cur_sum -= nums[start]; + start++; + } + + is_present[nums[end]] = true; + cur_sum += nums[end]; + + res = max(res, cur_sum); + } + + return res; + } +}; diff --git a/tests/1501-2000/1695. maximum-erasure-value/sol.cs b/tests/1501-2000/1695. maximum-erasure-value/sol.cs new file mode 100644 index 00000000..bb377afc --- /dev/null +++ b/tests/1501-2000/1695. maximum-erasure-value/sol.cs @@ -0,0 +1,24 @@ +public class Solution { + public int MaximumUniqueSubarray(int[] nums) { + int res = 0; + int curSum = 0; + int start = 0; + const int k = 10001; + bool[] isPresent = new bool[k]; + + for (int end = 0; end < nums.Length; end++) { + while (isPresent[nums[end]]) { + isPresent[nums[start]] = false; + curSum -= nums[start]; + start++; + } + + isPresent[nums[end]] = true; + curSum += nums[end]; + + res = Math.Max(res, curSum); + } + + return res; + } +} diff --git a/tests/1501-2000/1695. maximum-erasure-value/sol.dart b/tests/1501-2000/1695. maximum-erasure-value/sol.dart new file mode 100644 index 00000000..a4c614be --- /dev/null +++ b/tests/1501-2000/1695. maximum-erasure-value/sol.dart @@ -0,0 +1,26 @@ +class Solution { + int maximumUniqueSubarray(List nums) { + int res = 0; + int curSum = 0; + int start = 0; + final k = 10001; + List isPresent = List.filled(k, false); + + for (int end = 0; end < nums.length; end++) { + while (isPresent[nums[end]]) { + isPresent[nums[start]] = false; + curSum -= nums[start]; + start++; + } + + isPresent[nums[end]] = true; + curSum += nums[end]; + + if (curSum > res) { + res = curSum; + } + } + + return res; + } +} diff --git a/tests/1501-2000/1695. maximum-erasure-value/sol.go b/tests/1501-2000/1695. maximum-erasure-value/sol.go new file mode 100644 index 00000000..7cee3bb3 --- /dev/null +++ b/tests/1501-2000/1695. maximum-erasure-value/sol.go @@ -0,0 +1,24 @@ +func maximumUniqueSubarray(nums []int) int { + res := 0 + curSum := 0 + start := 0 + k := 10001 + isPresent := make([]bool, k) + + for end := 0; end < len(nums); end++ { + for isPresent[nums[end]] { + isPresent[nums[start]] = false + curSum -= nums[start] + start++ + } + + isPresent[nums[end]] = true + curSum += nums[end] + + if curSum > res { + res = curSum + } + } + + return res +} diff --git a/tests/1501-2000/1695. maximum-erasure-value/sol.java b/tests/1501-2000/1695. maximum-erasure-value/sol.java new file mode 100644 index 00000000..f27b6261 --- /dev/null +++ b/tests/1501-2000/1695. maximum-erasure-value/sol.java @@ -0,0 +1,24 @@ +class Solution { + public int maximumUniqueSubarray(int[] nums) { + int res = 0; + int cur_sum = 0; + int start = 0; + int k = 10001; + boolean[] is_present = new boolean[k]; + + for (int end = 0; end < nums.length; end++) { + while (is_present[nums[end]]) { + is_present[nums[start]] = false; + cur_sum -= nums[start]; + start++; + } + + is_present[nums[end]] = true; + cur_sum += nums[end]; + + res = Math.max(res, cur_sum); + } + + return res; + } +} diff --git a/tests/1501-2000/1695. maximum-erasure-value/sol.kt b/tests/1501-2000/1695. maximum-erasure-value/sol.kt new file mode 100644 index 00000000..baadcd6e --- /dev/null +++ b/tests/1501-2000/1695. maximum-erasure-value/sol.kt @@ -0,0 +1,24 @@ +class Solution { + fun maximumUniqueSubarray(nums: IntArray): Int { + var res = 0 + var curSum = 0 + var start = 0 + val k = 10001 + val isPresent = BooleanArray(k) + + for (end in nums.indices) { + while (isPresent[nums[end]]) { + isPresent[nums[start]] = false + curSum -= nums[start] + start++ + } + + isPresent[nums[end]] = true + curSum += nums[end] + + res = maxOf(res, curSum) + } + + return res + } +} diff --git a/tests/1501-2000/1695. maximum-erasure-value/sol.py b/tests/1501-2000/1695. maximum-erasure-value/sol.py new file mode 100644 index 00000000..3f0aca0b --- /dev/null +++ b/tests/1501-2000/1695. maximum-erasure-value/sol.py @@ -0,0 +1,20 @@ +class Solution: + def maximumUniqueSubarray(self, nums: List[int]) -> int: + res = 0 + cur_sum = 0 + start = 0 + k = 10001 + is_present = [False] * k + + for end in range(len(nums)): + while is_present[nums[end]]: + is_present[nums[start]] = False + cur_sum -= nums[start] + start += 1 + + is_present[nums[end]] = True + cur_sum += nums[end] + + res = max(res, cur_sum) + + return res diff --git a/tests/1501-2000/1695. maximum-erasure-value/sol.py2 b/tests/1501-2000/1695. maximum-erasure-value/sol.py2 new file mode 100644 index 00000000..ba5cee04 --- /dev/null +++ b/tests/1501-2000/1695. maximum-erasure-value/sol.py2 @@ -0,0 +1,24 @@ +class Solution(object): + def maximumUniqueSubarray(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + res = 0 + cur_sum = 0 + start = 0 + k = 10001 + is_present = [False] * k + + for end in range(len(nums)): + while is_present[nums[end]]: + is_present[nums[start]] = False + cur_sum -= nums[start] + start += 1 + + is_present[nums[end]] = True + cur_sum += nums[end] + + res = max(res, cur_sum) + + return res diff --git a/tests/1501-2000/1695. maximum-erasure-value/sol.rb b/tests/1501-2000/1695. maximum-erasure-value/sol.rb new file mode 100644 index 00000000..d233921f --- /dev/null +++ b/tests/1501-2000/1695. maximum-erasure-value/sol.rb @@ -0,0 +1,24 @@ +# @param {Integer[]} nums +# @return {Integer} +def maximum_unique_subarray(nums) + res = 0 + cur_sum = 0 + start = 0 + k = 10001 + is_present = Array.new(k, false) + + nums.each_with_index do |num, end_idx| + while is_present[num] + is_present[nums[start]] = false + cur_sum -= nums[start] + start += 1 + end + + is_present[num] = true + cur_sum += num + + res = [res, cur_sum].max + end + + res +end diff --git a/tests/1501-2000/1695. maximum-erasure-value/sol.rs b/tests/1501-2000/1695. maximum-erasure-value/sol.rs new file mode 100644 index 00000000..e426cdfb --- /dev/null +++ b/tests/1501-2000/1695. maximum-erasure-value/sol.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn maximum_unique_subarray(nums: Vec) -> i32 { + let mut res = 0; + let mut cur_sum = 0; + let mut start = 0; + let k = 10001; + let mut is_present = vec![false; k]; + + for end in 0..nums.len() { + while is_present[nums[end] as usize] { + is_present[nums[start] as usize] = false; + cur_sum -= nums[start]; + start += 1; + } + + is_present[nums[end] as usize] = true; + cur_sum += nums[end]; + + res = res.max(cur_sum); + } + + res + } +} diff --git a/tests/1501-2000/1695. maximum-erasure-value/sol.swift b/tests/1501-2000/1695. maximum-erasure-value/sol.swift new file mode 100644 index 00000000..3db93dad --- /dev/null +++ b/tests/1501-2000/1695. maximum-erasure-value/sol.swift @@ -0,0 +1,24 @@ +class Solution { + func maximumUniqueSubarray(_ nums: [Int]) -> Int { + var res = 0 + var curSum = 0 + var start = 0 + let k = 10001 + var isPresent = [Bool](repeating: false, count: k) + + for end in 0..& nums, int k) { + int n = nums.size(); + vector dp(n); + dp[0] = nums[0]; + deque dq; + dq.push_back(0); + for (int i = 1; i < n; i++) { + while (!dq.empty() && dq.front() < i - k) { + dq.pop_front(); + } + dp[i] = nums[i] + dp[dq.front()]; + while (!dq.empty() && dp[dq.back()] <= dp[i]) { + dq.pop_back(); + } + dq.push_back(i); + } + return dp[n-1]; + } +}; diff --git a/tests/1501-2000/1696. jump-game-vi/sol.cs b/tests/1501-2000/1696. jump-game-vi/sol.cs new file mode 100644 index 00000000..ecdd1335 --- /dev/null +++ b/tests/1501-2000/1696. jump-game-vi/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public int MaxResult(int[] nums, int k) { + int n = nums.Length; + int[] dp = new int[n]; + dp[0] = nums[0]; + var dq = new LinkedList(); + dq.AddLast(0); + for (int i = 1; i < n; i++) { + while (dq.Count > 0 && dq.First.Value < i - k) { + dq.RemoveFirst(); + } + dp[i] = nums[i] + dp[dq.First.Value]; + while (dq.Count > 0 && dp[dq.Last.Value] <= dp[i]) { + dq.RemoveLast(); + } + dq.AddLast(i); + } + return dp[n-1]; + } +} diff --git a/tests/1501-2000/1696. jump-game-vi/sol.dart b/tests/1501-2000/1696. jump-game-vi/sol.dart new file mode 100644 index 00000000..a15640f9 --- /dev/null +++ b/tests/1501-2000/1696. jump-game-vi/sol.dart @@ -0,0 +1,20 @@ +class Solution { + int maxResult(List nums, int k) { + int n = nums.length; + List dp = List.filled(n, 0); + dp[0] = nums[0]; + List dq = [0]; + int head = 0; + for (int i = 1; i < n; i++) { + if (dq[head] < i - k) { + head++; + } + dp[i] = nums[i] + dp[dq[head]]; + while (dq.length > head && dp[dq[dq.length - 1]] <= dp[i]) { + dq.removeLast(); + } + dq.add(i); + } + return dp[n - 1]; + } +} diff --git a/tests/1501-2000/1696. jump-game-vi/sol.go b/tests/1501-2000/1696. jump-game-vi/sol.go new file mode 100644 index 00000000..50ef86b1 --- /dev/null +++ b/tests/1501-2000/1696. jump-game-vi/sol.go @@ -0,0 +1,18 @@ +func maxResult(nums []int, k int) int { + n := len(nums) + dp := make([]int, n) + dp[0] = nums[0] + dq := []int{0} + head := 0 + for i := 1; i < n; i++ { + if dq[head] < i - k { + head++ + } + dp[i] = nums[i] + dp[dq[head]] + for len(dq) > head && dp[dq[len(dq)-1]] <= dp[i] { + dq = dq[:len(dq)-1] + } + dq = append(dq, i) + } + return dp[n-1] +} diff --git a/tests/1501-2000/1696. jump-game-vi/sol.java b/tests/1501-2000/1696. jump-game-vi/sol.java new file mode 100644 index 00000000..e072f381 --- /dev/null +++ b/tests/1501-2000/1696. jump-game-vi/sol.java @@ -0,0 +1,20 @@ +class Solution { + public int maxResult(int[] nums, int k) { + int n = nums.length; + int[] dp = new int[n]; + dp[0] = nums[0]; + Deque dq = new ArrayDeque<>(); + dq.addFirst(0); + for (int i = 1; i < n; i++) { + while (!dq.isEmpty() && dq.peekFirst() < i - k) { + dq.pollFirst(); + } + dp[i] = nums[i] + dp[dq.peekFirst()]; + while (!dq.isEmpty() && dp[dq.peekLast()] <= dp[i]) { + dq.pollLast(); + } + dq.addLast(i); + } + return dp[n-1]; + } +} diff --git a/tests/1501-2000/1696. jump-game-vi/sol.kt b/tests/1501-2000/1696. jump-game-vi/sol.kt new file mode 100644 index 00000000..d382f844 --- /dev/null +++ b/tests/1501-2000/1696. jump-game-vi/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun maxResult(nums: IntArray, k: Int): Int { + val n = nums.size + val dp = IntArray(n) + dp[0] = nums[0] + val dq = ArrayDeque() + dq.addLast(0) + for (i in 1 until n) { + while (!dq.isEmpty() && dq.first() < i - k) { + dq.removeFirst() + } + dp[i] = nums[i] + dp[dq.first()] + while (!dq.isEmpty() && dp[dq.last()] <= dp[i]) { + dq.removeLast() + } + dq.addLast(i) + } + return dp[n-1] + } +} diff --git a/tests/1501-2000/1696. jump-game-vi/sol.py b/tests/1501-2000/1696. jump-game-vi/sol.py new file mode 100644 index 00000000..0b03f46c --- /dev/null +++ b/tests/1501-2000/1696. jump-game-vi/sol.py @@ -0,0 +1,30 @@ +from collections import deque + + +class Solution: + def maxResult(self, nums: List[int], k: int) -> int: + n = len(nums) + # dp[i] will store the maximum score to reach index i + dp = [0] * n + dp[0] = nums[0] + + # Deque will store indices, maintaining a strictly decreasing order of dp values + dq = deque([0]) + + for i in range(1, n): + # 1. Evict indices that are out of the max jump range 'k' from the front + if dq and dq[0] < i - k: + dq.popleft() + + # 2. The front of the deque holds the index of the absolute max DP value in range + dp[i] = nums[i] + dp[dq[0]] + + # 3. Maintain the monotonic decreasing invariant at the back + # Erase any past choices that have a worse or equal DP score than our new dp[i] + while dq and dp[dq[-1]] <= dp[i]: + dq.pop() + + # 4. Push the current index as a valid launchpad for future jumps + dq.append(i) + + return dp[-1] diff --git a/tests/1501-2000/1696. jump-game-vi/sol.py2 b/tests/1501-2000/1696. jump-game-vi/sol.py2 new file mode 100644 index 00000000..bedb3123 --- /dev/null +++ b/tests/1501-2000/1696. jump-game-vi/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def maxResult(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + n = len(nums) + dp = [0] * n + dp[0] = nums[0] + dq = [0] + head = 0 + for i in range(1, n): + if dq[head] < i - k: + head += 1 + dp[i] = nums[i] + dp[dq[head]] + while len(dq) > head and dp[dq[-1]] <= dp[i]: + dq.pop() + dq.append(i) + return dp[-1] diff --git a/tests/1501-2000/1696. jump-game-vi/sol.rb b/tests/1501-2000/1696. jump-game-vi/sol.rb new file mode 100644 index 00000000..261368b0 --- /dev/null +++ b/tests/1501-2000/1696. jump-game-vi/sol.rb @@ -0,0 +1,19 @@ +# @param {Integer[]} nums +# @param {Integer} k +# @return {Integer} +def max_result(nums, k) + n = nums.length + dp = Array.new(n, 0) + dp[0] = nums[0] + dq = [0] + head = 0 + (1...n).each do |i| + head += 1 if dq[head] < i - k + dp[i] = nums[i] + dp[dq[head]] + while dq.length > head && dp[dq[-1]] <= dp[i] + dq.pop + end + dq << i + end + dp[-1] +end diff --git a/tests/1501-2000/1696. jump-game-vi/sol.rs b/tests/1501-2000/1696. jump-game-vi/sol.rs new file mode 100644 index 00000000..72baee08 --- /dev/null +++ b/tests/1501-2000/1696. jump-game-vi/sol.rs @@ -0,0 +1,30 @@ +use std::collections::VecDeque; + +impl Solution { + pub fn max_result(nums: Vec, k: i32) -> i32 { + let n = nums.len(); + let mut dp = vec![0; n]; + dp[0] = nums[0]; + let mut dq = VecDeque::from([0usize]); + let k = k as usize; + for i in 1..n { + while let Some(&front) = dq.front() { + if front + k < i { + dq.pop_front(); + } else { + break; + } + } + dp[i] = nums[i] + dp[*dq.front().unwrap()]; + while let Some(&back) = dq.back() { + if dp[back] <= dp[i] { + dq.pop_back(); + } else { + break; + } + } + dq.push_back(i); + } + dp[n - 1] + } +} diff --git a/tests/1501-2000/1696. jump-game-vi/sol.swift b/tests/1501-2000/1696. jump-game-vi/sol.swift new file mode 100644 index 00000000..76f5658b --- /dev/null +++ b/tests/1501-2000/1696. jump-game-vi/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func maxResult(_ nums: [Int], _ k: Int) -> Int { + let n = nums.count + var dp = [Int](repeating: 0, count: n) + dp[0] = nums[0] + var dq = [0] + var head = 0 + for i in 1.. head && dp[dq[dq.count - 1]] <= dp[i] { + dq.removeLast() + } + dq.append(i) + } + return dp[n - 1] + } +} diff --git a/tests/1501-2000/1696. jump-game-vi/sol.ts b/tests/1501-2000/1696. jump-game-vi/sol.ts new file mode 100644 index 00000000..16629c09 --- /dev/null +++ b/tests/1501-2000/1696. jump-game-vi/sol.ts @@ -0,0 +1,18 @@ +function maxResult(nums: number[], k: number): number { + const n = nums.length; + const dp = new Array(n).fill(0); + dp[0] = nums[0]; + const dq: number[] = [0]; + let head = 0; + for (let i = 1; i < n; i++) { + if (dq[head] < i - k) { + head++; + } + dp[i] = nums[i] + dp[dq[head]]; + while (dq.length > head && dp[dq[dq.length - 1]] <= dp[i]) { + dq.pop(); + } + dq.push(i); + } + return dp[n - 1]; +} diff --git a/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/manifest.yaml b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/manifest.yaml new file mode 100644 index 00000000..0133e6fc --- /dev/null +++ b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/manifest.yaml @@ -0,0 +1,643 @@ +entry: + id: 1697 + title: "checking-existence-of-edge-length-limited-paths" + params: + n: + type: int + edgeList: + type: array + items: + type: array + items: + type: int + queries: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().distanceLimitedPathsExist({n}, {edgeList}, {queries})" + rust: "Solution::distance_limited_paths_exist({n}, {edgeList}, {queries})" + python3: "Solution().distanceLimitedPathsExist({n}, {edgeList}, {queries})" + python2: "Solution().distanceLimitedPathsExist({n}, {edgeList}, {queries})" + ruby: "distance_limited_paths_exist({n}, {edgeList}, {queries})" + java: "new Solution().distanceLimitedPathsExist({n}, {edgeList}, {queries})" + csharp: "new Solution().DistanceLimitedPathsExist({n}, {edgeList}, {queries})" + kotlin: "Solution().distanceLimitedPathsExist({n}, {edgeList}, {queries})" + go: "distanceLimitedPathsExist({n}, {edgeList}, {queries})" + dart: "Solution().distanceLimitedPathsExist({n}, {edgeList}, {queries})" + swift: "Solution().distanceLimitedPathsExist({n}, {edgeList}, {queries})" + typescript: "distanceLimitedPathsExist({n}, {edgeList}, {queries})" + +judge: + type: exact + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().check(n, edgeList, queries, {result})" + checker: | + class Checker: + def check(self, n, edgeList, queries, result): + if not isinstance(result, list) or len(result) != len(queries): + return False + parent = list(range(n)) + rank = [0] * n + def find(x): + while parent[x] != x: + parent[x] = parent[parent[x]] + x = parent[x] + return x + def union(a, b): + a, b = find(a), find(b) + if a == b: + return + if rank[a] < rank[b]: + a, b = b, a + parent[b] = a + if rank[a] == rank[b]: + rank[a] += 1 + def valid_edge(edge): + return (isinstance(edge, list) and len(edge) == 3 and + all(isinstance(x, int) and not isinstance(x, bool) for x in edge) and + 0 <= edge[0] < n and 0 <= edge[1] < n and edge[0] != edge[1] and + 1 <= edge[2] <= 10**9) + + def valid_query(query): + return (isinstance(query, list) and len(query) == 3 and + all(isinstance(x, int) and not isinstance(x, bool) for x in query) and + 0 <= query[0] < n and 0 <= query[1] < n and query[0] != query[1] and + 1 <= query[2] <= 10**9) + + if not all(valid_edge(edge) for edge in edgeList): + return False + if not all(valid_query(query) for query in queries): + return False + + ordered_edges = sorted(edgeList, key=lambda edge: edge[2]) + ordered_queries = sorted(enumerate(queries), key=lambda item: item[1][2]) + expected = [False] * len(queries) + edge_index = 0 + for query_index, (p, q, limit) in ordered_queries: + while (edge_index < len(ordered_edges) and + ordered_edges[edge_index][2] < limit): + u, v, _ = ordered_edges[edge_index] + union(u, v) + edge_index += 1 + expected[query_index] = find(p) == find(q) + return all(isinstance(actual, bool) and actual == wanted + for actual, wanted in zip(result, expected)) + +seed: 1697 + +tests: + - name: example-overlapping-edges + in: + n: 3 + edgeList: + - [0, 1, 2] + - [1, 2, 4] + - [2, 0, 8] + - [1, 0, 16] + queries: + - [0, 1, 2] + - [0, 2, 5] + - name: example-chain + in: + n: 5 + edgeList: + - [0, 1, 10] + - [1, 2, 5] + - [2, 3, 9] + - [3, 4, 13] + queries: + - [0, 4, 14] + - [1, 4, 13] + - name: two-nodes-threshold + in: + n: 3 + edgeList: + - [0, 1, 1] + - [1, 2, 2] + queries: + - [0, 1, 1] + - [0, 1, 2] + - [0, 2, 3] + - [0, 2, 2] + - name: disconnected-components + in: + n: 6 + edgeList: + - [0, 1, 3] + - [1, 2, 7] + - [3, 4, 2] + queries: + - [0, 2, 8] + - [0, 2, 7] + - [0, 3, 100] + - [3, 4, 2] + - [3, 4, 3] + - [4, 5, 100] + - name: parallel-edges + in: + n: 4 + edgeList: + - [0, 1, 100] + - [0, 1, 4] + - [1, 2, 8] + - [2, 3, 9] + - [0, 3, 50] + queries: + - [0, 1, 4] + - [0, 1, 5] + - [0, 3, 10] + - [0, 3, 9] + - name: all-equal-weights + in: + n: 5 + edgeList: + - [0, 1, 6] + - [1, 2, 6] + - [2, 3, 6] + - [3, 4, 6] + queries: + - [0, 4, 6] + - [0, 4, 7] + - [1, 3, 7] + - [0, 2, 5] + - name: cycles-and-shortcut + in: + n: 7 + edgeList: + - [0, 1, 9] + - [1, 2, 4] + - [2, 0, 8] + - [2, 3, 2] + - [3, 4, 12] + - [4, 5, 1] + - [5, 6, 20] + - [0, 6, 30] + queries: + - [0, 3, 3] + - [0, 3, 4] + - [0, 4, 13] + - [0, 5, 13] + - [0, 6, 21] + - [0, 6, 20] + - name: min-distance + in: + n: 4 + edgeList: + - [0, 1, 1] + - [1, 2, 1] + - [2, 3, 1] + queries: + - [0, 1, 1] + - [0, 1, 2] + - [0, 3, 2] + - [0, 3, 3] + - name: max-distance + in: + n: 5 + edgeList: + - [0, 1, 999999999] + - [1, 2, 999999999] + - [2, 3, 1000000000] + - [3, 4, 1] + queries: + - [0, 1, 999999999] + - [0, 1, 1000000000] + - [0, 4, 1000000000] + - [0, 4, 999999999] + - [2, 4, 2] + - name: many-queries + in: + n: 8 + edgeList: + - [0, 1, 2] + - [1, 2, 5] + - [2, 3, 8] + - [3, 4, 11] + - [4, 5, 14] + - [5, 6, 17] + - [6, 7, 20] + queries: + - [0, 7, 1] + - [0, 7, 2] + - [0, 7, 3] + - [0, 7, 8] + - [0, 7, 21] + - [1, 5, 12] + - [1, 5, 15] + - [2, 6, 18] + - [2, 6, 20] + - [3, 7, 21] + - name: isolated-endpoints + in: + n: 10 + edgeList: + - [1, 2, 3] + - [2, 3, 4] + - [4, 5, 5] + - [6, 7, 6] + - [7, 8, 7] + queries: + - [0, 1, 100] + - [1, 3, 5] + - [1, 3, 4] + - [4, 5, 5] + - [4, 5, 6] + - [6, 8, 8] + - [0, 9, 1000000000] + - name: dense-small-graph + in: + n: 6 + edgeList: + - [0, 1, 9] + - [0, 2, 2] + - [0, 3, 15] + - [1, 2, 7] + - [1, 4, 3] + - [2, 3, 6] + - [2, 5, 10] + - [3, 4, 4] + - [4, 5, 8] + - [0, 5, 20] + queries: + - [0, 5, 3] + - [0, 5, 4] + - [0, 3, 5] + - [1, 5, 9] + - [1, 5, 8] + - [3, 5, 9] + - name: repeated-query-pairs + in: + n: 5 + edgeList: + - [0, 1, 10] + - [1, 2, 1] + - [2, 3, 10] + - [3, 4, 1] + queries: + - [0, 2, 2] + - [0, 2, 11] + - [0, 2, 10] + - [2, 4, 2] + - [2, 4, 11] + - [0, 4, 11] + - name: alternating-thresholds + in: + n: 9 + edgeList: + - [0, 1, 3] + - [1, 2, 12] + - [2, 3, 5] + - [3, 4, 20] + - [4, 5, 7] + - [5, 6, 30] + - [6, 7, 9] + - [7, 8, 40] + queries: + - [0, 8, 4] + - [0, 8, 13] + - [0, 8, 21] + - [0, 8, 31] + - [0, 8, 41] + - [1, 7, 13] + - [2, 6, 10] + - name: mixed-large-limits + in: + n: 12 + edgeList: + - [0, 1, 999999999] + - [1, 2, 1000000000] + - [2, 3, 500000000] + - [3, 4, 1] + - [5, 6, 2] + - [6, 7, 1000000000] + - [8, 9, 42] + - [9, 10, 43] + - [10, 11, 44] + queries: + - [0, 4, 500000001] + - [0, 4, 500000000] + - [0, 2, 1000000000] + - [0, 2, 1000000000] + - [5, 7, 1000000000] + - [5, 7, 1000000000] + - [8, 11, 44] + - [8, 11, 45] + - name: singleton-components + in: + n: 7 + edgeList: + - [0, 1, 2] + - [2, 3, 4] + - [4, 5, 6] + queries: + - [0, 1, 3] + - [0, 2, 100] + - [2, 3, 4] + - [2, 3, 5] + - [4, 6, 7] + - name: direct-edge-versus-path + in: + n: 5 + edgeList: + - [0, 4, 20] + - [0, 1, 3] + - [1, 2, 3] + - [2, 3, 3] + - [3, 4, 3] + queries: + - [0, 4, 3] + - [0, 4, 4] + - [0, 4, 20] + - [0, 4, 21] + - name: duplicate-identical-edges + in: + n: 4 + edgeList: + - [0, 1, 5] + - [0, 1, 5] + - [1, 2, 5] + - [2, 3, 5] + queries: + - [0, 3, 5] + - [0, 3, 6] + - [1, 3, 6] + - [0, 2, 5] + - name: reverse-endpoints + in: + n: 6 + edgeList: + - [5, 4, 1] + - [4, 3, 2] + - [3, 2, 3] + - [2, 1, 4] + - [1, 0, 5] + queries: + - [5, 0, 6] + - [0, 5, 5] + - [4, 1, 5] + - [3, 0, 4] + - name: low-limit-isolation + in: + n: 8 + edgeList: + - [0, 1, 2] + - [1, 2, 3] + - [2, 3, 4] + - [3, 4, 5] + - [4, 5, 6] + - [5, 6, 7] + - [6, 7, 8] + queries: + - [0, 7, 1] + - [0, 7, 2] + - [0, 7, 3] + - [0, 7, 4] + - [0, 7, 5] + - [0, 7, 9] + - name: star-graph + in: + n: 8 + edgeList: + - [0, 1, 10] + - [0, 2, 20] + - [0, 3, 30] + - [0, 4, 40] + - [0, 5, 50] + - [0, 6, 60] + - [0, 7, 70] + queries: + - [1, 2, 21] + - [1, 2, 20] + - [3, 7, 31] + - [3, 7, 30] + - [5, 6, 61] + - name: cycle-only + in: + n: 6 + edgeList: + - [0, 1, 9] + - [1, 2, 8] + - [2, 3, 7] + - [3, 4, 6] + - [4, 5, 5] + - [5, 0, 4] + queries: + - [0, 3, 8] + - [0, 3, 7] + - [0, 3, 6] + - [1, 4, 7] + - [1, 4, 6] + - name: bridge-threshold + in: + n: 8 + edgeList: + - [0, 1, 1] + - [1, 2, 1] + - [2, 3, 1] + - [4, 5, 1] + - [5, 6, 1] + - [6, 7, 1] + - [3, 4, 100] + queries: + - [0, 3, 2] + - [4, 7, 2] + - [0, 7, 100] + - [0, 7, 101] + - [2, 5, 100] + - name: unsorted-input + in: + n: 6 + edgeList: + - [4, 5, 9] + - [0, 2, 2] + - [3, 4, 1] + - [1, 3, 8] + - [2, 5, 7] + queries: + - [0, 5, 8] + - [0, 5, 7] + - [1, 5, 9] + - [0, 4, 3] + - [1, 2, 9] + - name: all-pairs-small + in: + n: 4 + edgeList: + - [0, 1, 2] + - [1, 2, 4] + - [2, 3, 6] + - [0, 3, 10] + queries: + - [0, 1, 2] + - [0, 1, 3] + - [0, 2, 5] + - [0, 2, 4] + - [0, 3, 7] + - [0, 3, 10] + - [1, 3, 7] + - [1, 3, 6] + - name: equal-limit-batch + in: + n: 7 + edgeList: + - [0, 1, 10] + - [1, 2, 10] + - [2, 3, 9] + - [3, 4, 10] + - [4, 5, 9] + - [5, 6, 10] + queries: + - [0, 3, 10] + - [0, 3, 11] + - [3, 6, 10] + - [3, 6, 11] + - [0, 6, 10] + - [0, 6, 11] + - name: sparse-high-node-ids + in: + n: 20 + edgeList: + - [19, 0, 2] + - [18, 19, 4] + - [17, 18, 6] + - [10, 11, 1] + - [11, 12, 1] + queries: + - [0, 17, 7] + - [0, 17, 6] + - [10, 12, 2] + - [10, 12, 1] + - [0, 10, 100] + - name: one-edge-graph + in: + n: 9 + edgeList: + - [3, 8, 123456789] + queries: + - [3, 8, 123456789] + - [3, 8, 123456790] + - [0, 1, 1000000000] + - [3, 0, 1000000000] + - name: descending-weights + in: + n: 7 + edgeList: + - [0, 1, 70] + - [1, 2, 60] + - [2, 3, 50] + - [3, 4, 40] + - [4, 5, 30] + - [5, 6, 20] + queries: + - [0, 6, 71] + - [0, 6, 70] + - [1, 6, 61] + - [1, 6, 60] + - [2, 5, 31] + - [2, 5, 30] + - name: multiple-components-with-duplicates + in: + n: 10 + edgeList: + - [0, 1, 4] + - [0, 1, 9] + - [2, 3, 3] + - [3, 4, 8] + - [5, 6, 2] + - [6, 7, 7] + - [7, 8, 5] + queries: + - [0, 1, 5] + - [0, 1, 4] + - [2, 4, 9] + - [2, 4, 8] + - [5, 8, 6] + - [5, 8, 5] + - [0, 8, 100] + - name: query-order-sensitive + in: + n: 6 + edgeList: + - [0, 1, 5] + - [1, 2, 10] + - [2, 3, 15] + - [3, 4, 20] + - [4, 5, 25] + queries: + - [0, 5, 26] + - [0, 1, 5] + - [2, 5, 26] + - [0, 3, 16] + - [1, 4, 21] + - [3, 5, 25] + - name: shortcut-beats-heavy-chain + in: + n: 8 + edgeList: + - [0, 1, 100] + - [1, 2, 100] + - [2, 3, 100] + - [3, 4, 100] + - [4, 5, 100] + - [5, 6, 100] + - [6, 7, 100] + - [0, 7, 1] + queries: + - [0, 7, 1] + - [0, 7, 2] + - [0, 6, 100] + - [0, 6, 101] + - [1, 7, 2] + - name: tight-small-limits + in: + n: 5 + edgeList: + - [0, 1, 1] + - [1, 2, 2] + - [2, 3, 3] + - [3, 4, 4] + queries: + - [0, 4, 1] + - [0, 4, 2] + - [0, 4, 3] + - [0, 4, 4] + - [0, 4, 5] + - name: high-limit-disconnected + in: + n: 10 + edgeList: + - [0, 1, 1000000000] + - [2, 3, 999999999] + - [4, 5, 100] + - [6, 7, 200] + queries: + - [0, 1, 999999999] + - [0, 1, 1000000000] + - [2, 3, 1000000000] + - [4, 5, 101] + - [6, 7, 200] + - [0, 9, 999999999] + - name: nonconsecutive-node-components + in: + n: 11 + edgeList: + - [0, 10, 11] + - [10, 5, 12] + - [5, 2, 13] + - [1, 7, 1] + - [7, 9, 2] + queries: + - [0, 2, 14] + - [0, 2, 13] + - [1, 9, 2] + - [1, 9, 3] + - [0, 1, 1000000000] diff --git a/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.cpp b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.cpp new file mode 100644 index 00000000..b47df339 --- /dev/null +++ b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.cpp @@ -0,0 +1,55 @@ +class Solution { +public: + vector distanceLimitedPathsExist(int n, vector>& edgeList, vector>& queries) { + vector parent(n); + vector rank(n, 0); + for (int i = 0; i < n; i++) parent[i] = i; + + function find = [&](int x) { + if (parent[x] != x) { + parent[x] = find(parent[x]); + } + return parent[x]; + }; + + auto unionSets = [&](int x, int y) { + int xroot = find(x); + int yroot = find(y); + if (xroot == yroot) return; + if (rank[xroot] < rank[yroot]) { + parent[xroot] = yroot; + } else if (rank[xroot] > rank[yroot]) { + parent[yroot] = xroot; + } else { + parent[yroot] = xroot; + rank[xroot]++; + } + }; + + // add index to queries + vector> queriesWithIdx; + for (int i = 0; i < queries.size(); i++) { + queriesWithIdx.push_back({queries[i][0], queries[i][1], queries[i][2], i}); + } + + sort(queriesWithIdx.begin(), queriesWithIdx.end(), [](const vector& a, const vector& b) { + return a[2] < b[2]; + }); + sort(edgeList.begin(), edgeList.end(), [](const vector& a, const vector& b) { + return a[2] < b[2]; + }); + + int idx = 0; + vector res(queries.size(), false); + for (auto& q : queriesWithIdx) { + while (idx < edgeList.size() && edgeList[idx][2] < q[2]) { + unionSets(edgeList[idx][0], edgeList[idx][1]); + idx++; + } + if (find(q[0]) == find(q[1])) { + res[q[3]] = true; + } + } + return res; + } +}; diff --git a/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.cs b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.cs new file mode 100644 index 00000000..bcc681cf --- /dev/null +++ b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.cs @@ -0,0 +1,51 @@ +public class Solution { + public bool[] DistanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) { + int[] parent = new int[n]; + int[] rank = new int[n]; + for (int i = 0; i < n; i++) parent[i] = i; + + Func find = null; + find = (int x) => { + if (parent[x] != x) { + parent[x] = find(parent[x]); + } + return parent[x]; + }; + + Action union = (int x, int y) => { + int xroot = find(x); + int yroot = find(y); + if (xroot == yroot) return; + if (rank[xroot] < rank[yroot]) { + parent[xroot] = yroot; + } else if (rank[xroot] > rank[yroot]) { + parent[yroot] = xroot; + } else { + parent[yroot] = xroot; + rank[xroot]++; + } + }; + + // add index to queries + int[][] queriesWithIdx = new int[queries.Length][]; + for (int i = 0; i < queries.Length; i++) { + queriesWithIdx[i] = new int[] { queries[i][0], queries[i][1], queries[i][2], i }; + } + + Array.Sort(queriesWithIdx, (a, b) => a[2].CompareTo(b[2])); + Array.Sort(edgeList, (a, b) => a[2].CompareTo(b[2])); + + int idx = 0; + bool[] res = new bool[queries.Length]; + foreach (var q in queriesWithIdx) { + while (idx < edgeList.Length && edgeList[idx][2] < q[2]) { + union(edgeList[idx][0], edgeList[idx][1]); + idx++; + } + if (find(q[0]) == find(q[1])) { + res[q[3]] = true; + } + } + return res; + } +} diff --git a/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.dart b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.dart new file mode 100644 index 00000000..25989d09 --- /dev/null +++ b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.dart @@ -0,0 +1,49 @@ +class Solution { + List distanceLimitedPathsExist(int n, List> edgeList, List> queries) { + List parent = List.generate(n, (i) => i); + List rank = List.filled(n, 0); + + int find(int x) { + if (parent[x] != x) { + parent[x] = find(parent[x]); + } + return parent[x]; + } + + void union(int x, int y) { + int xroot = find(x); + int yroot = find(y); + if (xroot == yroot) return; + if (rank[xroot] < rank[yroot]) { + parent[xroot] = yroot; + } else if (rank[xroot] > rank[yroot]) { + parent[yroot] = xroot; + } else { + parent[yroot] = xroot; + rank[xroot]++; + } + } + + // add index to queries + List> queriesWithIdx = []; + for (int i = 0; i < queries.length; i++) { + queriesWithIdx.add([queries[i][0], queries[i][1], queries[i][2], i]); + } + + queriesWithIdx.sort((a, b) => a[2].compareTo(b[2])); + edgeList.sort((a, b) => a[2].compareTo(b[2])); + + int idx = 0; + List res = List.filled(queries.length, false); + for (var q in queriesWithIdx) { + while (idx < edgeList.length && edgeList[idx][2] < q[2]) { + union(edgeList[idx][0], edgeList[idx][1]); + idx++; + } + if (find(q[0]) == find(q[1])) { + res[q[3]] = true; + } + } + return res; + } +} diff --git a/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.go b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.go new file mode 100644 index 00000000..eb2dc34a --- /dev/null +++ b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.go @@ -0,0 +1,57 @@ +func distanceLimitedPathsExist(n int, edgeList [][]int, queries [][]int) []bool { + parent := make([]int, n) + rank := make([]int, n) + for i := 0; i < n; i++ { + parent[i] = i + } + + find := func(x int) int { + for parent[x] != x { + parent[x] = parent[parent[x]] + x = parent[x] + } + return x + } + + union := func(x, y int) { + xroot := find(x) + yroot := find(y) + if xroot == yroot { + return + } + if rank[xroot] < rank[yroot] { + parent[xroot] = yroot + } else if rank[xroot] > rank[yroot] { + parent[yroot] = xroot + } else { + parent[yroot] = xroot + rank[xroot]++ + } + } + + // add index to queries + queriesWithIdx := make([][]int, len(queries)) + for i, q := range queries { + queriesWithIdx[i] = []int{q[0], q[1], q[2], i} + } + + sort.Slice(queriesWithIdx, func(i, j int) bool { + return queriesWithIdx[i][2] < queriesWithIdx[j][2] + }) + sort.Slice(edgeList, func(i, j int) bool { + return edgeList[i][2] < edgeList[j][2] + }) + + idx := 0 + res := make([]bool, len(queries)) + for _, q := range queriesWithIdx { + for idx < len(edgeList) && edgeList[idx][2] < q[2] { + union(edgeList[idx][0], edgeList[idx][1]) + idx++ + } + if find(q[0]) == find(q[1]) { + res[q[3]] = true + } + } + return res +} diff --git a/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.java b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.java new file mode 100644 index 00000000..d50f6f6c --- /dev/null +++ b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.java @@ -0,0 +1,55 @@ +class Solution { + public boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) { + int[] parent = new int[n]; + int[] rank = new int[n]; + for (int i = 0; i < n; i++) parent[i] = i; + + java.util.function.IntUnaryOperator find = new java.util.function.IntUnaryOperator() { + public int applyAsInt(int x) { + if (parent[x] != x) { + parent[x] = applyAsInt(parent[x]); + } + return parent[x]; + } + }; + + java.util.function.BiConsumer union = (x, y) -> { + int xroot = find.applyAsInt(x); + int yroot = find.applyAsInt(y); + if (xroot == yroot) return; + if (rank[xroot] < rank[yroot]) { + parent[xroot] = yroot; + } else if (rank[xroot] > rank[yroot]) { + parent[yroot] = xroot; + } else { + parent[yroot] = xroot; + rank[xroot]++; + } + }; + + // add index to queries + int[][] queriesWithIdx = new int[queries.length][4]; + for (int i = 0; i < queries.length; i++) { + queriesWithIdx[i][0] = queries[i][0]; + queriesWithIdx[i][1] = queries[i][1]; + queriesWithIdx[i][2] = queries[i][2]; + queriesWithIdx[i][3] = i; + } + + java.util.Arrays.sort(queriesWithIdx, (a, b) -> Integer.compare(a[2], b[2])); + java.util.Arrays.sort(edgeList, (a, b) -> Integer.compare(a[2], b[2])); + + int i = 0; + boolean[] res = new boolean[queries.length]; + for (int[] q : queriesWithIdx) { + while (i < edgeList.length && edgeList[i][2] < q[2]) { + union.accept(edgeList[i][0], edgeList[i][1]); + i++; + } + if (find.applyAsInt(q[0]) == find.applyAsInt(q[1])) { + res[q[3]] = true; + } + } + return res; + } +} diff --git a/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.kt b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.kt new file mode 100644 index 00000000..67ea5616 --- /dev/null +++ b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.kt @@ -0,0 +1,53 @@ +class Solution { + fun distanceLimitedPathsExist(n: Int, edgeList: Array, queries: Array): BooleanArray { + val parent = IntArray(n) { it } + val rank = IntArray(n) + + fun find(start: Int): Int { + var x = start + while (parent[x] != x) { + parent[x] = parent[parent[x]] + x = parent[x] + } + return x + } + + fun union(x: Int, y: Int) { + val xroot = find(x) + val yroot = find(y) + if (xroot == yroot) return + if (rank[xroot] < rank[yroot]) { + parent[xroot] = yroot + } else if (rank[xroot] > rank[yroot]) { + parent[yroot] = xroot + } else { + parent[yroot] = xroot + rank[xroot]++ + } + } + + val queriesWithIdx = Array(queries.size) { IntArray(4) } + for (i in queries.indices) { + queriesWithIdx[i][0] = queries[i][0] + queriesWithIdx[i][1] = queries[i][1] + queriesWithIdx[i][2] = queries[i][2] + queriesWithIdx[i][3] = i + } + + queriesWithIdx.sortBy { it[2] } + edgeList.sortBy { it[2] } + + var i = 0 + val res = BooleanArray(queries.size) + for (q in queriesWithIdx) { + while (i < edgeList.size && edgeList[i][2] < q[2]) { + union(edgeList[i][0], edgeList[i][1]) + i++ + } + if (find(q[0]) == find(q[1])) { + res[q[3]] = true + } + } + return res + } +} diff --git a/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.py b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.py new file mode 100644 index 00000000..4a1fe140 --- /dev/null +++ b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.py @@ -0,0 +1,46 @@ +class DSU: + def __init__(self, n): + self.parent = list(range(n)) + self.rank = [0] * n + + def find(self, x): + if self.parent[x] == x: + return x + self.parent[x] = self.find(self.parent[x]) + return self.parent[x] + + def union(self, x, y): + xset, yset = self.find(x), self.find(y) + if xset != yset: + if self.rank[xset] < self.rank[yset]: + self.parent[xset] = yset + else: + self.parent[yset] = xset + if self.rank[xset] == self.rank[yset]: + self.rank[xset] += 1 + return True + return False + + +class Solution: + def distanceLimitedPathsExist( + self, n: int, edgeList: List[List[int]], queries: List[List[int]] + ) -> List[bool]: + dsu = DSU(n) + for i, q in enumerate(queries): + queries[i].append(i) + + queries.sort(key=lambda q: q[2]) + edgeList.sort(key=lambda e: e[2]) + + i = 0 + res = [False] * len(queries) + for q in queries: + while i < len(edgeList) and edgeList[i][2] < q[2]: + dsu.union(edgeList[i][0], edgeList[i][1]) + i += 1 + + if dsu.find(q[0]) == dsu.find(q[1]): + res[q[3]] = True + + return res diff --git a/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.py2 b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.py2 new file mode 100644 index 00000000..51405e1d --- /dev/null +++ b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.py2 @@ -0,0 +1,45 @@ +class Solution(object): + def distanceLimitedPathsExist(self, n, edgeList, queries): + """ + :type n: int + :type edgeList: List[List[int]] + :type queries: List[List[int]] + :rtype: List[bool] + """ + parent = list(range(n)) + rank = [0] * n + + def find(x): + if parent[x] != x: + parent[x] = find(parent[x]) + return parent[x] + + def union(x, y): + xroot = find(x) + yroot = find(y) + if xroot == yroot: + return + if rank[xroot] < rank[yroot]: + parent[xroot] = yroot + elif rank[xroot] > rank[yroot]: + parent[yroot] = xroot + else: + parent[yroot] = xroot + rank[xroot] += 1 + + # add index to queries + for i, q in enumerate(queries): + q.append(i) + + queries.sort(key=lambda x: x[2]) + edgeList.sort(key=lambda x: x[2]) + + i = 0 + res = [False] * len(queries) + for q in queries: + while i < len(edgeList) and edgeList[i][2] < q[2]: + union(edgeList[i][0], edgeList[i][1]) + i += 1 + if find(q[0]) == find(q[1]): + res[q[3]] = True + return res diff --git a/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.rb b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.rb new file mode 100644 index 00000000..944b9077 --- /dev/null +++ b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.rb @@ -0,0 +1,48 @@ +# @param {Integer} n +# @param {Integer[][]} edge_list +# @param {Integer[][]} queries +# @return {Boolean[]} +def distance_limited_paths_exist(n, edge_list, queries) + parent = (0...n).to_a + rank = Array.new(n, 0) + + find = ->(x) { + if parent[x] != x + parent[x] = find.call(parent[x]) + end + parent[x] + } + + union = ->(x, y) { + xroot = find.call(x) + yroot = find.call(y) + return if xroot == yroot + if rank[xroot] < rank[yroot] + parent[xroot] = yroot + elsif rank[xroot] > rank[yroot] + parent[yroot] = xroot + else + parent[yroot] = xroot + rank[xroot] += 1 + end + } + + queries.each_with_index do |q, idx| + q << idx + end + queries.sort_by! { |q| q[2] } + edge_list.sort_by! { |e| e[2] } + + i = 0 + res = Array.new(queries.length, false) + queries.each do |q| + while i < edge_list.length && edge_list[i][2] < q[2] + union.call(edge_list[i][0], edge_list[i][1]) + i += 1 + end + if find.call(q[0]) == find.call(q[1]) + res[q[3]] = true + end + end + res +end diff --git a/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.rs b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.rs new file mode 100644 index 00000000..b5d7d0f0 --- /dev/null +++ b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.rs @@ -0,0 +1,50 @@ +impl Solution { + pub fn distance_limited_paths_exist(n: i32, edge_list: Vec>, queries: Vec>) -> Vec { + let mut parent: Vec = (0..n as usize).collect(); + let mut rank: Vec = vec![0; n as usize]; + + fn find(parent: &mut Vec, x: usize) -> usize { + if parent[x] != x { + parent[x] = find(parent, parent[x]); + } + parent[x] + } + + fn union(parent: &mut Vec, rank: &mut Vec, x: usize, y: usize) { + let xroot = find(parent, x); + let yroot = find(parent, y); + if xroot == yroot { return; } + if rank[xroot] < rank[yroot] { + parent[xroot] = yroot; + } else if rank[xroot] > rank[yroot] { + parent[yroot] = xroot; + } else { + parent[yroot] = xroot; + rank[xroot] += 1; + } + } + + // add index to queries + let mut queries_with_idx: Vec> = Vec::new(); + for (i, q) in queries.iter().enumerate() { + queries_with_idx.push(vec![q[0], q[1], q[2], i as i32]); + } + + queries_with_idx.sort_by(|a, b| a[2].cmp(&b[2])); + let mut sorted_edges = edge_list.clone(); + sorted_edges.sort_by(|a, b| a[2].cmp(&b[2])); + + let mut idx = 0; + let mut res = vec![false; queries.len()]; + for q in queries_with_idx { + while idx < sorted_edges.len() && sorted_edges[idx][2] < q[2] { + union(&mut parent, &mut rank, sorted_edges[idx][0] as usize, sorted_edges[idx][1] as usize); + idx += 1; + } + if find(&mut parent, q[0] as usize) == find(&mut parent, q[1] as usize) { + res[q[3] as usize] = true; + } + } + res + } +} diff --git a/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.swift b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.swift new file mode 100644 index 00000000..47cb8217 --- /dev/null +++ b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.swift @@ -0,0 +1,49 @@ +class Solution { + func distanceLimitedPathsExist(_ n: Int, _ edgeList: [[Int]], _ queries: [[Int]]) -> [Bool] { + var parent = Array(0.. Int { + if parent[x] != x { + parent[x] = find(parent[x]) + } + return parent[x] + } + + func union(_ x: Int, _ y: Int) { + let xroot = find(x) + let yroot = find(y) + if xroot == yroot { return } + if rank[xroot] < rank[yroot] { + parent[xroot] = yroot + } else if rank[xroot] > rank[yroot] { + parent[yroot] = xroot + } else { + parent[yroot] = xroot + rank[xroot] += 1 + } + } + + // add index to queries + var queriesWithIdx = [[Int]]() + for (i, q) in queries.enumerated() { + queriesWithIdx.append([q[0], q[1], q[2], i]) + } + + queriesWithIdx.sort { $0[2] < $1[2] } + var sortedEdges = edgeList.sorted { $0[2] < $1[2] } + + var idx = 0 + var res = Array(repeating: false, count: queries.count) + for q in queriesWithIdx { + while idx < sortedEdges.count && sortedEdges[idx][2] < q[2] { + union(sortedEdges[idx][0], sortedEdges[idx][1]) + idx += 1 + } + if find(q[0]) == find(q[1]) { + res[q[3]] = true + } + } + return res + } +} diff --git a/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.ts b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.ts new file mode 100644 index 00000000..2e830f64 --- /dev/null +++ b/tests/1501-2000/1697. checking-existence-of-edge-length-limited-paths/sol.ts @@ -0,0 +1,53 @@ +function distanceLimitedPathsExist( + n: number, + edgeList: number[][], + queries: number[][], +): boolean[] { + const parent: number[] = Array.from({ length: n }, (_, i) => i); + const rank: number[] = new Array(n).fill(0); + + const find = (start: number): number => { + let x = start; + while (parent[x] !== x) { + parent[x] = parent[parent[x]]; + x = parent[x]; + } + return x; + }; + + const union = (x: number, y: number): void => { + const xroot = find(x); + const yroot = find(y); + if (xroot === yroot) return; + if (rank[xroot] < rank[yroot]) { + parent[xroot] = yroot; + } else if (rank[xroot] > rank[yroot]) { + parent[yroot] = xroot; + } else { + parent[yroot] = xroot; + rank[xroot]++; + } + }; + + // add index to queries + const queriesWithIdx: number[][] = []; + for (let i = 0; i < queries.length; i++) { + queriesWithIdx.push([queries[i][0], queries[i][1], queries[i][2], i]); + } + + queriesWithIdx.sort((a, b) => a[2] - b[2]); + edgeList.sort((a, b) => a[2] - b[2]); + + let idx = 0; + const res: boolean[] = new Array(queries.length).fill(false); + for (const q of queriesWithIdx) { + while (idx < edgeList.length && edgeList[idx][2] < q[2]) { + union(edgeList[idx][0], edgeList[idx][1]); + idx++; + } + if (find(q[0]) === find(q[1])) { + res[q[3]] = true; + } + } + return res; +} diff --git a/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/manifest.yaml b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/manifest.yaml new file mode 100644 index 00000000..752cd93a --- /dev/null +++ b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/manifest.yaml @@ -0,0 +1,379 @@ +entry: + id: 1700 + title: "number-of-students-unable-to-eat-lunch" + params: + students: + type: array + items: + type: int + sandwiches: + type: array + items: + type: int + call: + cpp: "Solution().countStudents({students}, {sandwiches})" + rust: "Solution::count_students({students}, {sandwiches})" + python3: "Solution().countStudents({students}, {sandwiches})" + python2: "Solution().countStudents({students}, {sandwiches})" + ruby: "count_students({students}, {sandwiches})" + java: "new Solution().countStudents({students}, {sandwiches})" + csharp: "new Solution().CountStudents({students}, {sandwiches})" + kotlin: "Solution().countStudents({students}, {sandwiches})" + go: "countStudents({students}, {sandwiches})" + dart: "Solution().countStudents({students}, {sandwiches})" + swift: "Solution().countStudents({students}, {sandwiches})" + typescript: "countStudents({students}, {sandwiches})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().countStudents(students, sandwiches, {result})" + checker: | + class Checker: + def countStudents(self, students, sandwiches, result): + counts = [0, 0] + for value in students: + counts[value] += 1 + unable = 0 + for value in sandwiches: + if counts[value] == 0: + unable = sum(counts) + break + counts[value] -= 1 + return result == unable + +seed: 1700 + +tests: + - name: example-all-eat + in: + students: [1, 1, 0, 0] + sandwiches: [0, 1, 0, 1] + out: 0 + judge: + type: "exact" + - name: example-three-unable + in: + students: [1, 1, 1, 0, 0, 1] + sandwiches: [1, 0, 0, 0, 1, 1] + out: 3 + judge: + type: "exact" + - name: one-matching-zero + in: + students: [0] + sandwiches: [0] + out: 0 + judge: + type: "exact" + - name: one-matching-one + in: + students: [1] + sandwiches: [1] + out: 0 + judge: + type: "exact" + - name: one-mismatch-zero + in: + students: [0] + sandwiches: [1] + out: 1 + judge: + type: "exact" + - name: one-mismatch-one + in: + students: [1] + sandwiches: [0] + out: 1 + judge: + type: "exact" + - name: all-zero + in: + students: [0, 0, 0, 0, 0] + sandwiches: [0, 0, 0, 0, 0] + out: 0 + judge: + type: "exact" + - name: all-one + in: + students: [1, 1, 1, 1, 1] + sandwiches: [1, 1, 1, 1, 1] + out: 0 + judge: + type: "exact" + - name: all-prefer-zero + in: + students: [0, 0, 0, 0, 0, 0] + sandwiches: [1, 1, 1, 1, 1, 1] + out: 6 + judge: + type: "exact" + - name: all-prefer-one + in: + students: [1, 1, 1, 1, 1, 1] + sandwiches: [0, 0, 0, 0, 0, 0] + out: 6 + judge: + type: "exact" + - name: queue-rotation-needed + in: + students: [1, 0, 1, 0] + sandwiches: [0, 0, 1, 1] + out: 0 + judge: + type: "exact" + - name: early-zero-exhaustion + in: + students: [1, 1, 0, 1] + sandwiches: [0, 1, 1, 1] + out: 0 + judge: + type: "exact" + - name: zero-students-shortage + in: + students: [0, 1, 1, 0] + sandwiches: [1, 1, 1, 0] + out: 2 + judge: + type: "exact" + - name: alternating-four + in: + students: [0, 1, 0, 1] + sandwiches: [1, 0, 1, 0] + out: 0 + judge: + type: "exact" + - name: grouped-students + in: + students: [0, 0, 1, 1, 1] + sandwiches: [1, 0, 1, 0, 1] + out: 0 + judge: + type: "exact" + - name: grouped-sandwiches + in: + students: [0, 1, 0, 1, 0] + sandwiches: [0, 0, 0, 1, 1] + out: 0 + judge: + type: "exact" + - name: shortage-after-one + in: + students: [0, 0, 1, 1, 1] + sandwiches: [0, 1, 1, 1, 1] + out: 1 + judge: + type: "exact" + - name: shortage-after-two + in: + students: [0, 0, 0, 1, 1, 1] + sandwiches: [0, 0, 1, 1, 1, 1] + out: 1 + judge: + type: "exact" + - name: late-matching + in: + students: [1, 1, 0, 0, 1, 0] + sandwiches: [0, 1, 0, 1, 1, 0] + out: 0 + judge: + type: "exact" + - name: zero-majority + in: + students: [0, 0, 0, 1, 0, 1, 0] + sandwiches: [1, 0, 0, 0, 0, 1, 0] + out: 0 + judge: + type: "exact" + - name: one-majority + in: + students: [1, 1, 0, 1, 1, 0, 1] + sandwiches: [0, 1, 1, 1, 0, 1, 1] + out: 0 + judge: + type: "exact" + - name: impossible-first-type + in: + students: [0, 0, 1, 0, 1] + sandwiches: [1, 1, 0, 0, 0] + out: 0 + judge: + type: "exact" + - name: impossible-last-type + in: + students: [0, 1, 1, 0, 1] + sandwiches: [0, 0, 1, 1, 1] + out: 0 + judge: + type: "exact" + - name: six-rotation + in: + students: [1, 0, 1, 1, 0, 0] + sandwiches: [0, 1, 0, 1, 0, 1] + out: 0 + judge: + type: "exact" + - name: eight-balanced + in: + students: [1, 1, 0, 0, 1, 0, 1, 0] + sandwiches: [0, 1, 1, 0, 0, 1, 0, 1] + out: 0 + judge: + type: "exact" + - name: eight-shortage + in: + students: [0, 0, 0, 1, 1, 0, 1, 1] + sandwiches: [1, 1, 1, 0, 0, 0, 1, 0] + out: 0 + judge: + type: "exact" + - name: nine-balanced + in: + students: [0, 1, 0, 1, 1, 0, 1, 0, 1] + sandwiches: [1, 0, 1, 0, 1, 1, 0, 1, 0] + out: 0 + judge: + type: "exact" + - name: ten-zero-shortage + in: + students: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] + sandwiches: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0] + out: 0 + judge: + type: "exact" + - name: ten-one-shortage + in: + students: [1, 1, 1, 1, 1, 0, 0, 0, 0, 0] + sandwiches: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1] + out: 0 + judge: + type: "exact" + - name: twelve-blocked + in: + students: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1] + sandwiches: [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0] + out: 0 + judge: + type: "exact" + - name: twelve-shortage + in: + students: [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1] + sandwiches: [1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0] + out: 0 + judge: + type: "exact" + - name: twenty-balanced + in: + students: [0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1] + sandwiches: [1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1] + out: 0 + judge: + type: "exact" + - name: twenty-zero-shortage + in: + students: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + sandwiches: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + out: 0 + judge: + type: "exact" + - name: generated-small + in: + students: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 1 + elemType: "int" + sandwiches: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 1 + elemType: "int" + seed: 17001 + - name: generated-medium + in: + students: + gen: "array" + len: 25 + of: + gen: "int" + min: 0 + max: 1 + elemType: "int" + sandwiches: + gen: "array" + len: 25 + of: + gen: "int" + min: 0 + max: 1 + elemType: "int" + seed: 17002 + - name: generated-large-balanced + in: + students: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 1 + elemType: "int" + sandwiches: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 1 + elemType: "int" + seed: 17003 + - name: generated-large-zero-heavy + in: + students: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 1 + elemType: "int" + sandwiches: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 1 + elemType: "int" + seed: 17004 + - name: generated-large-one-heavy + in: + students: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 1 + elemType: "int" + sandwiches: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 1 + elemType: "int" + seed: 17005 diff --git a/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.cpp b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.cpp new file mode 100644 index 00000000..41aa3311 --- /dev/null +++ b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int countStudents(vector& students, vector& sandwiches) { + int count[2] = {0, 0}; + for (int preference : students) ++count[preference]; + for (int sandwich : sandwiches) { + if (count[sandwich] == 0) break; + --count[sandwich]; + } + return count[0] + count[1]; + } +}; diff --git a/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.cs b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.cs new file mode 100644 index 00000000..8ae0b1e1 --- /dev/null +++ b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.cs @@ -0,0 +1,21 @@ +public class Solution { + public int CountStudents(int[] students, int[] sandwiches) { + var s = new System.Collections.Generic.List(students); + var sw = new System.Collections.Generic.List(sandwiches); + int c = 0; + while (s.Count > 0) { + if (s[0] == sw[0]) { + sw.RemoveAt(0); + s.RemoveAt(0); + c = 0; + } else { + int front = s[0]; + s.RemoveAt(0); + s.Add(front); + c++; + } + if (c == s.Count) break; + } + return s.Count; + } +} diff --git a/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.dart b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.dart new file mode 100644 index 00000000..ae34b882 --- /dev/null +++ b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.dart @@ -0,0 +1,19 @@ +class Solution { + int countStudents(List students, List sandwiches) { + List s = List.from(students); + List sw = List.from(sandwiches); + int c = 0; + while (s.isNotEmpty) { + if (s[0] == sw[0]) { + sw.removeAt(0); + s.removeAt(0); + c = 0; + } else { + s.add(s.removeAt(0)); + c++; + } + if (c == s.length) break; + } + return s.length; + } +} diff --git a/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.go b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.go new file mode 100644 index 00000000..04951ab4 --- /dev/null +++ b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.go @@ -0,0 +1,21 @@ +func countStudents(students []int, sandwiches []int) int { + s := make([]int, len(students)) + copy(s, students) + sw := make([]int, len(sandwiches)) + copy(sw, sandwiches) + c := 0 + for len(s) > 0 { + if s[0] == sw[0] { + sw = sw[1:] + s = s[1:] + c = 0 + } else { + s = append(s[1:], s[0]) + c++ + } + if c == len(s) { + break + } + } + return len(s) +} diff --git a/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.java b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.java new file mode 100644 index 00000000..15c56d71 --- /dev/null +++ b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.java @@ -0,0 +1,21 @@ +class Solution { + public int countStudents(int[] students, int[] sandwiches) { + java.util.List s = new java.util.ArrayList<>(); + java.util.List sw = new java.util.ArrayList<>(); + for (int x : students) s.add(x); + for (int x : sandwiches) sw.add(x); + int c = 0; + while (!s.isEmpty()) { + if (s.get(0).equals(sw.get(0))) { + sw.remove(0); + s.remove(0); + c = 0; + } else { + s.add(s.remove(0)); + c++; + } + if (c == s.size()) break; + } + return s.size(); + } +} diff --git a/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.kt b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.kt new file mode 100644 index 00000000..27f48f70 --- /dev/null +++ b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.kt @@ -0,0 +1,19 @@ +class Solution { + fun countStudents(students: IntArray, sandwiches: IntArray): Int { + val s = students.toMutableList() + val sw = sandwiches.toMutableList() + var c = 0 + while (s.isNotEmpty()) { + if (s[0] == sw[0]) { + sw.removeAt(0) + s.removeAt(0) + c = 0 + } else { + s.add(s.removeAt(0)) + c++ + } + if (c == s.size) break + } + return s.size + } +} diff --git a/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.py b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.py new file mode 100644 index 00000000..bf8c9aba --- /dev/null +++ b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.py @@ -0,0 +1,14 @@ +class Solution(object): + def countStudents(self, students, sandwiches): + c = 0 + while students: + if students[0] == sandwiches[0]: + sandwiches.pop(0) + students.pop(0) + c = 0 + else: + students.append(students.pop(0)) + c += 1 + if c == len(students): + break + return len(students) diff --git a/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.py2 b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.py2 new file mode 100644 index 00000000..173ef0f5 --- /dev/null +++ b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.py2 @@ -0,0 +1,19 @@ +class Solution(object): + def countStudents(self, students, sandwiches): + """ + :type students: List[int] + :type sandwiches: List[int] + :rtype: int + """ + c = 0 + while students: + if students[0] == sandwiches[0]: + sandwiches.pop(0) + students.pop(0) + c = 0 + else: + students.append(students.pop(0)) + c += 1 + if c == len(students): + break + return len(students) diff --git a/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.rb b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.rb new file mode 100644 index 00000000..25904e74 --- /dev/null +++ b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.rb @@ -0,0 +1,18 @@ +# @param {Integer[]} students +# @param {Integer[]} sandwiches +# @return {Integer} +def count_students(students, sandwiches) + c = 0 + while !students.empty? + if students[0] == sandwiches[0] + sandwiches.shift + students.shift + c = 0 + else + students << students.shift + c += 1 + end + break if c == students.length + end + students.length +end diff --git a/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.rs b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.rs new file mode 100644 index 00000000..5bf34151 --- /dev/null +++ b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn count_students(students: Vec, sandwiches: Vec) -> i32 { + let mut s = students.clone(); + let mut sw = sandwiches.clone(); + let mut c = 0; + while !s.is_empty() { + if s[0] == sw[0] { + sw.remove(0); + s.remove(0); + c = 0; + } else { + let front = s.remove(0); + s.push(front); + c += 1; + } + if c == s.len() { break; } + } + s.len() as i32 + } +} diff --git a/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.swift b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.swift new file mode 100644 index 00000000..83fd28c2 --- /dev/null +++ b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.swift @@ -0,0 +1,19 @@ +class Solution { + func countStudents(_ students: [Int], _ sandwiches: [Int]) -> Int { + var s = students + var sw = sandwiches + var c = 0 + while !s.isEmpty { + if s[0] == sw[0] { + sw.removeFirst() + s.removeFirst() + c = 0 + } else { + s.append(s.removeFirst()) + c += 1 + } + if c == s.count { break } + } + return s.count + } +} diff --git a/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.ts b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.ts new file mode 100644 index 00000000..2108746f --- /dev/null +++ b/tests/1501-2000/1700. number-of-students-unable-to-eat-lunch/sol.ts @@ -0,0 +1,17 @@ +function countStudents(students: number[], sandwiches: number[]): number { + const s: number[] = [...students]; + const sw: number[] = [...sandwiches]; + let c = 0; + while (s.length > 0) { + if (s[0] === sw[0]) { + sw.shift(); + s.shift(); + c = 0; + } else { + s.push(s.shift()!); + c++; + } + if (c === s.length) break; + } + return s.length; +} diff --git a/tests/1501-2000/1701. average-waiting-time/manifest.yaml b/tests/1501-2000/1701. average-waiting-time/manifest.yaml new file mode 100644 index 00000000..ee0b0d40 --- /dev/null +++ b/tests/1501-2000/1701. average-waiting-time/manifest.yaml @@ -0,0 +1,315 @@ +entry: + id: 1701 + title: "average-waiting-time" + params: + customers: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().averageWaitingTime({customers})" + rust: "Solution::average_waiting_time({customers})" + python3: "Solution().averageWaitingTime({customers})" + python2: "Solution().averageWaitingTime({customers})" + ruby: "average_waiting_time({customers})" + java: "new Solution().averageWaitingTime({customers})" + csharp: "new Solution().AverageWaitingTime({customers})" + kotlin: "Solution().averageWaitingTime({customers})" + go: "averageWaitingTime({customers})" + dart: "Solution().averageWaitingTime({customers})" + swift: "Solution().averageWaitingTime({customers})" + typescript: "averageWaitingTime({customers})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().averageWaitingTime(customers, {result})" + checker: | + import math + + class Checker: + def averageWaitingTime(self, customers, result): + if not isinstance(customers, list) or not customers: + return False + previous = 0 + total = 0 + last_arrival = 0 + for customer in customers: + if not isinstance(customer, list) or len(customer) != 2: + return False + arrival, duration = customer + if not isinstance(arrival, int) or not isinstance(duration, int): + return False + if arrival < 1 or arrival > 10000 or duration < 1 or duration > 10000: + return False + if arrival < last_arrival: + return False + last_arrival = arrival + previous = max(previous, arrival) + duration + total += previous - arrival + expected = total / float(len(customers)) + return isinstance(result, (int, float)) and math.isfinite(result) and abs(result - expected) <= 1e-5 + +seed: 1701 + +tests: + - name: example-one + in: + customers: + - [1, 2] + - [2, 5] + - [4, 3] + - name: example-two + in: + customers: + - [5, 2] + - [5, 4] + - [10, 3] + - [20, 1] + - name: single-customer + in: + customers: + - [1, 7] + - name: single-at-maximum + in: + customers: + - [10000, 10000] + - name: all-arrive-together + in: + customers: + - [1, 1] + - [1, 2] + - [1, 3] + - [1, 4] + - name: idle-between-orders + in: + customers: + - [1, 2] + - [10, 1] + - [20, 5] + - name: exact-boundary-arrivals + in: + customers: + - [1, 3] + - [4, 2] + - [6, 1] + - name: long-first-order + in: + customers: + - [2, 10000] + - [3, 1] + - [4, 1] + - name: long-last-order + in: + customers: + - [1, 1] + - [2, 1] + - [3, 10000] + - name: repeated-arrivals + in: + customers: + - [7, 4] + - [7, 1] + - [7, 8] + - [7, 2] + - name: alternating-idle-and-busy + in: + customers: + - [1, 5] + - [2, 1] + - [20, 3] + - [21, 10] + - [50, 2] + - name: fractional-average-1 + in: + customers: + - [1, 1] + - [1, 2] + - [1, 4] + - name: fractional-average-2 + in: + customers: + - [1, 2] + - [3, 2] + - [3, 2] + - [10, 1] + - name: late-duplicate-arrivals + in: + customers: + - [1, 2] + - [100, 3] + - [100, 4] + - [100, 5] + - name: increasing-durations + in: + customers: + - [1, 1] + - [2, 2] + - [3, 3] + - [4, 4] + - [5, 5] + - name: decreasing-durations + in: + customers: + - [1, 5] + - [2, 4] + - [3, 3] + - [4, 2] + - [5, 1] + - name: same-arrival-long-queue + in: + customers: + - [10, 100] + - [10, 200] + - [10, 300] + - [10, 400] + - [10, 500] + - name: near-maximum-arrivals + in: + customers: + - [9990, 1] + - [9991, 10000] + - [9992, 1] + - [10000, 2] + - name: service-finishes-before-each-arrival + in: + customers: + - [1, 2] + - [4, 2] + - [7, 2] + - [10, 2] + - [13, 2] + - name: service-just-overlaps + in: + customers: + - [1, 3] + - [3, 3] + - [5, 3] + - [7, 3] + - name: two-phases + in: + customers: + - [1, 8] + - [2, 1] + - [3, 1] + - [20, 8] + - [21, 1] + - name: varied-small + in: + customers: + - [1, 9] + - [1, 1] + - [2, 5] + - [8, 2] + - [8, 7] + - [30, 3] + - name: many-equal-duration + in: + customers: + - [2, 17] + - [3, 17] + - [4, 17] + - [5, 17] + - [6, 17] + - [7, 17] + - name: large-duration-mix + in: + customers: + - [1, 10000] + - [1, 9999] + - [5000, 10000] + - [10000, 1] + - name: sparse-singletons + in: + customers: + - [1, 100] + - [1000, 100] + - [2000, 100] + - [3000, 100] + - [4000, 100] + - name: six-customer-chain + in: + customers: + - [1, 10] + - [2, 1] + - [3, 10] + - [20, 1] + - [21, 10] + - [22, 1] + - name: duplicate-boundary-groups + in: + customers: + - [1, 2] + - [1, 2] + - [5, 2] + - [5, 2] + - [9, 2] + - [9, 2] + - name: large-idle-gap + in: + customers: + - [1, 100] + - [10000, 10000] + - name: maximum-same-arrival + in: + customers: + - [10000, 10000] + - [10000, 9999] + - [10000, 1] + - name: balanced-workload + in: + customers: + - [1, 6] + - [3, 4] + - [8, 7] + - [10, 2] + - [20, 9] + - [21, 1] + - [40, 5] + - name: long-tail-queue + in: + customers: + - [1, 10000] + - [1, 1] + - [1, 1] + - [5000, 10000] + - [10000, 10000] + - name: clustered-arrivals + in: + customers: + - [3, 8] + - [3, 2] + - [3, 6] + - [4, 1] + - [4, 9] + - [20, 2] + - name: staircase-arrivals + in: + customers: + - [1, 10] + - [2, 9] + - [4, 8] + - [7, 7] + - [11, 6] + - [16, 5] + - [22, 4] + - name: max-values-busy + in: + customers: + - [1, 10000] + - [2, 10000] + - [3, 10000] + - [4, 10000] + - name: max-values-spread + in: + customers: + - [1, 10000] + - [10000, 10000] diff --git a/tests/1501-2000/1701. average-waiting-time/sol.cpp b/tests/1501-2000/1701. average-waiting-time/sol.cpp new file mode 100644 index 00000000..41d1d62e --- /dev/null +++ b/tests/1501-2000/1701. average-waiting-time/sol.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + double averageWaitingTime(vector>& customers) { + long long waiting = 0; + int current = 0; + for (auto& customer : customers) { + int arrival = customer[0]; + int time = customer[1]; + if (current <= arrival) { + current = arrival + time; + waiting += time; + } else { + current += time; + waiting += (current - arrival); + } + } + return (double) waiting / customers.size(); + } +}; diff --git a/tests/1501-2000/1701. average-waiting-time/sol.cs b/tests/1501-2000/1701. average-waiting-time/sol.cs new file mode 100644 index 00000000..c815cdaf --- /dev/null +++ b/tests/1501-2000/1701. average-waiting-time/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public double AverageWaitingTime(int[][] customers) { + long waiting = 0; + int current = 0; + foreach (var customer in customers) { + int arrival = customer[0]; + int time = customer[1]; + if (current <= arrival) { + current = arrival + time; + waiting += time; + } else { + current += time; + waiting += (current - arrival); + } + } + return (double) waiting / customers.Length; + } +} diff --git a/tests/1501-2000/1701. average-waiting-time/sol.dart b/tests/1501-2000/1701. average-waiting-time/sol.dart new file mode 100644 index 00000000..057d6537 --- /dev/null +++ b/tests/1501-2000/1701. average-waiting-time/sol.dart @@ -0,0 +1,18 @@ +class Solution { + double averageWaitingTime(List> customers) { + int waiting = 0; + int current = 0; + for (final customer in customers) { + int arrival = customer[0]; + int time = customer[1]; + if (current <= arrival) { + current = arrival + time; + waiting += time; + } else { + current += time; + waiting += (current - arrival); + } + } + return waiting / customers.length; + } +} diff --git a/tests/1501-2000/1701. average-waiting-time/sol.go b/tests/1501-2000/1701. average-waiting-time/sol.go new file mode 100644 index 00000000..7fc95876 --- /dev/null +++ b/tests/1501-2000/1701. average-waiting-time/sol.go @@ -0,0 +1,15 @@ +func averageWaitingTime(customers [][]int) float64 { + waiting := 0 + current := 0 + for _, c := range customers { + arrival, time := c[0], c[1] + if current <= arrival { + current = arrival + time + waiting += time + } else { + current += time + waiting += (current - arrival) + } + } + return float64(waiting) / float64(len(customers)) +} diff --git a/tests/1501-2000/1701. average-waiting-time/sol.java b/tests/1501-2000/1701. average-waiting-time/sol.java new file mode 100644 index 00000000..2ea69bc3 --- /dev/null +++ b/tests/1501-2000/1701. average-waiting-time/sol.java @@ -0,0 +1,18 @@ +class Solution { + public double averageWaitingTime(int[][] customers) { + long waiting = 0; + int current = 0; + for (int[] customer : customers) { + int arrival = customer[0]; + int time = customer[1]; + if (current <= arrival) { + current = arrival + time; + waiting += time; + } else { + current += time; + waiting += (current - arrival); + } + } + return (double) waiting / customers.length; + } +} diff --git a/tests/1501-2000/1701. average-waiting-time/sol.kt b/tests/1501-2000/1701. average-waiting-time/sol.kt new file mode 100644 index 00000000..5d6028a2 --- /dev/null +++ b/tests/1501-2000/1701. average-waiting-time/sol.kt @@ -0,0 +1,18 @@ +class Solution { + fun averageWaitingTime(customers: Array): Double { + var waiting = 0L + var current = 0 + for (customer in customers) { + val arrival = customer[0] + val time = customer[1] + if (current <= arrival) { + current = arrival + time + waiting += time + } else { + current += time + waiting += (current - arrival) + } + } + return waiting.toDouble() / customers.size + } +} diff --git a/tests/1501-2000/1701. average-waiting-time/sol.py b/tests/1501-2000/1701. average-waiting-time/sol.py new file mode 100644 index 00000000..a5f961e3 --- /dev/null +++ b/tests/1501-2000/1701. average-waiting-time/sol.py @@ -0,0 +1,11 @@ +class Solution: + def averageWaitingTime(self, customers: List[List[int]]) -> float: + waiting, current = 0, 0 + for arrival, time in customers: + if current <= arrival: + current = arrival + time + waiting += time + else: + current += time + waiting += current - arrival + return waiting / len(customers) diff --git a/tests/1501-2000/1701. average-waiting-time/sol.py2 b/tests/1501-2000/1701. average-waiting-time/sol.py2 new file mode 100644 index 00000000..e7144a1a --- /dev/null +++ b/tests/1501-2000/1701. average-waiting-time/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def averageWaitingTime(self, customers): + """ + :type customers: List[List[int]] + :rtype: float + """ + waiting = 0 + current = 0 + for arrival, time in customers: + if current <= arrival: + current = arrival + time + waiting += time + else: + current += time + waiting += (current - arrival) + return float(waiting) / len(customers) diff --git a/tests/1501-2000/1701. average-waiting-time/sol.rb b/tests/1501-2000/1701. average-waiting-time/sol.rb new file mode 100644 index 00000000..c660b5eb --- /dev/null +++ b/tests/1501-2000/1701. average-waiting-time/sol.rb @@ -0,0 +1,14 @@ +def average_waiting_time(customers) + waiting = 0 + current = 0 + customers.each do |arrival, time| + if current <= arrival + current = arrival + time + waiting += time + else + current += time + waiting += (current - arrival) + end + end + waiting.to_f / customers.length +end diff --git a/tests/1501-2000/1701. average-waiting-time/sol.rs b/tests/1501-2000/1701. average-waiting-time/sol.rs new file mode 100644 index 00000000..ef7802c1 --- /dev/null +++ b/tests/1501-2000/1701. average-waiting-time/sol.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn average_waiting_time(customers: Vec>) -> f64 { + let mut waiting = 0i64; + let mut current = 0i32; + let count = customers.len(); + for customer in customers { + let arrival = customer[0]; + let time = customer[1]; + if current <= arrival { + current = arrival + time; + waiting += time as i64; + } else { + current += time; + waiting += (current - arrival) as i64; + } + } + waiting as f64 / count as f64 + } +} diff --git a/tests/1501-2000/1701. average-waiting-time/sol.swift b/tests/1501-2000/1701. average-waiting-time/sol.swift new file mode 100644 index 00000000..28ea9462 --- /dev/null +++ b/tests/1501-2000/1701. average-waiting-time/sol.swift @@ -0,0 +1,18 @@ +class Solution { + func averageWaitingTime(_ customers: [[Int]]) -> Double { + var waiting = 0 + var current = 0 + for customer in customers { + let arrival = customer[0] + let time = customer[1] + if current <= arrival { + current = arrival + time + waiting += time + } else { + current += time + waiting += (current - arrival) + } + } + return Double(waiting) / Double(customers.count) + } +} diff --git a/tests/1501-2000/1701. average-waiting-time/sol.ts b/tests/1501-2000/1701. average-waiting-time/sol.ts new file mode 100644 index 00000000..39b42ec9 --- /dev/null +++ b/tests/1501-2000/1701. average-waiting-time/sol.ts @@ -0,0 +1,14 @@ +function averageWaitingTime(customers: number[][]): number { + let waiting = 0; + let current = 0; + for (const [arrival, time] of customers) { + if (current <= arrival) { + current = arrival + time; + waiting += time; + } else { + current += time; + waiting += current - arrival; + } + } + return waiting / customers.length; +} diff --git a/tests/1501-2000/1702. maximum-binary-string-after-change/manifest.yaml b/tests/1501-2000/1702. maximum-binary-string-after-change/manifest.yaml new file mode 100644 index 00000000..74afb04b --- /dev/null +++ b/tests/1501-2000/1702. maximum-binary-string-after-change/manifest.yaml @@ -0,0 +1,171 @@ +entry: + id: 1702 + title: "maximum-binary-string-after-change" + params: + binary: + type: string + call: + cpp: "Solution().maximumBinaryString({binary})" + rust: "Solution::maximum_binary_string({binary})" + python3: "Solution().maximumBinaryString({binary})" + python2: "Solution().maximumBinaryString({binary})" + ruby: "maximum_binary_string({binary})" + java: "new Solution().maximumBinaryString({binary})" + csharp: "new Solution().MaximumBinaryString({binary})" + kotlin: "Solution().maximumBinaryString({binary})" + go: "maximumBinaryString({binary})" + dart: "Solution().maximumBinaryString({binary})" + swift: "Solution().maximumBinaryString({binary})" + typescript: "maximumBinaryString({binary})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maximumBinaryString(binary, {result})" + checker: | + class Checker: + def maximumBinaryString(self, binary, result): + if not isinstance(binary, str) or not isinstance(result, str): + return False + if any(c not in '01' for c in binary) or len(result) != len(binary): + return False + zeros = binary.count('0') + if zeros < 2: + expected = binary + else: + p = binary.find('0') + zeros - 1 + expected = '1' * p + '0' + '1' * (len(binary) - p - 1) + return result == expected + +seed: 1702 + +tests: + - name: example-000110 + in: + binary: "000110" + - name: example-01 + in: + binary: "01" + - name: single-zero + in: + binary: "0" + - name: single-one + in: + binary: "1" + - name: all-zeros-two + in: + binary: "00" + - name: all-zeros-three + in: + binary: "000" + - name: all-zeros-eight + in: + binary: "00000000" + - name: all-ones + in: + binary: "11111111" + - name: zero-at-end + in: + binary: "1110" + - name: zero-at-start + in: + binary: "0111" + - name: two-zeros-at-end + in: + binary: "1100" + - name: two-zeros-at-start + in: + binary: "0011" + - name: separated-zeros + in: + binary: "01010" + - name: alternating-six + in: + binary: "010101" + - name: alternating-seven + in: + binary: "1010101" + - name: leading-ones + in: + binary: "1110001" + - name: trailing-ones + in: + binary: "1000111" + - name: internal-zero-block + in: + binary: "11000111" + - name: one-zero-middle + in: + binary: "1110111" + - name: two-zero-middle + in: + binary: "11100111" + - name: zeros-with-one + in: + binary: "0001000" + - name: sparse-one + in: + binary: "100000" + - name: sparse-zero + in: + binary: "011111" + - name: long-leading-zeroes + in: + binary: "0000011111" + - name: long-trailing-zeroes + in: + binary: "1111100000" + - name: zero-block-after-one + in: + binary: "10000" + - name: mixed-nine + in: + binary: "101001001" + - name: mixed-ten + in: + binary: "0010101101" + - name: two-zero-total + in: + binary: "1011110111" + - name: zeros-after-prefix + in: + binary: "111100001" + - name: long-balanced + in: + binary: "0011001100110011" + - name: generated-short + in: + binary: + gen: "str" + len: 17 + alphabet: "01" + - name: generated-medium + in: + binary: + gen: "str" + len: 100 + alphabet: "01" + - name: generated-large + in: + binary: + gen: "str" + len: 10000 + alphabet: "01" + - name: generated-near-limit + in: + binary: + gen: "str" + len: 100000 + alphabet: "01" + - name: generated-zero-heavy + in: + binary: + gen: "str" + len: 50000 + alphabet: "0001" diff --git a/tests/1501-2000/1702. maximum-binary-string-after-change/sol.cpp b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.cpp new file mode 100644 index 00000000..29aec60e --- /dev/null +++ b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + string maximumBinaryString(string binary) { + int n = binary.size(); + int z = 0; + for (char c : binary) { + if (c == '0') z++; + } + + if (z < 2) return binary; + + int firstZero = binary.find('0'); + int p = firstZero + z - 1; + + return string(p, '1') + "0" + string(n - p - 1, '1'); + } +}; diff --git a/tests/1501-2000/1702. maximum-binary-string-after-change/sol.cs b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.cs new file mode 100644 index 00000000..34d0b8cd --- /dev/null +++ b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public string MaximumBinaryString(string binary) { + int n = binary.Length; + int z = binary.Count(c => c == '0'); + + if (z < 2) return binary; + + int firstZero = binary.IndexOf('0'); + int p = firstZero + z - 1; + + return new string('1', p) + "0" + new string('1', n - p - 1); + } +} diff --git a/tests/1501-2000/1702. maximum-binary-string-after-change/sol.dart b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.dart new file mode 100644 index 00000000..f0b423d4 --- /dev/null +++ b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.dart @@ -0,0 +1,13 @@ +class Solution { + String maximumBinaryString(String binary) { + int n = binary.length; + int z = binary.split('').where((c) => c == '0').length; + + if (z < 2) return binary; + + int firstZero = binary.indexOf('0'); + int p = firstZero + z - 1; + + return '1' * p + '0' + '1' * (n - p - 1); + } +} diff --git a/tests/1501-2000/1702. maximum-binary-string-after-change/sol.go b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.go new file mode 100644 index 00000000..4db318a4 --- /dev/null +++ b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.go @@ -0,0 +1,13 @@ +func maximumBinaryString(binary string) string { + n := len(binary) + z := strings.Count(binary, "0") + + if z < 2 { + return binary + } + + firstZero := strings.Index(binary, "0") + p := firstZero + z - 1 + + return strings.Repeat("1", p) + "0" + strings.Repeat("1", n - p - 1) +} diff --git a/tests/1501-2000/1702. maximum-binary-string-after-change/sol.java b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.java new file mode 100644 index 00000000..2bbed278 --- /dev/null +++ b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.java @@ -0,0 +1,16 @@ +class Solution { + public String maximumBinaryString(String binary) { + int n = binary.length(); + int z = 0; + for (char c : binary.toCharArray()) { + if (c == '0') z++; + } + + if (z < 2) return binary; + + int firstZero = binary.indexOf('0'); + int p = firstZero + z - 1; + + return "1".repeat(p) + "0" + "1".repeat(n - p - 1); + } +} diff --git a/tests/1501-2000/1702. maximum-binary-string-after-change/sol.kt b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.kt new file mode 100644 index 00000000..06966fc4 --- /dev/null +++ b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun maximumBinaryString(binary: String): String { + val n = binary.length + val z = binary.count { it == '0' } + + if (z < 2) return binary + + val firstZero = binary.indexOf('0') + val p = firstZero + z - 1 + + return "1".repeat(p) + "0" + "1".repeat(n - p - 1) + } +} diff --git a/tests/1501-2000/1702. maximum-binary-string-after-change/sol.py b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.py new file mode 100644 index 00000000..a38d71a9 --- /dev/null +++ b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.py @@ -0,0 +1,16 @@ +class Solution(object): + def maximumBinaryString(self, binary): + """ + :type binary: str + :rtype: str + """ + n = len(binary) + z = binary.count("0") + + if z < 2: + return binary + + first_zero = binary.find("0") + p = first_zero + z - 1 + + return "1" * p + "0" + "1" * (n - p - 1) diff --git a/tests/1501-2000/1702. maximum-binary-string-after-change/sol.py2 b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.py2 new file mode 100644 index 00000000..67fe8742 --- /dev/null +++ b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def maximumBinaryString(self, binary): + """ + :type binary: str + :rtype: str + """ + n = len(binary) + z = binary.count('0') + + if z < 2: + return binary + + first_zero = binary.find('0') + p = first_zero + z - 1 + + return '1' * p + '0' + '1' * (n - p - 1) diff --git a/tests/1501-2000/1702. maximum-binary-string-after-change/sol.rb b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.rb new file mode 100644 index 00000000..3197280f --- /dev/null +++ b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.rb @@ -0,0 +1,13 @@ +# @param {String} binary +# @return {String} +def maximum_binary_string(binary) + n = binary.length + z = binary.count('0') + + return binary if z < 2 + + first_zero = binary.index('0') + p = first_zero + z - 1 + + '1' * p + '0' + '1' * (n - p - 1) +end diff --git a/tests/1501-2000/1702. maximum-binary-string-after-change/sol.rs b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.rs new file mode 100644 index 00000000..0ed40040 --- /dev/null +++ b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn maximum_binary_string(binary: String) -> String { + let n = binary.len(); + let z = binary.chars().filter(|&c| c == '0').count(); + + if z < 2 { + return binary; + } + + let first_zero = binary.find('0').unwrap(); + let p = first_zero + z - 1; + + "1".repeat(p) + "0" + &"1".repeat(n - p - 1) + } +} diff --git a/tests/1501-2000/1702. maximum-binary-string-after-change/sol.swift b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.swift new file mode 100644 index 00000000..7fdab5ef --- /dev/null +++ b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func maximumBinaryString(_ binary: String) -> String { + let n = binary.count + let z = binary.filter { $0 == "0" }.count + + if z < 2 { + return binary + } + + let firstZero = binary.firstIndex(of: "0")! + let firstZeroPos = binary.distance(from: binary.startIndex, to: firstZero) + let p = firstZeroPos + z - 1 + + return String(repeating: "1", count: p) + "0" + String(repeating: "1", count: n - p - 1) + } +} diff --git a/tests/1501-2000/1702. maximum-binary-string-after-change/sol.ts b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.ts new file mode 100644 index 00000000..01b31a39 --- /dev/null +++ b/tests/1501-2000/1702. maximum-binary-string-after-change/sol.ts @@ -0,0 +1,11 @@ +function maximumBinaryString(binary: string): string { + const n = binary.length; + const z = binary.split("").filter((c) => c === "0").length; + + if (z < 2) return binary; + + const firstZero = binary.indexOf("0"); + const p = firstZero + z - 1; + + return "1".repeat(p) + "0" + "1".repeat(n - p - 1); +} diff --git a/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/manifest.yaml b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/manifest.yaml new file mode 100644 index 00000000..b6a64a20 --- /dev/null +++ b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/manifest.yaml @@ -0,0 +1,421 @@ +entry: + id: 1703 + title: "minimum-adjacent-swaps-for-k-consecutive-ones" + params: + nums: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().minMoves({nums}, {k})" + rust: "Solution::min_moves({nums}, {k})" + python3: "Solution().minMoves({nums}, {k})" + python2: "Solution().minMoves({nums}, {k})" + ruby: "min_moves({nums}, {k})" + java: "new Solution().minMoves({nums}, {k})" + csharp: "new Solution().MinMoves({nums}, {k})" + kotlin: "Solution().minMoves({nums}, {k})" + go: "minMoves({nums}, {k})" + dart: "Solution().minMoves({nums}, {k})" + swift: "Solution().minMoves({nums}, {k})" + typescript: "minMoves({nums}, {k})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().minMoves(nums, k, {result})" + checker: | + class Checker: + def minMoves(self, nums, k, result): + pos = [i for i, x in enumerate(nums) if x == 1] + if not 1 <= k <= len(pos): + return False + best = None + for left in range(len(pos) - k + 1): + block = pos[left:left + k] + mid = k // 2 + center = block[mid] + cost = sum(abs(block[j] - center - j + mid) for j in range(k)) + best = cost if best is None else min(best, cost) + return isinstance(result, int) and not isinstance(result, bool) and result == best +seed: 1703 +tests: + - name: example-one + in: + nums: [1, 0, 0, 1, 0, 1] + k: 2 + out: 1 + - name: example-two + in: + nums: [1, 0, 0, 0, 0, 0, 1, 1] + k: 3 + out: 5 + - name: example-three + in: + nums: [1, 1, 0, 1] + k: 2 + out: 0 + - name: single-one + in: + nums: [0, 0, 1, 0] + k: 1 + out: 0 + - name: all-ones + in: + nums: [1, 1, 1, 1, 1] + k: 4 + out: 0 + - name: separated-pair + in: + nums: [1, 0, 1] + k: 2 + out: 1 + - name: separated-triple + in: + nums: [1, 0, 0, 1, 0, 0, 1] + k: 3 + out: 4 + - name: even-k + in: + nums: [1, 0, 0, 1, 0, 0, 1, 0, 1] + k: 4 + out: 7 + - name: odd-k + in: + nums: [1, 0, 1, 0, 1, 0, 1, 0, 1] + k: 5 + out: 6 + - name: dense-middle + in: + nums: [0, 0, 1, 1, 0, 1, 1, 1, 0, 0] + k: 5 + out: 2 + - name: best-right + in: + nums: [1, 0, 0, 0, 0, 1, 0, 1, 1] + k: 3 + out: 1 + - name: best-left + in: + nums: [1, 1, 0, 1, 0, 0, 0, 0, 1] + k: 3 + out: 1 + - name: alternating-six + in: + nums: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] + k: 6 + out: 9 + - name: long-gap + in: + nums: [1, 0, 0, 0, 0, 0, 0, 1] + k: 2 + out: 6 + - name: three-clusters + in: + nums: [1, 1, 0, 0, 1, 0, 0, 0, 1, 1] + k: 4 + out: 7 + - name: sparse-five + in: + nums: [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1] + k: 5 + out: 18 + - name: adjacent-two + in: + nums: [1, 0, 0, 1, 1, 0, 0, 0, 1] + k: 2 + out: 0 + - name: middle-optimum + in: + nums: [0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0] + k: 4 + out: 9 + - name: prefix-zeros + in: + nums: [0, 0, 0, 0, 0, 1, 0, 1, 0, 1] + k: 3 + out: 2 + - name: suffix-zeros + in: + nums: [1, 0, 1, 0, 1, 0, 0, 0, 0, 0] + k: 3 + out: 2 + - name: uneven-gaps + in: + nums: [1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1] + k: 4 + out: 8 + - name: many-candidates + in: + nums: [1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1] + k: 4 + out: 2 + - name: regular-25 + in: + nums: + [ + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + ] + k: 25 + out: 156 + - name: dense-40 + in: + nums: + [ + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + ] + k: 40 + out: 149 + - name: all-ones-large + in: + nums: + [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + ] + k: 37 + out: 0 + - name: extremes + in: + nums: [1, 0, 0, 0, 0, 0, 0, 0, 0, 1] + k: 2 + out: 8 + - name: all-but-one + in: + nums: [1, 1, 1, 1, 0, 1, 1, 1, 1] + k: 8 + out: 4 + - name: four-gaps + in: + nums: [1, 0, 1, 0, 0, 1, 0, 0, 0, 1] + k: 4 + out: 8 + - name: final-boundary + in: + nums: [0, 0, 1, 0, 0, 1, 0, 0, 1, 1] + k: 4 + out: 6 + - name: one-at-start + in: + nums: [1, 0, 0, 0, 0, 0, 0, 0] + k: 1 + out: 0 + - name: one-at-end + in: + nums: [0, 0, 0, 0, 0, 0, 0, 1] + k: 1 + out: 0 + - name: five-adjacent + in: + nums: [0, 1, 1, 1, 1, 1, 0, 0] + k: 5 + out: 0 + - name: two-windows + in: + nums: [1, 0, 1, 1, 0, 1, 0, 1, 1] + k: 3 + out: 1 + - name: late-cluster + in: + nums: [0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0] + k: 3 + out: 0 + - name: early-cluster + in: + nums: [1, 1, 1, 0, 1, 0, 0, 0, 0, 0] + k: 3 + out: 0 diff --git a/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.cpp b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.cpp new file mode 100644 index 00000000..6dd9e144 --- /dev/null +++ b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int minMoves(vector& nums, int k) { + vector idx; + for (int i = 0; i < nums.size(); i++) { + if (nums[i] == 1) idx.push_back(i); + } + int n = idx.size(); + vector a(n); + for (int i = 0; i < n; i++) { + a[i] = idx[i] - i; + } + vector prefix(n); + if (n > 0) { + prefix[0] = a[0]; + for (int i = 1; i < n; i++) { + prefix[i] = prefix[i-1] + a[i]; + } + } + long long ans = LLONG_MAX; + int l = 0; + for (int r = 0; r < n; r++) { + while (r - l + 1 > k) l++; + if (r - l + 1 == k) { + int mid = (l + r) / 2; + long long med = a[mid]; + long long leftSum = prefix[mid] - (l > 0 ? prefix[l-1] : 0); + long long rightSum = prefix[r] - prefix[mid]; + long long cost = (med * (mid - l + 1) - leftSum) + (rightSum - med * (r - mid)); + ans = min(ans, cost); + } + } + return (int)ans; + } +}; diff --git a/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.cs b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.cs new file mode 100644 index 00000000..bc22299a --- /dev/null +++ b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.cs @@ -0,0 +1,34 @@ +public class Solution { + public int MinMoves(int[] nums, int k) { + List idx = new List(); + for (int i = 0; i < nums.Length; i++) { + if (nums[i] == 1) idx.Add(i); + } + int n = idx.Count; + long[] a = new long[n]; + for (int i = 0; i < n; i++) { + a[i] = idx[i] - i; + } + long[] prefix = new long[n]; + if (n > 0) { + prefix[0] = a[0]; + for (int i = 1; i < n; i++) { + prefix[i] = prefix[i-1] + a[i]; + } + } + long ans = long.MaxValue; + int l = 0; + for (int r = 0; r < n; r++) { + while (r - l + 1 > k) l++; + if (r - l + 1 == k) { + int mid = (l + r) / 2; + long med = a[mid]; + long leftSum = prefix[mid] - (l > 0 ? prefix[l-1] : 0); + long rightSum = prefix[r] - prefix[mid]; + long cost = (med * (mid - l + 1) - leftSum) + (rightSum - med * (r - mid)); + ans = Math.Min(ans, cost); + } + } + return (int)ans; + } +} diff --git a/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.dart b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.dart new file mode 100644 index 00000000..ca948bcb --- /dev/null +++ b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.dart @@ -0,0 +1,38 @@ +class Solution { + int minMoves(List nums, int k) { + List idx = []; + for (int i = 0; i < nums.length; i++) { + if (nums[i] == 1) idx.add(i); + } + int n = idx.length; + List a = List.filled(n, 0); + for (int i = 0; i < n; i++) { + a[i] = idx[i] - i; + } + List prefix = List.filled(n, 0); + if (n > 0) { + prefix[0] = a[0]; + for (int i = 1; i < n; i++) { + prefix[i] = prefix[i-1] + a[i]; + } + } + int ans = 1 << 60; + int l = 0; + for (int r = 0; r < n; r++) { + while (r - l + 1 > k) { + l++; + } + if (r - l + 1 == k) { + int mid = (l + r) ~/ 2; + int med = a[mid]; + int leftSum = prefix[mid] - (l > 0 ? prefix[l-1] : 0); + int rightSum = prefix[r] - prefix[mid]; + int cost = (med * (mid - l + 1) - leftSum) + (rightSum - med * (r - mid)); + if (cost < ans) { + ans = cost; + } + } + } + return ans; + } +} diff --git a/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.go b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.go new file mode 100644 index 00000000..fc1f4438 --- /dev/null +++ b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.go @@ -0,0 +1,41 @@ +func minMoves(nums []int, k int) int { + idx := []int{} + for i, v := range nums { + if v == 1 { + idx = append(idx, i) + } + } + n := len(idx) + a := make([]int64, n) + for i, v := range idx { + a[i] = int64(v - i) + } + prefix := make([]int64, n) + if n > 0 { + prefix[0] = a[0] + for i := 1; i < n; i++ { + prefix[i] = prefix[i-1] + a[i] + } + } + ans := int64(1<<63 - 1) + l := 0 + for r := 0; r < n; r++ { + for r-l+1 > k { + l++ + } + if r-l+1 == k { + mid := (l + r) / 2 + med := a[mid] + leftSum := prefix[mid] + if l > 0 { + leftSum -= prefix[l-1] + } + rightSum := prefix[r] - prefix[mid] + cost := (med*int64(mid-l+1) - leftSum) + (rightSum - med*int64(r-mid)) + if cost < ans { + ans = cost + } + } + } + return int(ans) +} diff --git a/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.java b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.java new file mode 100644 index 00000000..233a9457 --- /dev/null +++ b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.java @@ -0,0 +1,34 @@ +class Solution { + public int minMoves(int[] nums, int k) { + List idx = new ArrayList<>(); + for (int i = 0; i < nums.length; i++) { + if (nums[i] == 1) idx.add(i); + } + int n = idx.size(); + long[] a = new long[n]; + for (int i = 0; i < n; i++) { + a[i] = idx.get(i) - i; + } + long[] prefix = new long[n]; + if (n > 0) { + prefix[0] = a[0]; + for (int i = 1; i < n; i++) { + prefix[i] = prefix[i-1] + a[i]; + } + } + long ans = Long.MAX_VALUE; + int l = 0; + for (int r = 0; r < n; r++) { + while (r - l + 1 > k) l++; + if (r - l + 1 == k) { + int mid = (l + r) / 2; + long med = a[mid]; + long leftSum = prefix[mid] - (l > 0 ? prefix[l-1] : 0); + long rightSum = prefix[r] - prefix[mid]; + long cost = (med * (mid - l + 1) - leftSum) + (rightSum - med * (r - mid)); + ans = Math.min(ans, cost); + } + } + return (int)ans; + } +} diff --git a/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.kt b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.kt new file mode 100644 index 00000000..0e5bfba3 --- /dev/null +++ b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.kt @@ -0,0 +1,34 @@ +class Solution { + fun minMoves(nums: IntArray, k: Int): Int { + val idx = mutableListOf() + for (i in nums.indices) { + if (nums[i] == 1) idx.add(i) + } + val n = idx.size + val a = LongArray(n) + for (i in 0 until n) { + a[i] = (idx[i] - i).toLong() + } + val prefix = LongArray(n) + if (n > 0) { + prefix[0] = a[0] + for (i in 1 until n) { + prefix[i] = prefix[i-1] + a[i] + } + } + var ans = Long.MAX_VALUE + var l = 0 + for (r in 0 until n) { + while (r - l + 1 > k) l++ + if (r - l + 1 == k) { + val mid = (l + r) / 2 + val med = a[mid] + val leftSum = prefix[mid] - if (l > 0) prefix[l-1] else 0L + val rightSum = prefix[r] - prefix[mid] + val cost = (med * (mid - l + 1) - leftSum) + (rightSum - med * (r - mid)) + ans = minOf(ans, cost) + } + } + return ans.toInt() + } +} diff --git a/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.py b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.py new file mode 100644 index 00000000..e051a1a6 --- /dev/null +++ b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.py @@ -0,0 +1,72 @@ +class Solution: + def minMoves(self, nums, k: int) -> int: + # we need k consecutive one + # find the minimum number of swaps + # to bring element at i to j + # we need j-i swaps + # what is the best pos for all to meet + # it is the middle spot (median) + # for all k size find median + idx = [] + for i, val in enumerate(nums): + if val == 1: + idx.append(i) + A = [] + for i, val in enumerate(idx): + A.append(val - i) + n = len(idx) + l = 0 + prefix = [0] * (n) + # prefix[0]=idx[0] + # for i in range(1,n): + # prefix[i]=prefix[i-1]+idx[i] + prefix[0] = A[0] + for i in range(1, n): + prefix[i] = prefix[i - 1] + A[i] + + def cost(l, r): + mid = (l + r) >> 1 + # as point can between them + if (r - l + 1) % 2 == 0: + med = A[(l + r) >> 1] + else: + med = A[(l + r) >> 1] + # this is trying to bring all to the med + # so everything will be at median + # but this is not we want the thing is we can k consecutive + # and the k consecitve should have its med at med + # so arrange accordingly + # the (r-l+1)>>1 move to med + # the (r-l+1)>>1-1 move to med-1 + # the (r-l+2)>>1-2 move to med-2 + # ...so one the (r-l+1)>>1-(r-l+1)>>1 element move to med-mid + # so element are moved from med-mid to med+mid + # this will be ok for odd elements then how for even elements ? + # for even elements -> 1 2 3 4 -> 1 0 1 2 med-(mid-1) to med+mid so this ok?? + # can we gurantee that the med+mid and med-mid is always in the bounds yes the med is at the mid + # val=(med*(mid-l+1)-(prefix[mid]-(prefix[l-1] if l>0 else 0)))+(prefix[r]-prefix[mid]-(med)*(r-mid)) this is wrong + # what is the new fromula then ? + # for one the extra (i-(mid)) will be added ig + # the cost for left most element to move from l to (med-mid) is med-mid-l + # the cost for left+1 element to move from l+1 to (med-mid+1) is med-mid+1-l-1 is med-mid-l + # the cost for the new elements is suprisingly the same formula ? med-mid-i + # the cost for right element from med+mid is r-(med+mid) + # lets see it for the left side elements cost + # we should move from idx[i] to idx[mid]+(i-mid) for i<=mid + # so it will be idx[mid]+(i-mid)-idx[i] + # simplyfy (idx[mid]-mid)-(idx[i]-i) + # now for the right elements we should move to idx[mid]+(i-mid) + # simplyfy similatly it is (idx[i]-i)-(idx[mid]-mid) + # lets define A as idx[i]-i then the mid for this is idx[mid]-mid + # for the A we can write med*(count)-pref[] + return ( + med * (mid - l + 1) - (prefix[mid] - (prefix[l - 1] if l > 0 else 0)) + ) + (prefix[r] - prefix[mid] - (med) * (r - mid)) + + ans = float("inf") + for r in range(n): + while r - l + 1 > k: + l += 1 + if r - l + 1 == k: + ans = min(ans, cost(l, r)) + return ans diff --git a/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.py2 b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.py2 new file mode 100644 index 00000000..c301db44 --- /dev/null +++ b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.py2 @@ -0,0 +1,34 @@ +class Solution(object): + def minMoves(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + idx = [] + for i, val in enumerate(nums): + if val == 1: + idx.append(i) + A = [] + for i, val in enumerate(idx): + A.append(val - i) + n = len(idx) + prefix = [0] * n + if n > 0: + prefix[0] = A[0] + for i in range(1, n): + prefix[i] = prefix[i-1] + A[i] + def cost(l, r): + mid = (l + r) // 2 + med = A[mid] + left_sum = prefix[mid] - (prefix[l-1] if l > 0 else 0) + right_sum = prefix[r] - prefix[mid] + return (med * (mid - l + 1) - left_sum) + (right_sum - med * (r - mid)) + ans = float('inf') + l = 0 + for r in range(n): + while r - l + 1 > k: + l += 1 + if r - l + 1 == k: + ans = min(ans, cost(l, r)) + return ans diff --git a/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.rb b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.rb new file mode 100644 index 00000000..b033632d --- /dev/null +++ b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.rb @@ -0,0 +1,39 @@ +# @param {Integer[]} nums +# @param {Integer} k +# @return {Integer} +def min_moves(nums, k) + idx = [] + nums.each_with_index do |val, i| + idx << i if val == 1 + end + a = [] + idx.each_with_index do |val, i| + a << val - i + end + n = idx.length + prefix = [0] * n + if n > 0 + prefix[0] = a[0] + (1...n).each do |i| + prefix[i] = prefix[i-1] + a[i] + end + end + cost = lambda do |l, r| + mid = (l + r) / 2 + med = a[mid] + left_sum = prefix[mid] - (l > 0 ? prefix[l-1] : 0) + right_sum = prefix[r] - prefix[mid] + (med * (mid - l + 1) - left_sum) + (right_sum - med * (r - mid)) + end + ans = Float::INFINITY + l = 0 + (0...n).each do |r| + while r - l + 1 > k + l += 1 + end + if r - l + 1 == k + ans = [ans, cost.call(l, r)].min + end + end + ans.to_i +end diff --git a/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.rs b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.rs new file mode 100644 index 00000000..4070487d --- /dev/null +++ b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.rs @@ -0,0 +1,32 @@ +impl Solution { + pub fn min_moves(nums: Vec, k: i32) -> i32 { + let idx: Vec = nums.iter().enumerate().filter(|&(_, &v)| v == 1).map(|(i, _)| i).collect(); + let n = idx.len(); + let a: Vec = (0..n).map(|i| (idx[i] as i64 - i as i64)).collect(); + let mut prefix = vec![0i64; n]; + if n > 0 { + prefix[0] = a[0]; + for i in 1..n { + prefix[i] = prefix[i-1] + a[i]; + } + } + let mut ans = i64::MAX; + let mut l = 0; + for r in 0..n { + while (r - l + 1) as i32 > k { + l += 1; + } + if (r - l + 1) as i32 == k { + let mid = (l + r) / 2; + let med = a[mid]; + let left_sum = prefix[mid] - if l > 0 { prefix[l-1] } else { 0 }; + let right_sum = prefix[r] - prefix[mid]; + let cost = (med * ((mid - l + 1) as i64) - left_sum) + (right_sum - med * ((r - mid) as i64)); + if cost < ans { + ans = cost; + } + } + } + ans as i32 + } +} diff --git a/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.swift b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.swift new file mode 100644 index 00000000..99d9ec68 --- /dev/null +++ b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.swift @@ -0,0 +1,38 @@ +class Solution { + func minMoves(_ nums: [Int], _ k: Int) -> Int { + var idx: [Int] = [] + for (i, val) in nums.enumerated() { + if val == 1 { + idx.append(i) + } + } + let n = idx.count + var a = [Int](repeating: 0, count: n) + for i in 0.. 0 { + prefix[0] = a[0] + for i in 1.. k { + l += 1 + } + if r - l + 1 == k { + let mid = (l + r) / 2 + let med = a[mid] + let leftSum = prefix[mid] - (l > 0 ? prefix[l-1] : 0) + let rightSum = prefix[r] - prefix[mid] + let cost = (med * (mid - l + 1) - leftSum) + (rightSum - med * (r - mid)) + ans = min(ans, cost) + } + } + return ans + } +} diff --git a/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.ts b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.ts new file mode 100644 index 00000000..8123f25d --- /dev/null +++ b/tests/1501-2000/1703. minimum-adjacent-swaps-for-k-consecutive-ones/sol.ts @@ -0,0 +1,32 @@ +function minMoves(nums: number[], k: number): number { + const idx: number[] = []; + for (let i = 0; i < nums.length; i++) { + if (nums[i] === 1) idx.push(i); + } + const n = idx.length; + const a: number[] = []; + for (let i = 0; i < n; i++) { + a.push(idx[i] - i); + } + const prefix: number[] = new Array(n).fill(0); + if (n > 0) { + prefix[0] = a[0]; + for (let i = 1; i < n; i++) { + prefix[i] = prefix[i - 1] + a[i]; + } + } + let ans = Number.MAX_SAFE_INTEGER; + let l = 0; + for (let r = 0; r < n; r++) { + while (r - l + 1 > k) l++; + if (r - l + 1 === k) { + const mid = Math.floor((l + r) / 2); + const med = a[mid]; + const leftSum = prefix[mid] - (l > 0 ? prefix[l - 1] : 0); + const rightSum = prefix[r] - prefix[mid]; + const cost = med * (mid - l + 1) - leftSum + (rightSum - med * (r - mid)); + ans = Math.min(ans, cost); + } + } + return ans; +} diff --git a/tests/1501-2000/1704. determine-if-string-halves-are-alike/manifest.yaml b/tests/1501-2000/1704. determine-if-string-halves-are-alike/manifest.yaml new file mode 100644 index 00000000..d5eed874 --- /dev/null +++ b/tests/1501-2000/1704. determine-if-string-halves-are-alike/manifest.yaml @@ -0,0 +1,199 @@ +entry: + id: 1704 + title: determine-if-string-halves-are-alike + params: + s: + type: string + call: + cpp: "Solution().halvesAreAlike({s})" + rust: "Solution::halves_are_alike({s})" + python3: "Solution().halvesAreAlike({s})" + python2: "Solution().halvesAreAlike({s})" + ruby: "halves_are_alike({s})" + java: "new Solution().halvesAreAlike({s})" + csharp: "new Solution().HalvesAreAlike({s})" + kotlin: "Solution().halvesAreAlike({s})" + go: "halvesAreAlike({s})" + dart: "Solution().halvesAreAlike({s})" + swift: "Solution().halvesAreAlike({s})" + typescript: "halvesAreAlike({s})" + +judge: + type: exact + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().halvesAreAlike(s, {result})" + checker: | + class Checker: + def halvesAreAlike(self, s, result): + vowels = set("aeiouAEIOU") + mid = len(s) // 2 + expected = sum(c in vowels for c in s[:mid]) == sum(c in vowels for c in s[mid:]) + return isinstance(result, bool) and result == expected + +seed: 1704 + +tests: + - name: example-book + in: + s: book + out: true + - name: example-textbook + in: + s: textbook + out: false + - name: minimum-consonants + in: + s: bbcc + out: true + - name: minimum-one-vowel-side + in: + s: abcd + out: false + - name: same-uppercase-vowels + in: + s: AEIO + out: true + - name: opposite-uppercase-vowels + in: + s: Axyz + out: false + - name: mixed-case-match + in: + s: aBcdEf + out: true + - name: repeated-vowel-match + in: + s: aeiouAEIOU + out: true + - name: repeated-vowel-mismatch + in: + s: aeioubcdef + out: false + - name: vowels-front + in: + s: AEIOUbcdef + out: false + - name: vowels-back + in: + s: bcdefAEIOU + out: false + - name: one-each-half + in: + s: xayz + out: false + - name: case-sensitive-looking-match + in: + s: aXxA + out: true + - name: all-a + in: + s: aaaaaaaaaa + out: true + - name: all-consonants + in: + s: bbbbbbbbbb + out: true + - name: alternating-balanced + in: + s: ababababab + out: false + - name: alternating-unbalanced + in: + s: aaaaaaaaab + out: false + - name: vowel-boundary-middle + in: + s: bcdEfghi + out: true + - name: uppercase-consonants + in: + s: BCDFghjk + out: true + - name: every-vowel-twice + in: + s: aAeEiIoOuU + out: true + - name: first-half-two-vowels + in: + s: aebcdfgh + out: false + - name: second-half-two-vowels + in: + s: bcdfaeio + out: false + - name: balanced-long-pattern + in: + s: aBecIdOfUgHjKlMn + out: false + - name: unbalanced-long-pattern + in: + s: aBecIdOfUxyzBCDF + out: false + - name: uppercase-lowercase-balanced + in: + s: AaBbCcDd + out: false + - name: uppercase-lowercase-unbalanced + in: + s: AaEeBbCc + out: false + - name: vowel-at-first-position + in: + s: abcdex + out: true + - name: vowel-at-last-position + in: + s: bcdefa + out: false + - name: equal-count-three + in: + s: aeibcdoU + out: false + - name: unequal-count-three + in: + s: aeibcdef + out: false + - name: mixed-alphabet-balanced + in: + s: qWeRtYuI + out: false + - name: mixed-alphabet-unbalanced + in: + s: qWeRtyuI + out: false + - name: generated-even-short + in: + s: + gen: str + len: 20 + alphabet: "aeiouAEIOUbcdfgHJKLM" + - name: generated-even-medium + in: + s: + gen: str + len: 100 + alphabet: "aeiouAEIOUbcdfgHJKLM" + - name: generated-even-large + in: + s: + gen: str + len: 500 + alphabet: "aeiouAEIOUbcdfgHJKLM" + - name: generated-maximum + in: + s: + gen: str + len: 1000 + alphabet: "aeiouAEIOUbcdfgHJKLM" + - name: generated-consonant-heavy + in: + s: + gen: str + len: 1000 + alphabet: "bcdfghjklmnpqrstvwxyzAE" diff --git a/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.cpp b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.cpp new file mode 100644 index 00000000..901ce8ec --- /dev/null +++ b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + bool halvesAreAlike(string s) { + string vowels = "aeiouAEIOU"; + int mid = s.length() / 2; + int count = 0; + for (int i = 0; i < mid; i++) { + if (vowels.find(s[i]) != string::npos) count++; + } + for (int i = mid; i < s.length(); i++) { + if (vowels.find(s[i]) != string::npos) count--; + } + return count == 0; + } +}; diff --git a/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.cs b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.cs new file mode 100644 index 00000000..1910719c --- /dev/null +++ b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.cs @@ -0,0 +1,14 @@ +public class Solution { + public bool HalvesAreAlike(string s) { + string vowels = "aeiouAEIOU"; + int mid = s.Length / 2; + int count = 0; + for (int i = 0; i < mid; i++) { + if (vowels.IndexOf(s[i]) != -1) count++; + } + for (int i = mid; i < s.Length; i++) { + if (vowels.IndexOf(s[i]) != -1) count--; + } + return count == 0; + } +} diff --git a/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.dart b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.dart new file mode 100644 index 00000000..5e4c2f67 --- /dev/null +++ b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.dart @@ -0,0 +1,14 @@ +class Solution { + bool halvesAreAlike(String s) { + final vowels = 'aeiouAEIOU'; + final mid = s.length ~/ 2; + var count = 0; + for (var i = 0; i < mid; i++) { + if (vowels.contains(s[i])) count++; + } + for (var i = mid; i < s.length; i++) { + if (vowels.contains(s[i])) count--; + } + return count == 0; + } +} diff --git a/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.go b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.go new file mode 100644 index 00000000..1d4fb6a1 --- /dev/null +++ b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.go @@ -0,0 +1,16 @@ +func halvesAreAlike(s string) bool { + vowels := "aeiouAEIOU" + mid := len(s) / 2 + count := 0 + for i := 0; i < mid; i++ { + if strings.ContainsRune(vowels, rune(s[i])) { + count++ + } + } + for i := mid; i < len(s); i++ { + if strings.ContainsRune(vowels, rune(s[i])) { + count-- + } + } + return count == 0 +} diff --git a/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.java b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.java new file mode 100644 index 00000000..fed867cc --- /dev/null +++ b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.java @@ -0,0 +1,18 @@ +class Solution { + public boolean halvesAreAlike(String s) { + String vowels = "aeiouAEIOU"; + int mid = s.length() / 2; + int count = 0; + for (int i = 0; i < mid; i++) { + if (vowels.indexOf(s.charAt(i)) != -1) { + count++; + } + } + for (int i = mid; i < s.length(); i++) { + if (vowels.indexOf(s.charAt(i)) != -1) { + count--; + } + } + return count == 0; + } +} diff --git a/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.kt b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.kt new file mode 100644 index 00000000..6805f8d8 --- /dev/null +++ b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun halvesAreAlike(s: String): Boolean { + val vowels = "aeiouAEIOU" + val mid = s.length / 2 + var count = 0 + for (i in 0 until mid) { + if (vowels.contains(s[i])) count++ + } + for (i in mid until s.length) { + if (vowels.contains(s[i])) count-- + } + return count == 0 + } +} diff --git a/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.py b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.py new file mode 100644 index 00000000..2827c582 --- /dev/null +++ b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.py @@ -0,0 +1,20 @@ +class Solution: + def halvesAreAlike(self, s: str) -> bool: + vowels = "aeiouAEIOU" + mid = len(s) // 2 + + first_half = s[:mid] + second_half = s[mid:] + + count1 = 0 + count2 = 0 + + for c in first_half: + if c in vowels: + count1 += 1 + + for c in second_half: + if c in vowels: + count2 += 1 + + return count1 == count2 diff --git a/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.py2 b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.py2 new file mode 100644 index 00000000..9e758a44 --- /dev/null +++ b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def halvesAreAlike(self, s): + """ + :type s: str + :rtype: bool + """ + vowels = set('aeiouAEIOU') + mid = len(s) // 2 + count = 0 + for i in range(mid): + if s[i] in vowels: + count += 1 + for i in range(mid, len(s)): + if s[i] in vowels: + count -= 1 + return count == 0 diff --git a/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.rb b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.rb new file mode 100644 index 00000000..55d5a1a8 --- /dev/null +++ b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.rb @@ -0,0 +1,14 @@ +# @param {String} s +# @return {Boolean} +def halves_are_alike(s) + vowels = 'aeiouAEIOU' + mid = s.length / 2 + count = 0 + (0...mid).each do |i| + count += 1 if vowels.include?(s[i]) + end + (mid...s.length).each do |i| + count -= 1 if vowels.include?(s[i]) + end + count == 0 +end diff --git a/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.rs b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.rs new file mode 100644 index 00000000..05cff6c3 --- /dev/null +++ b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn halves_are_alike(s: String) -> bool { + let vowels = "aeiouAEIOU"; + let mid = s.len() / 2; + let bytes = s.as_bytes(); + let mut count = 0; + for i in 0..mid { + if vowels.contains(bytes[i] as char) { count += 1; } + } + for i in mid..bytes.len() { + if vowels.contains(bytes[i] as char) { count -= 1; } + } + count == 0 + } +} diff --git a/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.swift b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.swift new file mode 100644 index 00000000..ae7cf54c --- /dev/null +++ b/tests/1501-2000/1704. determine-if-string-halves-are-alike/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func halvesAreAlike(_ s: String) -> Bool { + let vowels = "aeiouAEIOU" + let mid = s.count / 2 + var count = 0 + let chars = Array(s) + for i in 0..> 1; + let count = 0; + for (let i = 0; i < mid; i++) { + if (vowels.includes(s[i])) count++; + } + for (let i = mid; i < s.length; i++) { + if (vowels.includes(s[i])) count--; + } + return count === 0; +} diff --git a/tests/1501-2000/1705. maximum-number-of-eaten-apples/manifest.yaml b/tests/1501-2000/1705. maximum-number-of-eaten-apples/manifest.yaml new file mode 100644 index 00000000..ea197449 --- /dev/null +++ b/tests/1501-2000/1705. maximum-number-of-eaten-apples/manifest.yaml @@ -0,0 +1,266 @@ +entry: + id: 1705 + title: "maximum-number-of-eaten-apples" + params: + apples: + type: array + items: + type: int + days: + type: array + items: + type: int + call: + cpp: "Solution().eatenApples({apples}, {days})" + rust: "Solution::eaten_apples({apples}, {days})" + python3: "Solution().eatenApples({apples}, {days})" + python2: "Solution().eatenApples({apples}, {days})" + ruby: "eaten_apples({apples}, {days})" + java: "new Solution().eatenApples({apples}, {days})" + csharp: "new Solution().EatenApples({apples}, {days})" + kotlin: "Solution().eatenApples({apples}, {days})" + go: "eatenApples({apples}, {days})" + dart: "Solution().eatenApples({apples}, {days})" + swift: "Solution().eatenApples({apples}, {days})" + typescript: "eatenApples({apples}, {days})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().eatenApples(apples, days, {result})" + checker: | + import heapq + + class Checker: + def eatenApples(self, apples, days, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not isinstance(apples, list) or not isinstance(days, list): + return False + if len(apples) != len(days): + return False + heap = [] + answer = 0 + day = 0 + while heap or day < len(apples): + if day < len(apples) and apples[day] > 0: + heapq.heappush(heap, (day + days[day], apples[day])) + while heap and heap[0][0] <= day: + heapq.heappop(heap) + if heap: + expire, count = heapq.heappop(heap) + answer += 1 + if count > 1: + heapq.heappush(heap, (expire, count - 1)) + day += 1 + return result == answer + +seed: 1705 + +tests: + - name: "example_one" + in: + apples: [1, 2, 3, 5, 2] + days: [3, 2, 1, 4, 2] + out: 7 + - name: "example_two" + in: + apples: [3, 0, 0, 0, 0, 2] + days: [3, 0, 0, 0, 0, 2] + out: 5 + - name: "single_apple" + in: + apples: [1] + days: [1] + out: 1 + - name: "single_empty_day" + in: + apples: [0] + days: [0] + out: 0 + - name: "all_empty" + in: + apples: [0, 0, 0] + days: [0, 0, 0] + out: 0 + - name: "same_day_rot" + in: + apples: [5] + days: [1] + out: 1 + - name: "long_lived_single_batch" + in: + apples: [5] + days: [5] + out: 5 + - name: "one_per_day" + in: + apples: [2, 2, 2] + days: [1, 1, 1] + out: 3 + - name: "overlapping_batches" + in: + apples: [1, 1, 1] + days: [3, 3, 3] + out: 3 + - name: "only_first_day" + in: + apples: [10, 0, 0, 0] + days: [1, 0, 0, 0] + out: 1 + - name: "late_short_batch" + in: + apples: [1, 0, 0, 5] + days: [5, 0, 0, 1] + out: 2 + - name: "mixed_expiration" + in: + apples: [2, 1, 0, 3] + days: [2, 1, 0, 3] + out: 5 + - name: "early_long_lived" + in: + apples: [1, 2, 0, 0, 4] + days: [10, 2, 0, 0, 2] + out: 5 + - name: "gapped_growth" + in: + apples: [0, 4, 0, 2] + days: [0, 4, 0, 2] + out: 4 + - name: "uniform_two_days" + in: + apples: [1, 1, 1, 1, 1] + days: [2, 2, 2, 2, 2] + out: 5 + - name: "alternating_batches" + in: + apples: [2, 0, 3, 0, 4] + days: [2, 0, 3, 0, 4] + out: 8 + - name: "large_first_batch" + in: + apples: [100, 0, 0] + days: [100, 0, 0] + out: 100 + - name: "large_middle_batch" + in: + apples: [0, 100, 0] + days: [0, 100, 0] + out: 100 + - name: "increasing_expiration" + in: + apples: [1, 2, 3, 4, 5, 6] + days: [1, 2, 3, 4, 5, 6] + out: 11 + - name: "decreasing_batches" + in: + apples: [5, 4, 3, 2, 1] + days: [5, 4, 3, 2, 1] + out: 5 + - name: "sparse_long_lived" + in: + apples: [1, 0, 2, 0, 3, 0] + days: [6, 0, 6, 0, 6, 0] + out: 6 + - name: "short_followup" + in: + apples: [7, 1, 0, 0, 8] + days: [2, 1, 0, 0, 2] + out: 4 + - name: "long_final_batch" + in: + apples: [2, 3, 4, 0, 0, 5] + days: [3, 3, 3, 0, 0, 10] + out: 10 + - name: "repeated_gaps" + in: + apples: [1, 1, 0, 1, 1, 0, 1] + days: [7, 7, 0, 7, 7, 0, 7] + out: 5 + - name: "early_expiry" + in: + apples: [4, 0, 0, 0, 0, 0] + days: [2, 0, 0, 0, 0, 0] + out: 2 + - name: "delayed_start" + in: + apples: [0, 0, 4, 0, 0, 0] + days: [0, 0, 4, 0, 0, 0] + out: 4 + - name: "first_batch_priority" + in: + apples: [3, 3, 3] + days: [10, 1, 1] + out: 5 + - name: "middle_batch_priority" + in: + apples: [3, 3, 3] + days: [1, 10, 1] + out: 5 + - name: "last_batch_priority" + in: + apples: [3, 3, 3] + days: [1, 1, 10] + out: 5 + - name: "varied_counts" + in: + apples: [2, 1, 4, 1, 3] + days: [4, 2, 5, 1, 3] + out: 7 + - name: "two_short_batches" + in: + apples: [20, 0, 0, 10] + days: [2, 0, 0, 2] + out: 4 + - name: "alternating_lifetimes" + in: + apples: [1, 5, 1, 5] + days: [100, 1, 100, 1] + out: 4 + - name: "even_sparse" + in: + apples: [0, 2, 0, 2, 0, 2] + days: [0, 2, 0, 2, 0, 2] + out: 6 + - name: "mixed_tail" + in: + apples: [6, 1, 2, 0, 4, 3] + days: [3, 1, 2, 0, 5, 3] + out: 9 + - name: "late_huge_lifetime" + in: + apples: [50, 0, 0, 0, 1] + days: [1, 0, 0, 0, 100] + out: 2 + - name: "long_zero_run" + in: + apples: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + days: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + out: 0 + - name: "maximum_single_batch" + in: + apples: [20000] + days: [20000] + out: 20000 + - name: "daily_short_lived_batches" + in: + apples: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + days: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 10 + - name: "long_batch_after_empty_prefix" + in: + apples: [0, 0, 0, 5] + days: [0, 0, 0, 10] + out: 5 + - name: "competing_expirations" + in: + apples: [3, 3] + days: [2, 10] + out: 5 diff --git a/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.cpp b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.cpp new file mode 100644 index 00000000..60141a50 --- /dev/null +++ b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.cpp @@ -0,0 +1,31 @@ +#include +using namespace std; + +class Solution { +public: + int eatenApples(vector& apples, vector& days) { + priority_queue, vector>, greater>> pq; + int n = apples.size(); + int res = 0; + int day = 0; + while (!pq.empty() || day < n) { + if (day < n && apples[day] > 0) { + pq.push({day + days[day], apples[day]}); + } + while (!pq.empty() && pq.top().first <= day) { + pq.pop(); + } + if (!pq.empty()) { + auto [expire, count] = pq.top(); + pq.pop(); + res++; + count--; + if (count > 0) { + pq.push({expire, count}); + } + } + day++; + } + return res; + } +}; diff --git a/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.cs b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.cs new file mode 100644 index 00000000..07a858b6 --- /dev/null +++ b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public int EatenApples(int[] apples, int[] days) { + var batches = new SortedDictionary(); + int n = apples.Length; + int res = 0; + int day = 0; + while (batches.Count > 0 || day < n) { + if (day < n && apples[day] > 0) { + int expire = day + days[day]; + if (batches.ContainsKey(expire)) batches[expire] += apples[day]; + else batches[expire] = apples[day]; + } + while (batches.Count > 0 && batches.First().Key <= day) { + batches.Remove(batches.First().Key); + } + if (batches.Count > 0) { + int expire = batches.First().Key; + res++; + if (--batches[expire] == 0) batches.Remove(expire); + } + day++; + } + return res; + } +} diff --git a/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.dart b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.dart new file mode 100644 index 00000000..307819f2 --- /dev/null +++ b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.dart @@ -0,0 +1,27 @@ +import 'dart:collection'; + +class Solution { + int eatenApples(List apples, List days) { + final pq = PriorityQueue>((a, b) => a[0].compareTo(b[0])); + int n = apples.length; + int res = 0; + int day = 0; + while (pq.isNotEmpty || day < n) { + if (day < n && apples[day] > 0) { + pq.add([day + days[day], apples[day]]); + } + while (pq.isNotEmpty && pq.first[0] <= day) { + pq.removeFirst(); + } + if (pq.isNotEmpty) { + final cur = pq.removeFirst(); + res++; + if (cur[1] - 1 > 0) { + pq.add([cur[0], cur[1] - 1]); + } + } + day++; + } + return res; + } +} diff --git a/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.go b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.go new file mode 100644 index 00000000..bf1301ff --- /dev/null +++ b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.go @@ -0,0 +1,45 @@ +import containerheap "container/heap" + +type Item struct { + expire int + count int +} + +type MinHeap []Item + +func (h MinHeap) Len() int { return len(h) } +func (h MinHeap) Less(i, j int) bool { return h[i].expire < h[j].expire } +func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *MinHeap) Push(x interface{}) { *h = append(*h, x.(Item)) } +func (h *MinHeap) Pop() interface{} { + old := *h + n := len(old) + item := old[n-1] + *h = old[:n-1] + return item +} + +func eatenApples(apples []int, days []int) int { + pq := &MinHeap{} + containerheap.Init(pq) + n := len(apples) + res := 0 + day := 0 + for pq.Len() > 0 || day < n { + if day < n && apples[day] > 0 { + containerheap.Push(pq, Item{day + days[day], apples[day]}) + } + for pq.Len() > 0 && (*pq)[0].expire <= day { + containerheap.Pop(pq) + } + if pq.Len() > 0 { + item := containerheap.Pop(pq).(Item) + res++ + if item.count-1 > 0 { + containerheap.Push(pq, Item{item.expire, item.count - 1}) + } + } + day++ + } + return res +} diff --git a/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.java b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.java new file mode 100644 index 00000000..8c63df75 --- /dev/null +++ b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.java @@ -0,0 +1,26 @@ +class Solution { + public int eatenApples(int[] apples, int[] days) { + PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); + int n = apples.length; + int res = 0; + int day = 0; + while (!pq.isEmpty() || day < n) { + if (day < n && apples[day] > 0) { + pq.offer(new int[]{day + days[day], apples[day]}); + } + while (!pq.isEmpty() && pq.peek()[0] <= day) { + pq.poll(); + } + if (!pq.isEmpty()) { + int[] cur = pq.poll(); + res++; + cur[1]--; + if (cur[1] > 0) { + pq.offer(cur); + } + } + day++; + } + return res; + } +} diff --git a/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.kt b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.kt new file mode 100644 index 00000000..a3fa0934 --- /dev/null +++ b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun eatenApples(apples: IntArray, days: IntArray): Int { + val pq = PriorityQueue>(compareBy { it.first }) + val n = apples.size + var res = 0 + var day = 0 + while (pq.isNotEmpty() || day < n) { + if (day < n && apples[day] > 0) { + pq.add(day + days[day] to apples[day]) + } + while (pq.isNotEmpty() && pq.peek().first <= day) { + pq.poll() + } + if (pq.isNotEmpty()) { + val (expire, count) = pq.poll() + res++ + if (count - 1 > 0) { + pq.add(expire to count - 1) + } + } + day++ + } + return res + } +} diff --git a/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.py b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.py new file mode 100644 index 00000000..d603c587 --- /dev/null +++ b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.py @@ -0,0 +1,21 @@ +class Solution: + def eatenApples(self, apples: List[int], days: List[int]) -> int: + heap = [] + n = len(apples) + res = 0 + day = 0 + while heap or day < n: + if day < n and apples[day] > 0: + heapq.heappush(heap, (day + days[day], apples[day])) + + while heap and heap[0][0] <= day: + heapq.heappop(heap) + if heap: + expire, count = heapq.heappop(heap) + res += 1 + count -= 1 + if count > 0: + heapq.heappush(heap, (expire, count)) + day += 1 + + return res diff --git a/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.py2 b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.py2 new file mode 100644 index 00000000..ba51cd48 --- /dev/null +++ b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.py2 @@ -0,0 +1,25 @@ +class Solution(object): + def eatenApples(self, apples, days): + """ + :type apples: List[int] + :type days: List[int] + :rtype: int + """ + import heapq + heap = [] + n = len(apples) + res = 0 + day = 0 + while heap or day < n: + if day < n and apples[day] > 0: + heapq.heappush(heap, (day + days[day], apples[day])) + while heap and heap[0][0] <= day: + heapq.heappop(heap) + if heap: + expire, count = heapq.heappop(heap) + res += 1 + count -= 1 + if count > 0: + heapq.heappush(heap, (expire, count)) + day += 1 + return res diff --git a/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.rb b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.rb new file mode 100644 index 00000000..02a695ee --- /dev/null +++ b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.rb @@ -0,0 +1,29 @@ +# @param {Integer[]} apples +# @param {Integer[]} days +# @return {Integer} +def eaten_apples(apples, days) + heap = [] + n = apples.length + res = 0 + day = 0 + while !heap.empty? || day < n + if day < n && apples[day] > 0 + heap << [day + days[day], apples[day]] + heap.sort! + end + while !heap.empty? && heap[0][0] <= day + heap.shift + end + if !heap.empty? + expire, count = heap.shift + res += 1 + count -= 1 + if count > 0 + heap << [expire, count] + heap.sort! + end + end + day += 1 + end + res +end diff --git a/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.rs b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.rs new file mode 100644 index 00000000..2d55097a --- /dev/null +++ b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.rs @@ -0,0 +1,27 @@ +use std::collections::BinaryHeap; +use std::cmp::Reverse; + +impl Solution { + pub fn eaten_apples(apples: Vec, days: Vec) -> i32 { + let mut heap: BinaryHeap<(Reverse, i32)> = BinaryHeap::new(); + let n = apples.len(); + let mut res = 0; + let mut day = 0; + while !heap.is_empty() || day < n { + if day < n && apples[day] > 0 { + heap.push((Reverse(day as i32 + days[day]), apples[day])); + } + while !heap.is_empty() && heap.peek().unwrap().0.0 <= day as i32 { + heap.pop(); + } + if let Some((Reverse(expire), count)) = heap.pop() { + res += 1; + if count - 1 > 0 { + heap.push((Reverse(expire), count - 1)); + } + } + day += 1; + } + res + } +} diff --git a/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.swift b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.swift new file mode 100644 index 00000000..407187a7 --- /dev/null +++ b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.swift @@ -0,0 +1,27 @@ +class Solution { + func eatenApples(_ apples: [Int], _ days: [Int]) -> Int { + var heap = [(Int, Int)]() + let n = apples.count + var res = 0 + var day = 0 + while !heap.isEmpty || day < n { + if day < n && apples[day] > 0 { + heap.append((day + days[day], apples[day])) + heap.sort { $0.0 < $1.0 } + } + while !heap.isEmpty && heap[0].0 <= day { + heap.removeFirst() + } + if !heap.isEmpty { + let (expire, count) = heap.removeFirst() + res += 1 + if count - 1 > 0 { + heap.append((expire, count - 1)) + heap.sort { $0.0 < $1.0 } + } + } + day += 1 + } + return res + } +} diff --git a/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.ts b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.ts new file mode 100644 index 00000000..96dfd8cc --- /dev/null +++ b/tests/1501-2000/1705. maximum-number-of-eaten-apples/sol.ts @@ -0,0 +1,25 @@ +function eatenApples(apples: number[], days: number[]): number { + const heap: [number, number][] = []; + const n = apples.length; + let res = 0; + let day = 0; + while (heap.length > 0 || day < n) { + if (day < n && apples[day] > 0) { + heap.push([day + days[day], apples[day]]); + heap.sort((a, b) => a[0] - b[0]); + } + while (heap.length > 0 && heap[0][0] <= day) { + heap.shift(); + } + if (heap.length > 0) { + const [expire, count] = heap.shift()!; + res++; + if (count - 1 > 0) { + heap.push([expire, count - 1]); + heap.sort((a, b) => a[0] - b[0]); + } + } + day++; + } + return res; +} diff --git a/tests/1501-2000/1706. where-will-the-ball-fall/manifest.yaml b/tests/1501-2000/1706. where-will-the-ball-fall/manifest.yaml new file mode 100644 index 00000000..053e2115 --- /dev/null +++ b/tests/1501-2000/1706. where-will-the-ball-fall/manifest.yaml @@ -0,0 +1,370 @@ +entry: + id: 1706 + title: "where-will-the-ball-fall" + params: + grid: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().findBall({grid})" + rust: "Solution::find_ball({grid})" + python3: "Solution().findBall({grid})" + python2: "Solution().findBall({grid})" + ruby: "find_ball({grid})" + java: "new Solution().findBall({grid})" + csharp: "new Solution().FindBall({grid})" + kotlin: "Solution().findBall({grid})" + go: "findBall({grid})" + dart: "Solution().findBall({grid})" + swift: "Solution().findBall({grid})" + typescript: "findBall({grid})" + +judge: + type: exact + +limits: + time_ms: 5000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().check(grid, {result})" + checker: | + class Checker: + def check(self, grid, result): + if not isinstance(grid, list) or not grid or not isinstance(result, list): + return False + n = len(grid[0]) + if n < 1 or any(not isinstance(row, list) or len(row) != n for row in grid): + return False + if any(cell not in (-1, 1) for row in grid for cell in row): + return False + if len(result) != n or any(type(x) is not int for x in result): + return False + expected = [] + for start in range(n): + col = start + for row in grid: + nxt = col + row[col] + if nxt < 0 or nxt >= n or row[nxt] != row[col]: + col = -1 + break + col = nxt + expected.append(col) + return result == expected + +seed: 1706 + +tests: + - name: example-one + in: + grid: + - [1, 1, 1, -1, -1] + - [1, 1, 1, -1, -1] + - [-1, -1, -1, 1, 1] + - [1, 1, 1, 1, -1] + - [-1, -1, -1, -1, -1] + - name: example-two-left-wall + in: + grid: + - [-1] + - name: example-three + in: + grid: + - [1, 1, 1, 1, 1, 1] + - [-1, -1, -1, -1, -1, -1] + - [1, 1, 1, 1, 1, 1] + - [-1, -1, -1, -1, -1, -1] + - name: one-cell-right + in: + grid: + - [1] + - name: single-row-open-three + in: + grid: + - [1, 1, 1] + - name: single-row-open-left-three + in: + grid: + - [-1, -1, -1] + - name: single-row-zigzag + in: + grid: + - [1, -1, 1, -1, 1] + - name: two-row-all-right + in: + grid: + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - name: two-row-all-left + in: + grid: + - [-1, -1, -1, -1] + - [-1, -1, -1, -1] + - name: two-row-alternating + in: + grid: + - [1, -1, 1, -1] + - [-1, 1, -1, 1] + - name: two-column-right-then-left + in: + grid: + - [1, 1] + - [-1, -1] + - name: two-column-left-then-right + in: + grid: + - [-1, -1] + - [1, 1] + - name: three-column-clear-center + in: + grid: + - [1, 1, -1] + - [1, 1, -1] + - [1, 1, -1] + - name: three-column-center-trap + in: + grid: + - [1, -1, -1] + - [1, -1, -1] + - name: three-column-left-trap + in: + grid: + - [-1, 1, 1] + - [-1, 1, 1] + - name: four-column-mixed + in: + grid: + - [1, 1, -1, -1] + - [1, 1, -1, -1] + - [-1, -1, 1, 1] + - name: four-column-cross + in: + grid: + - [1, -1, -1, 1] + - [-1, 1, 1, -1] + - [1, -1, -1, 1] + - name: five-column-staircase + in: + grid: + - [1, 1, 1, 1, -1] + - [-1, 1, 1, -1, -1] + - [-1, -1, 1, 1, 1] + - [1, -1, -1, 1, 1] + - name: five-column-reverse-staircase + in: + grid: + - [-1, 1, 1, 1, 1] + - [-1, -1, 1, 1, -1] + - [1, 1, -1, -1, -1] + - [1, 1, 1, -1, -1] + - name: six-column-horizontal-bands + in: + grid: + - [1, 1, 1, 1, 1, 1] + - [-1, -1, -1, -1, -1, -1] + - [1, 1, 1, 1, 1, 1] + - name: six-column-reversed-bands + in: + grid: + - [-1, -1, -1, -1, -1, -1] + - [1, 1, 1, 1, 1, 1] + - [-1, -1, -1, -1, -1, -1] + - name: seven-column-center-split + in: + grid: + - [1, 1, 1, -1, -1, -1, -1] + - [1, 1, 1, -1, -1, -1, -1] + - [-1, -1, -1, 1, 1, 1, 1] + - [1, 1, 1, 1, -1, -1, -1] + - name: seven-column-alternating-rows + in: + grid: + - [1, -1, 1, -1, 1, -1, 1] + - [-1, 1, -1, 1, -1, 1, -1] + - [1, -1, 1, -1, 1, -1, 1] + - name: eight-column-left-heavy + in: + grid: + - [-1, -1, 1, 1, 1, 1, 1, 1] + - [-1, -1, 1, 1, 1, 1, 1, 1] + - [1, 1, -1, -1, -1, -1, -1, -1] + - name: eight-column-right-heavy + in: + grid: + - [1, 1, 1, 1, 1, 1, -1, -1] + - [1, 1, 1, 1, 1, 1, -1, -1] + - [-1, -1, -1, -1, -1, -1, 1, 1] + - name: nine-column-v-patterns + in: + grid: + - [1, 1, -1, -1, 1, 1, -1, -1, 1] + - [-1, 1, 1, -1, -1, 1, 1, -1, -1] + - [1, -1, -1, 1, 1, -1, -1, 1, 1] + - name: ten-column-random-one + in: + grid: + - [1, -1, 1, 1, -1, -1, 1, -1, 1, 1] + - [1, 1, -1, 1, -1, 1, 1, -1, -1, 1] + - [-1, 1, 1, -1, 1, -1, 1, 1, -1, -1] + - [1, -1, -1, 1, 1, -1, -1, 1, 1, -1] + - name: ten-column-random-two + in: + grid: + - [-1, -1, 1, 1, -1, 1, 1, -1, 1, -1] + - [1, -1, -1, 1, -1, -1, 1, 1, -1, 1] + - [-1, 1, -1, -1, 1, 1, -1, 1, 1, -1] + - [1, 1, -1, 1, 1, -1, -1, 1, -1, -1] + - name: eleven-column-all-right + in: + grid: + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: eleven-column-all-left + in: + grid: + - [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1] + - [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1] + - name: twelve-column-middle-escape + in: + grid: + - [1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1] + - [1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1] + - [-1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1] + - name: twelve-column-alternating + in: + grid: + - [1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1] + - [-1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1] + - name: thirteen-column-long-right + in: + grid: + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: fourteen-column-long-left + in: + grid: + - [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1] + - [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1] + - [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1] + - name: fifteen-column-wave + in: + grid: + - [1, 1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, -1] + - [-1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1] + - [1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1] + - name: sixteen-column-border-traps + in: + grid: + - [-1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1] + - [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1] + - name: seventeen-column-mixed + in: + grid: + - [1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, 1, 1, -1, 1] + - [-1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, 1, 1, -1] + - [1, 1, -1, -1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1] + - name: eighteen-column-wide + in: + grid: + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [ + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + ] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: nineteen-column-center-v + in: + grid: + - [1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1] + - [-1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: twenty-column-deep + in: + grid: + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: generated-one-row-max + in: + grid: + gen: array + len: 1 + of: + gen: array + len: 100 + of: + gen: int + min: 1 + max: 1 + - name: generated-one-column-max + in: + grid: + gen: array + len: 100 + of: + gen: array + len: 1 + of: + gen: int + min: -1 + max: -1 + - name: generated-square-medium + in: + grid: + gen: array + len: 50 + of: + gen: array + len: 50 + of: + gen: int + min: 1 + max: 1 + - name: generated-wide-medium + in: + grid: + gen: array + len: 20 + of: + gen: array + len: 100 + of: + gen: int + min: -1 + max: -1 + - name: generated-tall-medium + in: + grid: + gen: array + len: 100 + of: + gen: array + len: 20 + of: + gen: int + min: 1 + max: 1 diff --git a/tests/1501-2000/1706. where-will-the-ball-fall/sol.cpp b/tests/1501-2000/1706. where-will-the-ball-fall/sol.cpp new file mode 100644 index 00000000..4a0a8e5c --- /dev/null +++ b/tests/1501-2000/1706. where-will-the-ball-fall/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + vector findBall(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + vector result(n); + for (int col = 0; col < n; ++col) { + int cur = col; + for (int row = 0; row < m; ++row) { + int d = grid[row][cur]; + int nxt = cur + d; + if (nxt < 0 || nxt >= n || grid[row][nxt] != d) { + cur = -1; + break; + } + cur = nxt; + } + result[col] = cur; + } + return result; + } +}; diff --git a/tests/1501-2000/1706. where-will-the-ball-fall/sol.cs b/tests/1501-2000/1706. where-will-the-ball-fall/sol.cs new file mode 100644 index 00000000..ba439887 --- /dev/null +++ b/tests/1501-2000/1706. where-will-the-ball-fall/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public int[] FindBall(int[][] grid) { + int m = grid.Length, n = grid[0].Length; + int[] result = new int[n]; + for (int col = 0; col < n; col++) { + int cur = col; + for (int row = 0; row < m; row++) { + int d = grid[row][cur]; + int nxt = cur + d; + if (nxt < 0 || nxt >= n || grid[row][nxt] != d) { + cur = -1; + break; + } + cur = nxt; + } + result[col] = cur; + } + return result; + } +} diff --git a/tests/1501-2000/1706. where-will-the-ball-fall/sol.dart b/tests/1501-2000/1706. where-will-the-ball-fall/sol.dart new file mode 100644 index 00000000..1c2e1b53 --- /dev/null +++ b/tests/1501-2000/1706. where-will-the-ball-fall/sol.dart @@ -0,0 +1,20 @@ +class Solution { + List findBall(List> grid) { + int m = grid.length, n = grid[0].length; + List result = List.filled(n, 0); + for (int col = 0; col < n; col++) { + int cur = col; + for (int row = 0; row < m; row++) { + int d = grid[row][cur]; + int nxt = cur + d; + if (nxt < 0 || nxt >= n || grid[row][nxt] != d) { + cur = -1; + break; + } + cur = nxt; + } + result[col] = cur; + } + return result; + } +} diff --git a/tests/1501-2000/1706. where-will-the-ball-fall/sol.go b/tests/1501-2000/1706. where-will-the-ball-fall/sol.go new file mode 100644 index 00000000..77a70773 --- /dev/null +++ b/tests/1501-2000/1706. where-will-the-ball-fall/sol.go @@ -0,0 +1,19 @@ +func findBall(grid [][]int) []int { + m := len(grid) + n := len(grid[0]) + result := make([]int, n) + for col := 0; col < n; col++ { + cur := col + for row := 0; row < m; row++ { + d := grid[row][cur] + nxt := cur + d + if nxt < 0 || nxt >= n || grid[row][nxt] != d { + cur = -1 + break + } + cur = nxt + } + result[col] = cur + } + return result +} diff --git a/tests/1501-2000/1706. where-will-the-ball-fall/sol.java b/tests/1501-2000/1706. where-will-the-ball-fall/sol.java new file mode 100644 index 00000000..00b1d2b2 --- /dev/null +++ b/tests/1501-2000/1706. where-will-the-ball-fall/sol.java @@ -0,0 +1,20 @@ +class Solution { + public int[] findBall(int[][] grid) { + int m = grid.length, n = grid[0].length; + int[] result = new int[n]; + for (int col = 0; col < n; col++) { + int cur = col; + for (int row = 0; row < m; row++) { + int d = grid[row][cur]; + int nxt = cur + d; + if (nxt < 0 || nxt >= n || grid[row][nxt] != d) { + cur = -1; + break; + } + cur = nxt; + } + result[col] = cur; + } + return result; + } +} diff --git a/tests/1501-2000/1706. where-will-the-ball-fall/sol.kt b/tests/1501-2000/1706. where-will-the-ball-fall/sol.kt new file mode 100644 index 00000000..5886a409 --- /dev/null +++ b/tests/1501-2000/1706. where-will-the-ball-fall/sol.kt @@ -0,0 +1,21 @@ +class Solution { + fun findBall(grid: Array): IntArray { + val m = grid.size + val n = grid[0].size + val result = IntArray(n) + for (col in 0 until n) { + var cur = col + for (row in 0 until m) { + val d = grid[row][cur] + val nxt = cur + d + if (nxt < 0 || nxt >= n || grid[row][nxt] != d) { + cur = -1 + break + } + cur = nxt + } + result[col] = cur + } + return result + } +} diff --git a/tests/1501-2000/1706. where-will-the-ball-fall/sol.py b/tests/1501-2000/1706. where-will-the-ball-fall/sol.py new file mode 100644 index 00000000..3ae11fd3 --- /dev/null +++ b/tests/1501-2000/1706. where-will-the-ball-fall/sol.py @@ -0,0 +1,20 @@ +class Solution(object): + def findBall(self, grid): + """ + :type grid: List[List[int]] + :rtype: List[int] + """ + m, n = len(grid), len(grid[0]) + result = [] + + for col in range(n): + current_col = col + for row in range(m): + dir = grid[row][current_col] + next_col = current_col + dir + if next_col < 0 or next_col >= n or grid[row][next_col] != dir: + current_col = -1 + break + current_col = next_col + result.append(current_col) + return result diff --git a/tests/1501-2000/1706. where-will-the-ball-fall/sol.py2 b/tests/1501-2000/1706. where-will-the-ball-fall/sol.py2 new file mode 100644 index 00000000..1b744678 --- /dev/null +++ b/tests/1501-2000/1706. where-will-the-ball-fall/sol.py2 @@ -0,0 +1,19 @@ +class Solution(object): + def findBall(self, grid): + """ + :type grid: List[List[int]] + :rtype: List[int] + """ + m, n = len(grid), len(grid[0]) + result = [] + for col in range(n): + cur = col + for row in range(m): + d = grid[row][cur] + nxt = cur + d + if nxt < 0 or nxt >= n or grid[row][nxt] != d: + cur = -1 + break + cur = nxt + result.append(cur) + return result diff --git a/tests/1501-2000/1706. where-will-the-ball-fall/sol.rb b/tests/1501-2000/1706. where-will-the-ball-fall/sol.rb new file mode 100644 index 00000000..914f82c7 --- /dev/null +++ b/tests/1501-2000/1706. where-will-the-ball-fall/sol.rb @@ -0,0 +1,19 @@ +def find_ball(grid) + m = grid.length + n = grid[0].length + result = [] + (0...n).each do |col| + cur = col + (0...m).each do |row| + d = grid[row][cur] + nxt = cur + d + if nxt < 0 || nxt >= n || grid[row][nxt] != d + cur = -1 + break + end + cur = nxt + end + result << cur + end + result +end diff --git a/tests/1501-2000/1706. where-will-the-ball-fall/sol.rs b/tests/1501-2000/1706. where-will-the-ball-fall/sol.rs new file mode 100644 index 00000000..dad75686 --- /dev/null +++ b/tests/1501-2000/1706. where-will-the-ball-fall/sol.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn find_ball(grid: Vec>) -> Vec { + let m = grid.len(); + let n = grid[0].len(); + let mut result = vec![0; n]; + for col in 0..n { + let mut cur = col as i32; + for row in 0..m { + let d = grid[row][cur as usize]; + let nxt = cur + d; + if nxt < 0 || nxt >= n as i32 || grid[row][nxt as usize] != d { + cur = -1; + break; + } + cur = nxt; + } + result[col] = cur; + } + result + } +} diff --git a/tests/1501-2000/1706. where-will-the-ball-fall/sol.swift b/tests/1501-2000/1706. where-will-the-ball-fall/sol.swift new file mode 100644 index 00000000..c563808e --- /dev/null +++ b/tests/1501-2000/1706. where-will-the-ball-fall/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func findBall(_ grid: [[Int]]) -> [Int] { + let m = grid.count, n = grid[0].count + var result = [Int](repeating: 0, count: n) + for col in 0..= n || grid[row][nxt] != d { + cur = -1 + break + } + cur = nxt + } + result[col] = cur + } + return result + } +} diff --git a/tests/1501-2000/1706. where-will-the-ball-fall/sol.ts b/tests/1501-2000/1706. where-will-the-ball-fall/sol.ts new file mode 100644 index 00000000..eb594fa2 --- /dev/null +++ b/tests/1501-2000/1706. where-will-the-ball-fall/sol.ts @@ -0,0 +1,19 @@ +function findBall(grid: number[][]): number[] { + const m = grid.length, + n = grid[0].length; + const result: number[] = new Array(n).fill(0); + for (let col = 0; col < n; col++) { + let cur = col; + for (let row = 0; row < m; row++) { + const d = grid[row][cur]; + const nxt = cur + d; + if (nxt < 0 || nxt >= n || grid[row][nxt] !== d) { + cur = -1; + break; + } + cur = nxt; + } + result[col] = cur; + } + return result; +} diff --git a/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/manifest.yaml b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/manifest.yaml new file mode 100644 index 00000000..fbb58a7e --- /dev/null +++ b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/manifest.yaml @@ -0,0 +1,488 @@ +entry: + id: 1707 + title: "maximum-xor-with-an-element-from-array" + params: + nums: + type: array + items: + type: int + queries: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().maximizeXor({nums}, {queries})" + rust: "Solution::maximize_xor({nums}, {queries})" + python3: "Solution().maximizeXor({nums}, {queries})" + python2: "Solution().maximizeXor({nums}, {queries})" + ruby: "maximize_xor({nums}, {queries})" + java: "new Solution().maximizeXor({nums}, {queries})" + csharp: "new Solution().MaximizeXor({nums}, {queries})" + kotlin: "Solution().maximizeXor({nums}, {queries})" + go: "maximizeXor({nums}, {queries})" + dart: "Solution().maximizeXor({nums}, {queries})" + swift: "Solution().maximizeXor({nums}, {queries})" + typescript: "maximizeXor({nums}, {queries})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maximizeXor(nums, queries, {result})" + checker: | + class Checker: + def maximizeXor(self, nums, queries, result): + if not isinstance(result, list) or len(result) != len(queries): + return False + ordered = sorted(nums) + trie = [[-1, -1]] + def insert(value): + node = 0 + for bit_index in range(30, -1, -1): + bit = (value >> bit_index) & 1 + if trie[node][bit] == -1: + trie[node][bit] = len(trie) + trie.append([-1, -1]) + node = trie[node][bit] + def best(value): + if trie[0] == [-1, -1]: + return -1 + node = 0 + answer = 0 + for bit_index in range(30, -1, -1): + bit = (value >> bit_index) & 1 + other = bit ^ 1 + if trie[node][other] != -1: + answer |= 1 << bit_index + node = trie[node][other] + else: + node = trie[node][bit] + return answer + expected = [] + index = 0 + for x, limit in sorted(enumerate(queries), key=lambda item: item[1][1]): + while index < len(ordered) and ordered[index] <= limit[1]: + insert(ordered[index]) + index += 1 + expected.append((x, best(limit[0]))) + expected.sort() + return result == [value for _, value in expected] + +seed: 1707 + +tests: + - name: example-one + in: + nums: [0, 1, 2, 3, 4] + queries: + - [3, 1] + - [1, 3] + - [5, 6] + out: [3, 3, 7] + judge: + type: "exact" + - name: example-two + in: + nums: [5, 2, 4, 6, 6, 3] + queries: + - [12, 4] + - [8, 1] + - [6, 3] + out: [15, -1, 5] + judge: + type: "exact" + - name: single-match + in: + nums: [7] + queries: + - [0, 7] + out: [7] + judge: + type: "exact" + - name: single-ineligible + in: + nums: [7] + queries: + - [3, 6] + out: [-1] + judge: + type: "exact" + - name: zero-values + in: + nums: [0, 0, 0] + queries: + - [0, 0] + - [15, 0] + out: [0, 15] + judge: + type: "exact" + - name: duplicate-values + in: + nums: [5, 5, 5, 2, 2] + queries: + - [1, 5] + - [7, 2] + out: [4, 5] + judge: + type: "exact" + - name: threshold-boundary + in: + nums: [1, 4, 8, 16] + queries: + - [3, 3] + - [3, 4] + - [3, 8] + out: [2, 7, 11] + judge: + type: "exact" + - name: unsorted-input + in: + nums: [10, 1, 7, 3, 12] + queries: + - [6, 6] + - [9, 10] + - [2, 0] + out: [7, 14, -1] + judge: + type: "exact" + - name: query-order-preserved + in: + nums: [2, 8, 13] + queries: + - [1, 100] + - [7, 2] + - [15, 8] + - [0, 1] + out: [12, 5, 13, -1] + judge: + type: "exact" + - name: low-thresholds + in: + nums: [10, 20, 30] + queries: + - [1, 0] + - [1, 9] + - [1, 10] + out: [-1, -1, 11] + judge: + type: "exact" + - name: high-bit-values + in: + nums: [536870911, 536870912, 1073741823] + queries: + - [0, 536870911] + - [1, 1073741823] + - [1073741823, 536870912] + out: [536870911, 1073741822, 536870912] + judge: + type: "exact" + - name: max-values + in: + nums: [1000000000, 999999999] + queries: + - [1000000000, 1000000000] + - [0, 999999999] + out: [1023, 999999999] + judge: + type: "exact" + - name: powers-of-two + in: + nums: [1, 2, 4, 8, 16] + queries: + - [31, 3] + - [31, 7] + - [31, 31] + out: [30, 30, 30] + judge: + type: "exact" + - name: identical-queries + in: + nums: [3, 10, 12] + queries: + - [5, 10] + - [5, 10] + - [5, 10] + out: [15, 15, 15] + judge: + type: "exact" + - name: empty-eligible-mixed + in: + nums: [50, 60, 70] + queries: + - [1, 49] + - [1, 50] + - [100, 65] + out: [-1, 51, 88] + judge: + type: "exact" + - name: close-values + in: + nums: [14, 15, 16, 17] + queries: + - [8, 14] + - [8, 15] + - [8, 16] + out: [6, 7, 24] + judge: + type: "exact" + - name: mixed-small + in: + nums: [0, 3, 5, 6, 9] + queries: + - [2, 2] + - [4, 5] + - [7, 9] + out: [2, 7, 14] + judge: + type: "exact" + - name: many-duplicates + in: + nums: [1, 1, 1, 8, 8, 8, 15] + queries: + - [7, 1] + - [7, 8] + - [7, 15] + out: [6, 15, 15] + judge: + type: "exact" + - name: descending-values + in: + nums: [99, 50, 25, 12, 6, 3] + queries: + - [100, 5] + - [100, 50] + - [0, 100] + out: [103, 125, 99] + judge: + type: "exact" + - name: all-query-misses + in: + nums: [100, 200, 300] + queries: + - [0, 0] + - [1000, 99] + - [7, 50] + out: [-1, -1, -1] + judge: + type: "exact" + - name: all-query-hits + in: + nums: [4, 9, 12] + queries: + - [0, 100] + - [3, 100] + - [15, 100] + out: [12, 15, 11] + judge: + type: "exact" + - name: xor-zero-query + in: + nums: [0, 1, 2, 4, 8] + queries: + - [0, 0] + - [0, 3] + - [0, 8] + out: [0, 2, 8] + judge: + type: "exact" + - name: alternating-thresholds + in: + nums: [2, 6, 10, 14] + queries: + - [1, 14] + - [1, 2] + - [1, 10] + - [1, 0] + out: [15, 3, 11, -1] + judge: + type: "exact" + - name: thirty-one-mask + in: + nums: [7, 11, 13, 17, 31] + queries: + - [31, 13] + - [16, 20] + - [8, 30] + out: [24, 29, 25] + judge: + type: "exact" + - name: sparse-large + in: + nums: [1, 100, 10000, 1000000] + queries: + - [999999999, 0] + - [123456, 10000] + - [765432, 1000000] + out: [-1, 123457, 765433] + judge: + type: "exact" + - name: threshold-each-value + in: + nums: [3, 7, 12, 20] + queries: + - [9, 3] + - [9, 7] + - [9, 12] + - [9, 20] + out: [10, 14, 14, 29] + judge: + type: "exact" + - name: repeated-x-different-m + in: + nums: [2, 5, 9, 14] + queries: + - [6, 1] + - [6, 5] + - [6, 9] + - [6, 14] + out: [-1, 4, 15, 15] + judge: + type: "exact" + - name: twenty-five-values + in: + nums: [0, 1, 2, 4, 8, 16, 3, 5, 9, 17] + queries: + - [25, 0] + - [25, 5] + - [25, 10] + - [25, 20] + out: [25, 29, 29, 29] + judge: + type: "exact" + - name: boundary-nine-bits + in: + nums: [255, 256, 511, 512] + queries: + - [511, 255] + - [511, 511] + - [256, 512] + out: [256, 256, 768] + judge: + type: "exact" + - name: forty-small-values + in: + nums: [1, 3, 7, 15, 31, 63, 127] + queries: + - [2, 7] + - [10, 31] + - [100, 127] + out: [5, 21, 123] + judge: + type: "exact" + - name: generated-small + in: + nums: + gen: "array" + len: 8 + of: + gen: "int" + min: 0 + max: 63 + elemType: "int" + queries: + gen: "array" + len: 6 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 63 + elemType: "int" + seed: 170701 + - name: generated-medium + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 1000000 + elemType: "int" + queries: + gen: "array" + len: 100 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 1000000 + elemType: "int" + seed: 170702 + - name: generated-large-values + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" + queries: + gen: "array" + len: 1000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" + seed: 170703 + - name: generated-stress + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" + queries: + gen: "array" + len: 100000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" + seed: 170704 + - name: generated-zero-thresholds + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" + queries: + gen: "array" + len: 50000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" + seed: 170705 diff --git a/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.cpp b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.cpp new file mode 100644 index 00000000..beb47f96 --- /dev/null +++ b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + vector maximizeXor(vector& nums, vector>& queries) { + vector> trie; + trie.push_back({-1, -1}); + auto insert = [&](int num) { + int node = 0; + for (int i = 31; i >= 0; --i) { + int bit = (num >> i) & 1; + if (trie[node][bit] == -1) { + trie[node][bit] = trie.size(); + trie.push_back({-1, -1}); + } + node = trie[node][bit]; + } + }; + auto maxor = [&](int num) { + if (trie[0][0] == -1 && trie[0][1] == -1) return -1; + int node = 0; + int ans = 0; + for (int i = 31; i >= 0; --i) { + int bit = (num >> i) & 1; + int opp = 1 - bit; + if (trie[node][opp] != -1) { + ans |= (1 << i); + node = trie[node][opp]; + } else { + node = trie[node][bit]; + } + } + return ans; + }; + + sort(nums.begin(), nums.end()); + vector> q; + for (int i = 0; i < queries.size(); ++i) { + q.push_back({queries[i][1], queries[i][0], i}); + } + sort(q.begin(), q.end()); + vector res(queries.size(), -1); + int idx = 0; + int n = nums.size(); + for (auto& item : q) { + int m = item[0], x = item[1], i = item[2]; + while (idx < n && nums[idx] <= m) { + insert(nums[idx]); + idx++; + } + res[i] = maxor(x); + } + return res; + } +}; diff --git a/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.cs b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.cs new file mode 100644 index 00000000..3d03261f --- /dev/null +++ b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.cs @@ -0,0 +1,52 @@ +public class Solution { + public int[] MaximizeXor(int[] nums, int[][] queries) { + List trie = new List(); + trie.Add(new int[]{-1, -1}); + void Insert(int num) { + int node = 0; + for (int i = 31; i >= 0; --i) { + int bit = (num >> i) & 1; + if (trie[node][bit] == -1) { + trie[node][bit] = trie.Count; + trie.Add(new int[]{-1, -1}); + } + node = trie[node][bit]; + } + } + int Maxor(int num) { + if (trie[0][0] == -1 && trie[0][1] == -1) return -1; + int node = 0; + int ans = 0; + for (int i = 31; i >= 0; --i) { + int bit = (num >> i) & 1; + int opp = 1 - bit; + if (trie[node][opp] != -1) { + ans |= 1 << i; + node = trie[node][opp]; + } else { + node = trie[node][bit]; + } + } + return ans; + } + + Array.Sort(nums); + var q = new List<(int m, int x, int i)>(); + for (int i = 0; i < queries.Length; ++i) { + q.Add((queries[i][1], queries[i][0], i)); + } + q.Sort((a, b) => a.m.CompareTo(b.m)); + int[] res = new int[queries.Length]; + Array.Fill(res, -1); + int idx = 0; + int n = nums.Length; + foreach (var item in q) { + while (idx < n && nums[idx] <= item.m) { + Insert(nums[idx]); + idx++; + } + res[item.i] = Maxor(item.x); + } + return res; + } +} diff --git a/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.dart b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.dart new file mode 100644 index 00000000..d67d6ead --- /dev/null +++ b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.dart @@ -0,0 +1,55 @@ +class Solution { + List maximizeXor(List nums, List> queries) { + List> trie = [ + [-1, -1] + ]; + void insert(int num) { + int node = 0; + for (int i = 31; i >= 0; i--) { + int bit = (num >> i) & 1; + if (trie[node][bit] == -1) { + trie[node][bit] = trie.length; + trie.add([-1, -1]); + } + node = trie[node][bit]; + } + } + int maxor(int num) { + if (trie[0][0] == -1 && trie[0][1] == -1) return -1; + int node = 0; + int ans = 0; + for (int i = 31; i >= 0; i--) { + int bit = (num >> i) & 1; + int opp = 1 - bit; + if (trie[node][opp] != -1) { + ans |= 1 << i; + node = trie[node][opp]; + } else { + node = trie[node][bit]; + } + } + return ans; + } + + nums.sort(); + List> q = []; + for (int i = 0; i < queries.length; i++) { + q.add([queries[i][1], queries[i][0], i]); + } + q.sort((a, b) => a[0].compareTo(b[0])); + List res = List.filled(queries.length, -1); + int idx = 0; + int n = nums.length; + for (var item in q) { + int m = item[0]; + int x = item[1]; + int i = item[2]; + while (idx < n && nums[idx] <= m) { + insert(nums[idx]); + idx++; + } + res[i] = maxor(x); + } + return res; + } +} diff --git a/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.go b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.go new file mode 100644 index 00000000..4be0ce11 --- /dev/null +++ b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.go @@ -0,0 +1,55 @@ +func maximizeXor(nums []int, queries [][]int) []int { + trie := make([][2]int, 1) + trie[0] = [2]int{-1, -1} + insert := func(num int) { + node := 0 + for i := 31; i >= 0; i-- { + bit := (num >> i) & 1 + if trie[node][bit] == -1 { + trie[node][bit] = len(trie) + trie = append(trie, [2]int{-1, -1}) + } + node = trie[node][bit] + } + } + maxor := func(num int) int { + if trie[0][0] == -1 && trie[0][1] == -1 { + return -1 + } + node := 0 + ans := 0 + for i := 31; i >= 0; i-- { + bit := (num >> i) & 1 + opp := 1 - bit + if trie[node][opp] != -1 { + ans |= 1 << i + node = trie[node][opp] + } else { + node = trie[node][bit] + } + } + return ans + } + + sort.Ints(nums) + type qtype struct { + m, x, i int + } + q := make([]qtype, len(queries)) + for i, qv := range queries { + q[i] = qtype{qv[1], qv[0], i} + } + sort.Slice(q, func(i, j int) bool { return q[i].m < q[j].m }) + res := make([]int, len(queries)) + for i := range res { res[i] = -1 } + idx := 0 + n := len(nums) + for _, item := range q { + for idx < n && nums[idx] <= item.m { + insert(nums[idx]) + idx++ + } + res[item.i] = maxor(item.x) + } + return res +} diff --git a/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.java b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.java new file mode 100644 index 00000000..770451af --- /dev/null +++ b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.java @@ -0,0 +1,55 @@ +import java.util.*; + +class Solution { + public int[] maximizeXor(int[] nums, int[][] queries) { + List trie = new ArrayList<>(); + trie.add(new int[]{-1, -1}); + java.util.function.IntConsumer insert = num -> { + int node = 0; + for (int i = 31; i >= 0; --i) { + int bit = (num >> i) & 1; + if (trie.get(node)[bit] == -1) { + trie.get(node)[bit] = trie.size(); + trie.add(new int[]{-1, -1}); + } + node = trie.get(node)[bit]; + } + }; + java.util.function.IntUnaryOperator maxor = num -> { + if (trie.get(0)[0] == -1 && trie.get(0)[1] == -1) return -1; + int node = 0; + int ans = 0; + for (int i = 31; i >= 0; --i) { + int bit = (num >> i) & 1; + int opp = 1 - bit; + if (trie.get(node)[opp] != -1) { + ans |= (1 << i); + node = trie.get(node)[opp]; + } else { + node = trie.get(node)[bit]; + } + } + return ans; + }; + + Arrays.sort(nums); + List q = new ArrayList<>(); + for (int i = 0; i < queries.length; ++i) { + q.add(new int[]{queries[i][1], queries[i][0], i}); + } + q.sort((a, b) -> Integer.compare(a[0], b[0])); + int[] res = new int[queries.length]; + Arrays.fill(res, -1); + int idx = 0; + int n = nums.length; + for (int[] item : q) { + int m = item[0], x = item[1], i = item[2]; + while (idx < n && nums[idx] <= m) { + insert.accept(nums[idx]); + idx++; + } + res[i] = maxor.applyAsInt(x); + } + return res; + } +} diff --git a/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.kt b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.kt new file mode 100644 index 00000000..dc5c3d01 --- /dev/null +++ b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.kt @@ -0,0 +1,53 @@ +class Solution { + fun maximizeXor(nums: IntArray, queries: Array): IntArray { + val trie = mutableListOf(intArrayOf(-1, -1)) + fun insert(num: Int) { + var node = 0 + for (i in 31 downTo 0) { + val bit = (num shr i) and 1 + if (trie[node][bit] == -1) { + trie[node][bit] = trie.size + trie.add(intArrayOf(-1, -1)) + } + node = trie[node][bit] + } + } + fun maxor(num: Int): Int { + if (trie[0][0] == -1 && trie[0][1] == -1) return -1 + var node = 0 + var ans = 0 + for (i in 31 downTo 0) { + val bit = (num shr i) and 1 + val opp = 1 - bit + if (trie[node][opp] != -1) { + ans = ans or (1 shl i) + node = trie[node][opp] + } else { + node = trie[node][bit] + } + } + return ans + } + + nums.sort() + val q = mutableListOf() + for (i in queries.indices) { + q.add(intArrayOf(queries[i][1], queries[i][0], i)) + } + q.sortBy { it[0] } + val res = IntArray(queries.size) { -1 } + var idx = 0 + val n = nums.size + for (item in q) { + val m = item[0] + val x = item[1] + val i = item[2] + while (idx < n && nums[idx] <= m) { + insert(nums[idx]) + idx++ + } + res[i] = maxor(x) + } + return res + } +} diff --git a/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.py b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.py new file mode 100644 index 00000000..f046567f --- /dev/null +++ b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.py @@ -0,0 +1,49 @@ +class Solution(object): + def maximizeXor(self, nums, queries): + trie = [[-1, -1]] + + def insert(num): + node = 0 + for i in range(31, -1, -1): + bit = (num >> i) & 1 + if trie[node][bit] == -1: + trie[node][bit] = len(trie) + trie.append([-1, -1]) + node = trie[node][bit] + + def maxor(num): + if trie[0][0] == -1 and trie[0][1] == -1: + return -1 + node = 0 + ans = 0 + for i in range(31, -1, -1): + bit = (num >> i) & 1 + opp = 1 - bit + if trie[node][opp] != -1: + ans |= 1 << i + node = trie[node][opp] + else: + node = trie[node][bit] + return ans + + nums.sort() + q = [] + for i, (x, m) in enumerate(queries): + q.append((m, x, i)) + + q.sort() + res = [-1] * len(queries) + idx = 0 + n = len(nums) + for m, x, i in q: + while idx < n and nums[idx] <= m: + insert(nums[idx]) + idx += 1 + res[i] = maxor(x) + return res + + """ + :type nums: List[int] + :type queries: List[List[int]] + :rtype: List[int] + """ diff --git a/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.py2 b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.py2 new file mode 100644 index 00000000..63c964b5 --- /dev/null +++ b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.py2 @@ -0,0 +1,49 @@ +class Solution(object): + def maximizeXor(self, nums, queries): + left=[-1] + right=[-1] + def insert(num): + node=0 + for i in range(30,-1,-1): + bit=(num>>i)&1 + if bit: + if right[node] == -1: + right[node] = len(left); left.append(-1); right.append(-1) + node = right[node] + else: + if left[node] == -1: + left[node] = len(left); left.append(-1); right.append(-1) + node = left[node] + + def maxor(num): + if left[0] == -1 and right[0] == -1: + return -1 + node=0 + ans=0 + for i in range(30,-1,-1): + bit=(num>>i)&1 + if bit and left[node] != -1: + ans|=(1<> i) & 1 + if bit == 0 + child = left[node] + if child == -1 + child = left.length + left[node] = child + left << -1 + right << -1 + end + node = child + else + child = right[node] + if child == -1 + child = left.length + right[node] = child + left << -1 + right << -1 + end + node = child + end + end + end + + maxor = lambda do |num| + return -1 if left[0] == -1 && right[0] == -1 + node = 0 + ans = 0 + 30.downto(0) do |i| + bit = (num >> i) & 1 + if bit == 0 + if right[node] != -1 + ans |= (1 << i) + node = right[node] + else + node = left[node] + end + elsif left[node] != -1 + ans |= (1 << i) + node = left[node] + else + node = right[node] + end + end + ans + end + + res = Array.new(queries.length, -1) + idx = 0 + n = nums.length + queries_with_index.each do |m, x, i| + while idx < n && nums[idx] <= m + insert.call(nums[idx]) + idx += 1 + end + res[i] = maxor.call(x) + end + res +end diff --git a/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.rs b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.rs new file mode 100644 index 00000000..d30a7820 --- /dev/null +++ b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.rs @@ -0,0 +1,51 @@ +impl Solution { + pub fn maximize_xor(nums: Vec, queries: Vec>) -> Vec { + let mut trie: Vec> = vec![vec![-1, -1]]; + fn insert(num: i32, trie: &mut Vec>) { + let mut node = 0usize; + for i in (0..=31).rev() { + let bit = ((num >> i) & 1) as usize; + if trie[node][bit] == -1 { + trie[node][bit] = trie.len() as i32; + trie.push(vec![-1, -1]); + } + node = trie[node][bit] as usize; + } + } + fn maxor(num: i32, trie: &Vec>) -> i32 { + if trie[0][0] == -1 && trie[0][1] == -1 { return -1; } + let mut node = 0usize; + let mut ans = 0i32; + for i in (0..=31).rev() { + let bit = ((num >> i) & 1) as usize; + let opp = 1 - bit; + if trie[node][opp] != -1 { + ans |= 1 << i; + node = trie[node][opp] as usize; + } else { + node = trie[node][bit] as usize; + } + } + ans + } + + let mut nums = nums.clone(); + nums.sort(); + let mut q: Vec<(i32, i32, usize)> = Vec::new(); + for (i, qv) in queries.iter().enumerate() { + q.push((qv[1], qv[0], i)); + } + q.sort(); + let mut res = vec![-1; queries.len()]; + let mut idx = 0usize; + let n = nums.len(); + for (m, x, i) in q { + while idx < n && nums[idx] <= m { + insert(nums[idx], &mut trie); + idx += 1; + } + res[i] = maxor(x, &trie); + } + res + } +} diff --git a/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.swift b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.swift new file mode 100644 index 00000000..8a48db92 --- /dev/null +++ b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.swift @@ -0,0 +1,50 @@ +class Solution { + func maximizeXor(_ nums: [Int], _ queries: [[Int]]) -> [Int] { + var trie: [[Int]] = [[-1, -1]] + func insert(_ num: Int) { + var node = 0 + for i in stride(from: 31, through: 0, by: -1) { + let bit = (num >> i) & 1 + if trie[node][bit] == -1 { + trie[node][bit] = trie.count + trie.append([-1, -1]) + } + node = trie[node][bit] + } + } + func maxor(_ num: Int) -> Int { + if trie[0][0] == -1 && trie[0][1] == -1 { return -1 } + var node = 0 + var ans = 0 + for i in stride(from: 31, through: 0, by: -1) { + let bit = (num >> i) & 1 + let opp = 1 - bit + if trie[node][opp] != -1 { + ans |= (1 << i) + node = trie[node][opp] + } else { + node = trie[node][bit] + } + } + return ans + } + + var numsSorted = nums.sorted() + var q: [(m: Int, x: Int, i: Int)] = [] + for (i, qv) in queries.enumerated() { + q.append((qv[1], qv[0], i)) + } + q.sort { $0.m < $1.m } + var res = [Int](repeating: -1, count: queries.count) + var idx = 0 + let n = numsSorted.count + for item in q { + while idx < n && numsSorted[idx] <= item.m { + insert(numsSorted[idx]) + idx += 1 + } + res[item.i] = maxor(item.x) + } + return res + } +} diff --git a/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.ts b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.ts new file mode 100644 index 00000000..6acc7d0f --- /dev/null +++ b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.ts @@ -0,0 +1,48 @@ +function maximizeXor(nums: number[], queries: number[][]): number[] { + const trie: number[][] = [[-1, -1]]; + const insert = (num: number) => { + let node = 0; + for (let i = 31; i >= 0; --i) { + const bit = (num >> i) & 1; + if (trie[node][bit] === -1) { + trie[node][bit] = trie.length; + trie.push([-1, -1]); + } + node = trie[node][bit]; + } + }; + const maxor = (num: number): number => { + if (trie[0][0] === -1 && trie[0][1] === -1) return -1; + let node = 0; + let ans = 0; + for (let i = 31; i >= 0; --i) { + const bit = (num >> i) & 1; + const opp = 1 - bit; + if (trie[node][opp] !== -1) { + ans |= 1 << i; + node = trie[node][opp]; + } else { + node = trie[node][bit]; + } + } + return ans; + }; + + nums.sort((a, b) => a - b); + const q: number[][] = []; + for (let i = 0; i < queries.length; ++i) { + q.push([queries[i][1], queries[i][0], i]); + } + q.sort((a, b) => a[0] - b[0]); + const res: number[] = new Array(queries.length).fill(-1); + let idx = 0; + const n = nums.length; + for (const [m, x, i] of q) { + while (idx < n && nums[idx] <= m) { + insert(nums[idx]); + idx++; + } + res[i] = maxor(x); + } + return res; +} diff --git a/tests/1501-2000/1710. maximum-units-on-a-truck/manifest.yaml b/tests/1501-2000/1710. maximum-units-on-a-truck/manifest.yaml new file mode 100644 index 00000000..4c60d49e --- /dev/null +++ b/tests/1501-2000/1710. maximum-units-on-a-truck/manifest.yaml @@ -0,0 +1,423 @@ +entry: + id: 1710 + title: "maximum-units-on-a-truck" + params: + boxTypes: + type: array + items: + type: array + items: + type: int + truckSize: + type: int + call: + cpp: "Solution().maximumUnits({boxTypes}, {truckSize})" + rust: "Solution::maximum_units({boxTypes}, {truckSize})" + python3: "Solution().maximumUnits({boxTypes}, {truckSize})" + python2: "Solution().maximumUnits({boxTypes}, {truckSize})" + ruby: "maximum_units({boxTypes}, {truckSize})" + java: "new Solution().maximumUnits({boxTypes}, {truckSize})" + csharp: "new Solution().MaximumUnits({boxTypes}, {truckSize})" + kotlin: "Solution().maximumUnits({boxTypes}, {truckSize})" + go: "maximumUnits({boxTypes}, {truckSize})" + dart: "Solution().maximumUnits({boxTypes}, {truckSize})" + swift: "Solution().maximumUnits({boxTypes}, {truckSize})" + typescript: "maximumUnits({boxTypes}, {truckSize})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maximumUnits(boxTypes, truckSize, {result})" + checker: | + class Checker: + def maximumUnits(self, boxTypes, truckSize, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + remaining = truckSize + expected = 0 + for count, units in sorted(boxTypes, key=lambda pair: pair[1], reverse=True): + take = min(remaining, count) + expected += take * units + remaining -= take + if remaining == 0: + break + return result == expected + +seed: 1710 + +tests: + - name: example-one + in: + boxTypes: + - [1, 3] + - [2, 2] + - [3, 1] + truckSize: 4 + out: 8 + judge: + type: "exact" + - name: example-two + in: + boxTypes: + - [5, 10] + - [2, 5] + - [4, 7] + - [3, 9] + truckSize: 10 + out: 91 + judge: + type: "exact" + - name: one-type-partial + in: + boxTypes: + - [10, 7] + truckSize: 3 + out: 21 + judge: + type: "exact" + - name: one-type-all + in: + boxTypes: + - [4, 12] + truckSize: 10 + out: 48 + judge: + type: "exact" + - name: truck-one + in: + boxTypes: + - [4, 2] + - [3, 9] + - [2, 5] + truckSize: 1 + out: 9 + judge: + type: "exact" + - name: exact-capacity + in: + boxTypes: + - [2, 8] + - [3, 4] + truckSize: 5 + out: 28 + judge: + type: "exact" + - name: capacity-exceeds-all + in: + boxTypes: + - [2, 8] + - [3, 4] + truckSize: 20 + out: 28 + judge: + type: "exact" + - name: equal-units + in: + boxTypes: + - [5, 6] + - [2, 6] + - [4, 6] + truckSize: 7 + out: 42 + judge: + type: "exact" + - name: reverse-order + in: + boxTypes: + - [5, 1] + - [1, 100] + - [2, 50] + truckSize: 4 + out: 201 + judge: + type: "exact" + - name: many-low-types + in: + boxTypes: + - [1, 1] + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + truckSize: 3 + out: 12 + judge: + type: "exact" + - name: large-units + in: + boxTypes: + - [1000, 1000] + - [1000, 999] + truckSize: 1001 + out: 1000999 + judge: + type: "exact" + - name: large-count-low-value + in: + boxTypes: + - [1000, 1] + - [1, 2] + truckSize: 1000 + out: 1001 + judge: + type: "exact" + - name: alternating-values + in: + boxTypes: + - [2, 10] + - [5, 1] + - [3, 9] + - [4, 2] + truckSize: 7 + out: 51 + judge: + type: "exact" + - name: singleton-types + in: + boxTypes: + - [1, 20] + - [1, 19] + - [1, 18] + truckSize: 2 + out: 39 + judge: + type: "exact" + - name: zero-remainder + in: + boxTypes: + - [3, 4] + - [2, 3] + - [5, 2] + truckSize: 3 + out: 12 + judge: + type: "exact" + - name: tie-boundary + in: + boxTypes: + - [2, 7] + - [2, 7] + - [2, 6] + truckSize: 5 + out: 34 + judge: + type: "exact" + - name: descending-input + in: + boxTypes: + - [1, 10] + - [2, 9] + - [3, 8] + - [4, 7] + truckSize: 6 + out: 52 + judge: + type: "exact" + - name: ascending-input + in: + boxTypes: + - [4, 7] + - [3, 8] + - [2, 9] + - [1, 10] + truckSize: 6 + out: 52 + judge: + type: "exact" + - name: two-types-take-first + in: + boxTypes: + - [8, 5] + - [8, 4] + truckSize: 3 + out: 15 + judge: + type: "exact" + - name: two-types-split + in: + boxTypes: + - [2, 5] + - [8, 4] + truckSize: 5 + out: 22 + judge: + type: "exact" + - name: all-identical + in: + boxTypes: + - [3, 3] + - [3, 3] + - [3, 3] + truckSize: 8 + out: 24 + judge: + type: "exact" + - name: high-middle-wins + in: + boxTypes: + - [4, 2] + - [4, 8] + - [4, 5] + truckSize: 6 + out: 42 + judge: + type: "exact" + - name: max-box-types + in: + boxTypes: + - [1000, 1] + - [1000, 2] + - [1000, 3] + - [1000, 4] + - [1000, 5] + truckSize: 1 + out: 5 + judge: + type: "exact" + - name: capacity-six + in: + boxTypes: + - [1, 14] + - [2, 11] + - [5, 3] + truckSize: 6 + out: 45 + judge: + type: "exact" + - name: capacity-seven + in: + boxTypes: + - [3, 10] + - [3, 9] + - [3, 8] + truckSize: 7 + out: 65 + judge: + type: "exact" + - name: capacity-two + in: + boxTypes: + - [5, 4] + - [1, 20] + - [1, 19] + truckSize: 2 + out: 39 + judge: + type: "exact" + - name: units-one + in: + boxTypes: + - [3, 1] + - [2, 1] + truckSize: 4 + out: 4 + judge: + type: "exact" + - name: all-maximum + in: + boxTypes: + - [1000, 1000] + - [1000, 1000] + truckSize: 1000000 + out: 2000000 + judge: + type: "exact" + - name: large-partial + in: + boxTypes: + - [1000, 1000] + - [1000, 500] + - [1000, 1] + truckSize: 1500 + out: 1250000 + judge: + type: "exact" + - name: mixed-ten + in: + boxTypes: + - [1, 10] + - [2, 8] + - [3, 6] + - [4, 4] + - [5, 2] + truckSize: 10 + out: 60 + judge: + type: "exact" + - name: mixed-nine + in: + boxTypes: + - [4, 9] + - [1, 8] + - [2, 7] + - [3, 6] + truckSize: 9 + out: 70 + judge: + type: "exact" + - name: generated-small + in: + boxTypes: + - [5, 10] + - [4, 6] + - [3, 2] + truckSize: + gen: "int" + min: 1 + max: 12 + - name: generated-medium + in: + boxTypes: + - [20, 100] + - [30, 50] + - [40, 25] + - [50, 1] + truckSize: + gen: "int" + min: 1 + max: 140 + - name: generated-large-values + in: + boxTypes: + - [1000, 1000] + - [1000, 999] + - [1000, 1] + truckSize: + gen: "int" + min: 1 + max: 3000 + - name: generated-balanced + in: + boxTypes: + - [37, 91] + - [41, 73] + - [29, 55] + - [53, 12] + - [61, 3] + truckSize: + gen: "int" + min: 1 + max: 221 + - name: generated-many-types + in: + boxTypes: + - [11, 1] + - [12, 2] + - [13, 3] + - [14, 4] + - [15, 5] + - [16, 6] + - [17, 7] + - [18, 8] + - [19, 9] + - [20, 10] + truckSize: + gen: "int" + min: 1 + max: 155 diff --git a/tests/1501-2000/1710. maximum-units-on-a-truck/sol.cpp b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.cpp new file mode 100644 index 00000000..dff0c85e --- /dev/null +++ b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int maximumUnits(vector>& boxTypes, int truckSize) { + sort(boxTypes.begin(), boxTypes.end(), [](const vector& a, const vector& b) { + return a[1] > b[1]; + }); + int ans = 0; + int remaining = truckSize; + for (vector& box : boxTypes) { + int quantitytaken = min(remaining, box[0]); + ans += box[1] * quantitytaken; + remaining -= quantitytaken; + if (remaining == 0) break; + } + return ans; + } +}; diff --git a/tests/1501-2000/1710. maximum-units-on-a-truck/sol.cs b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.cs new file mode 100644 index 00000000..0d50ce2b --- /dev/null +++ b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.cs @@ -0,0 +1,14 @@ +public class Solution { + public int MaximumUnits(int[][] boxTypes, int truckSize) { + Array.Sort(boxTypes, (a, b) => b[1].CompareTo(a[1])); + int ans = 0; + int remaining = truckSize; + foreach (int[] box in boxTypes) { + int quantitytaken = Math.Min(remaining, box[0]); + ans += box[1] * quantitytaken; + remaining -= quantitytaken; + if (remaining == 0) break; + } + return ans; + } +} diff --git a/tests/1501-2000/1710. maximum-units-on-a-truck/sol.dart b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.dart new file mode 100644 index 00000000..088f6e2c --- /dev/null +++ b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.dart @@ -0,0 +1,14 @@ +class Solution { + int maximumUnits(List> boxTypes, int truckSize) { + boxTypes.sort((a, b) => b[1].compareTo(a[1])); + int ans = 0; + int remaining = truckSize; + for (var box in boxTypes) { + int quantitytaken = box[0] < remaining ? box[0] : remaining; + ans += box[1] * quantitytaken; + remaining -= quantitytaken; + if (remaining == 0) break; + } + return ans; + } +} diff --git a/tests/1501-2000/1710. maximum-units-on-a-truck/sol.go b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.go new file mode 100644 index 00000000..330948ef --- /dev/null +++ b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.go @@ -0,0 +1,19 @@ +func maximumUnits(boxTypes [][]int, truckSize int) int { + sort.Slice(boxTypes, func(i, j int) bool { + return boxTypes[i][1] > boxTypes[j][1] + }) + ans := 0 + remaining := truckSize + for _, box := range boxTypes { + quantitytaken := box[0] + if remaining < quantitytaken { + quantitytaken = remaining + } + ans += box[1] * quantitytaken + remaining -= quantitytaken + if remaining == 0 { + break + } + } + return ans +} diff --git a/tests/1501-2000/1710. maximum-units-on-a-truck/sol.java b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.java new file mode 100644 index 00000000..3d61512e --- /dev/null +++ b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int maximumUnits(int[][] boxTypes, int truckSize) { + Arrays.sort(boxTypes, (a, b) -> b[1] - a[1]); + int ans = 0; + for (int[] box : boxTypes) { + int quantitytaken = Math.min(truckSize, box[0]); + ans += box[1] * quantitytaken; + truckSize -= quantitytaken; + if (truckSize == 0) break; + } + return ans; + } +} diff --git a/tests/1501-2000/1710. maximum-units-on-a-truck/sol.kt b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.kt new file mode 100644 index 00000000..12bf0f73 --- /dev/null +++ b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun maximumUnits(boxTypes: Array, truckSize: Int): Int { + boxTypes.sortByDescending { it[1] } + var ans = 0 + var remaining = truckSize + for (box in boxTypes) { + val quantitytaken = minOf(remaining, box[0]) + ans += box[1] * quantitytaken + remaining -= quantitytaken + if (remaining == 0) break + } + return ans + } +} diff --git a/tests/1501-2000/1710. maximum-units-on-a-truck/sol.py b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.py new file mode 100644 index 00000000..415a2539 --- /dev/null +++ b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.py @@ -0,0 +1,36 @@ +class Solution: + def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int: + # standard approach-------------------------------------------------------- + boxTypes.sort(reverse=True, key=lambda x: x[1]) + # print(f"{boxTypes=}") + # boxTypes=[[5, 10], [3, 9], [4, 7], [2, 5]] + ans = 0 + for a, b in boxTypes: + quantitytaken = min(truckSize, a) + ans += b * quantitytaken + truckSize -= quantitytaken + if truckSize == 0: + break + return ans + + # ============================================================================================ + + # cool approach i learned in https://leetcode.com/problems/minimum-total-distance-traveled/description/ + # Robots and factory question. + temp = [] + for a, b in boxTypes: + # ------------------- + # for _ in range(a): + # temp.append(b) + # ----------------- + t = [b] * a + temp.extend(t) # this way lind of faster casue implemented in c + # ----------------- + + temp.sort(reverse=True) + # print(temp) [10, 10, 10, 10, 10, 9, 9, 9, 7, 7, 7, 7, 5, 5] + return sum(temp[:truckSize]) + + +# approach 2 is not scalable though mightfail for larger constraints +# ============================================================================================ diff --git a/tests/1501-2000/1710. maximum-units-on-a-truck/sol.py2 b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.py2 new file mode 100644 index 00000000..454a192c --- /dev/null +++ b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def maximumUnits(self, boxTypes, truckSize): + """ + :type boxTypes: List[List[int]] + :type truckSize: int + :rtype: int + """ + boxTypes.sort(reverse=True, key=lambda x: x[1]) + ans = 0 + for a, b in boxTypes: + quantitytaken = min(truckSize, a) + ans += b * quantitytaken + truckSize -= quantitytaken + if truckSize == 0: + break + return ans diff --git a/tests/1501-2000/1710. maximum-units-on-a-truck/sol.rb b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.rb new file mode 100644 index 00000000..02492edd --- /dev/null +++ b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[][]} box_types +# @param {Integer} truck_size +# @return {Integer} +def maximum_units(box_types, truck_size) + box_types.sort_by! { |x| -x[1] } + ans = 0 + box_types.each do |a, b| + quantitytaken = [truck_size, a].min + ans += b * quantitytaken + truck_size -= quantitytaken + break if truck_size == 0 + end + ans +end diff --git a/tests/1501-2000/1710. maximum-units-on-a-truck/sol.rs b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.rs new file mode 100644 index 00000000..2d8bf450 --- /dev/null +++ b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn maximum_units(box_types: Vec>, truck_size: i32) -> i32 { + let mut boxes = box_types; + boxes.sort_by(|a, b| b[1].cmp(&a[1])); + let mut remaining = truck_size; + let mut ans = 0; + for boxx in boxes { + let quantitytaken = remaining.min(boxx[0]); + ans += boxx[1] * quantitytaken; + remaining -= quantitytaken; + if remaining == 0 { break; } + } + ans + } +} diff --git a/tests/1501-2000/1710. maximum-units-on-a-truck/sol.swift b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.swift new file mode 100644 index 00000000..10eb8635 --- /dev/null +++ b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.swift @@ -0,0 +1,14 @@ +class Solution { + func maximumUnits(_ boxTypes: [[Int]], _ truckSize: Int) -> Int { + let sorted = boxTypes.sorted { $0[1] > $1[1] } + var remaining = truckSize + var ans = 0 + for box in sorted { + let quantitytaken = min(remaining, box[0]) + ans += box[1] * quantitytaken + remaining -= quantitytaken + if remaining == 0 { break } + } + return ans + } +} diff --git a/tests/1501-2000/1710. maximum-units-on-a-truck/sol.ts b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.ts new file mode 100644 index 00000000..a928c3aa --- /dev/null +++ b/tests/1501-2000/1710. maximum-units-on-a-truck/sol.ts @@ -0,0 +1,12 @@ +function maximumUnits(boxTypes: number[][], truckSize: number): number { + boxTypes.sort((a, b) => b[1] - a[1]); + let ans = 0; + let remaining = truckSize; + for (const [boxes, units] of boxTypes) { + const quantitytaken = Math.min(remaining, boxes); + ans += units * quantitytaken; + remaining -= quantitytaken; + if (remaining === 0) break; + } + return ans; +} diff --git a/tests/1501-2000/1711. count-good-meals/manifest.yaml b/tests/1501-2000/1711. count-good-meals/manifest.yaml new file mode 100644 index 00000000..a91060ba --- /dev/null +++ b/tests/1501-2000/1711. count-good-meals/manifest.yaml @@ -0,0 +1,246 @@ +entry: + id: 1711 + title: "count-good-meals" + params: + deliciousness: + type: array + items: + type: int + call: + cpp: "Solution().countPairs({deliciousness})" + rust: "Solution::count_pairs({deliciousness})" + python3: "Solution().countPairs({deliciousness})" + python2: "Solution().countPairs({deliciousness})" + ruby: "count_pairs({deliciousness})" + java: "new Solution().countPairs({deliciousness})" + csharp: "new Solution().CountPairs({deliciousness})" + kotlin: "Solution().countPairs({deliciousness})" + go: "countPairs({deliciousness})" + dart: "Solution().countPairs({deliciousness})" + swift: "Solution().countPairs({deliciousness})" + typescript: "countPairs({deliciousness})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().countPairs(deliciousness, {result})" + checker: | + class Checker: + def countPairs(self, deliciousness, result): + mod = 1000000007 + counts = {} + expected = 0 + for value in deliciousness: + for power in (1, 2, 4, 8, 16, 32, 64, 128, 256, 512, + 1024, 2048, 4096, 8192, 16384, 32768, + 65536, 131072, 262144, 524288, 1048576, + 2097152): + expected += counts.get(power - value, 0) + counts[value] = counts.get(value, 0) + 1 + return isinstance(result, int) and result == expected % mod + +seed: 1711 + +tests: + - name: example-one + in: + deliciousness: [1, 3, 5, 7, 9] + out: 4 + - name: example-two + in: + deliciousness: [1, 1, 1, 3, 3, 3, 7] + out: 15 + - name: single-item + in: + deliciousness: [0] + out: 0 + - name: two-zeroes + in: + deliciousness: [0, 0] + out: 0 + - name: zero-with-one + in: + deliciousness: [0, 1] + out: 1 + - name: zero-with-nonpower + in: + deliciousness: [0, 3] + out: 0 + - name: equal-power-pair + in: + deliciousness: [2, 2] + out: 1 + - name: equal-nonpower-pair + in: + deliciousness: [3, 3] + out: 0 + - name: duplicate-pairs + in: + deliciousness: [1, 1, 1, 1] + out: 6 + - name: complementary-duplicates + in: + deliciousness: [1, 1, 7, 7] + out: 5 + - name: mixed-small + in: + deliciousness: [1, 2, 3, 4, 5, 6, 7] + out: 4 + - name: powers-of-two + in: + deliciousness: [1, 2, 4, 8, 16] + out: 0 + - name: many-zeroes + in: + deliciousness: [0, 0, 0, 0, 0] + out: 0 + - name: all-three + in: + deliciousness: [3, 3, 3, 3, 3] + out: 0 + - name: broad-small-range + in: + deliciousness: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + out: 9 + - name: high-complement + in: + deliciousness: [524288, 524288, 524288, 0] + out: 6 + - name: maximum-value-pair + in: + deliciousness: [1048576, 1048576] + out: 1 + - name: maximum-with-zero + in: + deliciousness: [0, 1048576] + out: 1 + - name: near-maximum-no-pair + in: + deliciousness: [1048576, 1048575] + out: 0 + - name: repeated-complements + in: + deliciousness: [5, 5, 11, 11, 21, 21] + out: 8 + - name: negatives-not-allowed-boundary + in: + deliciousness: [0, 2, 6, 14, 30] + out: 4 + - name: alternating-values + in: + deliciousness: [1, 3, 1, 3, 1, 3] + out: 12 + - name: one-value-with-many-complements + in: + deliciousness: [1, 1, 1, 1, 3, 3, 3] + out: 18 + - name: sparse-high-values + in: + deliciousness: [100, 924, 100, 1948, 52] + out: 4 + - name: exact-power-sums + in: + deliciousness: [7, 9, 15, 17, 31, 33] + out: 3 + - name: zero-and-powers + in: + deliciousness: [0, 0, 1, 1, 2, 2, 4, 4] + out: 15 + - name: dense-range-sixteen + in: + deliciousness: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + out: 15 + - name: dense-range-with-duplicates + in: + deliciousness: [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5] + out: 23 + - name: large-gap-values + in: + deliciousness: [1, 1023, 2049, 4095, 12289] + out: 3 + - name: maximum-boundary-mix + in: + deliciousness: [1048576, 1048575, 524288, 524288, 0, 1] + out: 6 + - name: twenty-identical + in: + deliciousness: + [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7] + out: 0 + - name: complementary-blocks + in: + deliciousness: [1, 1, 1, 1, 15, 15, 15, 15] + out: 22 + - name: mixed-boundaries + in: + deliciousness: [0, 0, 0, 1, 1, 3, 3, 7, 7, 15, 15] + out: 19 + - name: generated-uniform + in: + deliciousness: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 1048576 + distinct: false + elemType: "int" + - name: generated-small-dense + in: + deliciousness: + gen: "array" + len: 250 + of: + gen: "int" + min: 0 + max: 63 + distinct: false + elemType: "int" + - name: generated-large-zero-heavy + in: + deliciousness: + gen: "array" + len: 100000 + of: + gen: "int" + min: 0 + max: 16 + distinct: false + elemType: "int" + - name: generated-large-boundary + in: + deliciousness: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1048000 + max: 1048576 + distinct: false + elemType: "int" + - name: generated-large-wide + in: + deliciousness: + gen: "array" + len: 100000 + of: + gen: "int" + min: 0 + max: 1048576 + distinct: false + elemType: "int" + - name: all-noncomplementary + in: + deliciousness: [6, 10, 22, 42, 86] + out: 4 + - name: maximal-small-pair-count + in: + deliciousness: [1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3] + out: 51 diff --git a/tests/1501-2000/1711. count-good-meals/sol.cpp b/tests/1501-2000/1711. count-good-meals/sol.cpp new file mode 100644 index 00000000..3c8a56d2 --- /dev/null +++ b/tests/1501-2000/1711. count-good-meals/sol.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int countPairs(vector& deliciousness) { + const long long MOD = 1'000'000'007; + int max_val = 0; + for (int d : deliciousness) max_val = max(max_val, d); + vector powers; + for (int i = 0; i < 22; i++) powers.push_back(1 << i); + + unordered_map count; + long long res = 0; + + for (int val : deliciousness) { + for (int target : powers) { + int complement = target - val; + if (count.find(complement) != count.end()) { + res += count[complement]; + res %= MOD; + } + } + count[val]++; + } + return (int)res; + } +}; diff --git a/tests/1501-2000/1711. count-good-meals/sol.cs b/tests/1501-2000/1711. count-good-meals/sol.cs new file mode 100644 index 00000000..6d085b3f --- /dev/null +++ b/tests/1501-2000/1711. count-good-meals/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public int CountPairs(int[] deliciousness) { + const long MOD = 1_000_000_007; + int maxVal = 0; + foreach (int d in deliciousness) maxVal = Math.Max(maxVal, d); + int[] powers = new int[22]; + for (int i = 0; i < 22; i++) powers[i] = 1 << i; + + var count = new Dictionary(); + long res = 0; + + foreach (int val in deliciousness) { + foreach (int target in powers) { + int complement = target - val; + if (count.ContainsKey(complement)) { + res += count[complement]; + res %= MOD; + } + } + if (!count.ContainsKey(val)) count[val] = 0; + count[val]++; + } + return (int)res; + } +} diff --git a/tests/1501-2000/1711. count-good-meals/sol.dart b/tests/1501-2000/1711. count-good-meals/sol.dart new file mode 100644 index 00000000..adfbdda5 --- /dev/null +++ b/tests/1501-2000/1711. count-good-meals/sol.dart @@ -0,0 +1,24 @@ +class Solution { + int countPairs(List deliciousness) { + const int MOD = 1000000007; + int maxVal = 0; + for (int d in deliciousness) { + if (d > maxVal) maxVal = d; + } + List powers = List.generate(22, (i) => 1 << i); + Map count = {}; + int res = 0; + + for (int val in deliciousness) { + for (int target in powers) { + int complement = target - val; + if (count.containsKey(complement)) { + res += count[complement]!; + res %= MOD; + } + } + count[val] = (count[val] ?? 0) + 1; + } + return res; + } +} diff --git a/tests/1501-2000/1711. count-good-meals/sol.go b/tests/1501-2000/1711. count-good-meals/sol.go new file mode 100644 index 00000000..48d05f8b --- /dev/null +++ b/tests/1501-2000/1711. count-good-meals/sol.go @@ -0,0 +1,28 @@ +func countPairs(deliciousness []int) int { + const MOD = 1000000007 + maxVal := 0 + for _, d := range deliciousness { + if d > maxVal { + maxVal = d + } + } + _ = maxVal + powers := make([]int, 22) + for i := 0; i < 22; i++ { + powers[i] = 1 << i + } + count := make(map[int]int) + res := 0 + + for _, val := range deliciousness { + for _, target := range powers { + complement := target - val + if c, ok := count[complement]; ok { + res += c + res %= MOD + } + } + count[val]++ + } + return res +} diff --git a/tests/1501-2000/1711. count-good-meals/sol.java b/tests/1501-2000/1711. count-good-meals/sol.java new file mode 100644 index 00000000..210456b1 --- /dev/null +++ b/tests/1501-2000/1711. count-good-meals/sol.java @@ -0,0 +1,24 @@ +class Solution { + public int countPairs(int[] deliciousness) { + final int MOD = 1_000_000_007; + int maxVal = 0; + for (int d : deliciousness) maxVal = Math.max(maxVal, d); + int[] powers = new int[22]; + for (int i = 0; i < 22; i++) powers[i] = 1 << i; + + Map count = new HashMap<>(); + long res = 0; + + for (int val : deliciousness) { + for (int target : powers) { + int complement = target - val; + if (count.containsKey(complement)) { + res += count.get(complement); + res %= MOD; + } + } + count.put(val, count.getOrDefault(val, 0) + 1); + } + return (int) res; + } +} diff --git a/tests/1501-2000/1711. count-good-meals/sol.kt b/tests/1501-2000/1711. count-good-meals/sol.kt new file mode 100644 index 00000000..07e629cc --- /dev/null +++ b/tests/1501-2000/1711. count-good-meals/sol.kt @@ -0,0 +1,21 @@ +class Solution { + fun countPairs(deliciousness: IntArray): Int { + val MOD = 1_000_000_007 + val maxVal = deliciousness.maxOrNull() ?: 0 + val powers = IntArray(22) { 1 shl it } + val count = mutableMapOf() + var res = 0L + + for (value in deliciousness) { + for (target in powers) { + val complement = target - value + if (count.containsKey(complement)) { + res += count[complement]!! + res %= MOD + } + } + count[value] = (count[value] ?: 0) + 1 + } + return res.toInt() + } +} diff --git a/tests/1501-2000/1711. count-good-meals/sol.py b/tests/1501-2000/1711. count-good-meals/sol.py new file mode 100644 index 00000000..e3eb1a13 --- /dev/null +++ b/tests/1501-2000/1711. count-good-meals/sol.py @@ -0,0 +1,23 @@ +class Solution(object): + def countPairs(self, deliciousness): + """ + :type deliciousness: List[int] + :rtype: int + """ + MOD = 10**9 + 7 + max_val = max(deliciousness) + max_sum = max_val * 2 + power_of_twos = [1 << i for i in range(22)] + + count = defaultdict(int) + res = 0 + + for val in deliciousness: + for target in power_of_twos: + complement = target - val + if complement in count: + res += count[complement] + res %= MOD + count[val] += 1 + + return res diff --git a/tests/1501-2000/1711. count-good-meals/sol.py2 b/tests/1501-2000/1711. count-good-meals/sol.py2 new file mode 100644 index 00000000..a5074ba7 --- /dev/null +++ b/tests/1501-2000/1711. count-good-meals/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def countPairs(self, deliciousness): + """ + :type deliciousness: List[int] + :rtype: int + """ + MOD = 10**9 + 7 + max_val = max(deliciousness) if deliciousness else 0 + max_sum = max_val * 2 + power_of_twos = [1 << i for i in range(22)] + + count = {} + res = 0 + + for val in deliciousness: + for target in power_of_twos: + complement = target - val + if complement in count: + res += count[complement] + res %= MOD + count[val] = count.get(val, 0) + 1 + + return res diff --git a/tests/1501-2000/1711. count-good-meals/sol.rb b/tests/1501-2000/1711. count-good-meals/sol.rb new file mode 100644 index 00000000..d10ac65f --- /dev/null +++ b/tests/1501-2000/1711. count-good-meals/sol.rb @@ -0,0 +1,19 @@ +# @param {Integer[]} deliciousness +# @return {Integer} +def count_pairs(deliciousness) + mod = 10**9 + 7 + max_val = deliciousness.max || 0 + powers = (0...22).map { |i| 1 << i } + count = Hash.new(0) + res = 0 + + deliciousness.each do |val| + powers.each do |target| + complement = target - val + res += count[complement] if count.key?(complement) + res %= mod + end + count[val] += 1 + end + res +end diff --git a/tests/1501-2000/1711. count-good-meals/sol.rs b/tests/1501-2000/1711. count-good-meals/sol.rs new file mode 100644 index 00000000..ecd38ff1 --- /dev/null +++ b/tests/1501-2000/1711. count-good-meals/sol.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn count_pairs(deliciousness: Vec) -> i32 { + const MOD: i64 = 1_000_000_007; + let max_val = deliciousness.iter().max().unwrap_or(&0); + let powers: Vec = (0..22).map(|i| 1 << i).collect(); + let mut count = std::collections::HashMap::new(); + let mut res: i64 = 0; + + for &val in &deliciousness { + for &target in &powers { + let complement = target - val; + if let Some(&c) = count.get(&complement) { + res += c as i64; + res %= MOD; + } + } + *count.entry(val).or_insert(0) += 1; + } + res as i32 + } +} diff --git a/tests/1501-2000/1711. count-good-meals/sol.swift b/tests/1501-2000/1711. count-good-meals/sol.swift new file mode 100644 index 00000000..347a3d70 --- /dev/null +++ b/tests/1501-2000/1711. count-good-meals/sol.swift @@ -0,0 +1,24 @@ +class Solution { + func countPairs(_ deliciousness: [Int]) -> Int { + let MOD = 1_000_000_007 + var maxVal = 0 + for d in deliciousness { + maxVal = max(maxVal, d) + } + let powers = (0..<22).map { 1 << $0 } + var count = [Int: Int]() + var res = 0 + + for val in deliciousness { + for target in powers { + let complement = target - val + if let c = count[complement] { + res += c + res %= MOD + } + } + count[val, default: 0] += 1 + } + return res + } +} diff --git a/tests/1501-2000/1711. count-good-meals/sol.ts b/tests/1501-2000/1711. count-good-meals/sol.ts new file mode 100644 index 00000000..3d8c0238 --- /dev/null +++ b/tests/1501-2000/1711. count-good-meals/sol.ts @@ -0,0 +1,21 @@ +function countPairs(deliciousness: number[]): number { + const MOD = 1000000007; + const maxVal = Math.max(...deliciousness); + const powers: number[] = []; + for (let i = 0; i < 22; i++) powers.push(1 << i); + + const count = new Map(); + let res = 0; + + for (const val of deliciousness) { + for (const target of powers) { + const complement = target - val; + if (count.has(complement)) { + res += count.get(complement)!; + res %= MOD; + } + } + count.set(val, (count.get(val) ?? 0) + 1); + } + return res; +} diff --git a/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/manifest.yaml b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/manifest.yaml new file mode 100644 index 00000000..4d78d50d --- /dev/null +++ b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/manifest.yaml @@ -0,0 +1,237 @@ +entry: + id: 1712 + title: "ways-to-split-array-into-three-subarrays" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().waysToSplit({nums})" + rust: "Solution::ways_to_split({nums})" + python3: "Solution().waysToSplit({nums})" + python2: "Solution().waysToSplit({nums})" + ruby: "ways_to_split({nums})" + java: "new Solution().waysToSplit({nums})" + csharp: "new Solution().WaysToSplit({nums})" + kotlin: "Solution().waysToSplit({nums})" + go: "waysToSplit({nums})" + dart: "Solution().waysToSplit({nums})" + swift: "Solution().waysToSplit({nums})" + typescript: "waysToSplit({nums})" +judge: + type: "exact" +limits: + time_ms: 3000 + memory_mb: 512 +oracle: + python3: + call: "Checker().waysToSplit(nums, {result})" + checker: | + from bisect import bisect_left, bisect_right + + class Checker: + def waysToSplit(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if len(nums) < 3 or any(not isinstance(x, int) or x < 0 for x in nums): + return False + prefix = [] + total = 0 + for value in nums: + total += value + prefix.append(total) + expected = 0 + end = len(nums) - 1 + for left_end in range(len(nums) - 2): + left = prefix[left_end] + first = bisect_left(prefix, 2 * left, left_end + 1, end) + last = bisect_right(prefix, (total + left) // 2, first, end) + expected = (expected + max(0, last - first)) % 1000000007 + return result == expected +seed: 17121712 +tests: + - name: example-one + in: + nums: [1, 1, 1] + out: 1 + - name: example-two + in: + nums: [1, 2, 2, 2, 5, 0] + out: 3 + - name: example-three + in: + nums: [3, 2, 1] + out: 0 + - name: all-zero-three + in: + nums: [0, 0, 0] + out: 1 + - name: all-zero-five + in: + nums: [0, 0, 0, 0, 0] + out: 6 + - name: all-ones + in: + nums: [1, 1, 1, 1, 1, 1] + out: 3 + - name: increasing + in: + nums: [1, 2, 3, 4, 5, 6] + out: 5 + - name: decreasing + in: + nums: [6, 5, 4, 3, 2, 1] + out: 0 + - name: one-large-value + in: + nums: [10000, 0, 0] + out: 0 + - name: equal-large-values + in: + nums: [10000, 10000, 10000, 10000, 10000] + out: 2 + - name: sparse-nonzero + in: + nums: [0, 1, 0, 1, 0, 1, 0] + out: 6 + - name: alternating-zero + in: + nums: [1, 0, 1, 0, 1, 0, 1, 0] + out: 4 + - name: balanced-seven + in: + nums: [1, 1, 1, 1, 1, 1, 1] + out: 4 + - name: left-heavy + in: + nums: [10, 0, 0, 0, 0, 0] + out: 0 + - name: right-heavy + in: + nums: [0, 0, 0, 0, 0, 10] + out: 10 + - name: repeated-blocks + in: + nums: [5, 5, 0, 5, 5, 0, 5, 5] + out: 7 + - name: all-equal-large + in: + nums: [10000, 0, 10000, 0, 10000, 0, 10000] + out: 4 + - name: many-zeros + in: + nums: [0, 0, 1, 0, 0, 1, 0, 0, 1] + out: 16 + - name: minimum-four + in: + nums: [2, 2, 2, 2] + out: 1 + - name: short-five + in: + nums: [1, 2, 3, 4, 5] + out: 3 + - name: short-six-unbalanced + in: + nums: [5, 1, 1, 1, 1, 5] + out: 0 + - name: powers-of-two + in: + nums: [1, 2, 4, 8, 16, 32, 64] + out: 15 + - name: plateau-with-gaps + in: + nums: [3, 3, 3, 0, 3, 3, 3, 0, 3] + out: 5 + - name: leading-zeros + in: + nums: [0, 0, 1, 2, 3, 4, 5] + out: 10 + - name: trailing-zeros + in: + nums: [1, 2, 3, 4, 5, 0, 0] + out: 3 + - name: symmetric-ends + in: + nums: [4, 1, 1, 1, 1, 4] + out: 1 + - name: modulo-pattern + in: + nums: [7, 0, 0, 7, 0, 0, 7, 0, 0] + out: 9 + - name: max-elements + in: + nums: [10000, 10000, 10000, 10000, 10000, 10000, 10000] + out: 4 + - name: uneven-balanced + in: + nums: [2, 0, 2, 0, 2, 0, 2] + out: 4 + - name: isolated-middle + in: + nums: [0, 0, 0, 9, 0, 0, 0] + out: 3 + - name: varied-small + in: + nums: [1, 3, 2, 0, 4, 1, 2, 0, 3] + out: 4 + - name: generator-minimum + in: + nums: + gen: "array" + len: 3 + of: + gen: "int" + min: 0 + max: 10000 + distinct: false + sorted: false + elemType: "int" + - name: generator-short + in: + nums: + gen: "array" + len: 17 + of: + gen: "int" + min: 0 + max: 10000 + distinct: false + sorted: false + elemType: "int" + - name: generator-medium + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 10000 + distinct: false + sorted: false + elemType: "int" + - name: generator-large + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 0 + max: 10000 + distinct: false + sorted: false + elemType: "int" + - name: generator-maximum + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 0 + max: 10000 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.cpp b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.cpp new file mode 100644 index 00000000..7f7bd9d5 --- /dev/null +++ b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.cpp @@ -0,0 +1,51 @@ +class Solution { +public: + int waysToSplit(vector& nums) { + const int MOD = 1000000007; + int n = nums.size(); + vector prefix(n); + prefix[0] = nums[0]; + + for (int i = 1; i < n; i++) { + prefix[i] = prefix[i - 1] + nums[i]; + } + + long long res = 0; + for (int i = 0; i < n - 2; i++) { + long long left = prefix[i]; + int j = lowerBound(prefix, 2 * left, i + 1, n - 1); + int k = upperBound(prefix, (prefix[n - 1] + left) / 2, j, n - 1); + if (j < k) { + res = (res + (k - j)) % MOD; + } + } + return (int)res; + } + +private: + int lowerBound(vector& arr, long long target, int lo, int hi) { + int l = lo, h = hi; + while (l < h) { + int mid = (l + h) / 2; + if (arr[mid] < target) { + l = mid + 1; + } else { + h = mid; + } + } + return l; + } + + int upperBound(vector& arr, long long target, int lo, int hi) { + int l = lo, h = hi; + while (l < h) { + int mid = (l + h) / 2; + if (arr[mid] <= target) { + l = mid + 1; + } else { + h = mid; + } + } + return l; + } +}; diff --git a/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.cs b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.cs new file mode 100644 index 00000000..6c03b343 --- /dev/null +++ b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.cs @@ -0,0 +1,49 @@ +public class Solution { + public int WaysToSplit(int[] nums) { + const int MOD = 1000000007; + int n = nums.Length; + long[] prefix = new long[n]; + prefix[0] = nums[0]; + + for (int i = 1; i < n; i++) { + prefix[i] = prefix[i - 1] + nums[i]; + } + + long res = 0; + for (int i = 0; i < n - 2; i++) { + long left = prefix[i]; + int j = LowerBound(prefix, 2 * left, i + 1, n - 1); + int k = UpperBound(prefix, (prefix[n - 1] + left) / 2, j, n - 1); + if (j < k) { + res = (res + (k - j)) % MOD; + } + } + return (int)res; + } + + private int LowerBound(long[] arr, long target, int lo, int hi) { + int l = lo, h = hi; + while (l < h) { + int mid = (l + h) / 2; + if (arr[mid] < target) { + l = mid + 1; + } else { + h = mid; + } + } + return l; + } + + private int UpperBound(long[] arr, long target, int lo, int hi) { + int l = lo, h = hi; + while (l < h) { + int mid = (l + h) / 2; + if (arr[mid] <= target) { + l = mid + 1; + } else { + h = mid; + } + } + return l; + } +} diff --git a/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.dart b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.dart new file mode 100644 index 00000000..c843b3b0 --- /dev/null +++ b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.dart @@ -0,0 +1,49 @@ +class Solution { + int waysToSplit(List nums) { + const MOD = 1000000007; + int n = nums.length; + List prefix = List.filled(n, 0); + prefix[0] = nums[0]; + + for (int i = 1; i < n; i++) { + prefix[i] = prefix[i - 1] + nums[i]; + } + + int res = 0; + for (int i = 0; i < n - 2; i++) { + int left = prefix[i]; + int j = lowerBound(prefix, 2 * left, i + 1, n - 1); + int k = upperBound(prefix, (prefix[n - 1] + left) ~/ 2, j, n - 1); + if (j < k) { + res = (res + (k - j)) % MOD; + } + } + return res; + } + + int lowerBound(List arr, int target, int lo, int hi) { + int l = lo, h = hi; + while (l < h) { + int mid = (l + h) ~/ 2; + if (arr[mid] < target) { + l = mid + 1; + } else { + h = mid; + } + } + return l; + } + + int upperBound(List arr, int target, int lo, int hi) { + int l = lo, h = hi; + while (l < h) { + int mid = (l + h) ~/ 2; + if (arr[mid] <= target) { + l = mid + 1; + } else { + h = mid; + } + } + return l; + } +} diff --git a/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.go b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.go new file mode 100644 index 00000000..53667316 --- /dev/null +++ b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.go @@ -0,0 +1,47 @@ +func waysToSplit(nums []int) int { + const MOD = 1000000007 + n := len(nums) + prefix := make([]int64, n) + prefix[0] = int64(nums[0]) + + for i := 1; i < n; i++ { + prefix[i] = prefix[i-1] + int64(nums[i]) + } + + res := int64(0) + for i := 0; i < n-2; i++ { + left := prefix[i] + j := lowerBound(prefix, 2*left, i+1, n-1) + k := upperBound(prefix, (prefix[n-1]+left)/2, j, n-1) + if j < k { + res = (res + int64(k-j)) % MOD + } + } + return int(res) +} + +func lowerBound(arr []int64, target int64, lo, hi int) int { + l, h := lo, hi + for l < h { + mid := (l + h) / 2 + if arr[mid] < target { + l = mid + 1 + } else { + h = mid + } + } + return l +} + +func upperBound(arr []int64, target int64, lo, hi int) int { + l, h := lo, hi + for l < h { + mid := (l + h) / 2 + if arr[mid] <= target { + l = mid + 1 + } else { + h = mid + } + } + return l +} diff --git a/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.java b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.java new file mode 100644 index 00000000..0d535845 --- /dev/null +++ b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.java @@ -0,0 +1,47 @@ +class Solution { + public int waysToSplit(int[] nums) { + int MOD = 1_000_000_007; + int n = nums.length; + long[] prefix = new long[n]; + prefix[0] = nums[0]; + + for (int i = 1; i < n; i++) { + prefix[i] = prefix[i - 1] + nums[i]; + } + + long res = 0; + for (int i = 0; i < n - 2; i++) { + long left = prefix[i]; + int j = lowerBound(prefix, 2 * left, i + 1, n - 1); + int k = upperBound(prefix, (prefix[n - 1] + left) / 2, j, n - 1); + if (j < k) { + res = (res + (k - j)) % MOD; + } + } + return (int) res; + } + + private int lowerBound(long[] arr, long target, int lo, int hi) { + while (lo < hi) { + int mid = (lo + hi) / 2; + if (arr[mid] < target) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; + } + + private int upperBound(long[] arr, long target, int lo, int hi) { + while (lo < hi) { + int mid = (lo + hi) / 2; + if (arr[mid] <= target) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; + } +} diff --git a/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.kt b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.kt new file mode 100644 index 00000000..6690e5d6 --- /dev/null +++ b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.kt @@ -0,0 +1,51 @@ +class Solution { + fun waysToSplit(nums: IntArray): Int { + val MOD = 1_000_000_007 + val n = nums.size + val prefix = LongArray(n) + prefix[0] = nums[0].toLong() + + for (i in 1 until n) { + prefix[i] = prefix[i - 1] + nums[i] + } + + var res = 0L + for (i in 0 until n - 2) { + val left = prefix[i] + val j = lowerBound(prefix, 2 * left, i + 1, n - 1) + val k = upperBound(prefix, (prefix[n - 1] + left) / 2, j, n - 1) + if (j < k) { + res = (res + (k - j)) % MOD + } + } + return res.toInt() + } + + private fun lowerBound(arr: LongArray, target: Long, lo: Int, hi: Int): Int { + var l = lo + var h = hi + while (l < h) { + val mid = (l + h) / 2 + if (arr[mid] < target) { + l = mid + 1 + } else { + h = mid + } + } + return l + } + + private fun upperBound(arr: LongArray, target: Long, lo: Int, hi: Int): Int { + var l = lo + var h = hi + while (l < h) { + val mid = (l + h) / 2 + if (arr[mid] <= target) { + l = mid + 1 + } else { + h = mid + } + } + return l + } +} diff --git a/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.py b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.py new file mode 100644 index 00000000..563c5d8d --- /dev/null +++ b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.py @@ -0,0 +1,27 @@ +import bisect + + +class Solution(object): + def waysToSplit(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + MOD = 10**9 + 7 + n = len(nums) + prefix = [0] * n + prefix[0] = nums[0] + + for i in range(1, n): + prefix[i] = prefix[i - 1] + nums[i] + + res = 0 + for i in range(n - 2): + left = prefix[i] + j = bisect.bisect_left(prefix, 2 * left, i + 1, n - 1) + k = bisect.bisect_right(prefix, (prefix[-1] + left) // 2, j, n - 1) + + if j < k: + res = (res + k - j) % MOD + + return res diff --git a/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.py2 b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.py2 new file mode 100644 index 00000000..670b6f31 --- /dev/null +++ b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.py2 @@ -0,0 +1,42 @@ +class Solution(object): + def waysToSplit(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + MOD = 10**9 + 7 + n = len(nums) + prefix = [0] * n + prefix[0] = nums[0] + + for i in range(1, n): + prefix[i] = prefix[i - 1] + nums[i] + + res = 0 + for i in range(n - 2): + left = prefix[i] + j = self.lower_bound(prefix, 2 * left, i + 1, n - 1) + k = self.upper_bound(prefix, (prefix[-1] + left) // 2, j, n - 1) + + if j < k: + res = (res + k - j) % MOD + + return res + + def lower_bound(self, arr, target, lo, hi): + while lo < hi: + mid = (lo + hi) // 2 + if arr[mid] < target: + lo = mid + 1 + else: + hi = mid + return lo + + def upper_bound(self, arr, target, lo, hi): + while lo < hi: + mid = (lo + hi) // 2 + if arr[mid] <= target: + lo = mid + 1 + else: + hi = mid + return lo diff --git a/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.rb b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.rb new file mode 100644 index 00000000..4704ab7f --- /dev/null +++ b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.rb @@ -0,0 +1,45 @@ +# @param {Integer[]} nums +# @return {Integer} +def ways_to_split(nums) + mod = 10**9 + 7 + n = nums.length + prefix = Array.new(n) + prefix[0] = nums[0] + + (1...n).each do |i| + prefix[i] = prefix[i - 1] + nums[i] + end + + res = 0 + (0...(n - 2)).each do |i| + left = prefix[i] + j = lower_bound(prefix, 2 * left, i + 1, n - 1) + k = upper_bound(prefix, (prefix[-1] + left) / 2, j, n - 1) + res = (res + [k - j, 0].max) % mod if j < k + end + res +end + +def lower_bound(arr, target, lo, hi) + while lo < hi + mid = (lo + hi) / 2 + if arr[mid] < target + lo = mid + 1 + else + hi = mid + end + end + lo +end + +def upper_bound(arr, target, lo, hi) + while lo < hi + mid = (lo + hi) / 2 + if arr[mid] <= target + lo = mid + 1 + else + hi = mid + end + end + lo +end diff --git a/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.rs b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.rs new file mode 100644 index 00000000..a074753e --- /dev/null +++ b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.rs @@ -0,0 +1,51 @@ +impl Solution { + pub fn ways_to_split(nums: Vec) -> i32 { + const MOD: i64 = 1_000_000_007; + let n = nums.len(); + let mut prefix = vec![0i64; n]; + prefix[0] = nums[0] as i64; + + for i in 1..n { + prefix[i] = prefix[i - 1] + nums[i] as i64; + } + + let mut res: i64 = 0; + for i in 0..(n - 2) { + let left = prefix[i]; + let j = Self::lower_bound(&prefix, 2 * left, i + 1, n - 1); + let k = Self::upper_bound(&prefix, (prefix[n - 1] + left) / 2, j, n - 1); + if j < k { + res = (res + (k - j) as i64) % MOD; + } + } + res as i32 + } + + fn lower_bound(arr: &Vec, target: i64, lo: usize, hi: usize) -> usize { + let mut l = lo; + let mut h = hi; + while l < h { + let mid = (l + h) / 2; + if arr[mid] < target { + l = mid + 1; + } else { + h = mid; + } + } + l + } + + fn upper_bound(arr: &Vec, target: i64, lo: usize, hi: usize) -> usize { + let mut l = lo; + let mut h = hi; + while l < h { + let mid = (l + h) / 2; + if arr[mid] <= target { + l = mid + 1; + } else { + h = mid; + } + } + l + } +} diff --git a/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.swift b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.swift new file mode 100644 index 00000000..2db12282 --- /dev/null +++ b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.swift @@ -0,0 +1,49 @@ +class Solution { + func waysToSplit(_ nums: [Int]) -> Int { + let MOD = 1_000_000_007 + let n = nums.count + var prefix = [Int](repeating: 0, count: n) + prefix[0] = nums[0] + + for i in 1.. Int { + var l = lo, h = hi + while l < h { + let mid = (l + h) / 2 + if arr[mid] < target { + l = mid + 1 + } else { + h = mid + } + } + return l + } + + private func upperBound(_ arr: [Int], _ target: Int, _ lo: Int, _ hi: Int) -> Int { + var l = lo, h = hi + while l < h { + let mid = (l + h) / 2 + if arr[mid] <= target { + l = mid + 1 + } else { + h = mid + } + } + return l + } +} diff --git a/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.ts b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.ts new file mode 100644 index 00000000..835409c8 --- /dev/null +++ b/tests/1501-2000/1712. ways-to-split-array-into-three-subarrays/sol.ts @@ -0,0 +1,64 @@ +function waysToSplit(nums: number[]): number { + const MOD = 1000000007; + const n = nums.length; + const prefix: number[] = new Array(n); + prefix[0] = nums[0]; + + for (let i = 1; i < n; i++) { + prefix[i] = prefix[i - 1] + nums[i]; + } + + let res = 0; + for (let i = 0; i < n - 2; i++) { + const left = prefix[i]; + const j = lowerBound(prefix, 2 * left, i + 1, n - 1); + const k = upperBound( + prefix, + Math.floor((prefix[n - 1] + left) / 2), + j, + n - 1, + ); + if (j < k) { + res = (res + (k - j)) % MOD; + } + } + return res; +} + +function lowerBound( + arr: number[], + target: number, + lo: number, + hi: number, +): number { + let l = lo, + h = hi; + while (l < h) { + const mid = Math.floor((l + h) / 2); + if (arr[mid] < target) { + l = mid + 1; + } else { + h = mid; + } + } + return l; +} + +function upperBound( + arr: number[], + target: number, + lo: number, + hi: number, +): number { + let l = lo, + h = hi; + while (l < h) { + const mid = Math.floor((l + h) / 2); + if (arr[mid] <= target) { + l = mid + 1; + } else { + h = mid; + } + } + return l; +} diff --git a/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/manifest.yaml b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/manifest.yaml new file mode 100644 index 00000000..d2511021 --- /dev/null +++ b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/manifest.yaml @@ -0,0 +1,312 @@ +entry: + id: 1713 + title: "minimum-operations-to-make-a-subsequence" + params: + target: + type: array + items: + type: int + arr: + type: array + items: + type: int + call: + cpp: "Solution().minOperations({target}, {arr})" + rust: "Solution::min_operations({target}, {arr})" + python3: "Solution().minOperations({target}, {arr})" + python2: "Solution().minOperations({target}, {arr})" + ruby: "min_operations({target}, {arr})" + java: "new Solution().minOperations({target}, {arr})" + csharp: "new Solution().MinOperations({target}, {arr})" + kotlin: "Solution().minOperations({target}, {arr})" + go: "minOperations({target}, {arr})" + dart: "Solution().minOperations({target}, {arr})" + swift: "Solution().minOperations({target}, {arr})" + typescript: "minOperations({target}, {arr})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().check(target, arr, {result})" + checker: | + from bisect import bisect_left + class Checker: + def check(self, target, arr, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + pos = {value: i for i, value in enumerate(target)} + lis = [] + for value in arr: + if value in pos: + x = pos[value] + i = bisect_left(lis, x) + if i == len(lis): + lis.append(x) + else: + lis[i] = x + return result == len(target) - len(lis) + +seed: 1713 + +tests: + - name: example-one + in: + target: [5, 1, 3] + arr: [9, 4, 2, 3, 4] + out: 2 + - name: example-two + in: + target: [6, 4, 8, 1, 3, 2] + arr: [4, 7, 6, 2, 3, 8, 6, 1] + out: 3 + - name: exact-target + in: + target: [1, 2, 3, 4] + arr: [1, 2, 3, 4] + out: 0 + - name: no-target-values + in: + target: [1, 2, 3] + arr: [4, 5, 6, 7] + out: 3 + - name: one-missing + in: + target: [1, 2, 3, 4] + arr: [1, 2, 4] + out: 1 + - name: reverse-order + in: + target: [1, 2, 3, 4, 5] + arr: [5, 4, 3, 2, 1] + out: 4 + - name: target-one-present + in: + target: [42] + arr: [7, 42, 7] + out: 0 + - name: target-one-absent + in: + target: [42] + arr: [7, 8, 9] + out: 1 + - name: duplicate-match + in: + target: [1, 2, 3] + arr: [1, 1, 1, 2, 2, 3, 3] + out: 0 + - name: duplicate-breaks-order + in: + target: [1, 2, 3] + arr: [3, 3, 2, 2, 1, 1] + out: 2 + - name: alternating-noise + in: + target: [10, 20, 30, 40, 50] + arr: [99, 10, 98, 30, 97, 50] + out: 2 + - name: subsequence-with-gaps + in: + target: [8, 6, 7, 5, 3, 0, 9] + arr: [8, 100, 6, 101, 7, 5, 3, 0, 9] + out: 0 + - name: one-increasing-chain + in: + target: [2, 4, 6, 8, 10] + arr: [2, 6, 10] + out: 2 + - name: best-chain-middle + in: + target: [1, 2, 3, 4, 5, 6] + arr: [2, 3, 4, 5] + out: 2 + - name: large-values + in: + target: [1, 1000000000, 999999999] + arr: [1000000000, 1, 999999999] + out: 1 + - name: large-values-in-order + in: + target: [999999997, 999999998, 999999999, 1000000000] + arr: [999999997, 999999998, 999999999, 1000000000] + out: 0 + - name: all-but-first + in: + target: [4, 8, 15, 16, 23, 42] + arr: [8, 15, 16, 23, 42] + out: 1 + - name: all-but-last + in: + target: [4, 8, 15, 16, 23, 42] + arr: [4, 8, 15, 16, 23] + out: 1 + - name: interleaved-repeats + in: + target: [1, 3, 5, 7] + arr: [1, 5, 3, 7, 5, 1] + out: 1 + - name: sparse-values + in: + target: [100, 200, 300, 400] + arr: [200, 400, 100, 300] + out: 2 + - name: repeated-single-match + in: + target: [2, 4, 6, 8] + arr: [6, 6, 6, 6] + out: 3 + - name: matching-prefix + in: + target: [3, 1, 4, 2, 5] + arr: [3, 1, 4, 5] + out: 1 + - name: matching-suffix + in: + target: [3, 1, 4, 2, 5] + arr: [1, 4, 2, 5] + out: 1 + - name: target-order-permutation + in: + target: [7, 2, 9, 1, 6] + arr: [2, 9, 1, 6] + out: 1 + - name: noisy-permutation + in: + target: [7, 2, 9, 1, 6] + arr: [6, 50, 2, 9, 60, 7, 1] + out: 2 + - name: repeated-noise + in: + target: [11, 22, 33, 44] + arr: [0, 11, 0, 22, 0, 33, 0, 44, 0] + out: 0 + - name: two-targets + in: + target: [10, 20, 30, 40] + arr: [20, 40] + out: 2 + - name: two-targets-wrong-order + in: + target: [10, 20, 30, 40] + arr: [40, 20] + out: 3 + - name: long-small-domain + in: + target: [1, 2, 3, 4, 5, 6, 7, 8] + arr: [8, 1, 8, 2, 8, 3, 8, 4, 8, 5, 8, 6, 8, 7, 8] + out: 0 + - name: singleton-array + in: + target: [9] + arr: [9] + out: 0 + - name: singleton-miss + in: + target: [9] + arr: [1] + out: 1 + - name: generated-distinct-medium + in: + target: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: true + elemType: "int" + arr: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + elemType: "int" + - name: generated-distinct-large + in: + target: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: true + elemType: "int" + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + elemType: "int" + - name: generated-distinct-large-two + in: + target: + gen: "array" + len: 99999 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: true + elemType: "int" + arr: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + elemType: "int" + - name: generated-small-random + in: + target: + gen: "array" + len: 50 + of: + gen: "int" + min: 1 + max: 1000 + distinct: true + elemType: "int" + arr: + gen: "array" + len: 80 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + elemType: "int" + - name: generated-small-random-two + in: + target: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 10000 + distinct: true + elemType: "int" + arr: + gen: "array" + len: 200 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + elemType: "int" diff --git a/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.cpp b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.cpp new file mode 100644 index 00000000..e2ab386c --- /dev/null +++ b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int minOperations(vector& target, vector& arr) { + unordered_map targetIndexMap; + for (int i = 0; i < target.size(); i++) { + targetIndexMap[target[i]] = i; + } + + vector transformedArr; + for (int num : arr) { + if (targetIndexMap.count(num)) { + transformedArr.push_back(targetIndexMap[num]); + } + } + + vector lis; + for (int index : transformedArr) { + auto it = lower_bound(lis.begin(), lis.end(), index); + if (it == lis.end()) { + lis.push_back(index); + } else { + *it = index; + } + } + + return target.size() - lis.size(); + } +}; diff --git a/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.cs b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.cs new file mode 100644 index 00000000..9bd9afae --- /dev/null +++ b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.cs @@ -0,0 +1,28 @@ +public class Solution { + public int MinOperations(int[] target, int[] arr) { + var targetIndexMap = new Dictionary(); + for (int i = 0; i < target.Length; i++) { + targetIndexMap[target[i]] = i; + } + + var transformedArr = new List(); + foreach (int num in arr) { + if (targetIndexMap.ContainsKey(num)) { + transformedArr.Add(targetIndexMap[num]); + } + } + + var lis = new List(); + foreach (int index in transformedArr) { + int pos = lis.BinarySearch(index); + if (pos < 0) pos = ~pos; + if (pos == lis.Count) { + lis.Add(index); + } else { + lis[pos] = index; + } + } + + return target.Length - lis.Count; + } +} diff --git a/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.dart b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.dart new file mode 100644 index 00000000..42eb008d --- /dev/null +++ b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.dart @@ -0,0 +1,40 @@ +class Solution { + int minOperations(List target, List arr) { + Map targetIndexMap = {}; + for (int i = 0; i < target.length; i++) { + targetIndexMap[target[i]] = i; + } + + List transformedArr = []; + for (int num in arr) { + if (targetIndexMap.containsKey(num)) { + transformedArr.add(targetIndexMap[num]!); + } + } + + List lis = []; + for (int index in transformedArr) { + int pos = lowerBound(lis, index); + if (pos == lis.length) { + lis.add(index); + } else { + lis[pos] = index; + } + } + + return target.length - lis.length; + } + + int lowerBound(List list, int target) { + int low = 0, high = list.length; + while (low < high) { + int mid = (low + high) ~/ 2; + if (list[mid] < target) { + low = mid + 1; + } else { + high = mid; + } + } + return low; + } +} diff --git a/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.go b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.go new file mode 100644 index 00000000..ebfe36c4 --- /dev/null +++ b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.go @@ -0,0 +1,25 @@ +func minOperations(target []int, arr []int) int { + targetIndexMap := make(map[int]int) + for i, num := range target { + targetIndexMap[num] = i + } + + transformedArr := []int{} + for _, num := range arr { + if idx, ok := targetIndexMap[num]; ok { + transformedArr = append(transformedArr, idx) + } + } + + lis := []int{} + for _, index := range transformedArr { + pos := sort.SearchInts(lis, index) + if pos == len(lis) { + lis = append(lis, index) + } else { + lis[pos] = index + } + } + + return len(target) - len(lis) +} diff --git a/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.java b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.java new file mode 100644 index 00000000..3b000b93 --- /dev/null +++ b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.java @@ -0,0 +1,32 @@ +import java.util.*; + +class Solution { + public int minOperations(int[] target, int[] arr) { + Map targetIndexMap = new HashMap<>(); + for (int i = 0; i < target.length; i++) { + targetIndexMap.put(target[i], i); + } + + List transformedArr = new ArrayList<>(); + for (int num : arr) { + if (targetIndexMap.containsKey(num)) { + transformedArr.add(targetIndexMap.get(num)); + } + } + + List lis = new ArrayList<>(); + for (int index : transformedArr) { + int pos = Collections.binarySearch(lis, index); + if (pos < 0) { + pos = -pos - 1; + } + if (pos == lis.size()) { + lis.add(index); + } else { + lis.set(pos, index); + } + } + + return target.length - lis.size(); + } +} diff --git a/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.kt b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.kt new file mode 100644 index 00000000..4ddc64ce --- /dev/null +++ b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun minOperations(target: IntArray, arr: IntArray): Int { + val targetIndexMap = target.withIndex().associate { it.value to it.index } + + val transformedArr = mutableListOf() + for (num in arr) { + if (targetIndexMap.containsKey(num)) { + transformedArr.add(targetIndexMap[num]!!) + } + } + + val lis = mutableListOf() + for (index in transformedArr) { + var pos = lis.binarySearch(index) + if (pos < 0) pos = -pos - 1 + if (pos == lis.size) { + lis.add(index) + } else { + lis[pos] = index + } + } + + return target.size - lis.size + } +} diff --git a/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.py b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.py new file mode 100644 index 00000000..a00e7355 --- /dev/null +++ b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.py @@ -0,0 +1,24 @@ +from bisect import bisect_left + + +class Solution: + def minOperations(self, target: list[int], arr: list[int]) -> int: + target_index_map = {num: i for i, num in enumerate(target)} + + # Create a list of indices from arr that exist in target + transformed_arr = [] + for num in arr: + if num in target_index_map: + transformed_arr.append(target_index_map[num]) + + # Find the length of the longest increasing subsequence (LIS) + lis = [] + for index in transformed_arr: + pos = bisect_left(lis, index) + if pos == len(lis): + lis.append(index) + else: + lis[pos] = index + + # The number of operations is the difference + return len(target) - len(lis) diff --git a/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.py2 b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.py2 new file mode 100644 index 00000000..c35222ca --- /dev/null +++ b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def minOperations(self, target, arr): + """ + :type target: List[int] + :type arr: List[int] + :rtype: int + """ + target_index_map = {num: i for i, num in enumerate(target)} + + transformed_arr = [] + for num in arr: + if num in target_index_map: + transformed_arr.append(target_index_map[num]) + + lis = [] + for index in transformed_arr: + pos = bisect_left(lis, index) + if pos == len(lis): + lis.append(index) + else: + lis[pos] = index + + return len(target) - len(lis) diff --git a/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.rb b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.rb new file mode 100644 index 00000000..897bf377 --- /dev/null +++ b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.rb @@ -0,0 +1,28 @@ +# @param {Integer[]} target +# @param {Integer[]} arr +# @return {Integer} +def min_operations(target, arr) + target_index_map = {} + target.each_with_index do |num, i| + target_index_map[num] = i + end + + transformed_arr = [] + arr.each do |num| + if target_index_map.key?(num) + transformed_arr << target_index_map[num] + end + end + + lis = [] + transformed_arr.each do |index| + pos = lis.bsearch_index { |x| x >= index } || lis.length + if pos == lis.length + lis << index + else + lis[pos] = index + end + end + + target.length - lis.length +end diff --git a/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.rs b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.rs new file mode 100644 index 00000000..fdd6a8bd --- /dev/null +++ b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn min_operations(target: Vec, arr: Vec) -> i32 { + let target_index_map: std::collections::HashMap = target.iter().enumerate().map(|(i, &num)| (num, i)).collect(); + + let transformed_arr: Vec = arr.iter().filter_map(|num| target_index_map.get(num).copied()).collect(); + + let mut lis: Vec = Vec::new(); + for index in transformed_arr { + let pos = lis.binary_search(&index).unwrap_or_else(|p| p); + if pos == lis.len() { + lis.push(index); + } else { + lis[pos] = index; + } + } + + (target.len() - lis.len()) as i32 + } +} diff --git a/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.swift b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.swift new file mode 100644 index 00000000..09055b29 --- /dev/null +++ b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.swift @@ -0,0 +1,33 @@ +class Solution { + func minOperations(_ target: [Int], _ arr: [Int]) -> Int { + var targetIndexMap: [Int: Int] = [:] + for (i, num) in target.enumerated() { + targetIndexMap[num] = i + } + + var transformedArr: [Int] = [] + for num in arr { + if let idx = targetIndexMap[num] { + transformedArr.append(idx) + } + } + + var lis: [Int] = [] + for index in transformedArr { + var low = 0 + var high = lis.count + while low < high { + let mid = (low + high) / 2 + if lis[mid] < index { low = mid + 1 } else { high = mid } + } + let pos = low + if pos == lis.count { + lis.append(index) + } else { + lis[pos] = index + } + } + + return target.count - lis.count + } +} diff --git a/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.ts b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.ts new file mode 100644 index 00000000..4fe8a023 --- /dev/null +++ b/tests/1501-2000/1713. minimum-operations-to-make-a-subsequence/sol.ts @@ -0,0 +1,35 @@ +function minOperations(target: number[], arr: number[]): number { + const targetIndexMap: Map = new Map(); + target.forEach((num, i) => targetIndexMap.set(num, i)); + + const transformedArr: number[] = []; + for (const num of arr) { + if (targetIndexMap.has(num)) { + transformedArr.push(targetIndexMap.get(num)!); + } + } + + const lis: number[] = []; + for (const index of transformedArr) { + let pos = 0; + let low = 0, + high = lis.length; + while (low < high) { + const mid = (low + high) >> 1; + if (lis[mid] < index) { + low = mid + 1; + } else { + high = mid; + } + } + pos = low; + + if (pos === lis.length) { + lis.push(index); + } else { + lis[pos] = index; + } + } + + return target.length - lis.length; +} diff --git a/tests/1501-2000/1716. calculate-money-in-leetcode-bank/manifest.yaml b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/manifest.yaml new file mode 100644 index 00000000..e02411ab --- /dev/null +++ b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/manifest.yaml @@ -0,0 +1,200 @@ +entry: + id: 1716 + title: calculate-money-in-leetcode-bank + params: + n: + type: int + call: + cpp: "Solution().totalMoney({n})" + rust: "Solution::total_money({n})" + python3: "Solution().totalMoney({n})" + python2: "Solution().totalMoney({n})" + ruby: "total_money({n})" + java: "new Solution().totalMoney({n})" + csharp: "new Solution().TotalMoney({n})" + kotlin: "Solution().totalMoney({n})" + go: "totalMoney({n})" + dart: "Solution().totalMoney({n})" + swift: "Solution().totalMoney({n})" + typescript: "totalMoney({n})" + +judge: + type: exact + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().totalMoney(n, {result})" + checker: | + class Checker: + def totalMoney(self, n, result): + q, r = divmod(n, 7) + expected = 28 * q + 7 * q * (q - 1) // 2 + expected += r * (q + 1) + r * (r - 1) // 2 + return result == expected + +seed: 1716 + +tests: + - name: first-day + in: + n: 1 + out: 1 + - name: second-day + in: + n: 2 + out: 3 + - name: first-week + in: + n: 7 + out: 28 + - name: first-day-second-week + in: + n: 8 + out: 30 + - name: example-four + in: + n: 4 + out: 10 + - name: example-ten + in: + n: 10 + out: 37 + - name: example-twenty + in: + n: 20 + out: 96 + - name: two-weeks + in: + n: 14 + out: 63 + - name: three-weeks + in: + n: 21 + out: 105 + - name: week-boundary-six + in: + n: 6 + out: 21 + - name: week-boundary-thirteen + in: + n: 13 + out: 55 + - name: week-boundary-fifteen + in: + n: 15 + out: 66 + - name: partial-week-three + in: + n: 3 + out: 6 + - name: partial-week-five + in: + n: 5 + out: 15 + - name: partial-week-nine + in: + n: 9 + out: 33 + - name: partial-week-sixteen + in: + n: 16 + out: 70 + - name: four-weeks-plus-one + in: + n: 29 + out: 159 + - name: five-weeks + in: + n: 35 + out: 210 + - name: six-weeks-plus-four + in: + n: 46 + out: 307 + - name: ten-weeks + in: + n: 70 + out: 595 + - name: ten-weeks-plus-one + in: + n: 71 + out: 606 + - name: uneven-mid + in: + n: 99 + out: 1044 + - name: hundred-days + in: + n: 100 + out: 1060 + - name: hundred-one-days + in: + n: 101 + out: 1077 + - name: long-prefix + in: + n: 256 + out: 5572 + - name: three-hundred-days + in: + n: 300 + out: 7476 + - name: five-hundred-days + in: + n: 500 + out: 19602 + - name: five-hundred-one-days + in: + n: 501 + out: 19677 + - name: seven-hundred-days + in: + n: 700 + out: 37450 + - name: nine-hundred-ninety-nine + in: + n: 999 + out: 74778 + - name: maximum-days + in: + n: 1000 + out: 74926 + - name: generated-small + in: + n: + gen: int + min: 1 + max: 30 + seed: 171601 + - name: generated-week-spans + in: + n: + gen: int + min: 31 + max: 250 + seed: 171602 + - name: generated-mid-range + in: + n: + gen: int + min: 251 + max: 600 + seed: 171603 + - name: generated-large-range + in: + n: + gen: int + min: 601 + max: 999 + seed: 171604 + - name: generated-maximum-range + in: + n: + gen: int + min: 950 + max: 1000 + seed: 171605 diff --git a/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.cpp b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.cpp new file mode 100644 index 00000000..ddfb1157 --- /dev/null +++ b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int totalMoney(int n) { + int q = n / 7; + int r = n % 7; + return arithmeticProgression(28, 28+(q-1)*7, q) + arithmeticProgression(q+1, q+r, r); + } +private: + int arithmeticProgression(int leading, int last, int terms) { + return (leading+last)*terms/2; + } +}; diff --git a/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.cs b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.cs new file mode 100644 index 00000000..4d847185 --- /dev/null +++ b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.cs @@ -0,0 +1,10 @@ +public class Solution { + public int TotalMoney(int n) { + int q = n / 7; + int r = n % 7; + return ArithmeticProgression(28, 28+(q-1)*7, q) + ArithmeticProgression(q+1, q+r, r); + } + private int ArithmeticProgression(int leading, int last, int terms) { + return (leading+last)*terms/2; + } +} diff --git a/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.dart b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.dart new file mode 100644 index 00000000..bbad8df0 --- /dev/null +++ b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.dart @@ -0,0 +1,10 @@ +class Solution { + int totalMoney(int n) { + int q = n ~/ 7; + int r = n % 7; + return arithmeticProgression(28, 28+(q-1)*7, q) + arithmeticProgression(q+1, q+r, r); + } + int arithmeticProgression(int leading, int last, int terms) { + return (leading+last)*terms ~/ 2; + } +} diff --git a/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.go b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.go new file mode 100644 index 00000000..050f20bf --- /dev/null +++ b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.go @@ -0,0 +1,9 @@ +func totalMoney(n int) int { + q := n / 7 + r := n % 7 + return arithmeticProgression(28, 28+(q-1)*7, q) + arithmeticProgression(q+1, q+r, r) +} + +func arithmeticProgression(leading, last, terms int) int { + return (leading+last)*terms/2 +} diff --git a/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.java b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.java new file mode 100644 index 00000000..a8b3977d --- /dev/null +++ b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.java @@ -0,0 +1,10 @@ +class Solution { + public int totalMoney(int n) { + int q = n / 7; + int r = n % 7; + return arithmeticProgression(28, 28+(q-1)*7, q) + arithmeticProgression(q+1, q+r, r); + } + private int arithmeticProgression(int leading, int last, int terms) { + return (leading+last)*terms/2; + } +} diff --git a/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.kt b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.kt new file mode 100644 index 00000000..e8bfbacc --- /dev/null +++ b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.kt @@ -0,0 +1,10 @@ +class Solution { + fun totalMoney(n: Int): Int { + val q = n / 7 + val r = n % 7 + return arithmeticProgression(28, 28+(q-1)*7, q) + arithmeticProgression(q+1, q+r, r) + } + private fun arithmeticProgression(leading: Int, last: Int, terms: Int): Int { + return (leading+last)*terms/2 + } +} diff --git a/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.py b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.py new file mode 100644 index 00000000..93bf2742 --- /dev/null +++ b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.py @@ -0,0 +1,9 @@ +class Solution: + def totalMoney(self, n: int) -> int: + def arithmeticProgression(leading, last, terms): + return (leading + last) * terms // 2 + + q, r = divmod(n, 7) + return arithmeticProgression(28, 28 + (q - 1) * 7, q) + arithmeticProgression( + q + 1, q + r, r + ) diff --git a/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.py2 b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.py2 new file mode 100644 index 00000000..22c6b241 --- /dev/null +++ b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.py2 @@ -0,0 +1,10 @@ +class Solution(object): + def totalMoney(self, n): + """ + :type n: int + :rtype: int + """ + def arithmeticProgression(leading, last, terms): + return (leading+last)*terms//2 + q, r= divmod(n, 7) + return arithmeticProgression(28, 28+(q-1)*7, q)+arithmeticProgression(q+1, q+r, r) diff --git a/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.rb b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.rb new file mode 100644 index 00000000..07a596ff --- /dev/null +++ b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.rb @@ -0,0 +1,7 @@ +# @param {Integer} n +# @return {Integer} +def total_money(n) + arithmeticProgression = ->(leading, last, terms) { (leading+last)*terms/2 } + q, r = n.divmod(7) + arithmeticProgression.call(28, 28+(q-1)*7, q) + arithmeticProgression.call(q+1, q+r, r) +end diff --git a/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.rs b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.rs new file mode 100644 index 00000000..07be62d8 --- /dev/null +++ b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.rs @@ -0,0 +1,10 @@ +impl Solution { + pub fn total_money(n: i32) -> i32 { + let q = n / 7; + let r = n % 7; + Self::arithmetic_progression(28, 28+(q-1)*7, q) + Self::arithmetic_progression(q+1, q+r, r) + } + fn arithmetic_progression(leading: i32, last: i32, terms: i32) -> i32 { + (leading+last)*terms/2 + } +} diff --git a/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.swift b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.swift new file mode 100644 index 00000000..a21ce727 --- /dev/null +++ b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.swift @@ -0,0 +1,10 @@ +class Solution { + func totalMoney(_ n: Int) -> Int { + let q = n / 7 + let r = n % 7 + return arithmeticProgression(28, 28+(q-1)*7, q) + arithmeticProgression(q+1, q+r, r) + } + private func arithmeticProgression(_ leading: Int, _ last: Int, _ terms: Int) -> Int { + return (leading+last)*terms/2 + } +} diff --git a/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.ts b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.ts new file mode 100644 index 00000000..acd2e590 --- /dev/null +++ b/tests/1501-2000/1716. calculate-money-in-leetcode-bank/sol.ts @@ -0,0 +1,16 @@ +function totalMoney(n: number): number { + const q = Math.floor(n / 7); + const r = n % 7; + return ( + arithmeticProgression(28, 28 + (q - 1) * 7, q) + + arithmeticProgression(q + 1, q + r, r) + ); +} + +function arithmeticProgression( + leading: number, + last: number, + terms: number, +): number { + return ((leading + last) * terms) / 2; +} diff --git a/tests/1501-2000/1717. maximum-score-from-removing-substrings/manifest.yaml b/tests/1501-2000/1717. maximum-score-from-removing-substrings/manifest.yaml new file mode 100644 index 00000000..fc05a7f4 --- /dev/null +++ b/tests/1501-2000/1717. maximum-score-from-removing-substrings/manifest.yaml @@ -0,0 +1,317 @@ +entry: + id: 1717 + title: maximum-score-from-removing-substrings + params: + s: + type: string + x: + type: int + y: + type: int + call: + cpp: "Solution().maximumGain({s}, {x}, {y})" + rust: "Solution::maximum_gain({s}, {x}, {y})" + python3: "Solution().maximumGain({s}, {x}, {y})" + python2: "Solution().maximumGain({s}, {x}, {y})" + ruby: "maximum_gain({s}, {x}, {y})" + java: "new Solution().maximumGain({s}, {x}, {y})" + csharp: "new Solution().MaximumGain({s}, {x}, {y})" + kotlin: "Solution().maximumGain({s}, {x}, {y})" + go: "maximumGain({s}, {x}, {y})" + dart: "Solution().maximumGain({s}, {x}, {y})" + swift: "Solution().maximumGain({s}, {x}, {y})" + typescript: "maximumGain({s}, {x}, {y})" + +judge: + type: exact + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maximumGain(s, x, y, {result})" + checker: | + class Checker: + def maximumGain(self, s, x, y, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if x >= y: + first, second = 'a', 'b' + high, low = x, y + else: + first, second = 'b', 'a' + high, low = y, x + pending_first = 0 + pending_second = 0 + expected = 0 + for ch in s: + if ch == first: + pending_first += 1 + elif ch == second: + if pending_first: + pending_first -= 1 + expected += high + else: + pending_second += 1 + else: + expected += min(pending_first, pending_second) * low + pending_first = 0 + pending_second = 0 + expected += min(pending_first, pending_second) * low + return result == expected + +seed: 1717 + +tests: + - name: example-one + in: + s: "cdbcbbaaabab" + x: 4 + y: 5 + out: 19 + - name: example-two + in: + s: "aabbaaxybbaabb" + x: 5 + y: 4 + out: 20 + - name: single-a + in: + s: "a" + x: 1 + y: 1 + out: 0 + - name: single-other + in: + s: "z" + x: 10000 + y: 1 + out: 0 + - name: one-ab + in: + s: "ab" + x: 7 + y: 3 + out: 7 + - name: one-ba + in: + s: "ba" + x: 7 + y: 3 + out: 3 + - name: reverse-price + in: + s: "ab" + x: 3 + y: 7 + out: 3 + - name: alternating + in: + s: "abababab" + x: 4 + y: 9 + out: 31 + - name: reverse-alternating + in: + s: "babababa" + x: 4 + y: 9 + out: 36 + - name: all-a + in: + s: "aaaaaaaaaa" + x: 10 + y: 20 + out: 0 + - name: all-b + in: + s: "bbbbbbbbbb" + x: 10 + y: 20 + out: 0 + - name: all-separators + in: + s: "cccccccc" + x: 1 + y: 10000 + out: 0 + - name: separated-pairs + in: + s: "abxabxab" + x: 8 + y: 2 + out: 24 + - name: separated-reverse-pairs + in: + s: "baxybaxyba" + x: 8 + y: 2 + out: 6 + - name: mixed-blocks + in: + s: "aabbababbaba" + x: 10 + y: 1 + out: 51 + - name: equal-prices + in: + s: "bbaababbab" + x: 6 + y: 6 + out: 24 + - name: max-prices + in: + s: "abababababab" + x: 10000 + y: 10000 + out: 60000 + - name: low-prices + in: + s: "bbaabb" + x: 1 + y: 1 + out: 2 + - name: nested-ab + in: + s: "aaabbb" + x: 9 + y: 4 + out: 27 + - name: nested-ba + in: + s: "bbbaaa" + x: 9 + y: 4 + out: 12 + - name: crossover + in: + s: "babababxabab" + x: 11 + y: 2 + out: 55 + - name: crossover-reverse + in: + s: "abababaxbaba" + x: 2 + y: 11 + out: 55 + - name: noise-between + in: + s: "acbdabcdbdab" + x: 13 + y: 5 + out: 26 + - name: long-run + in: + s: "aaaaabbbbbababab" + x: 17 + y: 19 + out: 142 + - name: digit-noise + in: + s: "xyabuvwbayzab" + x: 4 + y: 12 + out: 20 + - name: minimum-score + in: + s: "zzabzzba" + x: 1 + y: 1 + out: 2 + - name: maximum-score + in: + s: "ababab" + x: 10000 + y: 1 + out: 30000 + - name: imbalance-left + in: + s: "aaaaabb" + x: 5 + y: 8 + out: 10 + - name: imbalance-right + in: + s: "bbbba" + x: 5 + y: 8 + out: 8 + - name: repeated-separators + in: + s: "abcccbaccab" + x: 7 + y: 11 + out: 25 + - name: generator-balanced + in: + s: + gen: "str" + len: 100000 + alphabet: "abc" + x: + gen: "int" + min: 1 + max: 10000 + y: + gen: "int" + min: 1 + max: 10000 + - name: generator-binary + in: + s: + gen: "str" + len: 99999 + alphabet: "ab" + x: + gen: "int" + min: 1 + max: 10000 + y: + gen: "int" + min: 1 + max: 10000 + - name: generator-separators + in: + s: + gen: "str" + len: 100000 + alphabet: "abxyz" + x: + gen: "int" + min: 1 + max: 10000 + y: + gen: "int" + min: 1 + max: 10000 + - name: generator-heavy-a + in: + s: + gen: "str" + len: 75000 + alphabet: "aaabc" + x: + gen: "int" + min: 1 + max: 10000 + y: + gen: "int" + min: 1 + max: 10000 + - name: generator-heavy-b + in: + s: + gen: "str" + len: 75001 + alphabet: "bbbac" + x: + gen: "int" + min: 1 + max: 10000 + y: + gen: "int" + min: 1 + max: 10000 diff --git a/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.cpp b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.cpp new file mode 100644 index 00000000..c093e433 --- /dev/null +++ b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int maximumGain(string s, int x, int y) { + int score = 0; + char ch1 = 'a', ch2 = 'b'; + int cnt1 = 0, cnt2 = 0; + + if (x < y) { + int temp = x; + x = y; + y = temp; + ch1 = 'b'; + ch2 = 'a'; + } + + for (char ch : s) { + if (ch == ch1) { + cnt1++; + } else if (ch == ch2) { + if (cnt1 > 0) { + cnt1--; + score += x; + } else { + cnt2++; + } + } else { + score += min(cnt1, cnt2) * y; + cnt1 = 0; + cnt2 = 0; + } + } + + if (cnt1 != 0) { + score += min(cnt1, cnt2) * y; + } + + return score; + } +}; diff --git a/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.cs b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.cs new file mode 100644 index 00000000..ad8270e5 --- /dev/null +++ b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.cs @@ -0,0 +1,38 @@ +public class Solution { + public int MaximumGain(string s, int x, int y) { + int score = 0; + char ch1 = 'a', ch2 = 'b'; + int cnt1 = 0, cnt2 = 0; + + if (x < y) { + int temp = x; + x = y; + y = temp; + ch1 = 'b'; + ch2 = 'a'; + } + + foreach (char ch in s) { + if (ch == ch1) { + cnt1++; + } else if (ch == ch2) { + if (cnt1 > 0) { + cnt1--; + score += x; + } else { + cnt2++; + } + } else { + score += Math.Min(cnt1, cnt2) * y; + cnt1 = 0; + cnt2 = 0; + } + } + + if (cnt1 != 0) { + score += Math.Min(cnt1, cnt2) * y; + } + + return score; + } +} diff --git a/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.dart b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.dart new file mode 100644 index 00000000..24781fc2 --- /dev/null +++ b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.dart @@ -0,0 +1,39 @@ +class Solution { + int maximumGain(String s, int x, int y) { + int score = 0; + String ch1 = 'a', ch2 = 'b'; + int cnt1 = 0, cnt2 = 0; + + if (x < y) { + int temp = x; + x = y; + y = temp; + ch1 = 'b'; + ch2 = 'a'; + } + + for (int i = 0; i < s.length; i++) { + String ch = s[i]; + if (ch == ch1) { + cnt1++; + } else if (ch == ch2) { + if (cnt1 > 0) { + cnt1--; + score += x; + } else { + cnt2++; + } + } else { + score += (cnt1 < cnt2 ? cnt1 : cnt2) * y; + cnt1 = 0; + cnt2 = 0; + } + } + + if (cnt1 != 0) { + score += (cnt1 < cnt2 ? cnt1 : cnt2) * y; + } + + return score; + } +} diff --git a/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.go b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.go new file mode 100644 index 00000000..fbefe46b --- /dev/null +++ b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.go @@ -0,0 +1,40 @@ +func maximumGain(s string, x int, y int) int { + score := 0 + ch1, ch2 := byte('a'), byte('b') + cnt1, cnt2 := 0, 0 + + if x < y { + x, y = y, x + ch1, ch2 = 'b', 'a' + } + + for i := 0; i < len(s); i++ { + ch := s[i] + if ch == ch1 { + cnt1++ + } else if ch == ch2 { + if cnt1 > 0 { + cnt1-- + score += x + } else { + cnt2++ + } + } else { + score += min(cnt1, cnt2) * y + cnt1, cnt2 = 0, 0 + } + } + + if cnt1 != 0 { + score += min(cnt1, cnt2) * y + } + + return score +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} diff --git a/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.java b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.java new file mode 100644 index 00000000..251665b6 --- /dev/null +++ b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.java @@ -0,0 +1,38 @@ +class Solution { + public int maximumGain(String s, int x, int y) { + int score = 0; + char ch1 = 'a', ch2 = 'b'; + int cnt1 = 0, cnt2 = 0; + + if (x < y) { + int temp = x; + x = y; + y = temp; + ch1 = 'b'; + ch2 = 'a'; + } + + for (char ch : s.toCharArray()) { + if (ch == ch1) { + cnt1++; + } else if (ch == ch2) { + if (cnt1 > 0) { + cnt1--; + score += x; + } else { + cnt2++; + } + } else { + score += Math.min(cnt1, cnt2) * y; + cnt1 = 0; + cnt2 = 0; + } + } + + if (cnt1 != 0) { + score += Math.min(cnt1, cnt2) * y; + } + + return score; + } +} diff --git a/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.kt b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.kt new file mode 100644 index 00000000..2933a9af --- /dev/null +++ b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.kt @@ -0,0 +1,42 @@ +class Solution { + fun maximumGain(s: String, x: Int, y: Int): Int { + var score = 0 + var ch1 = 'a' + var ch2 = 'b' + var cnt1 = 0 + var cnt2 = 0 + var xx = x + var yy = y + + if (xx < yy) { + val temp = xx + xx = yy + yy = temp + ch1 = 'b' + ch2 = 'a' + } + + for (ch in s) { + if (ch == ch1) { + cnt1++ + } else if (ch == ch2) { + if (cnt1 > 0) { + cnt1-- + score += xx + } else { + cnt2++ + } + } else { + score += Math.min(cnt1, cnt2) * yy + cnt1 = 0 + cnt2 = 0 + } + } + + if (cnt1 != 0) { + score += Math.min(cnt1, cnt2) * yy + } + + return score + } +} diff --git a/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.py b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.py new file mode 100644 index 00000000..b0c43a52 --- /dev/null +++ b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.py @@ -0,0 +1,27 @@ +class Solution: + def maximumGain(self, s: str, x: int, y: int) -> int: + score = 0 + ch1, ch2 = "a", "b" + cnt1 = cnt2 = 0 + + if x < y: + x, y = y, x + ch1, ch2 = "b", "a" + + for ch in s: + if ch == ch1: + cnt1 += 1 + elif ch == ch2: + if cnt1 > 0: + cnt1 -= 1 + score += x + else: + cnt2 += 1 + else: + score += min(cnt1, cnt2) * y + cnt1 = cnt2 = 0 + + if cnt1 != 0: + score += min(cnt1, cnt2) * y + + return score diff --git a/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.py2 b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.py2 new file mode 100644 index 00000000..2a266432 --- /dev/null +++ b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.py2 @@ -0,0 +1,33 @@ +class Solution(object): + def maximumGain(self, s, x, y): + """ + :type s: str + :type x: int + :type y: int + :rtype: int + """ + score = 0 + ch1, ch2 = 'a', 'b' + cnt1 = cnt2 = 0 + + if x < y: + x, y = y, x + ch1, ch2 = 'b', 'a' + + for ch in s: + if ch == ch1: + cnt1 += 1 + elif ch == ch2: + if cnt1 > 0: + cnt1 -= 1 + score += x + else: + cnt2 += 1 + else: + score += min(cnt1, cnt2) * y + cnt1 = cnt2 = 0 + + if cnt1 != 0: + score += min(cnt1, cnt2) * y + + return score diff --git a/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.rb b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.rb new file mode 100644 index 00000000..d5499135 --- /dev/null +++ b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.rb @@ -0,0 +1,36 @@ +# @param {String} s +# @param {Integer} x +# @param {Integer} y +# @return {Integer} +def maximum_gain(s, x, y) + score = 0 + ch1, ch2 = 'a', 'b' + cnt1 = cnt2 = 0 + + if x < y + x, y = y, x + ch1, ch2 = 'b', 'a' + end + + s.each_char do |ch| + if ch == ch1 + cnt1 += 1 + elsif ch == ch2 + if cnt1 > 0 + cnt1 -= 1 + score += x + else + cnt2 += 1 + end + else + score += [cnt1, cnt2].min * y + cnt1 = cnt2 = 0 + end + end + + if cnt1 != 0 + score += [cnt1, cnt2].min * y + end + + return score +end diff --git a/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.rs b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.rs new file mode 100644 index 00000000..da1f887c --- /dev/null +++ b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.rs @@ -0,0 +1,42 @@ +impl Solution { + pub fn maximum_gain(s: String, x: i32, y: i32) -> i32 { + let mut score = 0; + let mut ch1 = 'a'; + let mut ch2 = 'b'; + let mut cnt1 = 0; + let mut cnt2 = 0; + let mut xx = x; + let mut yy = y; + + if xx < yy { + let temp = xx; + xx = yy; + yy = temp; + ch1 = 'b'; + ch2 = 'a'; + } + + for ch in s.chars() { + if ch == ch1 { + cnt1 += 1; + } else if ch == ch2 { + if cnt1 > 0 { + cnt1 -= 1; + score += xx; + } else { + cnt2 += 1; + } + } else { + score += cnt1.min(cnt2) * yy; + cnt1 = 0; + cnt2 = 0; + } + } + + if cnt1 != 0 { + score += cnt1.min(cnt2) * yy; + } + + return score; + } +} diff --git a/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.swift b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.swift new file mode 100644 index 00000000..b7d4a65f --- /dev/null +++ b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.swift @@ -0,0 +1,42 @@ +class Solution { + func maximumGain(_ s: String, _ x: Int, _ y: Int) -> Int { + var score = 0 + var ch1: Character = "a" + var ch2: Character = "b" + var cnt1 = 0 + var cnt2 = 0 + var xx = x + var yy = y + + if xx < yy { + let temp = xx + xx = yy + yy = temp + ch1 = "b" + ch2 = "a" + } + + for ch in s { + if ch == ch1 { + cnt1 += 1 + } else if ch == ch2 { + if cnt1 > 0 { + cnt1 -= 1 + score += xx + } else { + cnt2 += 1 + } + } else { + score += min(cnt1, cnt2) * yy + cnt1 = 0 + cnt2 = 0 + } + } + + if cnt1 != 0 { + score += min(cnt1, cnt2) * yy + } + + return score + } +} diff --git a/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.ts b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.ts new file mode 100644 index 00000000..ebeb22f3 --- /dev/null +++ b/tests/1501-2000/1717. maximum-score-from-removing-substrings/sol.ts @@ -0,0 +1,38 @@ +function maximumGain(s: string, x: number, y: number): number { + let score = 0; + let ch1: string = "a"; + let ch2: string = "b"; + let cnt1 = 0; + let cnt2 = 0; + + if (x < y) { + let temp = x; + x = y; + y = temp; + ch1 = "b"; + ch2 = "a"; + } + + for (const ch of s) { + if (ch === ch1) { + cnt1++; + } else if (ch === ch2) { + if (cnt1 > 0) { + cnt1--; + score += x; + } else { + cnt2++; + } + } else { + score += Math.min(cnt1, cnt2) * y; + cnt1 = 0; + cnt2 = 0; + } + } + + if (cnt1 !== 0) { + score += Math.min(cnt1, cnt2) * y; + } + + return score; +} diff --git a/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/manifest.yaml b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/manifest.yaml new file mode 100644 index 00000000..647c8a4f --- /dev/null +++ b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/manifest.yaml @@ -0,0 +1,265 @@ +entry: + id: 1718 + title: "construct-the-lexicographically-largest-valid-sequence" + params: + n: + type: int + call: + cpp: "Solution().constructDistancedSequence({n})" + rust: "Solution::construct_distanced_sequence({n})" + python3: "Solution().constructDistancedSequence({n})" + python2: "Solution().constructDistancedSequence({n})" + ruby: "construct_distanced_sequence({n})" + java: "new Solution().constructDistancedSequence({n})" + csharp: "new Solution().ConstructDistancedSequence({n})" + kotlin: "Solution().constructDistancedSequence({n})" + go: "constructDistancedSequence({n})" + dart: "Solution().constructDistancedSequence({n})" + swift: "Solution().constructDistancedSequence({n})" + typescript: "constructDistancedSequence({n})" + +judge: + type: "exact" + +limits: + time_ms: 5000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(n, {result})" + checker: | + class Checker: + def check(self, n, result): + if not isinstance(result, list) or len(result) != 2 * n - 1: + return False + expected_counts = {1: 1} + expected_counts.update({i: 2 for i in range(2, n + 1)}) + counts = {} + for value in result: + if not isinstance(value, int) or value < 1 or value > n: + return False + counts[value] = counts.get(value, 0) + 1 + if counts != expected_counts: + return False + positions = {} + for index, value in enumerate(result): + positions.setdefault(value, []).append(index) + if len(positions[1]) != 1: + return False + for value in range(2, n + 1): + if len(positions[value]) != 2 or positions[value][1] - positions[value][0] != value: + return False + + best = [0] * (2 * n - 1) + used = [False] * (n + 1) + + def search(index): + while index < len(best) and best[index] != 0: + index += 1 + if index == len(best): + return True + for value in range(n, 0, -1): + if used[value]: + continue + if value == 1: + best[index] = 1 + used[1] = True + if search(index + 1): + return True + used[1] = False + best[index] = 0 + elif index + value < len(best) and best[index + value] == 0: + best[index] = value + best[index + value] = value + used[value] = True + if search(index + 1): + return True + used[value] = False + best[index] = 0 + best[index + value] = 0 + return False + + if not search(0): + return False + return result == best + +seed: 1718 + +tests: + - name: minimum-n + in: + n: 2 + - name: example-three + in: + n: 3 + - name: example-five + in: + n: 5 + - name: n-four + in: + n: 4 + - name: n-six + in: + n: 6 + - name: n-seven + in: + n: 7 + - name: n-eight + in: + n: 8 + - name: n-nine + in: + n: 9 + - name: n-ten + in: + n: 10 + - name: n-eleven + in: + n: 11 + - name: n-twelve + in: + n: 12 + - name: n-thirteen + in: + n: 13 + - name: n-fourteen + in: + n: 14 + - name: n-fifteen + in: + n: 15 + - name: n-sixteen + in: + n: 16 + - name: n-seventeen + in: + n: 17 + - name: n-eighteen + in: + n: 18 + - name: n-nineteen + in: + n: 19 + - name: maximum-n + in: + n: 20 + - name: generated-small-a + in: + n: + gen: "int" + min: 2 + max: 5 + seed: 1721 + - name: generated-small-b + in: + n: + gen: "int" + min: 6 + max: 9 + seed: 1722 + - name: generated-medium-a + in: + n: + gen: "int" + min: 10 + max: 13 + seed: 1723 + - name: generated-medium-b + in: + n: + gen: "int" + min: 14 + max: 17 + seed: 1724 + - name: generated-large + in: + n: + gen: "int" + min: 18 + max: 20 + seed: 1725 + - name: generated-singleton-two + in: + n: + gen: "int" + min: 2 + max: 2 + seed: 1731 + - name: generated-singleton-four + in: + n: + gen: "int" + min: 4 + max: 4 + seed: 1732 + - name: generated-singleton-six + in: + n: + gen: "int" + min: 6 + max: 6 + seed: 1733 + - name: generated-singleton-eight + in: + n: + gen: "int" + min: 8 + max: 8 + seed: 1734 + - name: generated-singleton-ten + in: + n: + gen: "int" + min: 10 + max: 10 + seed: 1735 + - name: generated-singleton-twelve + in: + n: + gen: "int" + min: 12 + max: 12 + seed: 1736 + - name: generated-singleton-fourteen + in: + n: + gen: "int" + min: 14 + max: 14 + seed: 1737 + - name: generated-singleton-sixteen + in: + n: + gen: "int" + min: 16 + max: 16 + seed: 1738 + - name: generated-singleton-eighteen + in: + n: + gen: "int" + min: 18 + max: 18 + seed: 1739 + - name: generated-singleton-twenty + in: + n: + gen: "int" + min: 20 + max: 20 + seed: 1740 + - name: generated-full-range-a + in: + n: + gen: "int" + min: 2 + max: 20 + seed: 1741 + - name: generated-full-range-b + in: + n: + gen: "int" + min: 2 + max: 20 + seed: 1742 diff --git a/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.cpp b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.cpp new file mode 100644 index 00000000..d78296bb --- /dev/null +++ b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.cpp @@ -0,0 +1,46 @@ +class Solution { +public: + vector constructDistancedSequence(int n) { + vector result(2 * n - 1, 0); + vector used(n + 1, false); + backtrack(result, used, n, 0); + return result; + } + +private: + bool backtrack(vector& result, vector& used, int n, int index) { + int idx = index; + while (idx < result.size() && result[idx] != 0) { + idx++; + } + if (idx == result.size()) { + return true; + } + + for (int i = n; i >= 1; i--) { + if (used[i]) continue; + + if (i == 1) { + result[idx] = 1; + used[1] = true; + if (backtrack(result, used, n, idx + 1)) { + return true; + } + result[idx] = 0; + used[1] = false; + } else if (idx + i < result.size() && result[idx + i] == 0) { + result[idx] = i; + result[idx + i] = i; + used[i] = true; + if (backtrack(result, used, n, idx + 1)) { + return true; + } + result[idx] = 0; + result[idx + i] = 0; + used[i] = false; + } + } + + return false; + } +}; diff --git a/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.cs b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.cs new file mode 100644 index 00000000..8d58c9aa --- /dev/null +++ b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.cs @@ -0,0 +1,44 @@ +public class Solution { + public int[] ConstructDistancedSequence(int n) { + int[] result = new int[2 * n - 1]; + bool[] used = new bool[n + 1]; + Backtrack(result, used, n, 0); + return result; + } + + private bool Backtrack(int[] result, bool[] used, int n, int index) { + int idx = index; + while (idx < result.Length && result[idx] != 0) { + idx++; + } + if (idx == result.Length) { + return true; + } + + for (int i = n; i >= 1; i--) { + if (used[i]) continue; + + if (i == 1) { + result[idx] = 1; + used[1] = true; + if (Backtrack(result, used, n, idx + 1)) { + return true; + } + result[idx] = 0; + used[1] = false; + } else if (idx + i < result.Length && result[idx + i] == 0) { + result[idx] = i; + result[idx + i] = i; + used[i] = true; + if (Backtrack(result, used, n, idx + 1)) { + return true; + } + result[idx] = 0; + result[idx + i] = 0; + used[i] = false; + } + } + + return false; + } +} diff --git a/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.dart b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.dart new file mode 100644 index 00000000..cd78995e --- /dev/null +++ b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.dart @@ -0,0 +1,38 @@ +class Solution { + List constructDistancedSequence(int n) { + final result = List.filled(2 * n - 1, 0); + final used = List.filled(n + 1, false); + backtrack(result, used, n, 0); + return result; + } + + bool backtrack(List result, List used, int n, int index) { + var idx = index; + while (idx < result.length && result[idx] != 0) { + idx++; + } + if (idx == result.length) return true; + + for (var i = n; i >= 1; i--) { + if (used[i]) continue; + + if (i == 1) { + result[idx] = 1; + used[1] = true; + if (backtrack(result, used, n, idx + 1)) return true; + result[idx] = 0; + used[1] = false; + } else if (idx + i < result.length && result[idx + i] == 0) { + result[idx] = i; + result[idx + i] = i; + used[i] = true; + if (backtrack(result, used, n, idx + 1)) return true; + result[idx] = 0; + result[idx + i] = 0; + used[i] = false; + } + } + + return false; + } +} diff --git a/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.go b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.go new file mode 100644 index 00000000..313172a3 --- /dev/null +++ b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.go @@ -0,0 +1,44 @@ +func constructDistancedSequence(n int) []int { + result := make([]int, 2*n-1) + used := make([]bool, n+1) + backtrack(result, used, n, 0) + return result +} + +func backtrack(result []int, used []bool, n int, index int) bool { + idx := index + for idx < len(result) && result[idx] != 0 { + idx++ + } + if idx == len(result) { + return true + } + + for i := n; i >= 1; i-- { + if used[i] { + continue + } + + if i == 1 { + result[idx] = 1 + used[1] = true + if backtrack(result, used, n, idx+1) { + return true + } + result[idx] = 0 + used[1] = false + } else if idx+i < len(result) && result[idx+i] == 0 { + result[idx] = i + result[idx+i] = i + used[i] = true + if backtrack(result, used, n, idx+1) { + return true + } + result[idx] = 0 + result[idx+i] = 0 + used[i] = false + } + } + + return false +} diff --git a/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.java b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.java new file mode 100644 index 00000000..156a4237 --- /dev/null +++ b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.java @@ -0,0 +1,43 @@ +class Solution { + public int[] constructDistancedSequence(int n) { + int[] result = new int[2 * n - 1]; + boolean[] used = new boolean[n + 1]; + backtrack(result, used, n, 0); + return result; + } + + private boolean backtrack(int[] result, boolean[] used, int n, int index) { + while (index < result.length && result[index] != 0) { + index++; + } + if (index == result.length) { + return true; + } + + for (int i = n; i >= 1; i--) { + if (used[i]) continue; + + if (i == 1) { + result[index] = 1; + used[1] = true; + if (backtrack(result, used, n, index + 1)) { + return true; + } + result[index] = 0; + used[1] = false; + } else if (index + i < result.length && result[index + i] == 0) { + result[index] = i; + result[index + i] = i; + used[i] = true; + if (backtrack(result, used, n, index + 1)) { + return true; + } + result[index] = 0; + result[index + i] = 0; + used[i] = false; + } + } + + return false; + } +} diff --git a/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.kt b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.kt new file mode 100644 index 00000000..398136d2 --- /dev/null +++ b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.kt @@ -0,0 +1,38 @@ +class Solution { + fun constructDistancedSequence(n: Int): IntArray { + val result = IntArray(2 * n - 1) + val used = BooleanArray(n + 1) + backtrack(result, used, n, 0) + return result + } + + private fun backtrack(result: IntArray, used: BooleanArray, n: Int, index: Int): Boolean { + var idx = index + while (idx < result.size && result[idx] != 0) { + idx++ + } + if (idx == result.size) return true + + for (i in n downTo 1) { + if (used[i]) continue + + if (i == 1) { + result[idx] = 1 + used[1] = true + if (backtrack(result, used, n, idx + 1)) return true + result[idx] = 0 + used[1] = false + } else if (idx + i < result.size && result[idx + i] == 0) { + result[idx] = i + result[idx + i] = i + used[i] = true + if (backtrack(result, used, n, idx + 1)) return true + result[idx] = 0 + result[idx + i] = 0 + used[i] = false + } + } + + return false + } +} diff --git a/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.py b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.py new file mode 100644 index 00000000..41680a8f --- /dev/null +++ b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.py @@ -0,0 +1,37 @@ +class Solution: + def constructDistancedSequence(self, n: int) -> List[int]: + result = [0] * (2 * n - 1) + used = [False] * (n + 1) + self.backtrack(result, used, n, 0) + return result + + def backtrack( + self, result: List[int], used: List[bool], n: int, index: int + ) -> bool: + while index < len(result) and result[index] != 0: + index += 1 + if index == len(result): + return True + + for i in range(n, 0, -1): + if used[i]: + continue + + if i == 1: + result[index] = 1 + used[1] = True + if self.backtrack(result, used, n, index + 1): + return True + result[index] = 0 + used[1] = False + elif index + i < len(result) and result[index + i] == 0: + result[index] = i + result[index + i] = i + used[i] = True + if self.backtrack(result, used, n, index + 1): + return True + result[index] = 0 + result[index + i] = 0 + used[i] = False + + return False diff --git a/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.py2 b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.py2 new file mode 100644 index 00000000..50b7b678 --- /dev/null +++ b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.py2 @@ -0,0 +1,39 @@ +class Solution(object): + def constructDistancedSequence(self, n): + """ + :type n: int + :rtype: List[int] + """ + result = [0] * (2 * n - 1) + used = [False] * (n + 1) + self.backtrack(result, used, n, 0) + return result + + def backtrack(self, result, used, n, index): + while index < len(result) and result[index] != 0: + index += 1 + if index == len(result): + return True + + for i in range(n, 0, -1): + if used[i]: + continue + + if i == 1: + result[index] = 1 + used[1] = True + if self.backtrack(result, used, n, index + 1): + return True + result[index] = 0 + used[1] = False + elif index + i < len(result) and result[index + i] == 0: + result[index] = i + result[index + i] = i + used[i] = True + if self.backtrack(result, used, n, index + 1): + return True + result[index] = 0 + result[index + i] = 0 + used[i] = False + + return False diff --git a/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.rb b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.rb new file mode 100644 index 00000000..febd89d1 --- /dev/null +++ b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.rb @@ -0,0 +1,41 @@ +# @param {Integer} n +# @return {Integer[]} +def construct_distanced_sequence(n) + result = Array.new(2 * n - 1, 0) + used = Array.new(n + 1, false) + backtrack(result, used, n, 0) + result +end + +def backtrack(result, used, n, index) + while index < result.length && result[index] != 0 + index += 1 + end + return true if index == result.length + + n.downto(1) do |i| + next if used[i] + + if i == 1 + result[index] = 1 + used[1] = true + if backtrack(result, used, n, index + 1) + return true + end + result[index] = 0 + used[1] = false + elsif index + i < result.length && result[index + i] == 0 + result[index] = i + result[index + i] = i + used[i] = true + if backtrack(result, used, n, index + 1) + return true + end + result[index] = 0 + result[index + i] = 0 + used[i] = false + end + end + + false +end diff --git a/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.rs b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.rs new file mode 100644 index 00000000..ea594301 --- /dev/null +++ b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.rs @@ -0,0 +1,47 @@ +impl Solution { + pub fn construct_distanced_sequence(n: i32) -> Vec { + let n = n as usize; + let mut result = vec![0; 2 * n - 1]; + let mut used = vec![false; n + 1]; + Self::backtrack(&mut result, &mut used, n, 0); + result + } + + fn backtrack(result: &mut Vec, used: &mut Vec, n: usize, index: usize) -> bool { + let mut idx = index; + while idx < result.len() && result[idx] != 0 { + idx += 1; + } + if idx == result.len() { + return true; + } + + for i in (1..=n).rev() { + if used[i] { + continue; + } + + if i == 1 { + result[idx] = 1; + used[1] = true; + if Self::backtrack(result, used, n, idx + 1) { + return true; + } + result[idx] = 0; + used[1] = false; + } else if idx + i < result.len() && result[idx + i] == 0 { + result[idx] = i as i32; + result[idx + i] = i as i32; + used[i] = true; + if Self::backtrack(result, used, n, idx + 1) { + return true; + } + result[idx] = 0; + result[idx + i] = 0; + used[i] = false; + } + } + + false + } +} diff --git a/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.swift b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.swift new file mode 100644 index 00000000..016b1828 --- /dev/null +++ b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.swift @@ -0,0 +1,46 @@ +class Solution { + func constructDistancedSequence(_ n: Int) -> [Int] { + var result = Array(repeating: 0, count: 2 * n - 1) + var used = Array(repeating: false, count: n + 1) + backtrack(&result, &used, n, 0) + return result + } + + private func backtrack(_ result: inout [Int], _ used: inout [Bool], _ n: Int, _ index: Int) -> Bool { + var idx = index + while idx < result.count && result[idx] != 0 { + idx += 1 + } + if idx == result.count { + return true + } + + for i in stride(from: n, through: 1, by: -1) { + if used[i] { + continue + } + + if i == 1 { + result[idx] = 1 + used[1] = true + if backtrack(&result, &used, n, idx + 1) { + return true + } + result[idx] = 0 + used[1] = false + } else if idx + i < result.count && result[idx + i] == 0 { + result[idx] = i + result[idx + i] = i + used[i] = true + if backtrack(&result, &used, n, idx + 1) { + return true + } + result[idx] = 0 + result[idx + i] = 0 + used[i] = false + } + } + + return false + } +} diff --git a/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.ts b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.ts new file mode 100644 index 00000000..26bbc195 --- /dev/null +++ b/tests/1501-2000/1718. construct-the-lexicographically-largest-valid-sequence/sol.ts @@ -0,0 +1,47 @@ +function constructDistancedSequence(n: number): number[] { + const result: number[] = new Array(2 * n - 1).fill(0); + const used: boolean[] = new Array(n + 1).fill(false); + backtrack(result, used, n, 0); + return result; +} + +function backtrack( + result: number[], + used: boolean[], + n: number, + index: number, +): boolean { + let idx = index; + while (idx < result.length && result[idx] !== 0) { + idx++; + } + if (idx === result.length) { + return true; + } + + for (let i = n; i >= 1; i--) { + if (used[i]) continue; + + if (i === 1) { + result[idx] = 1; + used[1] = true; + if (backtrack(result, used, n, idx + 1)) { + return true; + } + result[idx] = 0; + used[1] = false; + } else if (idx + i < result.length && result[idx + i] === 0) { + result[idx] = i; + result[idx + i] = i; + used[i] = true; + if (backtrack(result, used, n, idx + 1)) { + return true; + } + result[idx] = 0; + result[idx + i] = 0; + used[i] = false; + } + } + + return false; +} diff --git a/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/manifest.yaml b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/manifest.yaml new file mode 100644 index 00000000..07d45ea9 --- /dev/null +++ b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/manifest.yaml @@ -0,0 +1,429 @@ +entry: + id: 1719 + title: "number-of-ways-to-reconstruct-a-tree" + params: + pairs: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().checkWays({pairs})" + rust: "Solution::check_ways({pairs})" + python3: "Solution().checkWays({pairs})" + python2: "Solution().checkWays({pairs})" + ruby: "check_ways({pairs})" + java: "new Solution().checkWays({pairs})" + csharp: "new Solution().CheckWays({pairs})" + kotlin: "Solution().checkWays({pairs})" + go: "checkWays({pairs})" + dart: "Solution().checkWays({pairs})" + swift: "Solution().checkWays({pairs})" + typescript: "checkWays({pairs})" + +judge: + type: exact + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().checkWays(pairs, {result})" + checker: | + class Checker: + def checkWays(self, pairs, result): + if not isinstance(result, int) or result not in (0, 1, 2): + return False + graph = {} + for edge in pairs: + if not isinstance(edge, list) or len(edge) != 2: + return False + x, y = edge + if not isinstance(x, int) or not isinstance(y, int) or x == y: + return False + graph.setdefault(x, set()).add(y) + graph.setdefault(y, set()).add(x) + if not graph: + return result == 0 + root = max(graph, key=lambda node: len(graph[node])) + if len(graph[root]) != len(graph) - 1: + return result == 0 + answer = 1 + for node, neighbors in graph.items(): + if node == root: + continue + candidates = [candidate for candidate in neighbors + if len(graph[candidate]) >= len(neighbors)] + if not candidates: + return result == 0 + parent = min(candidates, key=lambda candidate: len(graph[candidate])) + if neighbors - (graph[parent] | {parent}): + return result == 0 + if len(neighbors) == len(graph[parent]): + answer = 2 + return result == answer + +seed: 1719 + +tests: + - name: chain-three + in: + pairs: + - [1, 2] + - [2, 3] + out: 1 + - name: complete-three + in: + pairs: + - [1, 2] + - [1, 3] + - [2, 3] + out: 2 + - name: invalid-four + in: + pairs: + - [1, 2] + - [2, 3] + - [2, 4] + - [1, 5] + out: 0 + - name: single-pair + in: + pairs: + - [1, 2] + out: 2 + - name: star-four + in: + pairs: + - [1, 2] + - [1, 3] + - [1, 4] + out: 1 + - name: complete-four + in: + pairs: + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 3] + - [2, 4] + - [3, 4] + out: 2 + - name: disconnected-two-edges + in: + pairs: + - [1, 2] + - [3, 4] + out: 0 + - name: disconnected-singletons + in: + pairs: + - [1, 2] + - [2, 3] + - [4, 5] + out: 0 + - name: chain-four + in: + pairs: + - [1, 2] + - [2, 3] + - [3, 4] + out: 0 + - name: chain-five + in: + pairs: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + out: 0 + - name: star-five + in: + pairs: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + out: 1 + - name: equal-degree-children + in: + pairs: + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 3] + - [2, 4] + out: 2 + - name: nested-subtree + in: + pairs: + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 3] + - [2, 4] + - [3, 4] + - [2, 5] + - [3, 5] + - [4, 5] + out: 2 + - name: invalid-missing-cross-edge + in: + pairs: + - [1, 2] + - [1, 3] + - [2, 4] + - [3, 5] + out: 0 + - name: complete-five + in: + pairs: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [2, 3] + - [2, 4] + - [2, 5] + - [3, 4] + - [3, 5] + - [4, 5] + out: 2 + - name: root-two-levels + in: + pairs: + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 4] + out: 2 + - name: ambiguous-two-levels + in: + pairs: + - [1, 2] + - [1, 3] + - [2, 3] + - [1, 4] + - [2, 4] + out: 2 + - name: invalid-extra-branch + in: + pairs: + - [1, 2] + - [1, 3] + - [2, 4] + - [2, 5] + - [3, 4] + out: 0 + - name: chain-six + in: + pairs: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + out: 0 + - name: star-six + in: + pairs: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + out: 1 + - name: complete-six + in: + pairs: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [2, 3] + - [2, 4] + - [2, 5] + - [2, 6] + - [3, 4] + - [3, 5] + - [3, 6] + - [4, 5] + - [4, 6] + - [5, 6] + out: 2 + - name: disconnected-long-chain + in: + pairs: + - [1, 2] + - [2, 3] + - [3, 4] + - [5, 6] + out: 0 + - name: root-with-two-equal-branches + in: + pairs: + - [1, 2] + - [1, 3] + - [2, 4] + - [3, 5] + - [2, 3] + - [4, 5] + out: 0 + - name: invalid-cycle-like + in: + pairs: + - [1, 2] + - [1, 3] + - [2, 4] + - [3, 4] + - [2, 5] + out: 0 + - name: chain-seven + in: + pairs: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + out: 0 + - name: star-seven + in: + pairs: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + out: 1 + - name: complete-seven + in: + pairs: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [2, 3] + - [2, 4] + - [2, 5] + - [2, 6] + - [2, 7] + - [3, 4] + - [3, 5] + - [3, 6] + - [3, 7] + - [4, 5] + - [4, 6] + - [4, 7] + - [5, 6] + - [5, 7] + - [6, 7] + out: 2 + - name: sparse-invalid-eight + in: + pairs: + - [1, 2] + - [1, 3] + - [2, 4] + - [2, 5] + - [3, 6] + - [3, 7] + - [4, 8] + out: 0 + - name: nested-ambiguous + in: + pairs: + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 3] + - [2, 4] + - [3, 4] + - [1, 5] + - [2, 5] + - [3, 5] + - [4, 5] + - [1, 6] + - [2, 6] + - [3, 6] + - [4, 6] + - [5, 6] + out: 2 + - name: two-components-three + in: + pairs: + - [10, 11] + - [11, 12] + - [20, 21] + out: 0 + - name: labels-not-contiguous + in: + pairs: + - [7, 42] + - [42, 100] + - [7, 100] + out: 2 + - name: labels-large-chain + in: + pairs: + - [100, 200] + - [200, 300] + - [300, 400] + out: 0 + - name: labels-large-star + in: + pairs: + - [1, 500] + - [2, 500] + - [3, 500] + - [4, 500] + out: 1 + - name: invalid-cross-component + in: + pairs: + - [1, 2] + - [2, 3] + - [1, 4] + - [5, 6] + - [6, 7] + out: 0 + - name: complete-eight + in: + pairs: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [1, 8] + - [2, 3] + - [2, 4] + - [2, 5] + - [2, 6] + - [2, 7] + - [2, 8] + - [3, 4] + - [3, 5] + - [3, 6] + - [3, 7] + - [3, 8] + - [4, 5] + - [4, 6] + - [4, 7] + - [4, 8] + - [5, 6] + - [5, 7] + - [5, 8] + - [6, 7] + - [6, 8] + - [7, 8] + out: 2 diff --git a/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.cpp b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.cpp new file mode 100644 index 00000000..47beed4c --- /dev/null +++ b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + int checkWays(vector>& pairs) { + unordered_map> graph; + for (auto& p : pairs) { + graph[p[0]].insert(p[1]); + graph[p[1]].insert(p[0]); + } + if (graph.empty()) return 0; + int root = -1; + int maxSize = -1; + for (auto& [node, neighbors] : graph) { + if ((int)neighbors.size() > maxSize) { + maxSize = neighbors.size(); + root = node; + } + } + if ((int)graph[root].size() != (int)graph.size() - 1) return 0; + + int ans = 1; + for (auto& [node, neighbors] : graph) { + if (node == root) continue; + vector parents; + for (int cand : neighbors) { + if ((int)graph[cand].size() >= (int)neighbors.size()) parents.push_back(cand); + } + if (parents.empty()) return 0; + int parent = parents[0]; + for (int cand : parents) { + if (graph[cand].size() < graph[parent].size()) parent = cand; + } + unordered_set unionSet = graph[parent]; + unionSet.insert(parent); + for (int n : neighbors) { + if (!unionSet.count(n)) return 0; + } + if (neighbors.size() == graph[parent].size()) ans = 2; + } + return ans; + } +}; diff --git a/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.cs b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.cs new file mode 100644 index 00000000..82f0c9c7 --- /dev/null +++ b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.cs @@ -0,0 +1,39 @@ +public class Solution { + public int CheckWays(int[][] pairs) { + var graph = new Dictionary>(); + foreach (var p in pairs) { + if (!graph.ContainsKey(p[0])) graph[p[0]] = new HashSet(); + if (!graph.ContainsKey(p[1])) graph[p[1]] = new HashSet(); + graph[p[0]].Add(p[1]); + graph[p[1]].Add(p[0]); + } + if (graph.Count == 0) return 0; + int root = -1; + int maxSize = -1; + foreach (var kv in graph) { + if (kv.Value.Count > maxSize) { + maxSize = kv.Value.Count; + root = kv.Key; + } + } + if (graph[root].Count != graph.Count - 1) return 0; + + int ans = 1; + foreach (var kv in graph) { + int node = kv.Key; + var neighbors = kv.Value; + if (node == root) continue; + var parents = neighbors.Where(cand => graph[cand].Count >= neighbors.Count).ToList(); + if (parents.Count == 0) return 0; + int parent = parents[0]; + foreach (int cand in parents) { + if (graph[cand].Count < graph[parent].Count) parent = cand; + } + var union = new HashSet(graph[parent]); + union.Add(parent); + if (!union.IsSupersetOf(neighbors)) return 0; + if (neighbors.Count == graph[parent].Count) ans = 2; + } + return ans; + } +} diff --git a/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.dart b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.dart new file mode 100644 index 00000000..287716e1 --- /dev/null +++ b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.dart @@ -0,0 +1,27 @@ +class Solution { + int checkWays(List> pairs) { + Map> graph = {}; + for (var p in pairs) { + graph.putIfAbsent(p[0], () => {}); + graph.putIfAbsent(p[1], () => {}); + graph[p[0]]!.add(p[1]); + graph[p[1]]!.add(p[0]); + } + if (graph.isEmpty) return 0; + int root = graph.keys.reduce((a, b) => graph[a]!.length > graph[b]!.length ? a : b); + if (graph[root]!.length != graph.length - 1) return 0; + + int ans = 1; + graph.forEach((node, neighbors) { + if (node == root) return; + var parents = neighbors.where((cand) => graph[cand]!.length >= neighbors.length).toList(); + if (parents.isEmpty) { ans = 0; return; } + int parent = parents.reduce((a, b) => graph[a]!.length < graph[b]!.length ? a : b); + var union = Set.from(graph[parent]!); + union.add(parent); + if (!union.containsAll(neighbors)) { ans = 0; return; } + if (neighbors.length == graph[parent]!.length) ans = 2; + }); + return ans; + } +} diff --git a/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.go b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.go new file mode 100644 index 00000000..dfd8e48d --- /dev/null +++ b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.go @@ -0,0 +1,45 @@ +func checkWays(pairs [][]int) int { + graph := make(map[int]map[int]bool) + for _, p := range pairs { + if graph[p[0]] == nil { graph[p[0]] = make(map[int]bool) } + if graph[p[1]] == nil { graph[p[1]] = make(map[int]bool) } + graph[p[0]][p[1]] = true + graph[p[1]][p[0]] = true + } + if len(graph) == 0 { return 0 } + root := -1 + maxSize := -1 + for node, neighbors := range graph { + if len(neighbors) > maxSize { + maxSize = len(neighbors) + root = node + } + } + if len(graph[root]) != len(graph)-1 { return 0 } + + ans := 1 + for node, neighbors := range graph { + if node == root { continue } + parents := []int{} + for cand := range neighbors { + if len(graph[cand]) >= len(neighbors) { + parents = append(parents, cand) + } + } + if len(parents) == 0 { return 0 } + parent := parents[0] + for _, cand := range parents { + if len(graph[cand]) < len(graph[parent]) { parent = cand } + } + union := make(map[int]bool) + for k := range graph[parent] { + union[k] = true + } + union[parent] = true + for k := range neighbors { + if !union[k] { return 0 } + } + if len(neighbors) == len(graph[parent]) { ans = 2 } + } + return ans +} diff --git a/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.java b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.java new file mode 100644 index 00000000..24139d6d --- /dev/null +++ b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.java @@ -0,0 +1,40 @@ +class Solution { + public int checkWays(int[][] pairs) { + Map> graph = new HashMap<>(); + for (int[] p : pairs) { + graph.computeIfAbsent(p[0], k -> new HashSet<>()).add(p[1]); + graph.computeIfAbsent(p[1], k -> new HashSet<>()).add(p[0]); + } + if (graph.isEmpty()) return 0; + int root = -1; + int maxSize = -1; + for (Map.Entry> entry : graph.entrySet()) { + if (entry.getValue().size() > maxSize) { + maxSize = entry.getValue().size(); + root = entry.getKey(); + } + } + if (graph.get(root).size() != graph.size() - 1) return 0; + + int ans = 1; + for (Map.Entry> entry : graph.entrySet()) { + int node = entry.getKey(); + Set neighbors = entry.getValue(); + if (node == root) continue; + List parents = new ArrayList<>(); + for (int cand : neighbors) { + if (graph.get(cand).size() >= neighbors.size()) parents.add(cand); + } + if (parents.isEmpty()) return 0; + int parent = parents.get(0); + for (int cand : parents) { + if (graph.get(cand).size() < graph.get(parent).size()) parent = cand; + } + Set union = new HashSet<>(graph.get(parent)); + union.add(parent); + if (!union.containsAll(neighbors)) return 0; + if (neighbors.size() == graph.get(parent).size()) ans = 2; + } + return ans; + } +} diff --git a/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.kt b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.kt new file mode 100644 index 00000000..0c5b09cb --- /dev/null +++ b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.kt @@ -0,0 +1,24 @@ +class Solution { + fun checkWays(pairs: Array): Int { + val graph = mutableMapOf>() + for (p in pairs) { + graph.getOrPut(p[0]) { mutableSetOf() }.add(p[1]) + graph.getOrPut(p[1]) { mutableSetOf() }.add(p[0]) + } + if (graph.isEmpty()) return 0 + val root = graph.maxBy { it.value.size }!!.key + if (graph[root]!!.size != graph.size - 1) return 0 + + var ans = 1 + for ((node, neighbors) in graph) { + if (node == root) continue + val parents = neighbors.filter { graph[it]!!.size >= neighbors.size } + if (parents.isEmpty()) return 0 + val parent = parents.minBy { graph[it]!!.size } + val union = graph[parent]!! + parent + if (!union.containsAll(neighbors)) return 0 + if (neighbors.size == graph[parent]!!.size) ans = 2 + } + return ans + } +} diff --git a/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.py b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.py new file mode 100644 index 00000000..1bf0f03f --- /dev/null +++ b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.py @@ -0,0 +1,30 @@ +class Solution: + def checkWays(self, pairs: List[List[int]]) -> int: + graph = {} + for x, y in pairs: + graph.setdefault(x, set()).add(y) + graph.setdefault(y, set()).add(x) + + if not graph: + return 0 + root = max(graph, key=lambda node: len(graph[node])) + if len(graph[root]) != len(graph) - 1: + return 0 + + ans = 1 + for node in graph: + if node == root: + continue + parents = [ + candidate + for candidate in graph[node] + if len(graph[candidate]) >= len(graph[node]) + ] + if not parents: + return 0 + parent = min(parents, key=lambda candidate: len(graph[candidate])) + if graph[node] - (graph[parent] | {parent}): + return 0 + if len(graph[node]) == len(graph[parent]): + ans = 2 + return ans diff --git a/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.py2 b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.py2 new file mode 100644 index 00000000..947ce1c5 --- /dev/null +++ b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.py2 @@ -0,0 +1,31 @@ +class Solution(object): + def checkWays(self, pairs): + """ + :type pairs: List[List[int]] + :rtype: int + """ + graph = {} + for x, y in pairs: + graph.setdefault(x, set()).add(y) + graph.setdefault(y, set()).add(x) + + if not graph: + return 0 + root = max(graph, key=lambda node: len(graph[node])) + if len(graph[root]) != len(graph) - 1: + return 0 + + ans = 1 + for node in graph: + if node == root: + continue + parents = [candidate for candidate in graph[node] + if len(graph[candidate]) >= len(graph[node])] + if not parents: + return 0 + parent = min(parents, key=lambda candidate: len(graph[candidate])) + if graph[node] - (graph[parent] | {parent}): + return 0 + if len(graph[node]) == len(graph[parent]): + ans = 2 + return ans diff --git a/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.rb b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.rb new file mode 100644 index 00000000..588c258d --- /dev/null +++ b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.rb @@ -0,0 +1,26 @@ +# @param {Integer[][]} pairs +# @return {Integer} +def check_ways(pairs) + graph = {} + pairs.each do |x, y| + graph[x] ||= Set.new + graph[y] ||= Set.new + graph[x].add(y) + graph[y].add(x) + end + + return 0 if graph.empty? + root = graph.max_by { |_, vals| vals.size }[0] + return 0 if graph[root].size != graph.size - 1 + + ans = 1 + graph.each do |node, neighbors| + next if node == root + parents = neighbors.select { |cand| graph[cand].size >= neighbors.size } + return 0 if parents.empty? + parent = parents.min_by { |cand| graph[cand].size } + return 0 unless (neighbors - (graph[parent] | [parent])).empty? + ans = 2 if neighbors.size == graph[parent].size + end + return ans +end diff --git a/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.rs b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.rs new file mode 100644 index 00000000..2cf0f702 --- /dev/null +++ b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.rs @@ -0,0 +1,27 @@ +impl Solution { + pub fn check_ways(pairs: Vec>) -> i32 { + use std::collections::{HashMap, HashSet}; + let mut graph: HashMap> = HashMap::new(); + for p in &pairs { + graph.entry(p[0]).or_insert_with(HashSet::new).insert(p[1]); + graph.entry(p[1]).or_insert_with(HashSet::new).insert(p[0]); + } + if graph.is_empty() { return 0; } + let root = *graph.iter().max_by_key(|(_, v)| v.len()).unwrap().0; + if graph[&root].len() != graph.len() - 1 { return 0; } + + let mut ans = 1; + for (&node, neighbors) in &graph { + if node == root { continue; } + let parents: Vec = neighbors.iter().filter(|&&cand| graph[&cand].len() >= neighbors.len()).cloned().collect(); + if parents.is_empty() { return 0; } + let parent = parents.iter().min_by_key(|&&cand| graph[&cand].len()).unwrap(); + let union: HashSet = graph[parent].iter().cloned().collect::>().union(&HashSet::from([*parent])).cloned().collect(); + for n in neighbors { + if !union.contains(n) { return 0; } + } + if neighbors.len() == graph[parent].len() { ans = 2; } + } + ans + } +} diff --git a/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.swift b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.swift new file mode 100644 index 00000000..da92af19 --- /dev/null +++ b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.swift @@ -0,0 +1,25 @@ +class Solution { + func checkWays(_ pairs: [[Int]]) -> Int { + var graph: [Int: Set] = [:] + for p in pairs { + graph[p[0], default: []].insert(p[1]) + graph[p[1], default: []].insert(p[0]) + } + if graph.isEmpty { return 0 } + let root = graph.max(by: { $0.value.count < $1.value.count })!.key + if graph[root]!.count != graph.count - 1 { return 0 } + + var ans = 1 + for (node, neighbors) in graph { + if node == root { continue } + let parents = neighbors.filter { graph[$0]!.count >= neighbors.count } + if parents.isEmpty { return 0 } + let parent = parents.min(by: { graph[$0]!.count < graph[$1]!.count })! + var union = graph[parent]! + union.insert(parent) + if !union.isSuperset(of: neighbors) { return 0 } + if neighbors.count == graph[parent]!.count { ans = 2 } + } + return ans + } +} diff --git a/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.ts b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.ts new file mode 100644 index 00000000..fdb0a35b --- /dev/null +++ b/tests/1501-2000/1719. number-of-ways-to-reconstruct-a-tree/sol.ts @@ -0,0 +1,39 @@ +function checkWays(pairs: number[][]): number { + const graph: Map> = new Map(); + for (const [x, y] of pairs) { + if (!graph.has(x)) graph.set(x, new Set()); + if (!graph.has(y)) graph.set(y, new Set()); + graph.get(x)!.add(y); + graph.get(y)!.add(x); + } + if (graph.size === 0) return 0; + let root = -1; + let maxSize = -1; + for (const [node, neighbors] of graph) { + if (neighbors.size > maxSize) { + maxSize = neighbors.size; + root = node; + } + } + if (graph.get(root)!.size !== graph.size - 1) return 0; + + let ans = 1; + for (const [node, neighbors] of graph) { + if (node === root) continue; + const parents = Array.from(neighbors).filter( + (cand) => graph.get(cand)!.size >= neighbors.size, + ); + if (parents.length === 0) return 0; + let parent = parents[0]; + for (const cand of parents) { + if (graph.get(cand)!.size < graph.get(parent)!.size) parent = cand; + } + const union = new Set(graph.get(parent)!); + union.add(parent); + for (const n of neighbors) { + if (!union.has(n)) return 0; + } + if (neighbors.size === graph.get(parent)!.size) ans = 2; + } + return ans; +} diff --git a/tests/1501-2000/1720. decode-xored-array/manifest.yaml b/tests/1501-2000/1720. decode-xored-array/manifest.yaml new file mode 100644 index 00000000..b1f9e829 --- /dev/null +++ b/tests/1501-2000/1720. decode-xored-array/manifest.yaml @@ -0,0 +1,271 @@ +entry: + id: 1720 + title: "decode-xored-array" + params: + encoded: + type: array + items: + type: int + first: + type: int + call: + cpp: "Solution().decode({encoded}, {first})" + rust: "Solution::decode({encoded}, {first})" + python3: "Solution().decode({encoded}, {first})" + python2: "Solution().decode({encoded}, {first})" + ruby: "decode({encoded}, {first})" + java: "new Solution().decode({encoded}, {first})" + csharp: "new Solution().Decode({encoded}, {first})" + kotlin: "Solution().decode({encoded}, {first})" + go: "decode({encoded}, {first})" + dart: "Solution().decode({encoded}, {first})" + swift: "Solution().decode({encoded}, {first})" + typescript: "decode({encoded}, {first})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().decode(encoded, first, {result})" + checker: | + class Checker: + def decode(self, encoded, first, result): + if not isinstance(result, list) or len(result) != len(encoded) + 1: + return False + if not result or result[0] != first: + return False + return all(result[i] ^ result[i + 1] == encoded[i] for i in range(len(encoded))) + +seed: 1720 + +tests: + - name: example-one + in: + encoded: [1, 2, 3] + first: 1 + out: [1, 0, 2, 1] + - name: example-two + in: + encoded: [6, 2, 7, 3] + first: 4 + out: [4, 2, 0, 7, 4] + - name: minimum-length-zero-xor + in: + encoded: [0] + first: 0 + out: [0, 0] + - name: minimum-length-nonzero + in: + encoded: [100000] + first: 100000 + out: [100000, 0] + - name: all-zeroes + in: + encoded: [0, 0, 0, 0, 0] + first: 37 + out: [37, 37, 37, 37, 37, 37] + - name: alternating-bit + in: + encoded: [1, 1, 1, 1, 1, 1] + first: 0 + out: [0, 1, 0, 1, 0, 1, 0] + - name: high-bit-values + in: + encoded: [65535, 65535, 65535, 65535] + first: 65535 + out: [65535, 0, 65535, 0, 65535] + - name: max-values + in: + encoded: [100000, 100000, 99999] + first: 100000 + out: [100000, 0, 100000, 63] + - name: increasing-small + in: + encoded: [1, 2, 3, 4, 5, 6, 7] + first: 8 + out: [8, 9, 11, 8, 12, 9, 15, 8] + - name: powers-of-two + in: + encoded: [1, 2, 4, 8, 16, 32] + first: 63 + out: [63, 62, 60, 56, 48, 32, 0] + - name: repeated-pattern + in: + encoded: [5, 10, 5, 10, 5, 10] + first: 12 + out: [12, 9, 3, 6, 12, 9, 3] + - name: mixed-small + in: + encoded: [3, 7, 2, 6, 1, 4, 0, 5] + first: 2 + out: [2, 1, 6, 4, 2, 3, 7, 7, 2] + - name: byte-pattern + in: + encoded: [255, 15, 240, 170, 85] + first: 170 + out: [170, 85, 90, 170, 0, 85] + - name: sparse-large + in: + encoded: [0, 100000, 0, 99999, 1] + first: 1 + out: [1, 1, 100001, 100001, 62, 63] + - name: one-bit-first + in: + encoded: [8, 4, 2, 1] + first: 1 + out: [1, 9, 13, 15, 14] + - name: zero-first + in: + encoded: [12, 34, 56, 78] + first: 0 + out: [0, 12, 46, 22, 88] + - name: first-max + in: + encoded: [1, 2, 4, 8] + first: 100000 + out: [100000, 100001, 100003, 100007, 100015] + - name: powers-high + in: + encoded: [32768, 16384, 8192, 4096] + first: 65535 + out: [65535, 32767, 16383, 8191, 4095] + - name: xor-cancellation + in: + encoded: [12345, 12345, 54321, 54321, 99999] + first: 24680 + out: [24680, 20561, 24680, 46169, 24680, 124663] + - name: length-ten + in: + encoded: [1, 3, 5, 7, 9, 11, 13, 15, 17] + first: 42 + out: [42, 43, 40, 45, 42, 35, 40, 37, 42, 59] + - name: length-twelve + in: + encoded: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110] + first: 17 + out: [17, 27, 15, 17, 57, 11, 55, 113, 33, 123, 31, 113] + - name: alternating-large + in: + encoded: [100000, 99999, 100000, 99999, 100000, 99999] + first: 0 + out: [0, 100000, 63, 99999, 0, 100000, 63] + - name: mask-eight + in: + encoded: [255, 255, 255, 255, 255, 255, 255, 255] + first: 128 + out: [128, 127, 128, 127, 128, 127, 128, 127, 128] + - name: fibonacci-like + in: + encoded: [1, 1, 2, 3, 5, 8, 13, 21] + first: 34 + out: [34, 35, 34, 32, 35, 38, 46, 35, 54] + - name: random-mix-one + in: + encoded: [17, 2048, 73, 65536, 999, 4095] + first: 777 + out: [777, 792, 2840, 2897, 68433, 67766, 67401] + - name: random-mix-two + in: + encoded: [2, 19, 256, 4096, 8191, 65535, 100000] + first: 54321 + out: [54321, 54323, 54304, 54560, 50464, 56031, 9504, 107392] + - name: length-fifteen + in: + encoded: [31, 14, 7, 22, 3, 18, 29, 11, 5, 27, 9, 1, 16, 8] + first: 91 + out: [91, 68, 74, 77, 91, 88, 74, 87, 92, 89, 66, 75, 74, 90, 82] + - name: near-limit-chain + in: + encoded: [100000, 1, 99998, 2, 99997, 3, 99996] + first: 99999 + out: [99999, 63, 62, 100000, 100002, 63, 60, 100000] + - name: duplicate-blocks + in: + encoded: [7, 7, 7, 7, 7, 7, 7, 7, 7, 7] + first: 73 + out: [73, 78, 73, 78, 73, 78, 73, 78, 73, 78, 73] + - name: broad-range + in: + encoded: [4096, 8192, 16384, 32768, 65536, 99999] + first: 12345 + out: [12345, 8249, 57, 16441, 49209, 114745, 18086] + - name: generator-short + in: + encoded: + gen: "array" + len: 20 + of: + gen: "int" + min: 0 + max: 100000 + elemType: "int" + first: + gen: "int" + min: 0 + max: 100000 + seed: 172001 + - name: generator-medium + in: + encoded: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 100000 + elemType: "int" + first: + gen: "int" + min: 0 + max: 100000 + seed: 172002 + - name: generator-large + in: + encoded: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 100000 + elemType: "int" + first: + gen: "int" + min: 0 + max: 100000 + seed: 172003 + - name: generator-max-one + in: + encoded: + gen: "array" + len: 9999 + of: + gen: "int" + min: 0 + max: 100000 + elemType: "int" + first: + gen: "int" + min: 0 + max: 100000 + seed: 172004 + - name: generator-max-two + in: + encoded: + gen: "array" + len: 9998 + of: + gen: "int" + min: 0 + max: 100000 + elemType: "int" + first: + gen: "int" + min: 0 + max: 100000 + seed: 172005 diff --git a/tests/1501-2000/1720. decode-xored-array/sol.cpp b/tests/1501-2000/1720. decode-xored-array/sol.cpp new file mode 100644 index 00000000..592ddcfa --- /dev/null +++ b/tests/1501-2000/1720. decode-xored-array/sol.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + vector decode(vector& encoded, int first) { + vector arr = {first}; + for (int e : encoded) { + arr.push_back(arr.back() ^ e); + } + return arr; + } +}; diff --git a/tests/1501-2000/1720. decode-xored-array/sol.cs b/tests/1501-2000/1720. decode-xored-array/sol.cs new file mode 100644 index 00000000..37b4e523 --- /dev/null +++ b/tests/1501-2000/1720. decode-xored-array/sol.cs @@ -0,0 +1,10 @@ +public class Solution { + public int[] Decode(int[] encoded, int first) { + int[] arr = new int[encoded.Length + 1]; + arr[0] = first; + for (int i = 0; i < encoded.Length; i++) { + arr[i+1] = arr[i] ^ encoded[i]; + } + return arr; + } +} diff --git a/tests/1501-2000/1720. decode-xored-array/sol.dart b/tests/1501-2000/1720. decode-xored-array/sol.dart new file mode 100644 index 00000000..d0d84e4d --- /dev/null +++ b/tests/1501-2000/1720. decode-xored-array/sol.dart @@ -0,0 +1,9 @@ +class Solution { + List decode(List encoded, int first) { + List arr = [first]; + for (int e in encoded) { + arr.add(arr.last ^ e); + } + return arr; + } +} diff --git a/tests/1501-2000/1720. decode-xored-array/sol.go b/tests/1501-2000/1720. decode-xored-array/sol.go new file mode 100644 index 00000000..8475337d --- /dev/null +++ b/tests/1501-2000/1720. decode-xored-array/sol.go @@ -0,0 +1,8 @@ +func decode(encoded []int, first int) []int { + arr := make([]int, len(encoded)+1) + arr[0] = first + for i, e := range encoded { + arr[i+1] = arr[i] ^ e + } + return arr +} diff --git a/tests/1501-2000/1720. decode-xored-array/sol.java b/tests/1501-2000/1720. decode-xored-array/sol.java new file mode 100644 index 00000000..85afed17 --- /dev/null +++ b/tests/1501-2000/1720. decode-xored-array/sol.java @@ -0,0 +1,10 @@ +class Solution { + public int[] decode(int[] encoded, int first) { + int[] arr = new int[encoded.length + 1]; + arr[0] = first; + for (int i = 0; i < encoded.length; i++) { + arr[i+1] = arr[i] ^ encoded[i]; + } + return arr; + } +} diff --git a/tests/1501-2000/1720. decode-xored-array/sol.kt b/tests/1501-2000/1720. decode-xored-array/sol.kt new file mode 100644 index 00000000..a870dce3 --- /dev/null +++ b/tests/1501-2000/1720. decode-xored-array/sol.kt @@ -0,0 +1,10 @@ +class Solution { + fun decode(encoded: IntArray, first: Int): IntArray { + val arr = IntArray(encoded.size + 1) + arr[0] = first + for (i in encoded.indices) { + arr[i+1] = arr[i] xor encoded[i] + } + return arr + } +} diff --git a/tests/1501-2000/1720. decode-xored-array/sol.py b/tests/1501-2000/1720. decode-xored-array/sol.py new file mode 100644 index 00000000..180ceb73 --- /dev/null +++ b/tests/1501-2000/1720. decode-xored-array/sol.py @@ -0,0 +1,6 @@ +class Solution: + def decode(self, encoded: List[int], first: int) -> List[int]: + arr = [first] + for i in range(len(encoded)): + arr.append(arr[-1] ^ encoded[i]) + return arr diff --git a/tests/1501-2000/1720. decode-xored-array/sol.py2 b/tests/1501-2000/1720. decode-xored-array/sol.py2 new file mode 100644 index 00000000..31459692 --- /dev/null +++ b/tests/1501-2000/1720. decode-xored-array/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def decode(self, encoded, first): + """ + :type encoded: List[int] + :type first: int + :rtype: List[int] + """ + arr = [first] + for i in range(len(encoded)): + arr.append(arr[-1]^encoded[i]) + return arr diff --git a/tests/1501-2000/1720. decode-xored-array/sol.rb b/tests/1501-2000/1720. decode-xored-array/sol.rb new file mode 100644 index 00000000..6112a4ff --- /dev/null +++ b/tests/1501-2000/1720. decode-xored-array/sol.rb @@ -0,0 +1,10 @@ +# @param {Integer[]} encoded +# @param {Integer} first +# @return {Integer[]} +def decode(encoded, first) + arr = [first] + encoded.each do |e| + arr << (arr[-1] ^ e) + end + arr +end diff --git a/tests/1501-2000/1720. decode-xored-array/sol.rs b/tests/1501-2000/1720. decode-xored-array/sol.rs new file mode 100644 index 00000000..154c3c40 --- /dev/null +++ b/tests/1501-2000/1720. decode-xored-array/sol.rs @@ -0,0 +1,9 @@ +impl Solution { + pub fn decode(encoded: Vec, first: i32) -> Vec { + let mut arr = vec![first]; + for &e in encoded.iter() { + arr.push(arr[arr.len()-1] ^ e); + } + arr + } +} diff --git a/tests/1501-2000/1720. decode-xored-array/sol.swift b/tests/1501-2000/1720. decode-xored-array/sol.swift new file mode 100644 index 00000000..32930e53 --- /dev/null +++ b/tests/1501-2000/1720. decode-xored-array/sol.swift @@ -0,0 +1,9 @@ +class Solution { + func decode(_ encoded: [Int], _ first: Int) -> [Int] { + var arr = [first] + for e in encoded { + arr.append(arr.last! ^ e) + } + return arr + } +} diff --git a/tests/1501-2000/1720. decode-xored-array/sol.ts b/tests/1501-2000/1720. decode-xored-array/sol.ts new file mode 100644 index 00000000..6a2f8209 --- /dev/null +++ b/tests/1501-2000/1720. decode-xored-array/sol.ts @@ -0,0 +1,7 @@ +function decode(encoded: number[], first: number): number[] { + const arr = [first]; + for (let e of encoded) { + arr.push(arr[arr.length - 1] ^ e); + } + return arr; +} diff --git a/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/manifest.yaml b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/manifest.yaml new file mode 100644 index 00000000..183c504f --- /dev/null +++ b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/manifest.yaml @@ -0,0 +1,523 @@ +entry: + id: 1721 + title: "swapping-nodes-in-a-linked-list" + params: + head: + type: list_node + k: + type: int + call: + cpp: "listNodeToArray(Solution().swapNodes({head}, {k}))" + rust: "ListNode::list_node_to_array(Solution::swap_nodes({head}, {k}))" + python3: "list_node_to_array(Solution().swapNodes({head}, {k}))" + python2: "list_node_to_array(Solution().swapNodes({head}, {k}))" + ruby: "list_node_to_array(swap_nodes({head}, {k}))" + java: "ListNode.listNodeToArray(new Solution().swapNodes({head}, {k}))" + csharp: "ListNode.ListNodeToArray(new Solution().SwapNodes({head}, {k}))" + kotlin: "listNodeToArray(Solution().swapNodes({head}, {k}))" + go: "listNodeToArray(swapNodes({head}, {k}))" + dart: "list_node_to_array(Solution().swapNodes({head}, {k}))" + swift: "list_node_to_array(Solution().swapNodes({head}, {k}))" + typescript: "listNodeToArray(swapNodes({head}, {k}))" +judge: + type: "exact" +limits: + time_ms: 1000 + memory_mb: 300 +oracle: + python3: + call: "Checker().swapNodes(head, k, {result})" + checker: | + class Checker: + def swapNodes(self, head, k, result): + if not isinstance(result, list) or len(result) != len(head): + return False + expected = list(head) + i = k - 1 + j = len(expected) - k + expected[i], expected[j] = expected[j], expected[i] + return result == expected +seed: 1721 +tests: + - name: "example_one" + in: + head: [1, 2, 3, 4, 5] + k: 2 + out: [1, 4, 3, 2, 5] + - name: "example_two" + in: + head: [7, 9, 6, 6, 7, 8, 3, 0, 9, 5] + k: 5 + out: [7, 9, 6, 6, 8, 7, 3, 0, 9, 5] + - name: "two_first" + in: + head: [1, 2] + k: 1 + out: [2, 1] + - name: "two_second" + in: + head: [1, 2] + k: 2 + out: [2, 1] + - name: "three_first" + in: + head: [4, 8, 12] + k: 1 + out: [12, 8, 4] + - name: "three_middle" + in: + head: [4, 8, 12] + k: 2 + out: [4, 8, 12] + - name: "four_end" + in: + head: [1, 2, 3, 4] + k: 4 + out: [4, 2, 3, 1] + - name: "four_inner" + in: + head: [1, 2, 3, 4] + k: 2 + out: [1, 3, 2, 4] + - name: "six_first" + in: + head: [0, 1, 2, 3, 4, 5] + k: 1 + out: [5, 1, 2, 3, 4, 0] + - name: "six_last" + in: + head: [0, 1, 2, 3, 4, 5] + k: 6 + out: [5, 1, 2, 3, 4, 0] + - name: "six_second" + in: + head: [0, 1, 2, 3, 4, 5] + k: 2 + out: [0, 4, 2, 3, 1, 5] + - name: "seven_center" + in: + head: [1, 2, 3, 4, 5, 6, 7] + k: 4 + out: [1, 2, 3, 4, 5, 6, 7] + - name: "seven_third" + in: + head: [1, 2, 3, 4, 5, 6, 7] + k: 3 + out: [1, 2, 5, 4, 3, 6, 7] + - name: "duplicates" + in: + head: [5, 5, 1, 5, 5, 1, 5] + k: 2 + out: [5, 1, 1, 5, 5, 5, 5] + - name: "all_equal" + in: + head: [9, 9, 9, 9, 9] + k: 2 + out: [9, 9, 9, 9, 9] + - name: "zeros" + in: + head: [0, 0, 0, 1, 0, 0] + k: 3 + out: [0, 0, 1, 0, 0, 0] + - name: "alternating" + in: + head: [1, 0, 1, 0, 1, 0, 1, 0] + k: 2 + out: [1, 1, 1, 0, 1, 0, 0, 0] + - name: "boundary_values" + in: + head: [0, 1, 2, 3, 99, 100] + k: 2 + out: [0, 99, 2, 3, 1, 100] + - name: "max_values" + in: + head: [100, 99, 98, 97, 96] + k: 2 + out: [100, 97, 98, 99, 96] + - name: "eight_k_three" + in: + head: [10, 20, 30, 40, 50, 60, 70, 80] + k: 3 + out: [10, 20, 60, 40, 50, 30, 70, 80] + - name: "nine_k_four" + in: + head: [1, 3, 5, 7, 9, 11, 13, 15, 17] + k: 4 + out: [1, 3, 5, 11, 9, 7, 13, 15, 17] + - name: "ten_k_five" + in: + head: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + k: 5 + out: [0, 1, 2, 3, 5, 4, 6, 7, 8, 9] + - name: "ten_k_one" + in: + head: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] + k: 1 + out: [0, 8, 7, 6, 5, 4, 3, 2, 1, 9] + - name: "eleven_k_two" + in: + head: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121] + k: 2 + out: [1, 100, 9, 16, 25, 36, 49, 64, 81, 4, 121] + - name: "twelve_k_six" + in: + head: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + k: 6 + out: [1, 2, 3, 4, 5, 7, 6, 8, 9, 10, 11, 12] + - name: "thirteen_k_three" + in: + head: [13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + k: 3 + out: [13, 12, 3, 10, 9, 8, 7, 6, 5, 4, 11, 2, 1] + - name: "fourteen_k_seven" + in: + head: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] + k: 7 + out: [0, 1, 2, 3, 4, 5, 7, 6, 8, 9, 10, 11, 12, 13] + - name: "fifteen_k_four" + in: + head: [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + k: 4 + out: [15, 14, 13, 4, 11, 10, 9, 8, 7, 6, 5, 12, 3, 2, 1] + - name: "sixteen_k_two" + in: + head: [0, 100, 1, 99, 2, 98, 3, 97, 4, 96, 5, 95, 6, 94, 7, 93] + k: 2 + out: [0, 7, 1, 99, 2, 98, 3, 97, 4, 96, 5, 95, 6, 94, 100, 93] + - name: "seventeen_k_eight" + in: + head: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 100, 100, 100, 100, 100, 100] + k: 8 + out: [1, 1, 2, 3, 5, 8, 13, 55, 34, 21, 89, 100, 100, 100, 100, 100, 100] + - name: "eighteen_k_one" + in: + head: + [100, 0, 100, 0, 100, 0, 100, 0, 100, 0, 100, 0, 100, 0, 100, 0, 100, 0] + k: 1 + out: + [0, 0, 100, 0, 100, 0, 100, 0, 100, 0, 100, 0, 100, 0, 100, 0, 100, 100] + - name: "nineteen_k_nine" + in: + head: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] + k: 9 + out: [1, 2, 3, 4, 5, 6, 7, 8, 11, 10, 9, 12, 13, 14, 15, 16, 17, 18, 19] + - name: "twenty_k_ten" + in: + head: + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] + k: 10 + out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19] + - name: "twenty_one_k_two" + in: + head: + [ + 100, + 99, + 98, + 97, + 96, + 95, + 94, + 93, + 92, + 91, + 90, + 89, + 88, + 87, + 86, + 85, + 84, + 83, + 82, + 81, + 80, + ] + k: 2 + out: + [ + 100, + 81, + 98, + 97, + 96, + 95, + 94, + 93, + 92, + 91, + 90, + 89, + 88, + 87, + 86, + 85, + 84, + 83, + 82, + 99, + 80, + ] + - name: "twenty_two_k_eleven" + in: + head: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0] + k: 11 + out: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0] + - name: "twenty_five_k_five" + in: + head: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + ] + k: 5 + out: + [ + 1, + 2, + 3, + 4, + 21, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 5, + 22, + 23, + 24, + 25, + ] + - name: "twenty_five_k_one" + in: + head: + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 100, + ] + k: 1 + out: + [ + 100, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - name: "thirty_k_fifteen" + in: + head: + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + ] + k: 15 + out: + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 15, + 14, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + ] + - name: "thirty_one_k_thirty_one" + in: + head: + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + ] + k: 31 + out: + [ + 30, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 0, + ] diff --git a/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.cpp b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.cpp new file mode 100644 index 00000000..fc034459 --- /dev/null +++ b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.cpp @@ -0,0 +1,59 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* swapNodes(ListNode* head, int k) { + if (head == nullptr || head->next == nullptr) { + return head; + } + + ListNode* temp = head; + ListNode* firstPrev = nullptr; + + int n = 1; + while (n < k) { + firstPrev = temp; + temp = temp->next; + n++; + } + + ListNode* first = temp; + + ListNode* second = head; + ListNode* secondPrev = nullptr; + temp = first; + while (temp->next != nullptr) { + secondPrev = second; + temp = temp->next; + second = second->next; + } + + if (firstPrev != nullptr) { + firstPrev->next = second; + } + if (secondPrev != nullptr) { + secondPrev->next = first; + } + + ListNode* tempNext = first->next; + first->next = second->next; + second->next = tempNext; + + if (k == 1) { + return second; + } + if (second == head) { + return first; + } + + return head; + } +}; diff --git a/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.cs b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.cs new file mode 100644 index 00000000..b2a7f66a --- /dev/null +++ b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.cs @@ -0,0 +1,59 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode SwapNodes(ListNode head, int k) { + if (head == null || head.next == null) { + return head; + } + + ListNode temp = head; + ListNode firstPrev = null; + + int n = 1; + while (n < k) { + firstPrev = temp; + temp = temp.next; + n++; + } + + ListNode first = temp; + + ListNode second = head; + ListNode secondPrev = null; + temp = first; + while (temp.next != null) { + secondPrev = second; + temp = temp.next; + second = second.next; + } + + if (firstPrev != null) { + firstPrev.next = second; + } + if (secondPrev != null) { + secondPrev.next = first; + } + + ListNode tempNext = first.next; + first.next = second.next; + second.next = tempNext; + + if (k == 1) { + return second; + } + if (second == head) { + return first; + } + + return head; + } +} diff --git a/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.dart b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.dart new file mode 100644 index 00000000..c5550ff8 --- /dev/null +++ b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.dart @@ -0,0 +1,52 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode? next; + * ListNode([this.val = 0, this.next]); + * } + */ +class Solution { + ListNode? swapNodes(ListNode? head, int k) { + if (head == null || head.next == null) { + return head; + } + + ListNode? temp = head; + ListNode? firstPrev; + + int n = 1; + while (n < k) { + firstPrev = temp; + temp = temp?.next; + n++; + } + + ListNode? first = temp; + + ListNode? second = head; + ListNode? secondPrev; + temp = first; + while (temp?.next != null) { + secondPrev = second; + temp = temp?.next; + second = second?.next; + } + + firstPrev?.next = second; + secondPrev?.next = first; + + ListNode? tempNext = first?.next; + first?.next = second?.next; + second?.next = tempNext; + + if (k == 1) { + return second; + } + if (second == head) { + return first; + } + + return head; + } +} diff --git a/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.go b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.go new file mode 100644 index 00000000..ed642ef3 --- /dev/null +++ b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.go @@ -0,0 +1,53 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func swapNodes(head *ListNode, k int) *ListNode { + if head == nil || head.Next == nil { + return head + } + + temp := head + var firstPrev *ListNode + + n := 1 + for n < k { + firstPrev = temp + temp = temp.Next + n++ + } + + first := temp + + second := head + var secondPrev *ListNode + temp = first + for temp.Next != nil { + secondPrev = second + temp = temp.Next + second = second.Next + } + + if firstPrev != nil { + firstPrev.Next = second + } + if secondPrev != nil { + secondPrev.Next = first + } + + tempNext := first.Next + first.Next = second.Next + second.Next = tempNext + + if k == 1 { + return second + } + if second == head { + return first + } + + return head +} diff --git a/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.java b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.java new file mode 100644 index 00000000..4a36cc8e --- /dev/null +++ b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.java @@ -0,0 +1,58 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode swapNodes(ListNode head, int k) { + if (head == null || head.next == null) { + return head; + } + + ListNode temp = head; + ListNode firstPrev = null; + + int n = 1; + while (n < k) { + firstPrev = temp; + temp = temp.next; + n++; + } + + ListNode first = temp; + + ListNode second = head; + ListNode secondPrev = null; + temp = first; + while (temp.next != null) { + secondPrev = second; + temp = temp.next; + second = second.next; + } + + if (firstPrev != null) { + firstPrev.next = second; + } + if (secondPrev != null) { + secondPrev.next = first; + } + + temp = first.next; + first.next = second.next; + second.next = temp; + + if (k == 1) { + return second; + } + if (second == head) { + return first; + } + + return head; + } +} diff --git a/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.kt b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.kt new file mode 100644 index 00000000..720c95f5 --- /dev/null +++ b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.kt @@ -0,0 +1,53 @@ +/** + * Example: + * var li = ListNode(5) + * var v = li.`val` + * Definition for singly-linked list. + * class ListNode(var `val`: Int) { + * var next: ListNode? = null + * } + */ +class Solution { + fun swapNodes(head: ListNode?, k: Int): ListNode? { + if (head == null || head.next == null) { + return head + } + + var temp = head + var firstPrev: ListNode? = null + + var n = 1 + while (n < k) { + firstPrev = temp + temp = temp?.next + n++ + } + + val first = temp + + var second = head + var secondPrev: ListNode? = null + temp = first + while (temp?.next != null) { + secondPrev = second + temp = temp.next + second = second?.next + } + + firstPrev?.next = second + secondPrev?.next = first + + val tempNext = first?.next + first?.next = second?.next + second?.next = tempNext + + if (k == 1) { + return second + } + if (second == head) { + return first + } + + return head + } +} diff --git a/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.py b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.py new file mode 100644 index 00000000..367de2a8 --- /dev/null +++ b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.py @@ -0,0 +1,44 @@ +class Solution: + def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: + if head is None or head.next is None: + return head + + temp = head + first_prev = None + + # Find the k-th node from the beginning + n = 1 + while n < k: + first_prev = temp + temp = temp.next + n += 1 + + first = temp + + # Find the k-th node from the end + second = head + second_prev = None + temp = first + while temp.next: + second_prev = second + temp = temp.next + second = second.next + + # Change prev -> cur links + if first_prev: + first_prev.next = second + if second_prev: + second_prev.next = first + + # Change cur -> next links + temp = first.next + first.next = second.next + second.next = temp + + # Handle special cases + if k == 1: + return second + if second == head: + return first + + return head diff --git a/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.py2 b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.py2 new file mode 100644 index 00000000..6aab37d5 --- /dev/null +++ b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.py2 @@ -0,0 +1,49 @@ +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution(object): + def swapNodes(self, head, k): + """ + :type head: Optional[ListNode] + :type k: int + :rtype: Optional[ListNode] + """ + if not head or not head.next: + return head + + temp = head + first_prev = None + + n = 1 + while n < k: + first_prev = temp + temp = temp.next + n += 1 + + first = temp + + second = head + second_prev = None + temp = first + while temp.next: + second_prev = second + temp = temp.next + second = second.next + + if first_prev: + first_prev.next = second + if second_prev: + second_prev.next = first + + temp = first.next + first.next = second.next + second.next = temp + + if k == 1: + return second + if second == head: + return first + + return head diff --git a/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.rb b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.rb new file mode 100644 index 00000000..5e26fef9 --- /dev/null +++ b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.rb @@ -0,0 +1,47 @@ +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# @param {ListNode} head +# @param {Integer} k +# @return {ListNode} +def swap_nodes(head, k) + return head if head.nil? || head.next.nil? + + temp = head + first_prev = nil + + n = 1 + while n < k + first_prev = temp + temp = temp.next + n += 1 + end + + first = temp + + second = head + second_prev = nil + temp = first + while temp.next + second_prev = second + temp = temp.next + second = second.next + end + + first_prev.next = second if first_prev + second_prev.next = first if second_prev + + temp = first.next + first.next = second.next + second.next = temp + + return second if k == 1 + return first if second == head + + head +end diff --git a/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.rs b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.rs new file mode 100644 index 00000000..8b6cbeaa --- /dev/null +++ b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn swap_nodes(head: Option>, k: i32) -> Option> { + let mut values = Vec::new(); + let mut node = head; + while let Some(mut current) = node { + values.push(current.val); + node = current.next.take(); + } + if values.len() > 1 { + let a = (k - 1) as usize; + let b = values.len() - k as usize; + values.swap(a, b); + } + let mut result = None; + for value in values.into_iter().rev() { + result = Some(Box::new(ListNode { val: value, next: result })); + } + result + } +} diff --git a/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.swift b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.swift new file mode 100644 index 00000000..db026813 --- /dev/null +++ b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.swift @@ -0,0 +1,54 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public var val: Int + * public var next: ListNode? + * public init() { self.val = 0; self.next = nil; } + * public init(_ val: Int) { self.val = val; self.next = nil; } + * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } + * } + */ +class Solution { + func swapNodes(_ head: ListNode?, _ k: Int) -> ListNode? { + if head == nil || head?.next == nil { + return head + } + + var temp = head + var firstPrev: ListNode? + + var n = 1 + while n < k { + firstPrev = temp + temp = temp?.next + n += 1 + } + + let first = temp + + var second = head + var secondPrev: ListNode? + temp = first + while temp?.next != nil { + secondPrev = second + temp = temp?.next + second = second?.next + } + + firstPrev?.next = second + secondPrev?.next = first + + let tempNext = first?.next + first?.next = second?.next + second?.next = tempNext + + if k == 1 { + return second + } + if second === head { + return first + } + + return head + } +} diff --git a/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.ts b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.ts new file mode 100644 index 00000000..28340418 --- /dev/null +++ b/tests/1501-2000/1721. swapping-nodes-in-a-linked-list/sol.ts @@ -0,0 +1,58 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function swapNodes(head: ListNode | null, k: number): ListNode | null { + if (head === null || head.next === null) { + return head; + } + + let temp = head; + let firstPrev: ListNode | null = null; + + let n = 1; + while (n < k) { + firstPrev = temp; + temp = temp.next; + n++; + } + + const first = temp; + + let second: ListNode | null = head; + let secondPrev: ListNode | null = null; + temp = first; + while (temp.next !== null) { + secondPrev = second; + temp = temp.next; + second = second.next; + } + + if (firstPrev !== null) { + firstPrev.next = second; + } + if (secondPrev !== null) { + secondPrev.next = first; + } + + const tempNext = first.next; + first.next = second.next; + second.next = tempNext; + + if (k === 1) { + return second; + } + if (second === head) { + return first; + } + + return head; +} diff --git a/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/manifest.yaml b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/manifest.yaml new file mode 100644 index 00000000..fa57acb2 --- /dev/null +++ b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/manifest.yaml @@ -0,0 +1,485 @@ +entry: + id: 1722 + title: "minimize-hamming-distance-after-swap-operations" + params: + source: + type: array + items: + type: int + target: + type: array + items: + type: int + allowedSwaps: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().minimumHammingDistance({source}, {target}, {allowedSwaps})" + rust: "Solution::minimum_hamming_distance({source}, {target}, {allowedSwaps})" + python3: "Solution().minimumHammingDistance({source}, {target}, {allowedSwaps})" + python2: "Solution().minimumHammingDistance({source}, {target}, {allowedSwaps})" + ruby: "minimum_hamming_distance({source}, {target}, {allowedSwaps})" + java: "new Solution().minimumHammingDistance({source}, {target}, {allowedSwaps})" + csharp: "new Solution().MinimumHammingDistance({source}, {target}, {allowedSwaps})" + kotlin: "Solution().minimumHammingDistance({source}, {target}, {allowedSwaps})" + go: "minimumHammingDistance({source}, {target}, {allowedSwaps})" + dart: "Solution().minimumHammingDistance({source}, {target}, {allowedSwaps})" + swift: "Solution().minimumHammingDistance({source}, {target}, {allowedSwaps})" + typescript: "minimumHammingDistance({source}, {target}, {allowedSwaps})" +judge: + type: "exact" +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().minimumHammingDistance(source, target, allowedSwaps, {result})" + checker: | + class Checker: + def minimumHammingDistance(self, source, target, allowedSwaps, result): + n = len(source) + if len(target) != n or not isinstance(result, int) or isinstance(result, bool): + return False + parent = list(range(n)) + def find(x): + while parent[x] != x: + parent[x] = parent[parent[x]] + x = parent[x] + return x + for edge in allowedSwaps: + if not isinstance(edge, list) or len(edge) != 2: + return False + a, b = edge + if not isinstance(a, int) or not isinstance(b, int) or a < 0 or b < 0 or a >= n or b >= n or a == b: + return False + ra, rb = find(a), find(b) + if ra != rb: + parent[ra] = rb + from collections import Counter + source_counts = {} + target_counts = {} + for i, value in enumerate(source): + source_counts.setdefault(find(i), Counter())[value] += 1 + for i, value in enumerate(target): + target_counts.setdefault(find(i), Counter())[value] += 1 + expected = 0 + for root, counts in target_counts.items(): + available = source_counts.get(root, Counter()) + expected += sum(max(0, count - available[value]) for value, count in counts.items()) + return result == expected +seed: 1722 +tests: + - name: example-one + in: + source: [1, 2, 3, 4] + target: [2, 1, 4, 5] + allowedSwaps: + - [0, 1] + - [2, 3] + out: 1 + - name: example-two-no-swaps + in: + source: [1, 2, 3, 4] + target: [1, 3, 2, 4] + allowedSwaps: [] + out: 2 + - name: example-three-connected + in: + source: [5, 1, 2, 4, 3] + target: [1, 5, 4, 2, 3] + allowedSwaps: + - [0, 4] + - [4, 2] + - [1, 3] + - [1, 4] + out: 0 + - name: singleton-match + in: + source: [7] + target: [7] + allowedSwaps: [] + out: 0 + - name: singleton-mismatch + in: + source: [7] + target: [8] + allowedSwaps: [] + out: 1 + - name: duplicate-values + in: + source: [1, 1, 2, 2] + target: [2, 1, 1, 2] + allowedSwaps: + - [0, 2] + - [1, 3] + out: 0 + - name: disconnected-components + in: + source: [1, 2, 3, 4, 5, 6] + target: [2, 1, 4, 3, 6, 5] + allowedSwaps: + - [0, 1] + - [2, 3] + out: 2 + - name: redundant-swaps + in: + source: [4, 3, 2, 1] + target: [1, 2, 3, 4] + allowedSwaps: + - [0, 1] + - [1, 2] + - [2, 3] + - [0, 3] + - [1, 2] + out: 0 + - name: chain-partial-match + in: + source: [1, 2, 3, 4, 5] + target: [5, 4, 3, 2, 1] + allowedSwaps: + - [0, 1] + - [1, 2] + out: 4 + - name: isolated-mismatch + in: + source: [1, 2, 3, 4, 5] + target: [2, 1, 3, 5, 4] + allowedSwaps: + - [0, 1] + out: 2 + - name: all-equal + in: + source: [9, 9, 9, 9, 9] + target: [9, 9, 9, 9, 9] + allowedSwaps: [] + out: 0 + - name: all-different-no-swaps + in: + source: [1, 2, 3, 4, 5] + target: [5, 4, 3, 2, 1] + allowedSwaps: [] + out: 4 + - name: two-components-balance + in: + source: [1, 2, 2, 1, 3, 4, 4, 3] + target: [2, 1, 1, 2, 4, 3, 3, 4] + allowedSwaps: + - [0, 1] + - [1, 2] + - [2, 3] + - [4, 5] + - [5, 6] + - [6, 7] + out: 0 + - name: bridge-enables-match + in: + source: [10, 20, 30, 40] + target: [30, 10, 40, 20] + allowedSwaps: + - [0, 1] + - [1, 2] + - [2, 3] + out: 0 + - name: values-at-limit + in: + source: [100000, 1, 99999] + target: [1, 99999, 100000] + allowedSwaps: + - [0, 1] + - [1, 2] + out: 0 + - name: no-self-loop-assumption + in: + source: [1, 2, 3] + target: [3, 2, 1] + allowedSwaps: + - [0, 2] + out: 0 + - name: component-cannot-cross + in: + source: [1, 2, 3, 4] + target: [3, 2, 1, 4] + allowedSwaps: + - [0, 1] + out: 2 + - name: repeated-edge + in: + source: [8, 7, 6, 5] + target: [7, 8, 5, 6] + allowedSwaps: + - [0, 1] + - [0, 1] + - [2, 3] + - [2, 3] + out: 0 + - name: one-way-looking-chain + in: + source: [1, 2, 3, 4, 5, 6] + target: [6, 5, 4, 3, 2, 1] + allowedSwaps: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + out: 2 + - name: balanced-multiset-but-separated + in: + source: [1, 2, 3, 1, 2, 3] + target: [2, 1, 3, 2, 3, 1] + allowedSwaps: + - [0, 1] + - [3, 4] + out: 2 + - name: complete-graph-small + in: + source: [1, 2, 3, 4, 5] + target: [5, 4, 3, 2, 1] + allowedSwaps: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 3] + - [2, 4] + - [3, 4] + out: 0 + - name: alternating-components + in: + source: [1, 2, 1, 2, 3, 4, 3, 4] + target: [2, 1, 2, 1, 4, 3, 4, 3] + allowedSwaps: + - [0, 2] + - [1, 3] + - [4, 6] + - [5, 7] + out: 8 + - name: one-value-deficit + in: + source: [1, 1, 2, 3] + target: [1, 2, 2, 3] + allowedSwaps: + - [0, 1] + - [1, 2] + out: 1 + - name: isolated-equal-amid-mismatch + in: + source: [1, 2, 3, 4, 5, 6, 7] + target: [7, 2, 6, 5, 4, 3, 1] + allowedSwaps: + - [0, 6] + - [2, 5] + - [3, 4] + out: 0 + - name: sparse-edges + in: + source: [1, 2, 3, 4, 5, 6, 7, 8] + target: [2, 3, 4, 1, 6, 5, 8, 7] + allowedSwaps: + - [0, 1] + - [1, 2] + - [2, 3] + - [4, 5] + out: 2 + - name: all-singletons + in: + source: [1, 2, 3, 4, 5, 6] + target: [6, 5, 4, 3, 2, 1] + allowedSwaps: [] + out: 6 + - name: pairwise-duplicates + in: + source: [1, 1, 2, 2, 3, 3] + target: [2, 2, 3, 3, 1, 1] + allowedSwaps: + - [0, 2] + - [1, 3] + - [2, 4] + - [3, 5] + out: 0 + - name: nested-component + in: + source: [5, 4, 3, 2, 1, 0] + target: [0, 1, 2, 3, 4, 5] + allowedSwaps: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + out: 2 + - name: same-component-wrong-multiplicity + in: + source: [1, 1, 1, 2, 2, 3] + target: [1, 2, 2, 2, 1, 3] + allowedSwaps: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + out: 1 + - name: mixed-isolated-values + in: + source: [10, 20, 30, 40, 50, 60] + target: [20, 10, 60, 40, 30, 50] + allowedSwaps: + - [0, 1] + - [2, 5] + out: 2 + - name: large-value-duplicates + in: + source: [100000, 100000, 99999, 99999, 1, 1] + target: [99999, 99999, 1, 1, 100000, 100000] + allowedSwaps: + - [0, 2] + - [1, 3] + - [2, 4] + - [3, 5] + out: 0 + - name: component-size-three + in: + source: [1, 2, 3, 4, 5, 6, 7] + target: [3, 1, 2, 5, 4, 7, 6] + allowedSwaps: + - [0, 1] + - [1, 2] + - [3, 4] + - [5, 6] + out: 0 + - name: component-size-three-deficit + in: + source: [1, 2, 3, 4, 5, 6, 7] + target: [3, 1, 4, 5, 2, 7, 6] + allowedSwaps: + - [0, 1] + - [1, 2] + - [3, 4] + out: 4 + - name: max-small-chain + in: + source: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + target: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + allowedSwaps: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + out: 8 + - name: stress-long-valid-chain + in: + source: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + target: [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + allowedSwaps: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + out: 0 + - name: generated-no-swaps-small + in: + source: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + target: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + allowedSwaps: [] + - name: generated-no-swaps-medium + in: + source: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + target: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + allowedSwaps: [] + - name: generated-no-swaps-large + in: + source: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + target: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + allowedSwaps: [] + - name: generated-no-swaps-stress + in: + source: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + target: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + allowedSwaps: [] + - name: generated-no-swaps-maximum + in: + source: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + target: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + allowedSwaps: [] diff --git a/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.cpp b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.cpp new file mode 100644 index 00000000..9fa36f13 --- /dev/null +++ b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + int minimumHammingDistance(vector& source, vector& target, vector>& allowedSwaps) { + int n = source.size(); + vector parent(n); + iota(parent.begin(), parent.end(), 0); + + function find = [&](int x) -> int { + if (parent[x] != x) { + parent[x] = find(parent[x]); + } + return parent[x]; + }; + + auto unite = [&](int a, int b) { + parent[find(a)] = find(b); + }; + + for (auto& swap : allowedSwaps) { + unite(swap[0], swap[1]); + } + + unordered_map> groups; + for (int i = 0; i < n; i++) { + groups[find(i)].push_back(source[i]); + } + unordered_map> freq_map; + for (auto& [root, vals] : groups) { + unordered_map freq; + for (int v : vals) freq[v]++; + freq_map[root] = freq; + } + + int hamming_dist = 0; + for (int i = 0; i < n; i++) { + int root = find(i); + auto& freq = freq_map[root]; + int val = target[i]; + if (freq[val] > 0) { + freq[val]--; + } else { + hamming_dist++; + } + } + return hamming_dist; + } +}; diff --git a/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.cs b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.cs new file mode 100644 index 00000000..9a56dcb1 --- /dev/null +++ b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.cs @@ -0,0 +1,50 @@ +public class Solution { + public int MinimumHammingDistance(int[] source, int[] target, int[][] allowedSwaps) { + int n = source.Length; + int[] parent = new int[n]; + for (int i = 0; i < n; i++) parent[i] = i; + + int Find(int x) { + if (parent[x] != x) { + parent[x] = Find(parent[x]); + } + return parent[x]; + } + + void Unite(int a, int b) { + parent[Find(a)] = Find(b); + } + + foreach (var swap in allowedSwaps) { + Unite(swap[0], swap[1]); + } + + var groups = new Dictionary>(); + for (int i = 0; i < n; i++) { + int root = Find(i); + if (!groups.ContainsKey(root)) groups[root] = new List(); + groups[root].Add(source[i]); + } + var freqMap = new Dictionary>(); + foreach (var kvp in groups) { + var freq = new Dictionary(); + foreach (var v in kvp.Value) { + freq[v] = freq.GetValueOrDefault(v) + 1; + } + freqMap[kvp.Key] = freq; + } + + int hammingDist = 0; + for (int i = 0; i < n; i++) { + int root = Find(i); + var freq = freqMap[root]; + int val = target[i]; + if (freq.GetValueOrDefault(val) > 0) { + freq[val]--; + } else { + hammingDist++; + } + } + return hammingDist; + } +} diff --git a/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.dart b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.dart new file mode 100644 index 00000000..4594fc83 --- /dev/null +++ b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.dart @@ -0,0 +1,48 @@ +class Solution { + int minimumHammingDistance(List source, List target, List> allowedSwaps) { + int n = source.length; + List parent = List.generate(n, (i) => i); + + int find(int x) { + if (parent[x] != x) { + parent[x] = find(parent[x]); + } + return parent[x]; + } + + void unite(int a, int b) { + parent[find(a)] = find(b); + } + + for (var swap in allowedSwaps) { + unite(swap[0], swap[1]); + } + + Map> groups = {}; + for (int i = 0; i < n; i++) { + int root = find(i); + groups.putIfAbsent(root, () => []).add(source[i]); + } + Map> freqMap = {}; + groups.forEach((root, vals) { + Map freq = {}; + for (var v in vals) { + freq[v] = (freq[v] ?? 0) + 1; + } + freqMap[root] = freq; + }); + + int hammingDist = 0; + for (int i = 0; i < n; i++) { + int root = find(i); + var freq = freqMap[root]!; + int val = target[i]; + if (freq[val] != null && freq[val]! > 0) { + freq[val] = freq[val]! - 1; + } else { + hammingDist++; + } + } + return hammingDist; + } +} diff --git a/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.go b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.go new file mode 100644 index 00000000..c624bb61 --- /dev/null +++ b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.go @@ -0,0 +1,50 @@ +func minimumHammingDistance(source []int, target []int, allowedSwaps [][]int) int { + n := len(source) + parent := make([]int, n) + for i := range parent { + parent[i] = i + } + + var find func(int) int + find = func(x int) int { + if parent[x] != x { + parent[x] = find(parent[x]) + } + return parent[x] + } + + unite := func(a, b int) { + parent[find(a)] = find(b) + } + + for _, swap := range allowedSwaps { + unite(swap[0], swap[1]) + } + + groups := make(map[int][]int) + for i := 0; i < n; i++ { + root := find(i) + groups[root] = append(groups[root], source[i]) + } + freqMap := make(map[int]map[int]int) + for root, vals := range groups { + freq := make(map[int]int) + for _, v := range vals { + freq[v]++ + } + freqMap[root] = freq + } + + hammingDist := 0 + for i := 0; i < n; i++ { + root := find(i) + freq := freqMap[root] + val := target[i] + if freq[val] > 0 { + freq[val]-- + } else { + hammingDist++ + } + } + return hammingDist +} diff --git a/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.java b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.java new file mode 100644 index 00000000..13a5fa4b --- /dev/null +++ b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.java @@ -0,0 +1,49 @@ +class Solution { + public int minimumHammingDistance(int[] source, int[] target, int[][] allowedSwaps) { + int n = source.length; + int[] parent = new int[n]; + for (int i = 0; i < n; i++) parent[i] = i; + + java.util.function.IntFunction find = new java.util.function.IntFunction<>() { + @Override + public Integer apply(int x) { + if (parent[x] != x) { + parent[x] = apply(parent[x]); + } + return parent[x]; + } + }; + + for (int[] swap : allowedSwaps) { + int a = swap[0], b = swap[1]; + parent[find.apply(a)] = find.apply(b); + } + + java.util.Map> groups = new java.util.HashMap<>(); + for (int i = 0; i < n; i++) { + int root = find.apply(i); + groups.computeIfAbsent(root, k -> new java.util.ArrayList<>()).add(source[i]); + } + java.util.Map> freqMap = new java.util.HashMap<>(); + for (java.util.Map.Entry> entry : groups.entrySet()) { + java.util.Map freq = new java.util.HashMap<>(); + for (int val : entry.getValue()) { + freq.put(val, freq.getOrDefault(val, 0) + 1); + } + freqMap.put(entry.getKey(), freq); + } + + int hammingDist = 0; + for (int i = 0; i < n; i++) { + int root = find.apply(i); + java.util.Map freq = freqMap.get(root); + int val = target[i]; + if (freq.getOrDefault(val, 0) > 0) { + freq.put(val, freq.get(val) - 1); + } else { + hammingDist++; + } + } + return hammingDist; + } +} diff --git a/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.kt b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.kt new file mode 100644 index 00000000..1af406f2 --- /dev/null +++ b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.kt @@ -0,0 +1,41 @@ +class Solution { + fun minimumHammingDistance(source: IntArray, target: IntArray, allowedSwaps: Array): Int { + val n = source.size + val parent = IntArray(n) { it } + + fun find(x: Int): Int { + if (parent[x] != x) { + parent[x] = find(parent[x]) + } + return parent[x] + } + + fun unite(a: Int, b: Int) { + parent[find(a)] = find(b) + } + + for (swap in allowedSwaps) { + unite(swap[0], swap[1]) + } + + val groups = mutableMapOf>() + for (i in 0 until n) { + val root = find(i) + groups.getOrPut(root) { mutableListOf() }.add(source[i]) + } + val freqMap = groups.mapValues { (_, vals) -> vals.groupingBy { it }.eachCount().toMutableMap() } + + var hammingDist = 0 + for (i in 0 until n) { + val root = find(i) + val freq = freqMap.getValue(root) + val value = target[i] + if (freq.getOrDefault(value, 0) > 0) { + freq[value] = freq[value]!! - 1 + } else { + hammingDist++ + } + } + return hammingDist + } +} diff --git a/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.py b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.py new file mode 100644 index 00000000..c59e76c4 --- /dev/null +++ b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.py @@ -0,0 +1,36 @@ +class Solution: + def minimumHammingDistance( + self, source: list[int], target: list[int], allowedSwaps: list[list[int]] + ) -> int: + n = len(source) + parent = list(range(n)) + + def find(x): + if parent[x] != x: + parent[x] = find(parent[x]) + return parent[x] + + def unite(a, b): + parent[find(a)] = find(b) + + for a, b in allowedSwaps: + unite(a, b) + + # Group source values by their component root + from collections import defaultdict, Counter + + groups = defaultdict(list) + for i in range(n): + groups[find(i)].append(source[i]) + groups = {root: Counter(vals) for root, vals in groups.items()} + + hamming_dist = 0 + for i in range(n): + root = find(i) + freq = groups[root] + if freq[target[i]] > 0: + freq[target[i]] -= 1 # matched, consume this source value + else: + hamming_dist += 1 # no match found in this component + + return hamming_dist diff --git a/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.py2 b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.py2 new file mode 100644 index 00000000..122dc8af --- /dev/null +++ b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.py2 @@ -0,0 +1,37 @@ +class Solution(object): + def minimumHammingDistance(self, source, target, allowedSwaps): + """ + :type source: List[int] + :type target: List[int] + :type allowedSwaps: List[List[int]] + :rtype: int + """ + n = len(source) + parent = list(range(n)) + + def find(x): + if parent[x] != x: + parent[x] = find(parent[x]) + return parent[x] + + def unite(a, b): + parent[find(a)] = find(b) + + for a, b in allowedSwaps: + unite(a, b) + + from collections import defaultdict, Counter + groups = defaultdict(list) + for i in range(n): + groups[find(i)].append(source[i]) + groups = {root: Counter(vals) for root, vals in groups.items()} + + hamming_dist = 0 + for i in range(n): + root = find(i) + freq = groups[root] + if freq[target[i]] > 0: + freq[target[i]] -= 1 + else: + hamming_dist += 1 + return hamming_dist diff --git a/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.rb b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.rb new file mode 100644 index 00000000..7fa20748 --- /dev/null +++ b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.rb @@ -0,0 +1,41 @@ +# @param {Integer[]} source +# @param {Integer[]} target +# @param {Integer[][]} allowed_swaps +# @return {Integer} +def minimum_hamming_distance(source, target, allowed_swaps) + n = source.length + parent = (0...n).to_a + + find = ->(x) { + if parent[x] != x + parent[x] = find.call(parent[x]) + end + parent[x] + } + + unite = ->(a, b) { + parent[find.call(a)] = find.call(b) + } + + allowed_swaps.each do |a, b| + unite.call(a, b) + end + + groups = Hash.new { |h, k| h[k] = [] } + (0...n).each do |i| + groups[find.call(i)] << source[i] + end + groups = groups.transform_values { |vals| vals.tally } + + hamming_dist = 0 + (0...n).each do |i| + root = find.call(i) + freq = groups[root] + if freq[target[i]].to_i > 0 + freq[target[i]] -= 1 + else + hamming_dist += 1 + end + end + hamming_dist +end diff --git a/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.rs b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.rs new file mode 100644 index 00000000..54112467 --- /dev/null +++ b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.rs @@ -0,0 +1,52 @@ +impl Solution { + pub fn minimum_hamming_distance(source: Vec, target: Vec, allowed_swaps: Vec>) -> i32 { + let n = source.len(); + let mut parent: Vec = (0..n).collect(); + + fn find(parent: &mut Vec, x: usize) -> usize { + if parent[x] != x { + parent[x] = find(parent, parent[x]); + } + parent[x] + } + + fn unite(parent: &mut Vec, a: usize, b: usize) { + let ra = find(parent, a); + let rb = find(parent, b); + parent[ra] = rb; + } + + for swap in allowed_swaps { + unite(&mut parent, swap[0] as usize, swap[1] as usize); + } + + use std::collections::HashMap; + let mut groups: HashMap> = HashMap::new(); + for i in 0..n { + let root = find(&mut parent, i); + groups.entry(root).or_insert(Vec::new()).push(source[i]); + } + let mut freq_map: HashMap> = HashMap::new(); + for (root, vals) in groups { + let mut freq = HashMap::new(); + for v in vals { + *freq.entry(v).or_insert(0) += 1; + } + freq_map.insert(root, freq); + } + + let mut hamming_dist = 0; + for i in 0..n { + let root = find(&mut parent, i); + let freq = freq_map.get_mut(&root).unwrap(); + let val = target[i]; + let count = freq.entry(val).or_insert(0); + if *count > 0 { + *count -= 1; + } else { + hamming_dist += 1; + } + } + hamming_dist + } +} diff --git a/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.swift b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.swift new file mode 100644 index 00000000..05065427 --- /dev/null +++ b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.swift @@ -0,0 +1,47 @@ +class Solution { + func minimumHammingDistance(_ source: [Int], _ target: [Int], _ allowedSwaps: [[Int]]) -> Int { + let n = source.count + var parent = Array(0.. Int { + if parent[x] != x { + parent[x] = find(parent[x]) + } + return parent[x] + } + + func unite(_ a: Int, _ b: Int) { + parent[find(a)] = find(b) + } + + for swap in allowedSwaps { + unite(swap[0], swap[1]) + } + + var groups: [Int: [Int]] = [:] + for i in 0.. 0 { + freqMap[root]![val]! -= 1 + } else { + hammingDist += 1 + } + } + return hammingDist + } +} diff --git a/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.ts b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.ts new file mode 100644 index 00000000..49bd77a1 --- /dev/null +++ b/tests/1501-2000/1722. minimize-hamming-distance-after-swap-operations/sol.ts @@ -0,0 +1,52 @@ +function minimumHammingDistance( + source: number[], + target: number[], + allowedSwaps: number[][], +): number { + const n = source.length; + const parent: number[] = Array.from({ length: n }, (_, i) => i); + + function find(x: number): number { + if (parent[x] !== x) { + parent[x] = find(parent[x]); + } + return parent[x]; + } + + function unite(a: number, b: number): void { + parent[find(a)] = find(b); + } + + for (const [a, b] of allowedSwaps) { + unite(a, b); + } + + const groups: Map = new Map(); + for (let i = 0; i < n; i++) { + const root = find(i); + if (!groups.has(root)) groups.set(root, []); + groups.get(root)!.push(source[i]); + } + const freqMap: Map> = new Map(); + for (const [root, vals] of groups) { + const freq = new Map(); + for (const v of vals) { + freq.set(v, (freq.get(v) || 0) + 1); + } + freqMap.set(root, freq); + } + + let hammingDist = 0; + for (let i = 0; i < n; i++) { + const root = find(i); + const freq = freqMap.get(root)!; + const val = target[i]; + const count = freq.get(val) || 0; + if (count > 0) { + freq.set(val, count - 1); + } else { + hammingDist++; + } + } + return hammingDist; +} diff --git a/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/manifest.yaml b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/manifest.yaml new file mode 100644 index 00000000..ba6c9f29 --- /dev/null +++ b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/manifest.yaml @@ -0,0 +1,244 @@ +entry: + id: 1723 + title: "find-minimum-time-to-finish-all-jobs" + params: + jobs: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().minimumTimeRequired({jobs}, {k})" + rust: "Solution::minimum_time_required({jobs}, {k})" + python3: "Solution().minimumTimeRequired({jobs}, {k})" + python2: "Solution().minimumTimeRequired({jobs}, {k})" + ruby: "minimum_time_required({jobs}, {k})" + java: "new Solution().minimumTimeRequired({jobs}, {k})" + csharp: "new Solution().MinimumTimeRequired({jobs}, {k})" + kotlin: "Solution().minimumTimeRequired({jobs}, {k})" + go: "minimumTimeRequired({jobs}, {k})" + dart: "Solution().minimumTimeRequired({jobs}, {k})" + swift: "Solution().minimumTimeRequired({jobs}, {k})" + typescript: "minimumTimeRequired({jobs}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minimumTimeRequired(jobs, k, {result})" + checker: | + class Checker: + def minimumTimeRequired(self, jobs, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + jobs = sorted(jobs, reverse=True) + lo, hi = max(jobs), sum(jobs) + def feasible(limit): + loads = [0] * k + def dfs(i): + if i == len(jobs): + return True + seen = set() + job = jobs[i] + for w in range(k): + if loads[w] in seen: + continue + seen.add(loads[w]) + if loads[w] + job <= limit: + loads[w] += job + if dfs(i + 1): + return True + loads[w] -= job + if loads[w] == 0: + break + return False + return dfs(0) + while lo < hi: + mid = (lo + hi) // 2 + if feasible(mid): + hi = mid + else: + lo = mid + 1 + return result == lo + +seed: 1723 + +tests: + - name: example-one + in: + jobs: [3, 2, 3] + k: 3 + - name: example-two + in: + jobs: [1, 2, 4, 7, 8] + k: 2 + - name: one-job + in: + jobs: [9] + k: 1 + - name: two-jobs-two-workers + in: + jobs: [5, 11] + k: 2 + - name: all-equal + in: + jobs: [4, 4, 4, 4, 4, 4] + k: 3 + - name: all-equal-workers + in: + jobs: [7, 7, 7, 7] + k: 4 + - name: one-worker + in: + jobs: [1, 2, 3, 4, 5, 6] + k: 1 + - name: workers-equal-jobs + in: + jobs: [1, 8, 3, 10, 2] + k: 5 + - name: dominant-job + in: + jobs: [100, 1, 1, 1, 1, 1] + k: 3 + - name: balanced-pairs + in: + jobs: [8, 7, 6, 5, 4, 3] + k: 3 + - name: uneven-small + in: + jobs: [2, 2, 3, 7, 8] + k: 2 + - name: duplicate-large + in: + jobs: [20, 20, 20, 1, 1, 1] + k: 3 + - name: powers + in: + jobs: [1, 2, 4, 8, 16, 32] + k: 3 + - name: many-ones + in: + jobs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + k: 4 + - name: k-two + in: + jobs: [9, 8, 7, 6, 5, 4, 3, 2] + k: 2 + - name: k-three + in: + jobs: [13, 12, 11, 10, 9, 8, 7] + k: 3 + - name: tiny-mixed + in: + jobs: [1, 3, 1, 2] + k: 2 + - name: near-balanced + in: + jobs: [10, 9, 8, 7, 6, 5, 4] + k: 4 + - name: large-values + in: + jobs: [10000000, 9999999, 1, 2, 3, 4] + k: 2 + - name: large-equal + in: + jobs: [10000000, 10000000, 10000000, 10000000] + k: 2 + - name: max-length-one-worker + in: + jobs: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + k: 1 + - name: max-length-many-workers + in: + jobs: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + k: 12 + - name: max-length-two + in: + jobs: [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + k: 2 + - name: max-length-three + in: + jobs: [12, 12, 11, 11, 10, 10, 9, 9, 8, 8, 7, 7] + k: 3 + - name: max-length-four + in: + jobs: [30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19] + k: 4 + - name: max-length-five + in: + jobs: [50, 1, 49, 2, 48, 3, 47, 4, 46, 5, 45, 6] + k: 5 + - name: max-length-six + in: + jobs: [37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26] + k: 6 + - name: max-length-seven + in: + jobs: [100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 9, 8] + k: 7 + - name: max-length-eight + in: + jobs: [17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6] + k: 8 + - name: max-length-nine + in: + jobs: [1000, 999, 998, 997, 996, 995, 994, 993, 992, 991, 990, 989] + k: 9 + - name: max-length-ten + in: + jobs: [5, 15, 25, 35, 45, 55, 65, 75, 85, 95, 105, 115] + k: 10 + - name: max-length-eleven + in: + jobs: + [ + 10000000, + 1, + 9999998, + 2, + 9999996, + 3, + 9999994, + 4, + 9999992, + 5, + 9999990, + 6, + ] + k: 11 + - name: max-length-k-six + in: + jobs: [21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10] + k: 6 + - name: max-length-k-four + in: + jobs: [1, 100, 2, 99, 3, 98, 4, 97, 5, 96, 6, 95] + k: 4 + - name: max-length-k-two-alternating + in: + jobs: + [ + 10000000, + 1, + 9999999, + 2, + 9999998, + 3, + 9999997, + 4, + 9999996, + 5, + 9999995, + 6, + ] + k: 2 + - name: max-length-k-three-alternating + in: + jobs: [100, 1, 99, 2, 98, 3, 97, 4, 96, 5, 95, 6] + k: 3 diff --git a/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.cpp b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.cpp new file mode 100644 index 00000000..d017b658 --- /dev/null +++ b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int minimumTimeRequired(vector& jobs, int k) { + sort(jobs.rbegin(), jobs.rend()); + int left = jobs[0]; + int right = accumulate(jobs.begin(), jobs.end(), 0); + + function canDistribute = [&](int maxWorkload) { + vector workers(k, 0); + function assignJob = [&](int jobIndex) { + if (jobIndex == jobs.size()) return true; + for (int i = 0; i < k; i++) { + if (workers[i] + jobs[jobIndex] <= maxWorkload) { + workers[i] += jobs[jobIndex]; + if (assignJob(jobIndex + 1)) return true; + workers[i] -= jobs[jobIndex]; + } + if (workers[i] == 0) break; + } + return false; + }; + return assignJob(0); + }; + + while (left < right) { + int mid = (left + right) / 2; + if (canDistribute(mid)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; diff --git a/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.cs b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.cs new file mode 100644 index 00000000..843aad9f --- /dev/null +++ b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.cs @@ -0,0 +1,35 @@ +public class Solution { + public int MinimumTimeRequired(int[] jobs, int k) { + Array.Sort(jobs); + Array.Reverse(jobs); + int left = jobs[0]; + int right = jobs.Sum(); + + bool CanDistribute(int maxWorkload) { + int[] workers = new int[k]; + bool AssignJob(int jobIndex) { + if (jobIndex == jobs.Length) return true; + for (int i = 0; i < k; i++) { + if (workers[i] + jobs[jobIndex] <= maxWorkload) { + workers[i] += jobs[jobIndex]; + if (AssignJob(jobIndex + 1)) return true; + workers[i] -= jobs[jobIndex]; + } + if (workers[i] == 0) break; + } + return false; + } + return AssignJob(0); + } + + while (left < right) { + int mid = (left + right) / 2; + if (CanDistribute(mid)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} diff --git a/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.dart b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.dart new file mode 100644 index 00000000..47074b2a --- /dev/null +++ b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.dart @@ -0,0 +1,36 @@ +class Solution { + int minimumTimeRequired(List jobs, int k) { + jobs.sort((a, b) => b.compareTo(a)); + int left = jobs[0]; + int right = jobs.fold(0, (sum, j) => sum + j); + + bool canDistribute(int maxWorkload) { + List workers = List.filled(k, 0); + + bool assignJob(int jobIndex) { + if (jobIndex == jobs.length) return true; + for (int i = 0; i < k; i++) { + if (workers[i] + jobs[jobIndex] <= maxWorkload) { + workers[i] += jobs[jobIndex]; + if (assignJob(jobIndex + 1)) return true; + workers[i] -= jobs[jobIndex]; + } + if (workers[i] == 0) break; + } + return false; + } + + return assignJob(0); + } + + while (left < right) { + int mid = (left + right) ~/ 2; + if (canDistribute(mid)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} diff --git a/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.go b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.go new file mode 100644 index 00000000..067ca89f --- /dev/null +++ b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.go @@ -0,0 +1,43 @@ +func minimumTimeRequired(jobs []int, k int) int { + sort.Sort(sort.Reverse(sort.IntSlice(jobs))) + left, right := jobs[0], 0 + for _, j := range jobs { + right += j + } + + canDistribute := func(maxWorkload int) bool { + workers := make([]int, k) + + var assignJob func(int) bool + assignJob = func(jobIndex int) bool { + if jobIndex == len(jobs) { + return true + } + for i := 0; i < k; i++ { + if workers[i] + jobs[jobIndex] <= maxWorkload { + workers[i] += jobs[jobIndex] + if assignJob(jobIndex + 1) { + return true + } + workers[i] -= jobs[jobIndex] + } + if workers[i] == 0 { + break + } + } + return false + } + + return assignJob(0) + } + + for left < right { + mid := (left + right) / 2 + if canDistribute(mid) { + right = mid + } else { + left = mid + 1 + } + } + return left +} diff --git a/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.java b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.java new file mode 100644 index 00000000..457905d1 --- /dev/null +++ b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.java @@ -0,0 +1,42 @@ +class Solution { + public int minimumTimeRequired(int[] jobs, int k) { + java.util.Arrays.sort(jobs); + for (int i = 0, j = jobs.length - 1; i < j; i++, j--) { + int temp = jobs[i]; + jobs[i] = jobs[j]; + jobs[j] = temp; + } + + int left = jobs[0]; + long right = 0; + for (int j : jobs) right += j; + + while (left < right) { + int mid = (int) ((left + right) / 2); + if (canDistribute(mid, jobs, k)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } + + private boolean canDistribute(int maxWorkload, int[] jobs, int k) { + int[] workers = new int[k]; + return assignJob(0, maxWorkload, jobs, workers); + } + + private boolean assignJob(int jobIndex, int maxWorkload, int[] jobs, int[] workers) { + if (jobIndex == jobs.length) return true; + for (int i = 0; i < workers.length; i++) { + if (workers[i] + jobs[jobIndex] <= maxWorkload) { + workers[i] += jobs[jobIndex]; + if (assignJob(jobIndex + 1, maxWorkload, jobs, workers)) return true; + workers[i] -= jobs[jobIndex]; + } + if (workers[i] == 0) break; + } + return false; + } +} diff --git a/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.kt b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.kt new file mode 100644 index 00000000..a45b9fd5 --- /dev/null +++ b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.kt @@ -0,0 +1,36 @@ +class Solution { + fun minimumTimeRequired(jobs: IntArray, k: Int): Int { + jobs.sortDescending() + var left = jobs[0] + var right = jobs.sum() + + fun canDistribute(maxWorkload: Int): Boolean { + val workers = IntArray(k) + + fun assignJob(jobIndex: Int): Boolean { + if (jobIndex == jobs.size) return true + for (i in 0 until k) { + if (workers[i] + jobs[jobIndex] <= maxWorkload) { + workers[i] += jobs[jobIndex] + if (assignJob(jobIndex + 1)) return true + workers[i] -= jobs[jobIndex] + } + if (workers[i] == 0) break + } + return false + } + + return assignJob(0) + } + + while (left < right) { + val mid = (left + right) / 2 + if (canDistribute(mid)) { + right = mid + } else { + left = mid + 1 + } + } + return left + } +} diff --git a/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.py b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.py new file mode 100644 index 00000000..8d65e99e --- /dev/null +++ b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.py @@ -0,0 +1,37 @@ +class Solution: + def minimumTimeRequired(self, jobs: List[int], k: int) -> int: + # Sort the jobs in descending order + jobs.sort(reverse=True) + + # Define binary search boundaries + left, right = max(jobs), sum(jobs) + + def canDistribute(maxWorkload): + # Track how many workers are used and their current workloads + workers = [0] * k + + def assignJob(jobIndex): + if jobIndex == len(jobs): + return True + for i in range(k): + if workers[i] + jobs[jobIndex] <= maxWorkload: + workers[i] += jobs[jobIndex] + if assignJob(jobIndex + 1): + return True + workers[i] -= jobs[jobIndex] + # If this worker has no jobs assigned yet, break to avoid duplicates + if workers[i] == 0: + break + return False + + return assignJob(0) + + # Binary search to find the minimum possible maximum workload + while left < right: + mid = (left + right) // 2 + if canDistribute(mid): + right = mid + else: + left = mid + 1 + + return left diff --git a/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.py2 b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.py2 new file mode 100644 index 00000000..0e64349e --- /dev/null +++ b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.py2 @@ -0,0 +1,36 @@ +class Solution(object): + def minimumTimeRequired(self, jobs, k): + """ + :type jobs: List[int] + :type k: int + :rtype: int + """ + jobs.sort(reverse=True) + left, right = max(jobs), sum(jobs) + + def canDistribute(maxWorkload): + workers = [0] * k + + def assignJob(jobIndex): + if jobIndex == len(jobs): + return True + for i in range(k): + if workers[i] + jobs[jobIndex] <= maxWorkload: + workers[i] += jobs[jobIndex] + if assignJob(jobIndex + 1): + return True + workers[i] -= jobs[jobIndex] + if workers[i] == 0: + break + return False + + return assignJob(0) + + while left < right: + mid = (left + right) // 2 + if canDistribute(mid): + right = mid + else: + left = mid + 1 + + return left diff --git a/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.rb b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.rb new file mode 100644 index 00000000..1e59cf66 --- /dev/null +++ b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.rb @@ -0,0 +1,37 @@ +# @param {Integer[]} jobs +# @param {Integer} k +# @return {Integer} +def minimum_time_required(jobs, k) + jobs.sort! { |a, b| b <=> a } + left, right = jobs.max, jobs.sum + + can_distribute = lambda do |max_workload| + workers = Array.new(k, 0) + + assign_job = lambda do |job_index| + return true if job_index == jobs.length + (0...k).each do |i| + if workers[i] + jobs[job_index] <= max_workload + workers[i] += jobs[job_index] + return true if assign_job.call(job_index + 1) + workers[i] -= jobs[job_index] + end + break if workers[i] == 0 + end + false + end + + assign_job.call(0) + end + + while left < right + mid = (left + right) / 2 + if can_distribute.call(mid) + right = mid + else + left = mid + 1 + end + end + + left +end diff --git a/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.rs b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.rs new file mode 100644 index 00000000..ef352476 --- /dev/null +++ b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.rs @@ -0,0 +1,42 @@ +impl Solution { + pub fn minimum_time_required(jobs: Vec, k: i32) -> i32 { + let mut jobs = jobs; + jobs.sort_by(|a, b| b.cmp(a)); + let k = k as usize; + let mut left = jobs[0]; + let mut right: i32 = jobs.iter().sum(); + + fn can_distribute(jobs: &Vec, k: usize, max_workload: i32) -> bool { + let mut workers = vec![0; k]; + fn assign_job(jobs: &Vec, workers: &mut Vec, job_index: usize, max_workload: i32) -> bool { + if job_index == jobs.len() { + return true; + } + for i in 0..workers.len() { + if workers[i] + jobs[job_index] <= max_workload { + workers[i] += jobs[job_index]; + if assign_job(jobs, workers, job_index + 1, max_workload) { + return true; + } + workers[i] -= jobs[job_index]; + } + if workers[i] == 0 { + break; + } + } + false + } + assign_job(jobs, &mut workers, 0, max_workload) + } + + while left < right { + let mid = (left + right) / 2; + if can_distribute(&jobs, k, mid) { + right = mid; + } else { + left = mid + 1; + } + } + left + } +} diff --git a/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.swift b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.swift new file mode 100644 index 00000000..faaeffb6 --- /dev/null +++ b/tests/1501-2000/1723. find-minimum-time-to-finish-all-jobs/sol.swift @@ -0,0 +1,42 @@ +class Solution { + func minimumTimeRequired(_ jobs: [Int], _ k: Int) -> Int { + let jobs = jobs.sorted(by: >) + var left = jobs[0] + var right = jobs.reduce(0, +) + + func canDistribute(_ maxWorkload: Int) -> Bool { + var workers = Array(repeating: 0, count: k) + + func assignJob(_ jobIndex: Int) -> Bool { + if jobIndex == jobs.count { + return true + } + for i in 0.. b - a); + let left = jobs[0]; + let right = jobs.reduce((sum, j) => sum + j, 0); + + function canDistribute(maxWorkload: number): boolean { + const workers = new Array(k).fill(0); + + function assignJob(jobIndex: number): boolean { + if (jobIndex === jobs.length) return true; + for (let i = 0; i < k; i++) { + if (workers[i] + jobs[jobIndex] <= maxWorkload) { + workers[i] += jobs[jobIndex]; + if (assignJob(jobIndex + 1)) return true; + workers[i] -= jobs[jobIndex]; + } + if (workers[i] === 0) break; + } + return false; + } + + return assignJob(0); + } + + while (left < right) { + const mid = Math.floor((left + right) / 2); + if (canDistribute(mid)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; +} diff --git a/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/manifest.yaml b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/manifest.yaml new file mode 100644 index 00000000..c2a21b47 --- /dev/null +++ b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/manifest.yaml @@ -0,0 +1,407 @@ +entry: + id: 1725 + title: "number-of-rectangles-that-can-form-the-largest-square" + params: + rectangles: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().countGoodRectangles({rectangles})" + rust: "Solution::count_good_rectangles({rectangles})" + python3: "Solution().countGoodRectangles({rectangles})" + python2: "Solution().countGoodRectangles({rectangles})" + ruby: "count_good_rectangles({rectangles})" + java: "new Solution().countGoodRectangles({rectangles})" + csharp: "new Solution().CountGoodRectangles({rectangles})" + kotlin: "Solution().countGoodRectangles({rectangles})" + go: "countGoodRectangles({rectangles})" + dart: "Solution().countGoodRectangles({rectangles})" + swift: "Solution().countGoodRectangles({rectangles})" + typescript: "countGoodRectangles({rectangles})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().countGoodRectangles(rectangles, {result})" + checker: | + class Checker: + def countGoodRectangles(self, rectangles, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not rectangles or any(not isinstance(r, list) or len(r) != 2 for r in rectangles): + return False + best = max(min(r[0], r[1]) for r in rectangles) + expected = sum(1 for r in rectangles if min(r[0], r[1]) == best) + return result == expected + +seed: 1725 + +tests: + - name: example-one + in: + rectangles: + - [5, 8] + - [3, 9] + - [5, 12] + - [16, 5] + out: 3 + - name: example-two + in: + rectangles: + - [2, 3] + - [3, 7] + - [4, 3] + - [3, 7] + out: 3 + - name: single-rectangle + in: + rectangles: + - [4, 9] + out: 1 + - name: single-reversed + in: + rectangles: + - [100, 1] + out: 1 + - name: all-different-minima + in: + rectangles: + - [1, 10] + - [2, 9] + - [3, 8] + - [4, 7] + - [5, 6] + out: 1 + - name: all-share-maximum + in: + rectangles: + - [7, 11] + - [12, 7] + - [7, 8] + - [100, 7] + out: 4 + - name: maximum-comes-first + in: + rectangles: + - [999999999, 999999998] + - [2, 100] + - [3, 90] + out: 1 + - name: maximum-comes-last + in: + rectangles: + - [2, 100] + - [3, 90] + - [999999999, 999999998] + out: 1 + - name: alternating-orientation + in: + rectangles: + - [6, 20] + - [30, 6] + - [6, 7] + - [8, 6] + - [6, 100] + out: 5 + - name: one-best-among-ties + in: + rectangles: + - [4, 100] + - [5, 6] + - [8, 5] + - [7, 9] + - [1, 50] + out: 1 + - name: minima-one + in: + rectangles: + - [1, 2] + - [1, 100] + - [50, 1] + - [1, 3] + out: 4 + - name: minima-two + in: + rectangles: + - [2, 3] + - [2, 100] + - [4, 2] + - [1, 99] + - [3, 5] + out: 1 + - name: equal-long-sides + in: + rectangles: + - [10, 1] + - [10, 2] + - [10, 3] + - [10, 9] + out: 1 + - name: equal-wide-sides + in: + rectangles: + - [1, 10] + - [2, 10] + - [3, 10] + - [9, 10] + out: 1 + - name: increasing-minima + in: + rectangles: + - [2, 20] + - [7, 8] + - [3, 30] + - [9, 10] + - [4, 40] + - [6, 7] + out: 1 + - name: decreasing-minima + in: + rectangles: + - [20, 20] + - [9, 100] + - [8, 80] + - [7, 70] + - [1, 60] + out: 1 + - name: repeated-rectangles + in: + rectangles: + - [13, 21] + - [13, 21] + - [5, 50] + - [21, 13] + - [13, 100] + out: 4 + - name: near-int-limit + in: + rectangles: + - [1000000000, 999999999] + - [999999998, 1000000000] + - [999999999, 999999997] + - [1, 1000000000] + out: 1 + - name: tiny-values + in: + rectangles: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + out: 1 + - name: six-best + in: + rectangles: + - [11, 12] + - [12, 13] + - [13, 14] + - [14, 15] + - [15, 16] + - [16, 17] + - [10, 100] + out: 1 + - name: two-best-separated + in: + rectangles: + - [40, 41] + - [3, 100] + - [40, 100] + - [39, 90] + - [1, 2] + out: 2 + - name: three-best-separated + in: + rectangles: + - [25, 100] + - [1, 30] + - [25, 26] + - [8, 25] + - [25, 200] + - [24, 100] + out: 3 + - name: wide-rectangles + in: + rectangles: + - [2, 1000000000] + - [3, 999999999] + - [4, 999999998] + - [5, 999999997] + out: 1 + - name: tall-rectangles + in: + rectangles: + - [1000000000, 2] + - [999999999, 3] + - [999999998, 4] + - [999999997, 5] + out: 1 + - name: plateau-with-lower-tail + in: + rectangles: + - [17, 18] + - [18, 19] + - [17, 100] + - [2, 17] + - [17, 20] + - [16, 100] + - [17, 21] + out: 1 + - name: plateau-with-upper-tail + in: + rectangles: + - [17, 18] + - [18, 19] + - [17, 100] + - [19, 20] + - [17, 21] + - [16, 100] + out: 1 + - name: mixed-small + in: + rectangles: + - [9, 1] + - [8, 2] + - [7, 3] + - [6, 4] + - [5, 5] + - [4, 6] + - [3, 7] + - [2, 8] + out: 1 + - name: max-value-pair + in: + rectangles: + - [1000000000, 999999999] + out: 1 + - name: twenty-four-items + in: + rectangles: + - [1, 100] + - [2, 99] + - [3, 98] + - [4, 97] + - [5, 96] + - [6, 95] + - [7, 94] + - [8, 93] + - [9, 92] + - [10, 91] + - [11, 90] + - [12, 89] + - [13, 88] + - [14, 87] + - [15, 86] + - [16, 85] + - [17, 84] + - [18, 83] + - [19, 82] + - [20, 81] + - [21, 80] + - [22, 79] + - [23, 78] + - [24, 77] + out: 1 + - name: thirty-two-items + in: + rectangles: + - [31, 100] + - [32, 99] + - [33, 98] + - [34, 97] + - [35, 96] + - [36, 95] + - [37, 94] + - [38, 93] + - [39, 92] + - [40, 91] + - [41, 90] + - [42, 89] + - [43, 88] + - [44, 87] + - [45, 86] + - [46, 85] + - [47, 84] + - [48, 83] + - [49, 82] + - [50, 81] + - [51, 80] + - [52, 79] + - [53, 78] + - [54, 77] + - [55, 76] + - [56, 75] + - [57, 74] + - [58, 73] + - [59, 72] + - [60, 71] + - [61, 70] + - [62, 69] + out: 1 + - name: broad-tie + in: + rectangles: + - [42, 43] + - [43, 42] + - [100, 42] + - [42, 100] + - [42, 44] + - [44, 42] + - [41, 100] + - [1, 42] + out: 6 + - name: two-level-distribution + in: + rectangles: + - [100, 10] + - [10, 100] + - [99, 9] + - [9, 99] + - [98, 10] + - [10, 98] + - [97, 8] + - [8, 97] + - [96, 10] + out: 5 + - name: scattered-large + in: + rectangles: + - [123456789, 987654321] + - [222222222, 888888888] + - [777777777, 333333333] + - [444444444, 666666666] + - [555555555, 555555556] + - [999999999, 111111111] + out: 1 + - name: final-mixed + in: + rectangles: + - [30, 31] + - [31, 100] + - [29, 50] + - [100, 30] + - [30, 60] + - [28, 100] + - [30, 32] + - [1, 1000] + - [30, 33] + out: 1 + - name: four-equal-best-minima + in: + rectangles: + - [73, 100] + - [100, 73] + - [73, 74] + - [74, 73] + - [72, 100] + out: 4 diff --git a/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.cpp b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.cpp new file mode 100644 index 00000000..5c58706e --- /dev/null +++ b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int countGoodRectangles(vector>& rectangles) { + int maxLen = 0; + for (auto& rec : rectangles) { + maxLen = max(maxLen, min(rec[0], rec[1])); + } + int count = 0; + for (auto& rec : rectangles) { + if (min(rec[0], rec[1]) == maxLen) { + count++; + } + } + return count; + } +}; diff --git a/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.cs b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.cs new file mode 100644 index 00000000..0fe352e5 --- /dev/null +++ b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int CountGoodRectangles(int[][] rectangles) { + int maxLen = 0; + foreach (var rec in rectangles) { + maxLen = Math.Max(maxLen, Math.Min(rec[0], rec[1])); + } + int count = 0; + foreach (var rec in rectangles) { + if (Math.Min(rec[0], rec[1]) == maxLen) { + count++; + } + } + return count; + } +} diff --git a/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.dart b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.dart new file mode 100644 index 00000000..e4396bd9 --- /dev/null +++ b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.dart @@ -0,0 +1,15 @@ +class Solution { + int countGoodRectangles(List> rectangles) { + int best = 0; + for (final rectangle in rectangles) { + final side = rectangle[0] < rectangle[1] ? rectangle[0] : rectangle[1]; + if (side > best) best = side; + } + int count = 0; + for (final rectangle in rectangles) { + final side = rectangle[0] < rectangle[1] ? rectangle[0] : rectangle[1]; + if (side == best) count++; + } + return count; + } +} diff --git a/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.go b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.go new file mode 100644 index 00000000..9c6c29bc --- /dev/null +++ b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.go @@ -0,0 +1,23 @@ +func countGoodRectangles(rectangles [][]int) int { + maxLen := 0 + for _, rec := range rectangles { + mn := rec[0] + if rec[1] < mn { + mn = rec[1] + } + if mn > maxLen { + maxLen = mn + } + } + count := 0 + for _, rec := range rectangles { + mn := rec[0] + if rec[1] < mn { + mn = rec[1] + } + if mn == maxLen { + count++ + } + } + return count +} diff --git a/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.java b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.java new file mode 100644 index 00000000..be41a6fb --- /dev/null +++ b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.java @@ -0,0 +1,15 @@ +class Solution { + public int countGoodRectangles(int[][] rectangles) { + int maxLen = 0; + for (int[] rec : rectangles) { + maxLen = Math.max(maxLen, Math.min(rec[0], rec[1])); + } + int count = 0; + for (int[] rec : rectangles) { + if (Math.min(rec[0], rec[1]) == maxLen) { + count++; + } + } + return count; + } +} diff --git a/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.kt b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.kt new file mode 100644 index 00000000..839bfc16 --- /dev/null +++ b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.kt @@ -0,0 +1,6 @@ +class Solution { + fun countGoodRectangles(rectangles: Array): Int { + val maxLen = rectangles.maxOf { it.min() } + return rectangles.count { it.min() == maxLen } + } +} diff --git a/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.py b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.py new file mode 100644 index 00000000..89f69275 --- /dev/null +++ b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.py @@ -0,0 +1,4 @@ +class Solution: + def countGoodRectangles(self, rectangles: List[Tuple[int, int]]) -> int: + max_len = max(min(rec) for rec in rectangles) + return sum(int(min(rec) == max_len) for rec in rectangles) diff --git a/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.py2 b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.py2 new file mode 100644 index 00000000..7b9018b8 --- /dev/null +++ b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.py2 @@ -0,0 +1,8 @@ +class Solution(object): + def countGoodRectangles(self, rectangles): + """ + :type rectangles: List[List[int]] + :rtype: int + """ + max_len = max(min(rec) for rec in rectangles) + return sum(1 for rec in rectangles if min(rec) == max_len) diff --git a/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.rb b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.rb new file mode 100644 index 00000000..c9285f4f --- /dev/null +++ b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.rb @@ -0,0 +1,6 @@ +# @param {Integer[][]} rectangles +# @return {Integer} +def count_good_rectangles(rectangles) + max_len = rectangles.map { |rec| rec.min }.max + rectangles.count { |rec| rec.min == max_len } +end diff --git a/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.rs b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.rs new file mode 100644 index 00000000..408666d0 --- /dev/null +++ b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.rs @@ -0,0 +1,6 @@ +impl Solution { + pub fn count_good_rectangles(rectangles: Vec>) -> i32 { + let max_len = rectangles.iter().map(|r| r.iter().min().unwrap()).max().unwrap(); + rectangles.iter().filter(|r| r.iter().min().unwrap() == max_len).count() as i32 + } +} diff --git a/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.swift b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.swift new file mode 100644 index 00000000..08d7445d --- /dev/null +++ b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.swift @@ -0,0 +1,6 @@ +class Solution { + func countGoodRectangles(_ rectangles: [[Int]]) -> Int { + let maxLen = rectangles.map { $0.min()! }.max()! + return rectangles.filter { $0.min()! == maxLen }.count + } +} diff --git a/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.ts b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.ts new file mode 100644 index 00000000..6fe09d44 --- /dev/null +++ b/tests/1501-2000/1725. number-of-rectangles-that-can-form-the-largest-square/sol.ts @@ -0,0 +1,4 @@ +function countGoodRectangles(rectangles: number[][]): number { + const maxLen = Math.max(...rectangles.map((r) => Math.min(...r))); + return rectangles.filter((r) => Math.min(...r) === maxLen).length; +} diff --git a/tests/1501-2000/1726. tuple-with-same-product/manifest.yaml b/tests/1501-2000/1726. tuple-with-same-product/manifest.yaml new file mode 100644 index 00000000..72875fa8 --- /dev/null +++ b/tests/1501-2000/1726. tuple-with-same-product/manifest.yaml @@ -0,0 +1,209 @@ +entry: + id: 1726 + title: tuple-with-same-product + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().tupleSameProduct({nums})" + rust: "Solution::tuple_same_product({nums})" + python3: "Solution().tupleSameProduct({nums})" + python2: "Solution().tupleSameProduct({nums})" + ruby: "tuple_same_product({nums})" + java: "new Solution().tupleSameProduct({nums})" + csharp: "new Solution().TupleSameProduct({nums})" + kotlin: "Solution().tupleSameProduct({nums})" + go: "tupleSameProduct({nums})" + dart: "Solution().tupleSameProduct({nums})" + swift: "Solution().tupleSameProduct({nums})" + typescript: "tupleSameProduct({nums})" + +judge: + type: "exact" + +limits: + time_ms: 5000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().tupleSameProduct(nums, {result})" + checker: | + from collections import defaultdict + + class Checker: + def tupleSameProduct(self, nums, result): + counts = defaultdict(int) + pairs = 0 + for i in range(len(nums)): + for j in range(i + 1, len(nums)): + product = nums[i] * nums[j] + pairs += counts[product] + counts[product] += 1 + return result == 8 * pairs + +seed: 1726 + +tests: + - name: example-four + in: + nums: [2, 3, 4, 6] + out: 8 + - name: example-five + in: + nums: [1, 2, 4, 5, 10] + out: 16 + - name: two-elements + in: + nums: [1, 10000] + out: 0 + - name: three-elements + in: + nums: [1, 2, 3] + out: 0 + - name: four-no-match + in: + nums: [1, 2, 3, 7] + out: 0 + - name: four-one-match + in: + nums: [1, 2, 3, 6] + out: 8 + - name: powers-of-two + in: + nums: [1, 2, 4, 8, 16] + - name: consecutive-six + in: + nums: [1, 2, 3, 4, 5, 6] + - name: consecutive-ten + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - name: primes + in: + nums: [2, 3, 5, 7, 11, 13, 17, 19] + - name: repeated-products + in: + nums: [1, 2, 3, 4, 6, 8, 12, 24] + - name: factor-grid + in: + nums: [2, 3, 4, 6, 8, 9, 12, 18, 24, 36] + - name: near-limit-values + in: + nums: [9991, 9992, 9993, 9994, 9995, 9996] + - name: mixed-small-large + in: + nums: [1, 2, 5, 10, 25, 50, 100, 125] + - name: coprime-set + in: + nums: [1, 7, 13, 29, 31, 43, 59] + - name: duplicate-product-chain + in: + nums: [1, 2, 3, 4, 6, 8, 9, 12, 16, 18] + - name: scaled-example + in: + nums: [10, 20, 30, 40, 60] + - name: powers-and-three + in: + nums: [1, 2, 3, 4, 6, 8, 12, 24, 48] + - name: six-prime-products + in: + nums: [2, 3, 5, 6, 10, 15, 30] + - name: sparse-multiples + in: + nums: [1, 10, 100, 1000, 10000] + - name: balanced-factors + in: + nums: [2, 4, 8, 16, 32, 64, 128] + - name: many-small + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + - name: many-products + in: + nums: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 18, 20, 24, 30, 36] + - name: large-primes + in: + nums: [9973, 9967, 9949, 9941, 9931, 9929] + - name: mixed-divisors + in: + nums: [3, 4, 6, 7, 12, 14, 21, 28, 42, 84] + - name: powers-of-three + in: + nums: [1, 3, 9, 27, 81, 243, 729] + - name: no-product-collision + in: + nums: [97, 101, 103, 107, 109, 113, 127, 131] + - name: dense-twenty + in: + nums: + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 28, 30] + - name: two-factor-families + in: + nums: [2, 3, 4, 5, 6, 8, 10, 12, 15, 16, 20, 24, 30, 40] + - name: generated-random-small + in: + nums: + gen: "array" + len: 30 + of: + gen: "int" + min: 1 + max: 1000 + distinct: true + elemType: "int" + - name: generated-random-medium + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 10000 + distinct: true + elemType: "int" + - name: generated-random-large + in: + nums: + gen: "array" + len: 300 + of: + gen: "int" + min: 1 + max: 10000 + distinct: true + elemType: "int" + - name: generated-maximal + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 10000 + distinct: true + elemType: "int" + - name: generated-maximal-high-range + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 10000 + distinct: true + elemType: "int" + - name: generated-dense-range + in: + nums: + gen: "array" + len: 500 + of: + gen: "int" + min: 1 + max: 5000 + distinct: true + elemType: "int" diff --git a/tests/1501-2000/1726. tuple-with-same-product/sol.cpp b/tests/1501-2000/1726. tuple-with-same-product/sol.cpp new file mode 100644 index 00000000..5eaf70db --- /dev/null +++ b/tests/1501-2000/1726. tuple-with-same-product/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int tupleSameProduct(vector& nums) { + unordered_map productCount; + int ans = 0; + + for (int i = 0; i < nums.size(); i++) { + for (int j = i+1; j < nums.size(); j++) { + int product = nums[i] * nums[j]; + ans += 8 * productCount[product]; + productCount[product]++; + } + } + + return ans; + } +}; diff --git a/tests/1501-2000/1726. tuple-with-same-product/sol.cs b/tests/1501-2000/1726. tuple-with-same-product/sol.cs new file mode 100644 index 00000000..2d665b14 --- /dev/null +++ b/tests/1501-2000/1726. tuple-with-same-product/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public int TupleSameProduct(int[] nums) { + var productCount = new Dictionary(); + int ans = 0; + + for (int i = 0; i < nums.Length; i++) { + for (int j = i+1; j < nums.Length; j++) { + int product = nums[i] * nums[j]; + ans += 8 * productCount.GetValueOrDefault(product); + productCount[product] = productCount.GetValueOrDefault(product) + 1; + } + } + + return ans; + } +} diff --git a/tests/1501-2000/1726. tuple-with-same-product/sol.dart b/tests/1501-2000/1726. tuple-with-same-product/sol.dart new file mode 100644 index 00000000..4ee74226 --- /dev/null +++ b/tests/1501-2000/1726. tuple-with-same-product/sol.dart @@ -0,0 +1,16 @@ +class Solution { + int tupleSameProduct(List nums) { + Map productCount = {}; + int ans = 0; + + for (int i = 0; i < nums.length; i++) { + for (int j = i+1; j < nums.length; j++) { + int product = nums[i] * nums[j]; + ans += 8 * (productCount[product] ?? 0); + productCount[product] = (productCount[product] ?? 0) + 1; + } + } + + return ans; + } +} diff --git a/tests/1501-2000/1726. tuple-with-same-product/sol.go b/tests/1501-2000/1726. tuple-with-same-product/sol.go new file mode 100644 index 00000000..2cc2387e --- /dev/null +++ b/tests/1501-2000/1726. tuple-with-same-product/sol.go @@ -0,0 +1,14 @@ +func tupleSameProduct(nums []int) int { + productCount := make(map[int]int) + ans := 0 + + for i := 0; i < len(nums); i++ { + for j := i+1; j < len(nums); j++ { + product := nums[i] * nums[j] + ans += 8 * productCount[product] + productCount[product]++ + } + } + + return ans +} diff --git a/tests/1501-2000/1726. tuple-with-same-product/sol.java b/tests/1501-2000/1726. tuple-with-same-product/sol.java new file mode 100644 index 00000000..94541725 --- /dev/null +++ b/tests/1501-2000/1726. tuple-with-same-product/sol.java @@ -0,0 +1,16 @@ +class Solution { + public int tupleSameProduct(int[] nums) { + Map productCount = new HashMap<>(); + int ans = 0; + + for (int i = 0; i < nums.length; i++) { + for (int j = i+1; j < nums.length; j++) { + int product = nums[i] * nums[j]; + ans += 8 * productCount.getOrDefault(product, 0); + productCount.put(product, productCount.getOrDefault(product, 0) + 1); + } + } + + return ans; + } +} diff --git a/tests/1501-2000/1726. tuple-with-same-product/sol.kt b/tests/1501-2000/1726. tuple-with-same-product/sol.kt new file mode 100644 index 00000000..8a1d26ea --- /dev/null +++ b/tests/1501-2000/1726. tuple-with-same-product/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun tupleSameProduct(nums: IntArray): Int { + val productCount = mutableMapOf() + var ans = 0 + + for (i in nums.indices) { + for (j in i+1 until nums.size) { + val product = nums[i] * nums[j] + ans += 8 * (productCount[product] ?: 0) + productCount[product] = (productCount[product] ?: 0) + 1 + } + } + + return ans + } +} diff --git a/tests/1501-2000/1726. tuple-with-same-product/sol.py b/tests/1501-2000/1726. tuple-with-same-product/sol.py new file mode 100644 index 00000000..9d019f41 --- /dev/null +++ b/tests/1501-2000/1726. tuple-with-same-product/sol.py @@ -0,0 +1,15 @@ +from collections import defaultdict + + +class Solution: + def tupleSameProduct(self, nums): + product_count = defaultdict(int) + ans = 0 + + for i in range(len(nums)): + for j in range(i + 1, len(nums)): + product = nums[i] * nums[j] + ans += 8 * product_count[product] + product_count[product] += 1 + + return ans diff --git a/tests/1501-2000/1726. tuple-with-same-product/sol.py2 b/tests/1501-2000/1726. tuple-with-same-product/sol.py2 new file mode 100644 index 00000000..c1a6f533 --- /dev/null +++ b/tests/1501-2000/1726. tuple-with-same-product/sol.py2 @@ -0,0 +1,17 @@ +class Solution(object): + def tupleSameProduct(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + from collections import defaultdict + product_count = defaultdict(int) + ans = 0 + + for i in range(len(nums)): + for j in range(i+1, len(nums)): + product = nums[i] * nums[j] + ans += 8 * product_count[product] + product_count[product] += 1 + + return ans diff --git a/tests/1501-2000/1726. tuple-with-same-product/sol.rb b/tests/1501-2000/1726. tuple-with-same-product/sol.rb new file mode 100644 index 00000000..68b7ea74 --- /dev/null +++ b/tests/1501-2000/1726. tuple-with-same-product/sol.rb @@ -0,0 +1,16 @@ +# @param {Integer[]} nums +# @return {Integer} +def tuple_same_product(nums) + product_count = Hash.new(0) + ans = 0 + + (0...nums.length).each do |i| + (i+1...nums.length).each do |j| + product = nums[i] * nums[j] + ans += 8 * product_count[product] + product_count[product] += 1 + end + end + + ans +end diff --git a/tests/1501-2000/1726. tuple-with-same-product/sol.rs b/tests/1501-2000/1726. tuple-with-same-product/sol.rs new file mode 100644 index 00000000..e87c2d37 --- /dev/null +++ b/tests/1501-2000/1726. tuple-with-same-product/sol.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn tuple_same_product(nums: Vec) -> i32 { + use std::collections::HashMap; + let mut product_count: HashMap = HashMap::new(); + let mut ans = 0; + + for i in 0..nums.len() { + for j in (i+1)..nums.len() { + let product = nums[i] * nums[j]; + let count = *product_count.get(&product).unwrap_or(&0); + ans += 8 * count; + *product_count.entry(product).or_insert(0) += 1; + } + } + + ans + } +} diff --git a/tests/1501-2000/1726. tuple-with-same-product/sol.swift b/tests/1501-2000/1726. tuple-with-same-product/sol.swift new file mode 100644 index 00000000..107ab455 --- /dev/null +++ b/tests/1501-2000/1726. tuple-with-same-product/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func tupleSameProduct(_ nums: [Int]) -> Int { + var productCount: [Int: Int] = [:] + var ans = 0 + + for i in 0.. = new Map(); + let ans = 0; + + for (let i = 0; i < nums.length; i++) { + for (let j = i + 1; j < nums.length; j++) { + const product = nums[i] * nums[j]; + ans += 8 * (productCount.get(product) || 0); + productCount.set(product, (productCount.get(product) || 0) + 1); + } + } + + return ans; +} diff --git a/tests/1501-2000/1727. largest-submatrix-with-rearrangements/manifest.yaml b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/manifest.yaml new file mode 100644 index 00000000..573033f8 --- /dev/null +++ b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/manifest.yaml @@ -0,0 +1,425 @@ +entry: + id: 1727 + title: "largest-submatrix-with-rearrangements" + params: + matrix: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().largestSubmatrix({matrix})" + rust: "Solution::largest_submatrix({matrix})" + python3: "Solution().largestSubmatrix({matrix})" + python2: "Solution().largestSubmatrix({matrix})" + ruby: "largest_submatrix({matrix})" + java: "new Solution().largestSubmatrix({matrix})" + csharp: "new Solution().LargestSubmatrix({matrix})" + kotlin: "Solution().largestSubmatrix({matrix})" + go: "largestSubmatrix({matrix})" + dart: "Solution().largestSubmatrix({matrix})" + swift: "Solution().largestSubmatrix({matrix})" + typescript: "largestSubmatrix({matrix})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().largestSubmatrix(matrix, {result})" + checker: | + class Checker: + def largestSubmatrix(self, matrix, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not matrix or not matrix[0]: + return result == 0 + n = len(matrix[0]) + heights = [0] * n + expected = 0 + for row in matrix: + if len(row) != n or any(value not in (0, 1) for value in row): + return False + for j, value in enumerate(row): + heights[j] = heights[j] + 1 if value == 1 else 0 + ordered = sorted(heights, reverse=True) + for width, height in enumerate(ordered, 1): + expected = max(expected, width * height) + return result == expected + +seed: 1727 + +tests: + - name: example-1 + in: + matrix: + - [0, 0, 1] + - [1, 1, 1] + - [1, 0, 1] + out: 4 + - name: example-2 + in: + matrix: + - [1, 0, 1, 0, 1] + out: 3 + - name: example-3 + in: + matrix: + - [1, 1, 0] + - [1, 0, 1] + out: 2 + - name: one-one + in: + matrix: + - [1] + out: 1 + - name: all-zero-row + in: + matrix: + - [0, 0, 0, 0] + out: 0 + - name: all-one-row + in: + matrix: + - [1, 1, 1, 1] + out: 4 + - name: all-zero-column + in: + matrix: + - [0] + - [0] + - [0] + - [0] + out: 0 + - name: all-one-column + in: + matrix: + - [1] + - [1] + - [1] + - [1] + out: 4 + - name: all-ones-square + in: + matrix: + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + out: 9 + - name: checkerboard-3 + in: + matrix: + - [1, 0, 1] + - [0, 1, 0] + - [1, 0, 1] + out: 2 + - name: diagonal-4 + in: + matrix: + - [1, 0, 0, 0] + - [0, 1, 0, 0] + - [0, 0, 1, 0] + - [0, 0, 0, 1] + out: 1 + - name: increasing-prefixes + in: + matrix: + - [1, 0, 0, 0, 0] + - [1, 1, 0, 0, 0] + - [1, 1, 1, 0, 0] + - [1, 1, 1, 1, 0] + - [1, 1, 1, 1, 1] + out: 9 + - name: decreasing-prefixes + in: + matrix: + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 0] + - [1, 1, 1, 0, 0] + - [1, 1, 0, 0, 0] + - [1, 0, 0, 0, 0] + out: 9 + - name: tall-mixed + in: + matrix: + - [1, 1, 0, 1] + - [1, 0, 1, 1] + - [1, 1, 1, 0] + - [1, 1, 1, 1] + - [0, 1, 1, 1] + - [1, 1, 0, 1] + out: 6 + - name: wide-mixed + in: + matrix: + - [1, 0, 1, 1, 0, 1, 0, 1] + - [1, 1, 1, 0, 0, 1, 1, 0] + - [0, 1, 1, 1, 1, 0, 1, 1] + out: 6 + - name: isolated-column + in: + matrix: + - [1, 0, 0] + - [1, 0, 0] + - [1, 0, 0] + - [1, 0, 0] + - [1, 0, 0] + out: 5 + - name: two-full-columns + in: + matrix: + - [1, 1, 0, 0] + - [1, 1, 0, 1] + - [1, 1, 1, 0] + - [1, 1, 0, 0] + out: 8 + - name: alternating-columns + in: + matrix: + - [1, 0, 1, 0, 1, 0] + - [1, 0, 1, 0, 1, 0] + - [0, 1, 0, 1, 0, 1] + - [1, 0, 1, 0, 1, 0] + out: 6 + - name: sparse-5x5 + in: + matrix: + - [0, 1, 0, 0, 1] + - [1, 0, 1, 0, 0] + - [0, 1, 0, 1, 0] + - [1, 0, 1, 0, 1] + - [0, 0, 1, 1, 0] + out: 3 + - name: dense-6x6 + in: + matrix: + - [1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 0, 1] + - [1, 1, 1, 0, 0, 1] + - [1, 1, 0, 0, 0, 1] + - [1, 0, 0, 0, 0, 1] + - [1, 1, 1, 1, 1, 1] + out: 12 + - name: full-rectangle-2x7 + in: + matrix: + - [1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1] + out: 14 + - name: full-rectangle-7x2 + in: + matrix: + - [1, 1] + - [1, 1] + - [1, 1] + - [1, 1] + - [1, 1] + - [1, 1] + - [1, 1] + out: 14 + - name: single-row-nine + in: + matrix: + - [1, 0, 1, 1, 0, 1, 1, 1, 0] + out: 6 + - name: single-column-nine + in: + matrix: + - [1] + - [0] + - [1] + - [1] + - [1] + - [0] + - [1] + - [1] + - [1] + out: 3 + - name: height-dominates + in: + matrix: + - [1, 1, 0, 0] + - [1, 1, 0, 0] + - [1, 1, 0, 0] + - [1, 1, 0, 0] + - [1, 1, 0, 0] + - [0, 0, 1, 1] + out: 10 + - name: width-dominates + in: + matrix: + - [1, 1, 1, 1, 1, 1, 1, 1] + - [0, 0, 0, 0, 0, 0, 0, 0] + - [1, 1, 1, 1, 1, 1, 1, 1] + out: 8 + - name: mixed-7x7 + in: + matrix: + - [1, 0, 1, 1, 0, 1, 0] + - [1, 1, 1, 0, 1, 1, 0] + - [1, 1, 0, 1, 1, 0, 1] + - [0, 1, 1, 1, 1, 1, 0] + - [1, 1, 1, 1, 0, 1, 1] + - [1, 0, 1, 1, 1, 0, 1] + - [1, 1, 0, 1, 1, 1, 1] + out: 9 + - name: large-all-ones-20x20 + in: + matrix: + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 380 + - name: two-row-staircase + in: + matrix: + - [1, 1, 0, 1, 0, 1] + - [0, 1, 1, 1, 1, 0] + out: 4 + - name: three-row-blocks + in: + matrix: + - [1, 1, 0, 0, 1, 0] + - [1, 0, 1, 0, 1, 1] + - [1, 1, 1, 0, 0, 1] + out: 6 + - name: four-by-eight-dense + in: + matrix: + - [1, 1, 1, 0, 1, 1, 0, 1] + - [1, 0, 1, 1, 1, 0, 1, 1] + - [1, 1, 0, 1, 1, 1, 1, 0] + - [0, 1, 1, 1, 0, 1, 1, 1] + out: 8 + - name: alternating-rows + in: + matrix: + - [1, 1, 1, 1, 1, 1] + - [0, 0, 0, 0, 0, 0] + - [1, 1, 1, 1, 1, 1] + - [0, 0, 0, 0, 0, 0] + - [1, 1, 1, 1, 1, 1] + out: 6 + - name: all-ones-10x10 + in: + matrix: + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 100 + - name: one-zero-restored + in: + matrix: + - [0] + out: 0 + - name: restored-example + in: + matrix: + - [0, 0, 1] + - [1, 1, 1] + - [1, 0, 1] + out: 4 + - name: generated-single-row-maximum + in: + matrix: + gen: array + len: 1 + of: + gen: array + len: 20000 + of: + gen: int + min: 0 + max: 1 + elemType: int + elemType: int + seed: 1727001 + - name: generated-two-row-wide + in: + matrix: + gen: array + len: 2 + of: + gen: array + len: 10000 + of: + gen: int + min: 0 + max: 1 + elemType: int + elemType: int + seed: 1727002 + - name: generated-hundred-by-thousand + in: + matrix: + gen: array + len: 100 + of: + gen: array + len: 1000 + of: + gen: int + min: 0 + max: 1 + elemType: int + elemType: int + seed: 1727003 + - name: generated-two-hundred-by-five-hundred + in: + matrix: + gen: array + len: 200 + of: + gen: array + len: 500 + of: + gen: int + min: 0 + max: 1 + elemType: int + elemType: int + seed: 1727004 + - name: generated-square-boundary + in: + matrix: + gen: array + len: 316 + of: + gen: array + len: 316 + of: + gen: int + min: 0 + max: 1 + elemType: int + elemType: int + seed: 1727005 diff --git a/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.cpp b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.cpp new file mode 100644 index 00000000..0e01d8df --- /dev/null +++ b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int largestSubmatrix(vector>& matrix) { + int m = matrix.size(); + int n = matrix[0].size(); + int maxArea = 0; + vector h(n, 0); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (j < matrix[i].size() && matrix[i][j] == 1) { + h[j]++; + } else { + h[j] = 0; + } + } + vector count(m + 1, 0); + for (int height : h) count[height]++; + int width = 0; + for (int height = m; height > 0; height--) { + while (count[height]-- > 0) { + width++; + maxArea = max(maxArea, height * width); + } + } + } + return maxArea; + } +}; diff --git a/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.cs b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.cs new file mode 100644 index 00000000..6e303e5b --- /dev/null +++ b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public int LargestSubmatrix(int[][] matrix) { + int m = matrix.Length; + int n = matrix[0].Length; + int maxArea = 0; + int[] h = new int[n]; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (j < matrix[i].Length && matrix[i][j] == 1) { + h[j]++; + } else { + h[j] = 0; + } + } + int[] sh = (int[])h.Clone(); + Array.Sort(sh); + Array.Reverse(sh); + for (int j = 0; j < n; j++) { + if (sh[j] == 0) break; + maxArea = Math.Max(maxArea, sh[j] * (j + 1)); + } + } + return maxArea; + } +} diff --git a/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.dart b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.dart new file mode 100644 index 00000000..115aa442 --- /dev/null +++ b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.dart @@ -0,0 +1,23 @@ +class Solution { + int largestSubmatrix(List> matrix) { + int m = matrix.length; + int n = matrix[0].length; + int maxArea = 0; + List h = List.filled(n, 0); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (j < matrix[i].length && matrix[i][j] == 1) { + h[j]++; + } else { + h[j] = 0; + } + } + List sh = List.from(h)..sort((a, b) => b.compareTo(a)); + for (int j = 0; j < n; j++) { + if (sh[j] == 0) break; + maxArea = maxArea > sh[j] * (j + 1) ? maxArea : sh[j] * (j + 1); + } + } + return maxArea; + } +} diff --git a/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.go b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.go new file mode 100644 index 00000000..36b0a3fd --- /dev/null +++ b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.go @@ -0,0 +1,27 @@ +func largestSubmatrix(matrix [][]int) int { + m := len(matrix) + n := len(matrix[0]) + maxArea := 0 + h := make([]int, n) + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if j < len(matrix[i]) && matrix[i][j] == 1 { + h[j]++ + } else { + h[j] = 0 + } + } + sh := make([]int, n) + copy(sh, h) + sort.Sort(sort.Reverse(sort.IntSlice(sh))) + for j := 0; j < n; j++ { + if sh[j] == 0 { + break + } + if sh[j]*(j+1) > maxArea { + maxArea = sh[j] * (j + 1) + } + } + } + return maxArea +} diff --git a/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.java b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.java new file mode 100644 index 00000000..41ddccd2 --- /dev/null +++ b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.java @@ -0,0 +1,30 @@ +class Solution { + public int largestSubmatrix(int[][] matrix) { + int m = matrix.length; + int n = matrix[0].length; + int maxArea = 0; + int[] h = new int[n]; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (j < matrix[i].length && matrix[i][j] == 1) { + h[j]++; + } else { + h[j] = 0; + } + } + int[] sh = h.clone(); + Arrays.sort(sh); + // reverse + for (int l = 0, r = n - 1; l < r; l++, r--) { + int temp = sh[l]; + sh[l] = sh[r]; + sh[r] = temp; + } + for (int j = 0; j < n; j++) { + if (sh[j] == 0) break; + maxArea = Math.max(maxArea, sh[j] * (j + 1)); + } + } + return maxArea; + } +} diff --git a/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.kt b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.kt new file mode 100644 index 00000000..4d437041 --- /dev/null +++ b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.kt @@ -0,0 +1,23 @@ +class Solution { + fun largestSubmatrix(matrix: Array): Int { + val m = matrix.size + val n = matrix[0].size + var maxArea = 0 + val h = IntArray(n) + for (i in 0 until m) { + for (j in 0 until n) { + if (j < matrix[i].size && matrix[i][j] == 1) { + h[j]++ + } else { + h[j] = 0 + } + } + val sh = h.sortedDescending().toIntArray() + for (j in 0 until n) { + if (sh[j] == 0) break + maxArea = maxOf(maxArea, sh[j] * (j + 1)) + } + } + return maxArea + } +} diff --git a/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.py b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.py new file mode 100644 index 00000000..69fcc2d7 --- /dev/null +++ b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.py @@ -0,0 +1,20 @@ +# Added using AI +class Solution: + def largestSubmatrix(self, matrix: list[list[int]]) -> int: + m, n = len(matrix), len(matrix[0]) + maxArea = 0 + h = [0] * n + + for i in range(m): + for j in range(n): + if j < len(matrix[i]) and matrix[i][j] == 1: + h[j] += 1 + else: + h[j] = 0 + sh = sorted(h, reverse=True) + for j in range(n): + if sh[j] == 0: + break + maxArea = max(maxArea, sh[j] * (j + 1)) + + return maxArea diff --git a/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.py2 b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.py2 new file mode 100644 index 00000000..a424e0b7 --- /dev/null +++ b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def largestSubmatrix(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: int + """ + m, n = len(matrix), len(matrix[0]) + max_area = 0 + h = [0] * n + for i in range(m): + for j in range(n): + if j < len(matrix[i]) and matrix[i][j] == 1: + h[j] += 1 + else: + h[j] = 0 + sh = sorted(h, reverse=True) + for j in range(n): + if sh[j] == 0: + break + max_area = max(max_area, sh[j] * (j + 1)) + return max_area diff --git a/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.rb b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.rb new file mode 100644 index 00000000..3bb6a091 --- /dev/null +++ b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.rb @@ -0,0 +1,21 @@ +def largest_submatrix(matrix) + m = matrix.length + n = matrix[0].length + max_area = 0 + h = Array.new(n, 0) + (0...m).each do |i| + (0...n).each do |j| + if j < matrix[i].length && matrix[i][j] == 1 + h[j] += 1 + else + h[j] = 0 + end + end + sh = h.sort.reverse + (0...n).each do |j| + break if sh[j] == 0 + max_area = [max_area, sh[j] * (j + 1)].max + end + end + max_area +end diff --git a/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.rs b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.rs new file mode 100644 index 00000000..adb6ba19 --- /dev/null +++ b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn largest_submatrix(matrix: Vec>) -> i32 { + let m = matrix.len(); + let n = matrix[0].len(); + let mut max_area = 0; + let mut h = vec![0; n]; + for i in 0..m { + for j in 0..n { + if j < matrix[i].len() && matrix[i][j] == 1 { + h[j] += 1; + } else { + h[j] = 0; + } + } + let mut sh = h.clone(); + sh.sort_by(|a, b| b.cmp(a)); + for j in 0..n { + if sh[j] == 0 { + break; + } + max_area = max_area.max(sh[j] * (j as i32 + 1)); + } + } + max_area + } +} diff --git a/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.swift b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.swift new file mode 100644 index 00000000..cd02add6 --- /dev/null +++ b/tests/1501-2000/1727. largest-submatrix-with-rearrangements/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func largestSubmatrix(_ matrix: [[Int]]) -> Int { + let m = matrix.count + let n = matrix[0].count + var maxArea = 0 + var h = [Int](repeating: 0, count: n) + for i in 0..) + for j in 0.. b - a); + for (let j = 0; j < n; j++) { + if (sh[j] === 0) break; + maxArea = Math.max(maxArea, sh[j] * (j + 1)); + } + } + return maxArea; +} diff --git a/tests/1501-2000/1728. cat-and-mouse-ii/manifest.yaml b/tests/1501-2000/1728. cat-and-mouse-ii/manifest.yaml new file mode 100644 index 00000000..75901695 --- /dev/null +++ b/tests/1501-2000/1728. cat-and-mouse-ii/manifest.yaml @@ -0,0 +1,394 @@ +entry: + id: 1728 + title: cat-and-mouse-ii + params: + grid: + type: array + items: + type: string + catJump: + type: int + mouseJump: + type: int + call: + cpp: "Solution().canMouseWin({grid}, {catJump}, {mouseJump})" + rust: "Solution::can_mouse_win({grid}, {catJump}, {mouseJump})" + python3: "Solution().canMouseWin({grid}, {catJump}, {mouseJump})" + python2: "Solution().canMouseWin({grid}, {catJump}, {mouseJump})" + ruby: "can_mouse_win({grid}, {catJump}, {mouseJump})" + java: "new Solution().canMouseWin({grid}, {catJump}, {mouseJump})" + csharp: "new Solution().CanMouseWin({grid}, {catJump}, {mouseJump})" + kotlin: "Solution().canMouseWin({grid}, {catJump}, {mouseJump})" + go: "canMouseWin({grid}, {catJump}, {mouseJump})" + dart: "Solution().canMouseWin({grid}, {catJump}, {mouseJump})" + swift: "Solution().canMouseWin({grid}, {catJump}, {mouseJump})" + typescript: "canMouseWin({grid}, {catJump}, {mouseJump})" + +judge: + type: exact + +limits: + time_ms: 5000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().canMouseWin(grid, catJump, mouseJump, {result})" + checker: | + from functools import lru_cache + class Checker: + def canMouseWin(self, grid, catJump, mouseJump, result): + if not isinstance(result, bool): + return False + h, w = len(grid), len(grid[0]) + walls = set() + cat = mouse = food = None + for r, row in enumerate(grid): + if not isinstance(row, str) or len(row) != w: + return False + for c, ch in enumerate(row): + if ch == '#': + walls.add((r, c)) + elif ch == 'C': + cat = (r, c) + elif ch == 'M': + mouse = (r, c) + elif ch == 'F': + food = (r, c) + if cat is None or mouse is None or food is None: + return False + dirs = ((1, 0), (-1, 0), (0, 1), (0, -1)) + def moves(pos, jump): + r, c = pos + yield pos + for dr, dc in dirs: + for step in range(1, jump + 1): + nr, nc = r + dr * step, c + dc * step + if not (0 <= nr < h and 0 <= nc < w) or (nr, nc) in walls: + break + yield (nr, nc) + @lru_cache(None) + def win(cp, mp, turn): + if cp == food or cp == mp or turn >= 2 * h * w: + return False + if mp == food: + return True + if turn % 2 == 0: + return any(win(cp, np, turn + 1) for np in moves(mp, mouseJump)) + return all(win(np, mp, turn + 1) for np in moves(cp, catJump)) + return result == win(cat, mouse, 0) + +seed: 1728 + +tests: + - name: example-one + in: + grid: + - "####F" + - "#C..." + - "M...." + catJump: 1 + mouseJump: 2 + - name: example-two + in: + grid: + - "M.C...F" + catJump: 1 + mouseJump: 4 + - name: example-three + in: + grid: + - "M.C...F" + catJump: 1 + mouseJump: 3 + - name: adjacent-cat + in: + grid: + - "MC.F" + catJump: 1 + mouseJump: 1 + - name: mouse-one-step-food + in: + grid: + - "M.F.C" + catJump: 1 + mouseJump: 2 + - name: cat-one-step-food + in: + grid: + - "M.CF" + catJump: 1 + mouseJump: 1 + - name: blocked-row + in: + grid: + - "M#.." + - "..C#" + - "...F" + catJump: 2 + mouseJump: 1 + - name: narrow-column + in: + grid: + - "M" + - "." + - "C" + - "." + - "F" + catJump: 1 + mouseJump: 2 + - name: narrow-column-walls + in: + grid: + - "M" + - "." + - "#" + - "C" + - "." + - "F" + catJump: 2 + mouseJump: 3 + - name: open-square + in: + grid: + - "M.." + - "..." + - "C.F" + catJump: 1 + mouseJump: 1 + - name: open-square-long-jump + in: + grid: + - "M.." + - "..." + - "C.F" + catJump: 3 + mouseJump: 3 + - name: corner-maze + in: + grid: + - "M#..." + - ".##.#" + - "...C." + - "##.#." + - "...F." + catJump: 2 + mouseJump: 2 + - name: horizontal-wall + in: + grid: + - "M...F" + - "#####" + - "C...." + catJump: 2 + mouseJump: 2 + - name: vertical-wall + in: + grid: + - "M.#." + - "..#." + - "C.#F" + - "...." + catJump: 1 + mouseJump: 3 + - name: escape-around-wall + in: + grid: + - "M#..." + - "..#.." + - "..C.." + - "...#F" + catJump: 1 + mouseJump: 2 + - name: dense-maze + in: + grid: + - "M...#F" + - ".##..." + - "..C#.." + - "...#.." + - "#....." + catJump: 2 + mouseJump: 3 + - name: six-by-six-open + in: + grid: + - "M....." + - "......" + - "......" + - "...C.." + - "......" + - ".....F" + catJump: 2 + mouseJump: 3 + - name: six-by-six-blocked + in: + grid: + - "M..#.." + - ".#...." + - "...#.." + - "..C..." + - "....#." + - "..#..F" + catJump: 3 + mouseJump: 2 + - name: seven-wide + in: + grid: + - "M......" + - "......." + - "..C...." + - "......." + - "......F" + catJump: 2 + mouseJump: 4 + - name: seven-wide-cat-fast + in: + grid: + - "M......" + - "......." + - "..C...." + - "......." + - "......F" + catJump: 6 + mouseJump: 1 + - name: ring-corridor + in: + grid: + - "M....#" + - ".####." + - ".#C..F" + - ".####." + - "......" + catJump: 1 + mouseJump: 2 + - name: zigzag-corridor + in: + grid: + - "M#...." + - ".#C#.." + - "..#..F" + - "....#." + - "......" + catJump: 2 + mouseJump: 1 + - name: isolated-cat + in: + grid: + - "M...F" + - "####." + - "C####" + - "....." + catJump: 4 + mouseJump: 1 + - name: isolated-mouse + in: + grid: + - "M####" + - "....#" + - "..C.F" + - "....." + catJump: 2 + mouseJump: 4 + - name: equal-jumps + in: + grid: + - "M...." + - "..#.." + - "..C.." + - "..#.." + - "....F" + catJump: 2 + mouseJump: 2 + - name: mouse-maximum + in: + grid: + - "M.#...F" + - "..#...." + - "..C...." + - "......." + catJump: 1 + mouseJump: 8 + - name: cat-maximum + in: + grid: + - "M.....F" + - ".###..." + - "..C...." + - "......." + catJump: 8 + mouseJump: 1 + - name: three-by-eight + in: + grid: + - "M..#...." + - "...#C..F" + - "........" + catJump: 3 + mouseJump: 4 + - name: four-by-eight + in: + grid: + - "M......." + - ".###...." + - "....C#.." + - ".....F.." + catJump: 2 + mouseJump: 3 + - name: eight-by-eight-open + in: + grid: + - "M......." + - "........" + - "........" + - "........" + - "...C...." + - "........" + - "........" + - ".......F" + catJump: 4 + mouseJump: 4 + - name: eight-by-eight-maze + in: + grid: + - "M..#...." + - ".##.#..." + - "...#..#." + - "#..C...." + - "....##.." + - ".#....#." + - "...#...F" + - "........" + catJump: 3 + mouseJump: 2 + - name: food-near-mouse + in: + grid: + - "M.F...." + - "..#...." + - "..C...." + catJump: 2 + mouseJump: 1 + - name: food-near-cat + in: + grid: + - "M...." + - "..C.F" + - "....." + catJump: 1 + mouseJump: 2 + - name: forced-wait + in: + grid: + - "M#F" + - "..#" + - "C.." + catJump: 1 + mouseJump: 1 + - name: long-open-line + in: + grid: + - "M........F" + - "....C....." + catJump: 2 + mouseJump: 5 diff --git a/tests/1501-2000/1728. cat-and-mouse-ii/sol.cpp b/tests/1501-2000/1728. cat-and-mouse-ii/sol.cpp new file mode 100644 index 00000000..3b1beb3a --- /dev/null +++ b/tests/1501-2000/1728. cat-and-mouse-ii/sol.cpp @@ -0,0 +1,75 @@ +class Solution { +public: + bool canMouseWin(vector& grid, int catJump, int mouseJump) { + int m = grid.size(), n = grid[0].size(); + unordered_set walls; + int food, cat, mouse; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + int idx = i * n + j; + if (grid[i][j] == 'F') food = idx; + else if (grid[i][j] == 'C') cat = idx; + else if (grid[i][j] == 'M') mouse = idx; + else if (grid[i][j] == '#') walls.insert(idx); + } + } + + int dirs[4][2] = {{-1,0},{0,1},{1,0},{0,-1}}; + int maxTurns = m * n * 2; + auto key = [&](int c, int mo, int turn) { + return (c * m * n + mo) * maxTurns + turn; + }; + unordered_map memo; + + function dfs = [&](int c, int mo, int turn) -> bool { + int k = key(c, mo, turn); + if (memo.count(k)) return memo[k]; + + if (c == food || c == mo || turn >= maxTurns) { + memo[k] = false; + return false; + } + if (mo == food) { + memo[k] = true; + return true; + } + + bool result; + if (turn % 2 == 0) { // mouse + result = false; + int mx = mo / n, my = mo % n; + for (auto& d : dirs) { + for (int jump = 0; jump <= mouseJump; jump++) { + int nx = mx + jump * d[0], ny = my + jump * d[1]; + if (nx < 0 || nx >= m || ny < 0 || ny >= n || walls.count(nx * n + ny)) break; + if (dfs(c, nx * n + ny, turn + 1)) { + result = true; + break; + } + } + if (result) break; + } + } else { // cat + result = true; + int cx = c / n, cy = c % n; + for (auto& d : dirs) { + for (int jump = 0; jump <= catJump; jump++) { + int nx = cx + jump * d[0], ny = cy + jump * d[1]; + if (nx < 0 || nx >= m || ny < 0 || ny >= n || walls.count(nx * n + ny)) break; + if (!dfs(nx * n + ny, mo, turn + 1)) { + result = false; + break; + } + } + if (!result) break; + } + } + + memo[k] = result; + return result; + }; + + return dfs(cat, mouse, 0); + } +}; diff --git a/tests/1501-2000/1728. cat-and-mouse-ii/sol.cs b/tests/1501-2000/1728. cat-and-mouse-ii/sol.cs new file mode 100644 index 00000000..924f5ae4 --- /dev/null +++ b/tests/1501-2000/1728. cat-and-mouse-ii/sol.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; + +public class Solution { + private int m, n; + private HashSet walls = new HashSet(); + private int food; + private int catJump, mouseJump; + private int[][] dirs = new int[][] { new int[] {-1,0}, new int[] {0,1}, new int[] {1,0}, new int[] {0,-1} }; + private Dictionary memo = new Dictionary(); + + public bool CanMouseWin(string[] grid, int catJump, int mouseJump) { + m = grid.Length; + n = grid[0].Length; + this.catJump = catJump; + this.mouseJump = mouseJump; + + int cat = 0, mouse = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + int idx = i * n + j; + if (grid[i][j] == 'F') food = idx; + else if (grid[i][j] == 'C') cat = idx; + else if (grid[i][j] == 'M') mouse = idx; + else if (grid[i][j] == '#') walls.Add(idx); + } + } + + return Dfs(cat, mouse, 0); + } + + private int Key(int cat, int mouse, int turn) { + return (cat * m * n + mouse) * (m * n * 2) + turn; + } + + private bool Dfs(int cat, int mouse, int turn) { + int key = Key(cat, mouse, turn); + if (memo.ContainsKey(key)) return memo[key]; + + int cx = cat / n, cy = cat % n; + int mx = mouse / n, my = mouse % n; + + if (cat == food || cat == mouse || turn >= m * n * 2) { + memo[key] = false; + return false; + } + if (mouse == food) { + memo[key] = true; + return true; + } + + bool result = false; + if (turn % 2 == 0) { // mouse + foreach (int[] d in dirs) { + for (int jump = 0; jump <= mouseJump; jump++) { + int nx = mx + jump * d[0], ny = my + jump * d[1]; + if (nx < 0 || nx >= m || ny < 0 || ny >= n || walls.Contains(nx * n + ny)) break; + if (Dfs(cat, nx * n + ny, turn + 1)) { + result = true; + break; + } + } + if (result) break; + } + } else { // cat + result = true; + foreach (int[] d in dirs) { + for (int jump = 0; jump <= catJump; jump++) { + int nx = cx + jump * d[0], ny = cy + jump * d[1]; + if (nx < 0 || nx >= m || ny < 0 || ny >= n || walls.Contains(nx * n + ny)) break; + if (!Dfs(nx * n + ny, mouse, turn + 1)) { + result = false; + break; + } + } + if (!result) break; + } + } + + memo[key] = result; + return result; + } +} diff --git a/tests/1501-2000/1728. cat-and-mouse-ii/sol.dart b/tests/1501-2000/1728. cat-and-mouse-ii/sol.dart new file mode 100644 index 00000000..f1d62d2c --- /dev/null +++ b/tests/1501-2000/1728. cat-and-mouse-ii/sol.dart @@ -0,0 +1,71 @@ +class Solution { + bool canMouseWin(List grid, int catJump, int mouseJump) { + int m = grid.length, n = grid[0].length; + Set walls = {}; + int food = -1, cat = -1, mouse = -1; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + int idx = i * n + j; + if (grid[i][j] == 'F') food = idx; + else if (grid[i][j] == 'C') cat = idx; + else if (grid[i][j] == 'M') mouse = idx; + else if (grid[i][j] == '#') walls.add(idx); + } + } + + final dirs = [[-1,0],[0,1],[1,0],[0,-1]]; + final memo = Map(); + int maxTurns = m * n * 2; + + bool dfs(int c, int mo, int turn) { + int key = (c * m * n + mo) * maxTurns + turn; + if (memo.containsKey(key)) return memo[key]!; + + if (c == food || c == mo || turn >= maxTurns) { + memo[key] = false; + return false; + } + if (mo == food) { + memo[key] = true; + return true; + } + + bool result; + if (turn % 2 == 0) { // mouse + result = false; + int mx = mo ~/ n, my = mo % n; + for (var d in dirs) { + for (int jump = 0; jump <= mouseJump; jump++) { + int nx = mx + jump * d[0], ny = my + jump * d[1]; + if (nx < 0 || nx >= m || ny < 0 || ny >= n || walls.contains(nx * n + ny)) break; + if (dfs(c, nx * n + ny, turn + 1)) { + result = true; + break; + } + } + if (result) break; + } + } else { // cat + result = true; + int cx = c ~/ n, cy = c % n; + for (var d in dirs) { + for (int jump = 0; jump <= catJump; jump++) { + int nx = cx + jump * d[0], ny = cy + jump * d[1]; + if (nx < 0 || nx >= m || ny < 0 || ny >= n || walls.contains(nx * n + ny)) break; + if (!dfs(nx * n + ny, mo, turn + 1)) { + result = false; + break; + } + } + if (!result) break; + } + } + + memo[key] = result; + return result; + } + + return dfs(cat, mouse, 0); + } +} diff --git a/tests/1501-2000/1728. cat-and-mouse-ii/sol.go b/tests/1501-2000/1728. cat-and-mouse-ii/sol.go new file mode 100644 index 00000000..6cc2848e --- /dev/null +++ b/tests/1501-2000/1728. cat-and-mouse-ii/sol.go @@ -0,0 +1,82 @@ +func canMouseWin(grid []string, catJump int, mouseJump int) bool { + m, n := len(grid), len(grid[0]) + walls := make(map[int]bool) + var food, cat, mouse int + + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + idx := i*n + j + switch grid[i][j] { + case 'F': + food = idx + case 'C': + cat = idx + case 'M': + mouse = idx + case '#': + walls[idx] = true + } + } + } + + dirs := [][]int{{-1,0},{0,1},{1,0},{0,-1}} + memo := make(map[int]bool) + maxTurns := m*n*2 + + var dfs func(c, mo, turn int) bool + dfs = func(c, mo, turn int) bool { + key := (c*m*n + mo)*maxTurns + turn + if val, ok := memo[key]; ok { + return val + } + + if c == food || c == mo || turn >= maxTurns { + memo[key] = false + return false + } + if mo == food { + memo[key] = true + return true + } + + var result bool + if turn%2 == 0 { // mouse turn + result = false + mx, my := mo/n, mo%n + mouseOuter: + for _, d := range dirs { + for jump := 0; jump <= mouseJump; jump++ { + nx, ny := mx+jump*d[0], my+jump*d[1] + if nx < 0 || nx >= m || ny < 0 || ny >= n || walls[nx*n+ny] { + break + } + if dfs(c, nx*n+ny, turn+1) { + result = true + break mouseOuter + } + } + } + } else { // cat turn + result = true + cx, cy := c/n, c%n + catOuter: + for _, d := range dirs { + for jump := 0; jump <= catJump; jump++ { + nx, ny := cx+jump*d[0], cy+jump*d[1] + if nx < 0 || nx >= m || ny < 0 || ny >= n || walls[nx*n+ny] { + break + } + if !dfs(nx*n+ny, mo, turn+1) { + result = false + break catOuter + } + } + } + } + + memo[key] = result + return result + } + + return dfs(cat, mouse, 0) +} diff --git a/tests/1501-2000/1728. cat-and-mouse-ii/sol.java b/tests/1501-2000/1728. cat-and-mouse-ii/sol.java new file mode 100644 index 00000000..81fc1b53 --- /dev/null +++ b/tests/1501-2000/1728. cat-and-mouse-ii/sol.java @@ -0,0 +1,83 @@ +import java.util.*; + +class Solution { + private int m, n; + private int[][] dirs = {{-1,0},{0,1},{1,0},{0,-1}}; + private Set walls = new HashSet<>(); + private int[] food; + private int catJump, mouseJump; + private Map memo = new HashMap<>(); + + public boolean canMouseWin(String[] grid, int catJump, int mouseJump) { + m = grid.length; + n = grid[0].length(); + this.catJump = catJump; + this.mouseJump = mouseJump; + + int cat = -1, mouse = -1; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + char c = grid[i].charAt(j); + if (c == 'F') food = new int[]{i, j}; + else if (c == 'C') cat = i * n + j; + else if (c == 'M') mouse = i * n + j; + else if (c == '#') walls.add(i * n + j); + } + } + + return dfs(cat, mouse, 0); + } + + private int key(int cat, int mouse, int turn) { + return ((cat * m * n + mouse) * (m * n * 2) + turn); + } + + private boolean dfs(int cat, int mouse, int turn) { + Integer k = key(cat, mouse, turn); + if (memo.containsKey(k)) return memo.get(k); + + int cx = cat / n, cy = cat % n; + int mx = mouse / n, my = mouse % n; + + if ((cat == food[0]*n + food[1]) || cat == mouse || turn >= m*n*2) { + memo.put(k, false); + return false; + } + if (mouse == food[0]*n + food[1]) { + memo.put(k, true); + return true; + } + + boolean result; + if (turn % 2 == 0) { // mouse + result = false; + for (int[] d : dirs) { + for (int jump = 0; jump <= mouseJump; jump++) { + int nx = mx + jump*d[0], ny = my + jump*d[1]; + if (nx < 0 || nx >= m || ny < 0 || ny >= n || walls.contains(nx*n+ny)) break; + if (dfs(cat, nx*n+ny, turn+1)) { + result = true; + break; + } + } + if (result) break; + } + } else { // cat + result = true; + for (int[] d : dirs) { + for (int jump = 0; jump <= catJump; jump++) { + int nx = cx + jump*d[0], ny = cy + jump*d[1]; + if (nx < 0 || nx >= m || ny < 0 || ny >= n || walls.contains(nx*n+ny)) break; + if (!dfs(nx*n+ny, mouse, turn+1)) { + result = false; + break; + } + } + if (!result) break; + } + } + + memo.put(k, result); + return result; + } +} diff --git a/tests/1501-2000/1728. cat-and-mouse-ii/sol.kt b/tests/1501-2000/1728. cat-and-mouse-ii/sol.kt new file mode 100644 index 00000000..4633b273 --- /dev/null +++ b/tests/1501-2000/1728. cat-and-mouse-ii/sol.kt @@ -0,0 +1,89 @@ +class Solution { + private lateinit var grid: Array + private var m = 0 + private var n = 0 + private var catJump = 0 + private var mouseJump = 0 + private val dirs = arrayOf(intArrayOf(-1,0), intArrayOf(0,1), intArrayOf(1,0), intArrayOf(0,-1)) + private val walls = mutableSetOf() + private lateinit var food: IntArray + private val memo = mutableMapOf() + + fun canMouseWin(grid: Array, catJump: Int, mouseJump: Int): Boolean { + this.grid = grid + this.catJump = catJump + this.mouseJump = mouseJump + m = grid.size + n = grid[0].length + + var cat = 0 + var mouse = 0 + for (i in 0 until m) { + for (j in 0 until n) { + when (grid[i][j]) { + 'F' -> food = intArrayOf(i, j) + 'C' -> cat = i * n + j + 'M' -> mouse = i * n + j + '#' -> walls.add(i * n + j) + } + } + } + + return dfs(cat, mouse, 0) + } + + private fun key(cat: Int, mouse: Int, turn: Int): Int { + return ((cat * m * n + mouse) * (m * n * 2) + turn) + } + + private fun dfs(cat: Int, mouse: Int, turn: Int): Boolean { + val k = key(cat, mouse, turn) + memo[k]?.let { return it } + + val cx = cat / n + val cy = cat % n + val mx = mouse / n + val my = mouse % n + + if ((cat == food[0] * n + food[1]) || cat == mouse || turn >= m * n * 2) { + memo[k] = false + return false + } + if (mouse == food[0] * n + food[1]) { + memo[k] = true + return true + } + + var result: Boolean + if (turn % 2 == 0) { // mouse + result = false + outer@ for (d in dirs) { + for (jump in 0..mouseJump) { + val nx = mx + jump * d[0] + val ny = my + jump * d[1] + if (nx < 0 || nx >= m || ny < 0 || ny >= n || walls.contains(nx * n + ny)) break + if (dfs(cat, nx * n + ny, turn + 1)) { + result = true + break@outer + } + } + } + } else { // cat + result = true + outer@ for (d in dirs) { + for (jump in 0..catJump) { + val nx = cx + jump * d[0] + val ny = cy + jump * d[1] + if (nx < 0 || nx >= m || ny < 0 || ny >= n || walls.contains(nx * n + ny)) break + if (!dfs(nx * n + ny, mouse, turn + 1)) { + result = false + break@outer + } + } + } + } + + memo[k] = result + return result + } +} diff --git a/tests/1501-2000/1728. cat-and-mouse-ii/sol.py b/tests/1501-2000/1728. cat-and-mouse-ii/sol.py new file mode 100644 index 00000000..a631484f --- /dev/null +++ b/tests/1501-2000/1728. cat-and-mouse-ii/sol.py @@ -0,0 +1,45 @@ +class Solution: + def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool: + m, n = len(grid), len(grid[0]) # dimensions + walls = set() + for i in range(m): + for j in range(n): + if grid[i][j] == "F": + food = (i, j) + elif grid[i][j] == "C": + cat = (i, j) + elif grid[i][j] == "M": + mouse = (i, j) + elif grid[i][j] == "#": + walls.add((i, j)) + + @lru_cache(None) + def fn(cat, mouse, turn): + """Return True if mouse wins.""" + if cat == food or cat == mouse or turn >= m * n * 2: + return False + if mouse == food: + return True # mouse reaching food + + if not turn & 1: # mouse moving + x, y = mouse + for dx, dy in (-1, 0), (0, 1), (1, 0), (0, -1): + for jump in range(0, mouseJump + 1): + xx, yy = x + jump * dx, y + jump * dy + if not (0 <= xx < m and 0 <= yy < n) or (xx, yy) in walls: + break + if fn(cat, (xx, yy), turn + 1): + return True + return False + else: # cat moving + x, y = cat + for dx, dy in (-1, 0), (0, 1), (1, 0), (0, -1): + for jump in range(0, catJump + 1): + xx, yy = x + jump * dx, y + jump * dy + if not (0 <= xx < m and 0 <= yy < n) or (xx, yy) in walls: + break + if not fn((xx, yy), mouse, turn + 1): + return False + return True + + return fn(cat, mouse, 0) diff --git a/tests/1501-2000/1728. cat-and-mouse-ii/sol.py2 b/tests/1501-2000/1728. cat-and-mouse-ii/sol.py2 new file mode 100644 index 00000000..75b58761 --- /dev/null +++ b/tests/1501-2000/1728. cat-and-mouse-ii/sol.py2 @@ -0,0 +1,59 @@ +class Solution(object): + def canMouseWin(self, grid, catJump, mouseJump): + """ + :type grid: List[str] + :type catJump: int + :type mouseJump: int + :rtype: bool + """ + m, n = len(grid), len(grid[0]) + walls = set() + for i in range(m): + for j in range(n): + if grid[i][j] == "F": + food = i * n + j + elif grid[i][j] == "C": + cat = i * n + j + elif grid[i][j] == "M": + mouse = i * n + j + elif grid[i][j] == "#": + walls.add(i * n + j) + + memo = {} + def fn(cat, mouse, turn): + key = (cat * m * n + mouse) * (m * n * 2) + turn + if key in memo: + return memo[key] + if cat == food or cat == mouse or turn >= m*n*2: + memo[key] = False + return False + if mouse == food: + memo[key] = True + return True + + if turn % 2 == 0: # mouse turn + x, y = divmod(mouse, n) + for dx, dy in [(-1,0),(0,1),(1,0),(0,-1)]: + for jump in range(mouseJump+1): + xx, yy = x + jump*dx, y + jump*dy + if not (0 <= xx < m and 0 <= yy < n) or xx * n + yy in walls: + break + if fn(cat, xx * n + yy, turn+1): + memo[key] = True + return True + memo[key] = False + return False + else: # cat turn + x, y = divmod(cat, n) + for dx, dy in [(-1,0),(0,1),(1,0),(0,-1)]: + for jump in range(catJump+1): + xx, yy = x + jump*dx, y + jump*dy + if not (0 <= xx < m and 0 <= yy < n) or xx * n + yy in walls: + break + if not fn(xx * n + yy, mouse, turn+1): + memo[key] = False + return False + memo[key] = True + return True + + return fn(cat, mouse, 0) diff --git a/tests/1501-2000/1728. cat-and-mouse-ii/sol.rb b/tests/1501-2000/1728. cat-and-mouse-ii/sol.rb new file mode 100644 index 00000000..83a45b9d --- /dev/null +++ b/tests/1501-2000/1728. cat-and-mouse-ii/sol.rb @@ -0,0 +1,65 @@ +# @param {String[]} grid +# @param {Integer} cat_jump +# @param {Integer} mouse_jump +# @return {Boolean} +def can_mouse_win(grid, cat_jump, mouse_jump) + m = grid.size + n = grid[0].size + walls = {} + food = cat = mouse = 0 + + (0...m).each do |i| + (0...n).each do |j| + if grid[i][j] == "F" + food = i * n + j + elsif grid[i][j] == "C" + cat = i * n + j + elsif grid[i][j] == "M" + mouse = i * n + j + elsif grid[i][j] == "#" + walls[i * n + j] = true + end + end + end + + memo = {} + solve = lambda do |cat_pos, mouse_pos, turn| + key = (cat_pos * m * n + mouse_pos) * (m * n * 2) + turn + return memo[key] if memo.key?(key) + + if cat_pos == food || cat_pos == mouse_pos || turn >= m*n*2 + return memo[key] = false + end + if mouse_pos == food + return memo[key] = true + end + + if turn % 2 == 0 # mouse + x, y = mouse_pos.divmod(n) + [[-1,0],[0,1],[1,0],[0,-1]].each do |dx, dy| + (0..mouse_jump).each do |jump| + xx, yy = x + jump*dx, y + jump*dy + break if xx < 0 || xx >= m || yy < 0 || yy >= n || walls[xx * n + yy] + if solve.call(cat_pos, xx * n + yy, turn+1) + return memo[key] = true + end + end + end + return memo[key] = false + else # cat + x, y = cat_pos.divmod(n) + [[-1,0],[0,1],[1,0],[0,-1]].each do |dx, dy| + (0..cat_jump).each do |jump| + xx, yy = x + jump*dx, y + jump*dy + break if xx < 0 || xx >= m || yy < 0 || yy >= n || walls[xx * n + yy] + if !solve.call(xx * n + yy, mouse_pos, turn+1) + return memo[key] = false + end + end + end + return memo[key] = true + end + end + + solve.call(cat, mouse, 0) +end diff --git a/tests/1501-2000/1728. cat-and-mouse-ii/sol.rs b/tests/1501-2000/1728. cat-and-mouse-ii/sol.rs new file mode 100644 index 00000000..0b054403 --- /dev/null +++ b/tests/1501-2000/1728. cat-and-mouse-ii/sol.rs @@ -0,0 +1,95 @@ +use std::collections::{HashMap, HashSet}; + +impl Solution { + pub fn can_mouse_win(grid: Vec, cat_jump: i32, mouse_jump: i32) -> bool { + let m = grid.len(); + let n = grid[0].len(); + let mut walls = HashSet::new(); + let mut food: usize = 0; + let mut cat: usize = 0; + let mut mouse: usize = 0; + + for i in 0..m { + let chars: Vec = grid[i].chars().collect(); + for j in 0..n { + let idx = i * n + j; + match chars[j] { + 'F' => food = idx, + 'C' => cat = idx, + 'M' => mouse = idx, + '#' => { walls.insert(idx); } + _ => {} + } + } + } + + let dirs: [[i32; 2]; 4] = [[-1,0],[0,1],[1,0],[0,-1]]; + let max_turns = m * n * 2; + let mut memo = HashMap::new(); + + fn dfs( + c: usize, mo: usize, turn: usize, + m: usize, n: usize, food: usize, walls: &HashSet, + cat_jump: i32, mouse_jump: i32, dirs: &[[i32;2];4], max_turns: usize, + memo: &mut HashMap + ) -> bool { + let key = (c * m * n + mo) * max_turns + turn; + if let Some(&val) = memo.get(&key) { return val; } + + if c == food || c == mo || turn >= max_turns { + memo.insert(key, false); + return false; + } + if mo == food { + memo.insert(key, true); + return true; + } + + let result: bool; + if turn % 2 == 0 { // mouse + result = { + let mx = mo / n; + let my = mo % n; + let mut found = false; + 'outer: for d in dirs { + for jump in 0..=mouse_jump { + let nx = mx as i32 + jump * d[0]; + let ny = my as i32 + jump * d[1]; + if nx < 0 || nx >= m as i32 || ny < 0 || ny >= n as i32 || + walls.contains(&((nx as usize) * n + ny as usize)) { break; } + if dfs(c, (nx as usize)*n + ny as usize, turn+1, m, n, food, walls, cat_jump, mouse_jump, dirs, max_turns, memo) { + found = true; + break 'outer; + } + } + } + found + } + } else { // cat + result = { + let cx = c / n; + let cy = c % n; + let mut ok = true; + 'outer: for d in dirs { + for jump in 0..=cat_jump { + let nx = cx as i32 + jump * d[0]; + let ny = cy as i32 + jump * d[1]; + if nx < 0 || nx >= m as i32 || ny < 0 || ny >= n as i32 || + walls.contains(&((nx as usize) * n + ny as usize)) { break; } + if !dfs((nx as usize)*n + ny as usize, mo, turn+1, m, n, food, walls, cat_jump, mouse_jump, dirs, max_turns, memo) { + ok = false; + break 'outer; + } + } + } + ok + } + } + + memo.insert(key, result); + result + } + + dfs(cat, mouse, 0, m, n, food, &walls, cat_jump, mouse_jump, &dirs, max_turns, &mut memo) + } +} diff --git a/tests/1501-2000/1728. cat-and-mouse-ii/sol.swift b/tests/1501-2000/1728. cat-and-mouse-ii/sol.swift new file mode 100644 index 00000000..401b975f --- /dev/null +++ b/tests/1501-2000/1728. cat-and-mouse-ii/sol.swift @@ -0,0 +1,91 @@ +class Solution { + private var m: Int! + private var n: Int! + private var catJump: Int! + private var mouseJump: Int! + private let dirs = [(-1,0),(0,1),(1,0),(0,-1)] + private var walls = Set() + private var food: Int! + private var memo = [Int: Bool]() + + func canMouseWin(_ grid: [String], _ catJump: Int, _ mouseJump: Int) -> Bool { + m = grid.count + n = grid[0].count + self.catJump = catJump + self.mouseJump = mouseJump + + var cat = 0 + var mouse = 0 + for i in 0.. Int { + return (cat * m * n + mouse) * (m * n * 2) + turn + } + + private func dfs(_ cat: Int, _ mouse: Int, _ turn: Int) -> Bool { + let k = key(cat, mouse, turn) + if let val = memo[k] { return val } + + let cx = cat / n, cy = cat % n + let mx = mouse / n, my = mouse % n + + if (cat == food || cat == mouse || turn >= m * n * 2) { + memo[k] = false + return false + } + if mouse == food { + memo[k] = true + return true + } + + var result: Bool + if turn % 2 == 0 { // mouse + result = false + outer: for d in dirs { + for jump in 0...mouseJump { + let nx = mx + jump * d.0, ny = my + jump * d.1 + if nx < 0 || nx >= m || ny < 0 || ny >= n || walls.contains(nx * n + ny) { break } + if dfs(cat, nx * n + ny, turn + 1) { + result = true + break outer + } + } + } + } else { // cat + result = true + outer: for d in dirs { + for jump in 0...catJump { + let nx = cx + jump * d.0, ny = cy + jump * d.1 + if nx < 0 || nx >= m || ny < 0 || ny >= n || walls.contains(nx * n + ny) { break } + if !dfs(nx * n + ny, mouse, turn + 1) { + result = false + break outer + } + } + } + } + + memo[k] = result + return result + } +} diff --git a/tests/1501-2000/1728. cat-and-mouse-ii/sol.ts b/tests/1501-2000/1728. cat-and-mouse-ii/sol.ts new file mode 100644 index 00000000..6dc78605 --- /dev/null +++ b/tests/1501-2000/1728. cat-and-mouse-ii/sol.ts @@ -0,0 +1,85 @@ +function canMouseWin( + grid: string[], + catJump: number, + mouseJump: number, +): boolean { + const m = grid.length, + n = grid[0].length; + const walls = new Set(); + let food: number, cat: number, mouse: number; + + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + const idx = i * n + j; + if (grid[i][j] === "F") food = idx; + else if (grid[i][j] === "C") cat = idx; + else if (grid[i][j] === "M") mouse = idx; + else if (grid[i][j] === "#") walls.add(idx); + } + } + + const dirs = [ + [-1, 0], + [0, 1], + [1, 0], + [0, -1], + ]; + const memo = new Map(); + const maxTurns = m * n * 2; + + function dfs(c: number, mo: number, turn: number): boolean { + const key = (c * m * n + mo) * maxTurns + turn; + if (memo.has(key)) return memo.get(key)!; + + if (c === food || c === mo || turn >= maxTurns) { + memo.set(key, false); + return false; + } + if (mo === food) { + memo.set(key, true); + return true; + } + + let result: boolean; + if (turn % 2 === 0) { + // mouse + result = false; + const mx = Math.floor(mo / n), + my = mo % n; + outer: for (const d of dirs) { + for (let jump = 0; jump <= mouseJump; jump++) { + const nx = mx + jump * d[0], + ny = my + jump * d[1]; + if (nx < 0 || nx >= m || ny < 0 || ny >= n || walls.has(nx * n + ny)) + break; + if (dfs(c, nx * n + ny, turn + 1)) { + result = true; + break outer; + } + } + } + } else { + // cat + result = true; + const cx = Math.floor(c / n), + cy = c % n; + outer: for (const d of dirs) { + for (let jump = 0; jump <= catJump; jump++) { + const nx = cx + jump * d[0], + ny = cy + jump * d[1]; + if (nx < 0 || nx >= m || ny < 0 || ny >= n || walls.has(nx * n + ny)) + break; + if (!dfs(nx * n + ny, mo, turn + 1)) { + result = false; + break outer; + } + } + } + } + + memo.set(key, result); + return result; + } + + return dfs(cat!, mouse!, 0); +} diff --git a/tests/1501-2000/1732. find-the-highest-altitude/manifest.yaml b/tests/1501-2000/1732. find-the-highest-altitude/manifest.yaml new file mode 100644 index 00000000..b3da8b52 --- /dev/null +++ b/tests/1501-2000/1732. find-the-highest-altitude/manifest.yaml @@ -0,0 +1,243 @@ +entry: + id: 1732 + title: "find-the-highest-altitude" + params: + gain: + type: array + items: + type: int + call: + cpp: "Solution().largestAltitude({gain})" + rust: "Solution::largest_altitude({gain})" + python3: "Solution().largestAltitude({gain})" + python2: "Solution().largestAltitude({gain})" + ruby: "largest_altitude({gain})" + java: "new Solution().largestAltitude({gain})" + csharp: "new Solution().LargestAltitude({gain})" + kotlin: "Solution().largestAltitude({gain})" + go: "largestAltitude({gain})" + dart: "Solution().largestAltitude({gain})" + swift: "Solution().largestAltitude({gain})" + typescript: "largestAltitude({gain})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().largestAltitude(gain, {result})" + checker: | + class Checker: + def largestAltitude(self, gain, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + altitude = 0 + highest = 0 + for delta in gain: + altitude += delta + highest = max(highest, altitude) + return result == highest + +seed: 1732 + +tests: + - name: example-negative-then-rise + in: + gain: [-5, 1, 5, 0, -7] + out: 1 + - name: example-never-positive + in: + gain: [-4, -3, -2, -1, 4, 3, 2] + out: 0 + - name: one-positive + in: + gain: [5] + out: 5 + - name: one-negative + in: + gain: [-5] + out: 0 + - name: one-zero + in: + gain: [0] + out: 0 + - name: all-zero + in: + gain: [0, 0, 0, 0, 0] + out: 0 + - name: monotone-rise + in: + gain: [1, 2, 3, 4, 5] + out: 15 + - name: monotone-fall + in: + gain: [-1, -2, -3, -4, -5] + out: 0 + - name: rise-then-fall + in: + gain: [10, 10, -5, -20] + out: 20 + - name: late-maximum + in: + gain: [-10, -10, 30] + out: 10 + - name: maximum-at-start + in: + gain: [-1, -1, -1, -1] + out: 0 + - name: maximum-after-recovery + in: + gain: [-5, 10, -2, 8] + out: 11 + - name: alternating-small + in: + gain: [1, -1, 1, -1, 1, -1] + out: 1 + - name: alternating-large + in: + gain: [100, -100, 100, -100] + out: 100 + - name: negative-dip + in: + gain: [-100, 100, -100, 100] + out: 0 + - name: repeated-positive + in: + gain: [7, 7, 7, -3, -3] + out: 21 + - name: repeated-negative + in: + gain: [-7, -7, -7, 3, 3] + out: 0 + - name: balanced-sum + in: + gain: [20, -10, -10] + out: 20 + - name: exact-recovery + in: + gain: [-50, 25, 25] + out: 0 + - name: large-positive-peak + in: + gain: [100, 100, 100, 100, 100] + out: 500 + - name: large-negative-deltas + in: + gain: [-100, -100, -100, -100, -100] + out: 0 + - name: mixed-boundaries + in: + gain: [100, -99, -99, 100, -99, 100] + out: 100 + - name: peak-before-final-drop + in: + gain: [30, -10, 20, -100] + out: 40 + - name: several-records + in: + gain: [3, -8, 12, -4, 6, -20, 5] + out: 9 + - name: deep-negative-recovery + in: + gain: [-20, -20, 50, -5] + out: 10 + - name: peak-on-last-step + in: + gain: [-10, -10, 5, 30] + out: 15 + - name: zero-between-changes + in: + gain: [4, 0, 0, -2, 0, 3] + out: 5 + - name: symmetric-cycle + in: + gain: [9, -4, -5, 9, -4, -5] + out: 9 + - name: small-negative-positive + in: + gain: [-1, 2, -1, 2, -1] + out: 2 + - name: long-flat-tail + in: + gain: [8, -3, 0, 0, 0, 0, -5] + out: 8 + - name: max-length-pattern + in: + gain: [10, -20, 30, -40, 50, -60, 70, -80, 90, -100] + out: 50 + - name: positive-plateau + in: + gain: [6, -2, 4, -8, 10, 0, -10] + out: 10 + - name: ending-at-zero + in: + gain: [12, -4, -4, -4] + out: 12 + - name: two-high-peaks + in: + gain: [25, -5, 5, -30, 40, -10] + out: 35 + - name: generator-random-small + in: + gain: + gen: "array" + len: 17 + of: + gen: "int" + min: -100 + max: 100 + distinct: false + sorted: false + elemType: "int" + - name: generator-random-medium + in: + gain: + gen: "array" + len: 63 + of: + gen: "int" + min: -100 + max: 100 + distinct: false + sorted: false + elemType: "int" + - name: generator-all-positive + in: + gain: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + - name: generator-all-negative + in: + gain: + gen: "array" + len: 100 + of: + gen: "int" + min: -100 + max: -1 + distinct: false + sorted: false + elemType: "int" + - name: generator-full-range + in: + gain: + gen: "array" + len: 100 + of: + gen: "int" + min: -100 + max: 100 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1732. find-the-highest-altitude/sol.cpp b/tests/1501-2000/1732. find-the-highest-altitude/sol.cpp new file mode 100644 index 00000000..3bed3262 --- /dev/null +++ b/tests/1501-2000/1732. find-the-highest-altitude/sol.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int largestAltitude(vector& gain) { + int ans = 0, acc = 0; + for (int it : gain) { + acc += it; + int d = acc - ans; + ans += d & ~(d >> 31); + } + return ans; + } +}; diff --git a/tests/1501-2000/1732. find-the-highest-altitude/sol.cs b/tests/1501-2000/1732. find-the-highest-altitude/sol.cs new file mode 100644 index 00000000..32c59e28 --- /dev/null +++ b/tests/1501-2000/1732. find-the-highest-altitude/sol.cs @@ -0,0 +1,11 @@ +public class Solution { + public int LargestAltitude(int[] gain) { + int ans = 0, acc = 0; + foreach (int it in gain) { + acc += it; + int d = acc - ans; + ans += d & ~(d >> 31); + } + return ans; + } +} diff --git a/tests/1501-2000/1732. find-the-highest-altitude/sol.dart b/tests/1501-2000/1732. find-the-highest-altitude/sol.dart new file mode 100644 index 00000000..563cd1c1 --- /dev/null +++ b/tests/1501-2000/1732. find-the-highest-altitude/sol.dart @@ -0,0 +1,11 @@ +class Solution { + int largestAltitude(List gain) { + int ans = 0, acc = 0; + for (int it in gain) { + acc += it; + int d = acc - ans; + ans += d & ~(d >> 31); + } + return ans; + } +} diff --git a/tests/1501-2000/1732. find-the-highest-altitude/sol.go b/tests/1501-2000/1732. find-the-highest-altitude/sol.go new file mode 100644 index 00000000..7a8db1db --- /dev/null +++ b/tests/1501-2000/1732. find-the-highest-altitude/sol.go @@ -0,0 +1,9 @@ +func largestAltitude(gain []int) int { + ans, acc := 0, 0 + for _, it := range gain { + acc += it + d := acc - ans + ans += d & ^(d >> 31) + } + return ans +} diff --git a/tests/1501-2000/1732. find-the-highest-altitude/sol.java b/tests/1501-2000/1732. find-the-highest-altitude/sol.java new file mode 100644 index 00000000..a9ad6778 --- /dev/null +++ b/tests/1501-2000/1732. find-the-highest-altitude/sol.java @@ -0,0 +1,11 @@ +class Solution { + public int largestAltitude(int[] gain) { + int ans = 0, acc = 0; + for (int it : gain) { + acc += it; + int d = acc - ans; + ans += d & ~(d >> 31); + } + return ans; + } +} diff --git a/tests/1501-2000/1732. find-the-highest-altitude/sol.kt b/tests/1501-2000/1732. find-the-highest-altitude/sol.kt new file mode 100644 index 00000000..c183d994 --- /dev/null +++ b/tests/1501-2000/1732. find-the-highest-altitude/sol.kt @@ -0,0 +1,11 @@ +class Solution { + fun largestAltitude(gain: IntArray): Int { + var ans = 0 + var acc = 0 + for (it in gain) { + acc += it + ans = maxOf(ans, acc) + } + return ans + } +} diff --git a/tests/1501-2000/1732. find-the-highest-altitude/sol.py b/tests/1501-2000/1732. find-the-highest-altitude/sol.py new file mode 100644 index 00000000..1fe705e2 --- /dev/null +++ b/tests/1501-2000/1732. find-the-highest-altitude/sol.py @@ -0,0 +1,10 @@ +class Solution: + def largestAltitude(self, gain: List[int]) -> int: + ans = acc = 0 + + for it in gain: + acc += it + d = acc - ans + ans += d & ~(d >> 0x1F) + + return ans diff --git a/tests/1501-2000/1732. find-the-highest-altitude/sol.py2 b/tests/1501-2000/1732. find-the-highest-altitude/sol.py2 new file mode 100644 index 00000000..179ba257 --- /dev/null +++ b/tests/1501-2000/1732. find-the-highest-altitude/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def largestAltitude(self, gain): + """ + :type gain: List[int] + :rtype: int + """ + ans = acc = 0 + for it in gain: + acc += it + d = acc - ans + ans += d & ~(d >> 0x1F) + return ans diff --git a/tests/1501-2000/1732. find-the-highest-altitude/sol.rb b/tests/1501-2000/1732. find-the-highest-altitude/sol.rb new file mode 100644 index 00000000..e9757044 --- /dev/null +++ b/tests/1501-2000/1732. find-the-highest-altitude/sol.rb @@ -0,0 +1,11 @@ +# @param {Integer[]} gain +# @return {Integer} +def largest_altitude(gain) + ans = acc = 0 + gain.each do |it| + acc += it + d = acc - ans + ans += d & ~(d >> 0x1F) + end + ans +end diff --git a/tests/1501-2000/1732. find-the-highest-altitude/sol.rs b/tests/1501-2000/1732. find-the-highest-altitude/sol.rs new file mode 100644 index 00000000..bfcc1b45 --- /dev/null +++ b/tests/1501-2000/1732. find-the-highest-altitude/sol.rs @@ -0,0 +1,12 @@ +impl Solution { + pub fn largest_altitude(gain: Vec) -> i32 { + let mut ans = 0i32; + let mut acc = 0i32; + for it in gain { + acc += it; + let d = acc - ans; + ans += d & !(d >> 31); + } + ans + } +} diff --git a/tests/1501-2000/1732. find-the-highest-altitude/sol.swift b/tests/1501-2000/1732. find-the-highest-altitude/sol.swift new file mode 100644 index 00000000..c29908f8 --- /dev/null +++ b/tests/1501-2000/1732. find-the-highest-altitude/sol.swift @@ -0,0 +1,12 @@ +class Solution { + func largestAltitude(_ gain: [Int]) -> Int { + var ans = 0 + var acc = 0 + for it in gain { + acc += it + let d = acc - ans + ans += d & ~(d >> 31) + } + return ans + } +} diff --git a/tests/1501-2000/1732. find-the-highest-altitude/sol.ts b/tests/1501-2000/1732. find-the-highest-altitude/sol.ts new file mode 100644 index 00000000..8da83c07 --- /dev/null +++ b/tests/1501-2000/1732. find-the-highest-altitude/sol.ts @@ -0,0 +1,10 @@ +function largestAltitude(gain: number[]): number { + let ans = 0, + acc = 0; + for (const it of gain) { + acc += it; + const d = acc - ans; + ans += d & ~(d >> 31); + } + return ans; +} diff --git a/tests/1501-2000/1733. minimum-number-of-people-to-teach/manifest.yaml b/tests/1501-2000/1733. minimum-number-of-people-to-teach/manifest.yaml new file mode 100644 index 00000000..eb3e8dfe --- /dev/null +++ b/tests/1501-2000/1733. minimum-number-of-people-to-teach/manifest.yaml @@ -0,0 +1,574 @@ +entry: + id: 1733 + title: "minimum-number-of-people-to-teach" + params: + n: + type: int + languages: + type: array + items: + type: array + items: + type: int + friendships: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().minimumTeachings({n}, {languages}, {friendships})" + rust: "Solution::minimum_teachings({n}, {languages}, {friendships})" + python3: "Solution().minimumTeachings({n}, {languages}, {friendships})" + python2: "Solution().minimumTeachings({n}, {languages}, {friendships})" + ruby: "minimum_teachings({n}, {languages}, {friendships})" + java: "new Solution().minimumTeachings({n}, {languages}, {friendships})" + csharp: "new Solution().MinimumTeachings({n}, {languages}, {friendships})" + kotlin: "Solution().minimumTeachings({n}, {languages}, {friendships})" + go: "minimumTeachings({n}, {languages}, {friendships})" + dart: "Solution().minimumTeachings({n}, {languages}, {friendships})" + swift: "Solution().minimumTeachings({n}, {languages}, {friendships})" + typescript: "minimumTeachings({n}, {languages}, {friendships})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().minimumTeachings(n, languages, friendships, {result})" + checker: | + class Checker: + def minimumTeachings(self, n, languages, friendships, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + known = [set(row) for row in languages] + involved = set() + for a, b in friendships: + a -= 1 + b -= 1 + if known[a].isdisjoint(known[b]): + involved.add(a) + involved.add(b) + expected = len(involved) + if involved: + expected = min(sum(lang not in known[user] for user in involved) + for lang in range(1, n + 1)) + else: + expected = 0 + return result == expected + +seed: 17331733 + +tests: + - name: example-one + in: + n: 2 + languages: + - [1] + - [2] + - [1, 2] + friendships: + - [1, 2] + - [1, 3] + - [2, 3] + - name: example-two + in: + n: 3 + languages: + - [2] + - [1, 3] + - [1, 2] + - [3] + friendships: + - [1, 4] + - [1, 2] + - [3, 4] + - [2, 3] + - name: minimum-two-users + in: + n: 3 + languages: + - [2] + - [1] + friendships: + - [1, 2] + - name: already-compatible + in: + n: 3 + languages: + - [1] + - [1, 2] + - [2, 3] + friendships: + - [1, 2] + - [2, 3] + - name: one-conflicting-pair + in: + n: 4 + languages: + - [1] + - [2] + friendships: + - [1, 2] + - name: same-teaching-language + in: + n: 4 + languages: + - [1] + - [2] + - [3] + - [4] + friendships: + - [1, 2] + - [1, 3] + - [1, 4] + - name: best-existing-language + in: + n: 3 + languages: + - [1] + - [2] + - [2] + - [3] + friendships: + - [1, 2] + - [1, 3] + - [1, 4] + - name: no-friendships + in: + n: 5 + languages: + - [1] + - [2] + - [3] + friendships: + - [1, 2] + - name: isolated-compatible-user + in: + n: 3 + languages: + - [1] + - [2] + - [1, 2] + - [3] + friendships: + - [1, 2] + - name: chain-conflicts + in: + n: 3 + languages: + - [1] + - [2] + - [3] + - [1, 2] + - [2, 3] + friendships: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - name: complete-three + in: + n: 3 + languages: + - [1] + - [2] + - [3] + friendships: + - [1, 2] + - [1, 3] + - [2, 3] + - name: complete-four-with-pairs + in: + n: 4 + languages: + - [1, 2] + - [2, 3] + - [3, 4] + - [1, 4] + friendships: + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 3] + - [2, 4] + - [3, 4] + - name: duplicate-single-language + in: + n: 2 + languages: + - [1] + - [1] + - [2] + - [2] + friendships: + - [1, 3] + - [2, 4] + - name: one-user-knows-all + in: + n: 5 + languages: + - [1, 2, 3, 4, 5] + - [1] + - [2] + - [3] + friendships: + - [1, 2] + - [1, 3] + - [1, 4] + - name: language-five-optimal + in: + n: 5 + languages: + - [1, 5] + - [2, 5] + - [3] + - [4] + - [5] + friendships: + - [1, 3] + - [2, 4] + - [3, 5] + - name: two-disconnected-conflicts + in: + n: 4 + languages: + - [1] + - [2] + - [3] + - [4] + - [1, 2] + - [3, 4] + friendships: + - [1, 2] + - [3, 4] + - name: overlapping-conflicts + in: + n: 4 + languages: + - [1] + - [2] + - [3] + - [1, 4] + - [2, 4] + friendships: + - [1, 2] + - [2, 3] + - [1, 5] + - name: mixed-compatible-and-bad + in: + n: 6 + languages: + - [1, 2] + - [2, 3] + - [4] + - [5] + - [4, 6] + - [1, 6] + friendships: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - name: all-pairs-already-good + in: + n: 3 + languages: + - [1, 2] + - [2, 3] + - [1, 3] + friendships: + - [1, 2] + - [1, 3] + - [2, 3] + - name: minimum-zero-with-unused-language + in: + n: 500 + languages: + - [1] + - [1] + friendships: + - [1, 2] + - name: n-two-all-conflict + in: + n: 2 + languages: + - [1] + - [2] + - [1] + - [2] + friendships: + - [1, 2] + - [2, 3] + - [3, 4] + - name: repeated-optimal-language + in: + n: 6 + languages: + - [1] + - [2] + - [1, 3] + - [4] + - [1, 5] + - [6] + friendships: + - [1, 2] + - [2, 4] + - [4, 6] + - [1, 6] + - name: dense-five + in: + n: 5 + languages: + - [1] + - [2] + - [3] + - [4] + - [5] + friendships: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [2, 3] + - [2, 4] + - [2, 5] + - [3, 4] + - [3, 5] + - [4, 5] + - name: six-language-cycle + in: + n: 6 + languages: + - [1] + - [2] + - [3] + - [4] + - [5] + - [6] + friendships: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [1, 6] + - name: varied-language-sets + in: + n: 7 + languages: + - [1, 2, 3] + - [2, 4] + - [3, 5] + - [4, 6] + - [5, 7] + - [1, 6] + - [2, 7] + friendships: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - name: two-user-max-language + in: + n: 500 + languages: + - [500] + - [1] + friendships: + - [1, 2] + - name: ten-users-sparse + in: + n: 10 + languages: + - [1] + - [2] + - [3] + - [4] + - [5] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + friendships: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - name: ten-users-dense + in: + n: 10 + languages: + - [1] + - [2] + - [3] + - [4] + - [5] + - [6] + - [7] + - [8] + - [9] + - [10] + friendships: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [2, 3] + - [2, 4] + - [2, 5] + - [2, 6] + - [3, 4] + - [3, 5] + - [3, 6] + - [4, 5] + - [4, 6] + - [5, 6] + - name: users-with-many-languages + in: + n: 8 + languages: + - [1, 2, 3, 4] + - [2, 3, 5, 6] + - [1, 4, 7, 8] + - [3, 5, 7] + - [2, 4, 6, 8] + - [1, 3, 5, 7] + - [2, 4, 6, 8] + - [1, 2, 7, 8] + friendships: + - [1, 2] + - [1, 3] + - [2, 4] + - [3, 5] + - [4, 6] + - [5, 7] + - [6, 8] + - name: three-disjoint-pairs + in: + n: 6 + languages: + - [1] + - [2] + - [3] + - [4] + - [5] + - [6] + friendships: + - [1, 2] + - [3, 4] + - [5, 6] + - name: all-users-share-fallback + in: + n: 4 + languages: + - [1, 2] + - [2, 3] + - [1, 3] + - [1, 2, 3] + - [4] + friendships: + - [1, 5] + - [2, 5] + - [3, 5] + - [4, 5] + - name: twelve-users + in: + n: 12 + languages: + - [1] + - [2] + - [3] + - [4] + - [5] + - [6] + - [7] + - [8] + - [9] + - [10] + - [11] + - [12] + friendships: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [11, 12] + - name: mixed-equal-sets + in: + n: 5 + languages: + - [1, 2] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [1, 5] + friendships: + - [1, 3] + - [2, 4] + - [3, 5] + - [4, 6] + - name: maximal-n-small-m + in: + n: 500 + languages: + - [1, 250, 500] + - [2, 251, 500] + - [3, 252] + - [4, 253] + - [5, 254] + friendships: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - name: thirteen-overlapping + in: + n: 13 + languages: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [11, 12] + - [12, 13] + - [1, 13] + friendships: + - [1, 3] + - [2, 4] + - [3, 5] + - [4, 6] + - [5, 7] + - [6, 8] + - [7, 9] + - [8, 10] + - [9, 11] + - [10, 12] + - [11, 13] diff --git a/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.cpp b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.cpp new file mode 100644 index 00000000..faa60cb2 --- /dev/null +++ b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.cpp @@ -0,0 +1,42 @@ +class Solution { +public: + int minimumTeachings(int n, vector>& languages, vector>& friendships) { + unordered_set users_to_teach; + + for (auto& friendship : friendships) { + int user1 = friendship[0] - 1; + int user2 = friendship[1] - 1; + bool can_communicate = false; + for (int lang1 : languages[user1]) { + for (int lang2 : languages[user2]) { + if (lang1 == lang2) { + can_communicate = true; + break; + } + } + if (can_communicate) break; + } + if (!can_communicate) { + users_to_teach.insert(user1); + users_to_teach.insert(user2); + } + } + + int min_users = languages.size() + 1; + for (int language = 1; language <= n; language++) { + int count = 0; + for (int user : users_to_teach) { + bool has_lang = false; + for (int lang : languages[user]) { + if (lang == language) { + has_lang = true; + break; + } + } + if (!has_lang) count++; + } + min_users = min(min_users, count); + } + return min_users; + } +}; diff --git a/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.cs b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.cs new file mode 100644 index 00000000..f2759f12 --- /dev/null +++ b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.cs @@ -0,0 +1,41 @@ +public class Solution { + public int MinimumTeachings(int n, int[][] languages, int[][] friendships) { + var usersToTeach = new HashSet(); + + foreach (var friendship in friendships) { + int user1 = friendship[0] - 1; + int user2 = friendship[1] - 1; + bool canCommunicate = false; + foreach (int lang1 in languages[user1]) { + foreach (int lang2 in languages[user2]) { + if (lang1 == lang2) { + canCommunicate = true; + break; + } + } + if (canCommunicate) break; + } + if (!canCommunicate) { + usersToTeach.Add(user1); + usersToTeach.Add(user2); + } + } + + int minUsers = languages.Length + 1; + for (int language = 1; language <= n; language++) { + int count = 0; + foreach (int user in usersToTeach) { + bool hasLang = false; + foreach (int lang in languages[user]) { + if (lang == language) { + hasLang = true; + break; + } + } + if (!hasLang) count++; + } + minUsers = Math.Min(minUsers, count); + } + return minUsers; + } +} diff --git a/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.dart b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.dart new file mode 100644 index 00000000..22fb3e40 --- /dev/null +++ b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.dart @@ -0,0 +1,35 @@ +class Solution { + int minimumTeachings(int n, List> languages, List> friendships) { + Set usersToTeach = {}; + + for (var friendship in friendships) { + int user1 = friendship[0] - 1; + int user2 = friendship[1] - 1; + bool canCommunicate = false; + for (int lang1 in languages[user1]) { + for (int lang2 in languages[user2]) { + if (lang1 == lang2) { + canCommunicate = true; + break; + } + } + if (canCommunicate) break; + } + if (!canCommunicate) { + usersToTeach.add(user1); + usersToTeach.add(user2); + } + } + + int minUsers = languages.length + 1; + for (int language = 1; language <= n; language++) { + int count = 0; + for (int user in usersToTeach) { + bool hasLang = languages[user].contains(language); + if (!hasLang) count++; + } + minUsers = count < minUsers ? count : minUsers; + } + return minUsers; + } +} diff --git a/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.go b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.go new file mode 100644 index 00000000..72717e6d --- /dev/null +++ b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.go @@ -0,0 +1,45 @@ +func minimumTeachings(n int, languages [][]int, friendships [][]int) int { + usersToTeach := make(map[int]bool) + + for _, friendship := range friendships { + user1 := friendship[0] - 1 + user2 := friendship[1] - 1 + canCommunicate := false + for _, lang1 := range languages[user1] { + for _, lang2 := range languages[user2] { + if lang1 == lang2 { + canCommunicate = true + break + } + } + if canCommunicate { + break + } + } + if !canCommunicate { + usersToTeach[user1] = true + usersToTeach[user2] = true + } + } + + minUsers := len(languages) + 1 + for language := 1; language <= n; language++ { + count := 0 + for user := range usersToTeach { + hasLang := false + for _, lang := range languages[user] { + if lang == language { + hasLang = true + break + } + } + if !hasLang { + count++ + } + } + if count < minUsers { + minUsers = count + } + } + return minUsers +} diff --git a/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.java b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.java new file mode 100644 index 00000000..7dc37f3c --- /dev/null +++ b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.java @@ -0,0 +1,43 @@ +import java.util.*; + +class Solution { + public int minimumTeachings(int n, int[][] languages, int[][] friendships) { + Set usersToTeach = new HashSet<>(); + + for (int[] friendship : friendships) { + int user1 = friendship[0] - 1; + int user2 = friendship[1] - 1; + boolean canCommunicate = false; + for (int lang1 : languages[user1]) { + for (int lang2 : languages[user2]) { + if (lang1 == lang2) { + canCommunicate = true; + break; + } + } + if (canCommunicate) break; + } + if (!canCommunicate) { + usersToTeach.add(user1); + usersToTeach.add(user2); + } + } + + int minUsers = languages.length + 1; + for (int language = 1; language <= n; language++) { + int count = 0; + for (int user : usersToTeach) { + boolean hasLang = false; + for (int lang : languages[user]) { + if (lang == language) { + hasLang = true; + break; + } + } + if (!hasLang) count++; + } + minUsers = Math.min(minUsers, count); + } + return minUsers; + } +} diff --git a/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.kt b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.kt new file mode 100644 index 00000000..9872546f --- /dev/null +++ b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.kt @@ -0,0 +1,41 @@ +class Solution { + fun minimumTeachings(n: Int, languages: Array, friendships: Array): Int { + val usersToTeach = mutableSetOf() + + for (friendship in friendships) { + val user1 = friendship[0] - 1 + val user2 = friendship[1] - 1 + var canCommunicate = false + for (lang1 in languages[user1]) { + for (lang2 in languages[user2]) { + if (lang1 == lang2) { + canCommunicate = true + break + } + } + if (canCommunicate) break + } + if (!canCommunicate) { + usersToTeach.add(user1) + usersToTeach.add(user2) + } + } + + var minUsers = languages.size + 1 + for (language in 1..n) { + var count = 0 + for (user in usersToTeach) { + var hasLang = false + for (lang in languages[user]) { + if (lang == language) { + hasLang = true + break + } + } + if (!hasLang) count++ + } + minUsers = minOf(minUsers, count) + } + return minUsers + } +} diff --git a/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.py b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.py new file mode 100644 index 00000000..86e8be66 --- /dev/null +++ b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.py @@ -0,0 +1,30 @@ +class Solution: + def minimumTeachings(self, n, languages, friendships): + users_to_teach = set() + + # Step 1: Identify users who can't communicate + for user1, user2 in friendships: + user1 -= 1 # Convert to 0-based index + user2 -= 1 + can_communicate = False + + for lang1 in languages[user1]: + if lang1 in languages[user2]: + can_communicate = True + break + + if not can_communicate: + users_to_teach.add(user1) + users_to_teach.add(user2) + + # Step 2: Try teaching each language + min_users_to_teach = len(languages) + 1 + + for language in range(1, n + 1): + count = 0 + for user in users_to_teach: + if language not in languages[user]: + count += 1 + min_users_to_teach = min(min_users_to_teach, count) + + return min_users_to_teach diff --git a/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.py2 b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.py2 new file mode 100644 index 00000000..a02d6440 --- /dev/null +++ b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.py2 @@ -0,0 +1,30 @@ +class Solution(object): + def minimumTeachings(self, n, languages, friendships): + """ + :type n: int + :type languages: List[List[int]] + :type friendships: List[List[int]] + :rtype: int + """ + users_to_teach = set() + + for user1, user2 in friendships: + user1 -= 1 + user2 -= 1 + can_communicate = False + for lang1 in languages[user1]: + if lang1 in languages[user2]: + can_communicate = True + break + if not can_communicate: + users_to_teach.add(user1) + users_to_teach.add(user2) + + min_users = len(languages) + 1 + for language in range(1, n + 1): + count = 0 + for user in users_to_teach: + if language not in languages[user]: + count += 1 + min_users = min(min_users, count) + return min_users diff --git a/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.rb b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.rb new file mode 100644 index 00000000..080bd477 --- /dev/null +++ b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.rb @@ -0,0 +1,33 @@ +# @param {Integer} n +# @param {Integer[][]} languages +# @param {Integer[][]} friendships +# @return {Integer} +def minimum_teachings(n, languages, friendships) + users_to_teach = Set.new + + friendships.each do |user1, user2| + user1 -= 1 + user2 -= 1 + can_communicate = false + languages[user1].each do |lang1| + if languages[user2].include?(lang1) + can_communicate = true + break + end + end + unless can_communicate + users_to_teach.add(user1) + users_to_teach.add(user2) + end + end + + min_users = languages.length + 1 + (1..n).each do |language| + count = 0 + users_to_teach.each do |user| + count += 1 unless languages[user].include?(language) + end + min_users = [min_users, count].min + end + min_users +end diff --git a/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.rs b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.rs new file mode 100644 index 00000000..9276ed00 --- /dev/null +++ b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.rs @@ -0,0 +1,35 @@ +impl Solution { + pub fn minimum_teachings(n: i32, languages: Vec>, friendships: Vec>) -> i32 { + use std::collections::HashSet; + + let mut users_to_teach = HashSet::new(); + + for friendship in &friendships { + let user1 = (friendship[0] - 1) as usize; + let user2 = (friendship[1] - 1) as usize; + let mut can_communicate = false; + for &lang1 in &languages[user1] { + if languages[user2].contains(&lang1) { + can_communicate = true; + break; + } + } + if !can_communicate { + users_to_teach.insert(user1); + users_to_teach.insert(user2); + } + } + + let mut min_users = languages.len() + 1; + for language in 1..=n as i32 { + let mut count = 0; + for &user in &users_to_teach { + if !languages[user].contains(&language) { + count += 1; + } + } + min_users = min_users.min(count); + } + min_users as i32 + } +} diff --git a/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.swift b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.swift new file mode 100644 index 00000000..d7db5e5d --- /dev/null +++ b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.swift @@ -0,0 +1,33 @@ +class Solution { + func minimumTeachings(_ n: Int, _ languages: [[Int]], _ friendships: [[Int]]) -> Int { + var usersToTeach = Set() + + for friendship in friendships { + let user1 = friendship[0] - 1 + let user2 = friendship[1] - 1 + var canCommunicate = false + for lang1 in languages[user1] { + if languages[user2].contains(lang1) { + canCommunicate = true + break + } + } + if !canCommunicate { + usersToTeach.insert(user1) + usersToTeach.insert(user2) + } + } + + var minUsers = languages.count + 1 + for language in 1...n { + var count = 0 + for user in usersToTeach { + if !languages[user].contains(language) { + count += 1 + } + } + minUsers = min(minUsers, count) + } + return minUsers + } +} diff --git a/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.ts b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.ts new file mode 100644 index 00000000..f437c94b --- /dev/null +++ b/tests/1501-2000/1733. minimum-number-of-people-to-teach/sol.ts @@ -0,0 +1,35 @@ +function minimumTeachings( + n: number, + languages: number[][], + friendships: number[][], +): number { + const usersToTeach = new Set(); + + for (const friendship of friendships) { + const user1 = friendship[0] - 1; + const user2 = friendship[1] - 1; + let canCommunicate = false; + for (const lang1 of languages[user1]) { + if (languages[user2].includes(lang1)) { + canCommunicate = true; + break; + } + } + if (!canCommunicate) { + usersToTeach.add(user1); + usersToTeach.add(user2); + } + } + + let minUsers = languages.length + 1; + for (let language = 1; language <= n; language++) { + let count = 0; + for (const user of usersToTeach) { + if (!languages[user].includes(language)) { + count++; + } + } + minUsers = Math.min(minUsers, count); + } + return minUsers; +} diff --git a/tests/1501-2000/1734. decode-xored-permutation/manifest.yaml b/tests/1501-2000/1734. decode-xored-permutation/manifest.yaml new file mode 100644 index 00000000..f097fc6e --- /dev/null +++ b/tests/1501-2000/1734. decode-xored-permutation/manifest.yaml @@ -0,0 +1,642 @@ +entry: + id: 1734 + title: "decode-xored-permutation" + params: + encoded: + type: array + items: + type: int + call: + cpp: "Solution().decode({encoded})" + rust: "Solution::decode({encoded})" + python3: "Solution().decode({encoded})" + python2: "Solution().decode({encoded})" + ruby: "decode({encoded})" + java: "new Solution().decode({encoded})" + csharp: "new Solution().Decode({encoded})" + kotlin: "Solution().decode({encoded})" + go: "decode({encoded})" + dart: "Solution().decode({encoded})" + swift: "Solution().decode({encoded})" + typescript: "decode({encoded})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().decode(encoded, {result})" + checker: | + class Checker: + def decode(self, encoded, result): + n = len(encoded) + 1 + if not isinstance(result, list) or len(result) != n: + return False + if sorted(result) != list(range(1, n + 1)): + return False + return all(result[i] ^ result[i + 1] == encoded[i] for i in range(n - 1)) + +seed: 1734 + +tests: + - name: example-one + in: + encoded: [3, 1] + out: [1, 2, 3] + judge: + type: "exact" + - name: example-two + in: + encoded: [6, 5, 4, 6] + out: [2, 4, 1, 5, 3] + judge: + type: "exact" + - name: identity-5 + in: + encoded: [3, 1, 7, 1] + out: [1, 2, 3, 4, 5] + judge: + type: "exact" + - name: reverse-5 + in: + encoded: [1, 7, 1, 3] + out: [5, 4, 3, 2, 1] + judge: + type: "exact" + - name: alternating-5 + in: + encoded: [4, 5, 6, 1] + out: [5, 1, 4, 2, 3] + judge: + type: "exact" + - name: identity-7 + in: + encoded: [3, 1, 7, 1, 3, 1] + out: [1, 2, 3, 4, 5, 6, 7] + judge: + type: "exact" + - name: reverse-7 + in: + encoded: [1, 3, 1, 7, 1, 3] + out: [7, 6, 5, 4, 3, 2, 1] + judge: + type: "exact" + - name: alternating-7 + in: + encoded: [6, 7, 4, 7, 6, 7] + out: [7, 1, 6, 2, 5, 3, 4] + judge: + type: "exact" + - name: identity-9 + in: + encoded: [3, 1, 7, 1, 3, 1, 15, 1] + out: [1, 2, 3, 4, 5, 6, 7, 8, 9] + judge: + type: "exact" + - name: reverse-9 + in: + encoded: [1, 15, 1, 3, 1, 7, 1, 3] + out: [9, 8, 7, 6, 5, 4, 3, 2, 1] + judge: + type: "exact" + - name: alternating-9 + in: + encoded: [8, 9, 10, 5, 4, 5, 2, 1] + out: [9, 1, 8, 2, 7, 3, 6, 4, 5] + judge: + type: "exact" + - name: identity-11 + in: + encoded: [3, 1, 7, 1, 3, 1, 15, 1, 3, 1] + out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + judge: + type: "exact" + - name: reverse-11 + in: + encoded: [1, 3, 1, 15, 1, 3, 1, 7, 1, 3] + out: [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + judge: + type: "exact" + - name: alternating-11 + in: + encoded: [10, 11, 8, 11, 10, 11, 12, 3, 2, 3] + out: [11, 1, 10, 2, 9, 3, 8, 4, 7, 5, 6] + judge: + type: "exact" + - name: identity-13 + in: + encoded: [3, 1, 7, 1, 3, 1, 15, 1, 3, 1, 7, 1] + out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] + judge: + type: "exact" + - name: reverse-13 + in: + encoded: [1, 7, 1, 3, 1, 15, 1, 3, 1, 7, 1, 3] + out: [13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + judge: + type: "exact" + - name: alternating-15 + in: + encoded: [14, 15, 12, 15, 14, 15, 8, 15, 14, 15, 12, 15, 14, 15] + out: [15, 1, 14, 2, 13, 3, 12, 4, 11, 5, 10, 6, 9, 7, 8] + judge: + type: "exact" + - name: identity-15 + in: + encoded: [3, 1, 7, 1, 3, 1, 15, 1, 3, 1, 7, 1, 3, 1] + out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + judge: + type: "exact" + - name: reverse-15 + in: + encoded: [1, 3, 1, 7, 1, 3, 1, 15, 1, 3, 1, 7, 1, 3] + out: [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + judge: + type: "exact" + - name: identity-17 + in: + encoded: [3, 1, 7, 1, 3, 1, 15, 1, 3, 1, 7, 1, 3, 1, 31, 1] + out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17] + judge: + type: "exact" + - name: reverse-17 + in: + encoded: [1, 31, 1, 3, 1, 7, 1, 3, 1, 15, 1, 3, 1, 7, 1, 3] + out: [17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + judge: + type: "exact" + - name: alternating-21 + in: + encoded: + [20, 21, 22, 17, 16, 17, 22, 21, 20, 21, 22, 9, 8, 9, 6, 5, 4, 5, 6, 1] + out: + [ + 21, + 1, + 20, + 2, + 19, + 3, + 18, + 4, + 17, + 5, + 16, + 6, + 15, + 7, + 14, + 8, + 13, + 9, + 12, + 10, + 11, + ] + judge: + type: "exact" + - name: identity-21 + in: + encoded: [3, 1, 7, 1, 3, 1, 15, 1, 3, 1, 7, 1, 3, 1, 31, 1, 3, 1, 7, 1] + out: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + ] + judge: + type: "exact" + - name: reverse-21 + in: + encoded: [1, 7, 1, 3, 1, 31, 1, 3, 1, 7, 1, 3, 1, 15, 1, 3, 1, 7, 1, 3] + out: + [ + 21, + 20, + 19, + 18, + 17, + 16, + 15, + 14, + 13, + 12, + 11, + 10, + 9, + 8, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + ] + judge: + type: "exact" + - name: identity-25 + in: + encoded: + [ + 3, + 1, + 7, + 1, + 3, + 1, + 15, + 1, + 3, + 1, + 7, + 1, + 3, + 1, + 31, + 1, + 3, + 1, + 7, + 1, + 3, + 1, + 15, + 1, + ] + out: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + ] + judge: + type: "exact" + - name: reverse-25 + in: + encoded: + [ + 1, + 15, + 1, + 3, + 1, + 7, + 1, + 3, + 1, + 31, + 1, + 3, + 1, + 7, + 1, + 3, + 1, + 15, + 1, + 3, + 1, + 7, + 1, + 3, + ] + out: + [ + 25, + 24, + 23, + 22, + 21, + 20, + 19, + 18, + 17, + 16, + 15, + 14, + 13, + 12, + 11, + 10, + 9, + 8, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + ] + judge: + type: "exact" + - name: identity-31 + in: + encoded: + [ + 3, + 1, + 7, + 1, + 3, + 1, + 15, + 1, + 3, + 1, + 7, + 1, + 3, + 1, + 31, + 1, + 3, + 1, + 7, + 1, + 3, + 1, + 15, + 1, + 3, + 1, + 7, + 1, + 3, + 1, + ] + out: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + ] + judge: + type: "exact" + - name: reverse-31 + in: + encoded: + [ + 1, + 3, + 1, + 7, + 1, + 3, + 1, + 15, + 1, + 3, + 1, + 7, + 1, + 3, + 1, + 31, + 1, + 3, + 1, + 7, + 1, + 3, + 1, + 15, + 1, + 3, + 1, + 7, + 1, + 3, + ] + out: + [ + 31, + 30, + 29, + 28, + 27, + 26, + 25, + 24, + 23, + 22, + 21, + 20, + 19, + 18, + 17, + 16, + 15, + 14, + 13, + 12, + 11, + 10, + 9, + 8, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + ] + judge: + type: "exact" + - name: rotated-5 + in: + encoded: [6, 7, 2, 4] + out: [2, 4, 3, 1, 5] + judge: + type: "exact" + - name: rotated-7 + in: + encoded: [5, 3, 2, 6, 3, 6] + out: [3, 6, 5, 7, 1, 2, 4] + judge: + type: "exact" + - name: sparse-high-bit-9 + in: + encoded: [14, 13, 2, 7, 9, 11, 1, 7] + out: [7, 9, 4, 6, 1, 8, 3, 2, 5] + judge: + type: "exact" + - name: zigzag-11 + in: + encoded: [10, 11, 8, 11, 10, 11, 12, 3, 2, 3] + out: [11, 1, 10, 2, 9, 3, 8, 4, 7, 5, 6] + judge: + type: "exact" + - name: peak-valley-13 + in: + encoded: [12, 13, 14, 9, 8, 9, 14, 13, 12, 13, 14, 1] + out: [13, 1, 12, 2, 11, 3, 10, 4, 9, 5, 8, 6, 7] + judge: + type: "exact" + - name: duplicate-xor-pattern + in: + encoded: [3, 1, 7, 1, 3, 1, 15, 1, 3, 1, 7, 1] + out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] + judge: + type: "exact" + - name: odd-boundary-3 + in: + encoded: [1, 2] + out: [2, 3, 1] + judge: + type: "exact" + - name: high-variation-15 + in: + encoded: [9, 11, 14, 11, 13, 14, 9, 12, 7, 13, 4, 10, 11, 13] + out: [8, 1, 10, 4, 15, 2, 12, 5, 9, 14, 3, 7, 13, 6, 11] + judge: + type: "exact" + - name: identity-33 + in: + encoded: + [ + 3, + 1, + 7, + 1, + 3, + 1, + 15, + 1, + 3, + 1, + 7, + 1, + 3, + 1, + 31, + 1, + 3, + 1, + 7, + 1, + 3, + 1, + 15, + 1, + 3, + 1, + 7, + 1, + 3, + 1, + 63, + 1, + ] + out: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + ] + judge: + type: "exact" diff --git a/tests/1501-2000/1734. decode-xored-permutation/sol.cpp b/tests/1501-2000/1734. decode-xored-permutation/sol.cpp new file mode 100644 index 00000000..222214b1 --- /dev/null +++ b/tests/1501-2000/1734. decode-xored-permutation/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + vector decode(vector& encoded) { + int n = encoded.size() + 1; + int xr = 0; + for (int i = 1; i <= n; i++) xr ^= i; + int nxr = 0; + for (int i = 0; i < encoded.size(); i++) { + if (i % 2 == 1) nxr ^= encoded[i]; + } + vector perm(n); + perm[0] = xr ^ nxr; + for (int i = 0; i < encoded.size(); i++) { + perm[i + 1] = encoded[i] ^ perm[i]; + } + return perm; + } +}; diff --git a/tests/1501-2000/1734. decode-xored-permutation/sol.cs b/tests/1501-2000/1734. decode-xored-permutation/sol.cs new file mode 100644 index 00000000..6f4e3997 --- /dev/null +++ b/tests/1501-2000/1734. decode-xored-permutation/sol.cs @@ -0,0 +1,17 @@ +public class Solution { + public int[] Decode(int[] encoded) { + int n = encoded.Length + 1; + int xr = 0; + for (int i = 1; i <= n; i++) xr ^= i; + int nxr = 0; + for (int i = 0; i < encoded.Length; i++) { + if (i % 2 == 1) nxr ^= encoded[i]; + } + int[] perm = new int[n]; + perm[0] = xr ^ nxr; + for (int i = 0; i < encoded.Length; i++) { + perm[i + 1] = encoded[i] ^ perm[i]; + } + return perm; + } +} diff --git a/tests/1501-2000/1734. decode-xored-permutation/sol.dart b/tests/1501-2000/1734. decode-xored-permutation/sol.dart new file mode 100644 index 00000000..ed3e2299 --- /dev/null +++ b/tests/1501-2000/1734. decode-xored-permutation/sol.dart @@ -0,0 +1,17 @@ +class Solution { + List decode(List encoded) { + int n = encoded.length + 1; + int xr = 0; + for (int i = 1; i <= n; i++) xr ^= i; + int nxr = 0; + for (int i = 0; i < encoded.length; i++) { + if (i % 2 == 1) nxr ^= encoded[i]; + } + List perm = List.filled(n, 0); + perm[0] = xr ^ nxr; + for (int i = 0; i < encoded.length; i++) { + perm[i + 1] = encoded[i] ^ perm[i]; + } + return perm; + } +} diff --git a/tests/1501-2000/1734. decode-xored-permutation/sol.go b/tests/1501-2000/1734. decode-xored-permutation/sol.go new file mode 100644 index 00000000..8a9b0ee3 --- /dev/null +++ b/tests/1501-2000/1734. decode-xored-permutation/sol.go @@ -0,0 +1,19 @@ +func decode(encoded []int) []int { + n := len(encoded) + 1 + xr := 0 + for i := 1; i <= n; i++ { + xr ^= i + } + nxr := 0 + for i, v := range encoded { + if i%2 == 1 { + nxr ^= v + } + } + perm := make([]int, n) + perm[0] = xr ^ nxr + for i, v := range encoded { + perm[i+1] = v ^ perm[i] + } + return perm +} diff --git a/tests/1501-2000/1734. decode-xored-permutation/sol.java b/tests/1501-2000/1734. decode-xored-permutation/sol.java new file mode 100644 index 00000000..e35fcabb --- /dev/null +++ b/tests/1501-2000/1734. decode-xored-permutation/sol.java @@ -0,0 +1,17 @@ +class Solution { + public int[] decode(int[] encoded) { + int n = encoded.length + 1; + int xr = 0; + for (int i = 1; i <= n; i++) xr ^= i; + int nxr = 0; + for (int i = 0; i < encoded.length; i++) { + if (i % 2 == 1) nxr ^= encoded[i]; + } + int[] perm = new int[n]; + perm[0] = xr ^ nxr; + for (int i = 0; i < encoded.length; i++) { + perm[i + 1] = encoded[i] ^ perm[i]; + } + return perm; + } +} diff --git a/tests/1501-2000/1734. decode-xored-permutation/sol.kt b/tests/1501-2000/1734. decode-xored-permutation/sol.kt new file mode 100644 index 00000000..ed74b5dc --- /dev/null +++ b/tests/1501-2000/1734. decode-xored-permutation/sol.kt @@ -0,0 +1,17 @@ +class Solution { + fun decode(encoded: IntArray): IntArray { + val n = encoded.size + 1 + var xr = 0 + for (i in 1..n) xr = xr xor i + var nxr = 0 + for (i in encoded.indices) { + if (i % 2 == 1) nxr = nxr xor encoded[i] + } + val perm = IntArray(n) + perm[0] = xr xor nxr + for (i in encoded.indices) { + perm[i + 1] = encoded[i] xor perm[i] + } + return perm + } +} diff --git a/tests/1501-2000/1734. decode-xored-permutation/sol.py b/tests/1501-2000/1734. decode-xored-permutation/sol.py new file mode 100644 index 00000000..eabd5ab4 --- /dev/null +++ b/tests/1501-2000/1734. decode-xored-permutation/sol.py @@ -0,0 +1,17 @@ +class Solution: + def decode(self, encoded: List[int]) -> List[int]: + xr = 0 + for i in range(1, len(encoded) + 2): + xr ^= i + nxr = 0 + for i in range(len(encoded)): + if i & 1: + nxr ^= encoded[i] + + perm = [] + perm.append(xr ^ nxr) + # print() + for i in range(len(encoded)): + perm.append(encoded[i] ^ perm[i]) + # print(perm) + return perm diff --git a/tests/1501-2000/1734. decode-xored-permutation/sol.py2 b/tests/1501-2000/1734. decode-xored-permutation/sol.py2 new file mode 100644 index 00000000..5801567e --- /dev/null +++ b/tests/1501-2000/1734. decode-xored-permutation/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def decode(self, encoded): + """ + :type encoded: List[int] + :rtype: List[int] + """ + n = len(encoded) + 1 + xr = 0 + for i in range(1, n + 1): + xr ^= i + nxr = 0 + for i in range(len(encoded)): + if i % 2 == 1: + nxr ^= encoded[i] + perm = [xr ^ nxr] + for i in range(len(encoded)): + perm.append(encoded[i] ^ perm[i]) + return perm diff --git a/tests/1501-2000/1734. decode-xored-permutation/sol.rb b/tests/1501-2000/1734. decode-xored-permutation/sol.rb new file mode 100644 index 00000000..6aa02cc7 --- /dev/null +++ b/tests/1501-2000/1734. decode-xored-permutation/sol.rb @@ -0,0 +1,16 @@ +# @param {Integer[]} encoded +# @return {Integer[]} +def decode(encoded) + n = encoded.length + 1 + xr = 0 + (1..n).each { |i| xr ^= i } + nxr = 0 + encoded.each_with_index do |val, i| + nxr ^= val if i.odd? + end + perm = [xr ^ nxr] + encoded.each_with_index do |val, i| + perm << (val ^ perm[i]) + end + perm +end diff --git a/tests/1501-2000/1734. decode-xored-permutation/sol.rs b/tests/1501-2000/1734. decode-xored-permutation/sol.rs new file mode 100644 index 00000000..8d1b242a --- /dev/null +++ b/tests/1501-2000/1734. decode-xored-permutation/sol.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn decode(encoded: Vec) -> Vec { + let n = encoded.len() + 1; + let mut xr = 0; + for i in 1..=n { xr ^= i as i32; } + let mut nxr = 0; + for (i, &v) in encoded.iter().enumerate() { + if i % 2 == 1 { nxr ^= v; } + } + let mut perm = vec![0; n]; + perm[0] = xr ^ nxr; + for i in 0..encoded.len() { + perm[i + 1] = encoded[i] ^ perm[i]; + } + perm + } +} diff --git a/tests/1501-2000/1734. decode-xored-permutation/sol.swift b/tests/1501-2000/1734. decode-xored-permutation/sol.swift new file mode 100644 index 00000000..778a08a6 --- /dev/null +++ b/tests/1501-2000/1734. decode-xored-permutation/sol.swift @@ -0,0 +1,17 @@ +class Solution { + func decode(_ encoded: [Int]) -> [Int] { + let n = encoded.count + 1 + var xr = 0 + for i in 1...n { xr ^= i } + var nxr = 0 + for (i, v) in encoded.enumerated() { + if i % 2 == 1 { nxr ^= v } + } + var perm = [Int](repeating: 0, count: n) + perm[0] = xr ^ nxr + for i in 0.. 1: + counts[value] = counts.get(value, 0) + 1 + ways = 1 + for exponent in counts.values(): + ways = ways * __import__('math').comb(n + exponent - 1, exponent) % mod + expected.append(ways) + return result == expected + +seed: 1735 + +tests: + - name: one-one + in: + queries: [[1, 1]] + out: [1] + judge: + type: "exact" + - name: one-prime + in: + queries: [[1, 2]] + out: [1] + judge: + type: "exact" + - name: two-prime + in: + queries: [[2, 2]] + out: [2] + judge: + type: "exact" + - name: example-product + in: + queries: [[2, 6]] + out: [4] + judge: + type: "exact" + - name: repeated-primes + in: + queries: [[3, 12]] + out: [18] + judge: + type: "exact" + - name: power-four + in: + queries: [[4, 16]] + out: [35] + judge: + type: "exact" + - name: product-one + in: + queries: [[5, 1]] + out: [1] + judge: + type: "exact" + - name: single-prime-five + in: + queries: [[5, 5]] + out: [5] + judge: + type: "exact" + - name: two-distinct-primes + in: + queries: [[5, 10]] + out: [25] + judge: + type: "exact" + - name: square-product + in: + queries: [[5, 100]] + out: [225] + judge: + type: "exact" + - name: ten-prime + in: + queries: [[10, 2]] + out: [10] + judge: + type: "exact" + - name: ten-power-six + in: + queries: [[10, 64]] + out: [5005] + judge: + type: "exact" + - name: max-k-small-n + in: + queries: [[10, 10000]] + out: [511225] + judge: + type: "exact" + - name: composite-near-limit + in: + queries: [[20, 9999]] + out: [84000] + judge: + type: "exact" + - name: many-factors + in: + queries: [[50, 720]] + out: [667593624] + judge: + type: "exact" + - name: published-example + in: + queries: [[73, 660]] + out: [50734910] + judge: + type: "exact" + - name: large-n-one + in: + queries: [[100, 1]] + out: [1] + judge: + type: "exact" + - name: large-n-prime + in: + queries: [[100, 2]] + out: [100] + judge: + type: "exact" + - name: large-n-max-k + in: + queries: [[100, 10000]] + out: [672488796] + judge: + type: "exact" + - name: max-n-one + in: + queries: [[10000, 1]] + out: [1] + judge: + type: "exact" + - name: max-n-prime + in: + queries: [[10000, 2]] + out: [10000] + judge: + type: "exact" + - name: max-both + in: + queries: [[10000, 10000]] + out: [418224726] + judge: + type: "exact" + - name: max-composite + in: + queries: [[9999, 9999]] + out: [115005500] + judge: + type: "exact" + - name: two-slots-max-k + in: + queries: [[2, 9999]] + out: [12] + judge: + type: "exact" + - name: three-slots-max-k + in: + queries: [[3, 9999]] + out: [54] + judge: + type: "exact" + - name: four-slots-max-k + in: + queries: [[4, 9999]] + out: [160] + judge: + type: "exact" + - name: five-slots-max-k + in: + queries: [[5, 9999]] + out: [375] + judge: + type: "exact" + - name: power-six + in: + queries: [[6, 7776]] + out: [63504] + judge: + type: "exact" + - name: power-two-twelve + in: + queries: [[7, 4096]] + out: [18564] + judge: + type: "exact" + - name: power-three-eight + in: + queries: [[8, 6561]] + out: [6435] + judge: + type: "exact" + - name: mixed-batch + in: + queries: [[1, 1], [2, 6], [5, 10], [10, 64], [100, 10000]] + out: [1, 4, 25, 5005, 672488796] + judge: + type: "exact" + - name: repeated-queries + in: + queries: [[73, 660], [73, 660], [1, 1], [10000, 2], [73, 660]] + out: [50734910, 50734910, 1, 10000, 50734910] + judge: + type: "exact" + - name: generated-small + in: + queries: + gen: "array" + len: 1 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 10000 + elemType: "int" + elemType: "int" + seed: 173501 + - name: generated-medium + in: + queries: + gen: "array" + len: 25 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 10000 + elemType: "int" + elemType: "int" + seed: 173502 + - name: generated-large + in: + queries: + gen: "array" + len: 10000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 10000 + elemType: "int" + elemType: "int" + seed: 173503 + - name: generated-large-repeat + in: + queries: + gen: "array" + len: 10000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 10000 + elemType: "int" + elemType: "int" + seed: 173504 + - name: generated-boundary-batch + in: + queries: + gen: "array" + len: 10000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 10000 + elemType: "int" + elemType: "int" + seed: 173505 diff --git a/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.cpp b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.cpp new file mode 100644 index 00000000..4f732aa5 --- /dev/null +++ b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.cpp @@ -0,0 +1,42 @@ +class Solution { +public: + vector waysToFillArray(vector>& queries) { + const int MOD = 1'000'000'007; + vector result; + + for (const auto& q : queries) { + int n = q[0], k = q[1]; + auto factors = primeFactors(k); + long long total = 1; + for (auto& [_, cnt] : factors) { + total = total * comb(n + cnt - 1, n - 1) % MOD; + } + result.push_back(total); + } + return result; + } + +private: + unordered_map primeFactors(int n) { + unordered_map map; + int p = 2; + while (p * p <= n) { + while (n % p == 0) { + map[p]++; + n /= p; + } + p++; + } + if (n > 1) map[n]++; + return map; + } + + long long comb(int n, int r) { + r = min(r, n - r); + long long result = 1; + for (int i = 1; i <= r; i++) result = result * (n - i + 1) % 1000000007 * modPow(i, 1000000005) % 1000000007; + return result; + } + + long long modPow(long long a, long long e) { long long r = 1; while (e) { if (e & 1) r = r * a % 1000000007; a = a * a % 1000000007; e >>= 1; } return r; } +}; diff --git a/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.cs b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.cs new file mode 100644 index 00000000..8ff42b42 --- /dev/null +++ b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.cs @@ -0,0 +1,45 @@ +public class Solution { + private const int MOD = 1_000_000_007; + + public int[] WaysToFillArray(int[][] queries) { + var result = new int[queries.Length]; + for (int i = 0; i < queries.Length; i++) { + int n = queries[i][0]; + int k = queries[i][1]; + var factors = PrimeFactors(k); + long total = 1; + foreach (var cnt in factors.Values) { + total = total * Comb(n + cnt - 1, n - 1) % MOD; + } + result[i] = (int)total; + } + return result; + } + + private Dictionary PrimeFactors(int n) { + var dict = new Dictionary(); + int p = 2; + while (p * p <= n) { + while (n % p == 0) { + if (dict.ContainsKey(p)) dict[p]++; + else dict[p] = 1; + n /= p; + } + p++; + } + if (n > 1) { + if (dict.ContainsKey(n)) dict[n]++; + else dict[n] = 1; + } + return dict; + } + + private long Comb(int n, int r) { + r = Math.Min(r, n - r); + long result = 1; + for (int i = 1; i <= r; i++) result = result * (n - i + 1) % MOD * ModPow(i, MOD - 2) % MOD; + return result; + } + + private long ModPow(long a, long e) { long r = 1; while (e > 0) { if ((e & 1) != 0) r = r * a % MOD; a = a * a % MOD; e >>= 1; } return r; } +} diff --git a/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.dart b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.dart new file mode 100644 index 00000000..dc7ca6d8 --- /dev/null +++ b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.dart @@ -0,0 +1,41 @@ +class Solution { + List waysToFillArray(List> queries) { + const int mod = 1000000007; + List result = []; + + for (var q in queries) { + int n = q[0]; + int k = q[1]; + var factors = primeFactors(k); + BigInt total = BigInt.one; + for (var cnt in factors.values) { + total = total * BigInt.from(comb(n + cnt - 1, n - 1)) % BigInt.from(mod); + } + result.add(total.toInt()); + } + return result; + } + + Map primeFactors(int n) { + Map map = {}; + int p = 2; + while (p * p <= n) { + while (n % p == 0) { + map[p] = (map[p] ?? 0) + 1; + n ~/= p; + } + p++; + } + if (n > 1) map[n] = (map[n] ?? 0) + 1; + return map; + } + + int comb(int n, int r) { + r = r < n - r ? r : n - r; + int result = 1; + for (int i = 1; i <= r; i++) result = result * (n - i + 1) % 1000000007 * modPow(i, 1000000005) % 1000000007; + return result; + } + + int modPow(int a, int e) { int r = 1; while (e > 0) { if (e & 1 == 1) r = r * a % 1000000007; a = a * a % 1000000007; e >>= 1; } return r; } +} diff --git a/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.go b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.go new file mode 100644 index 00000000..514c4ad7 --- /dev/null +++ b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.go @@ -0,0 +1,46 @@ +func waysToFillArray(queries [][]int) []int { + const mod = int64(1e9 + 7) + ans := make([]int, len(queries)) + + for idx, q := range queries { + n, k := q[0], q[1] + primes := primeFactors(k) + total := int64(1) + for _, cnt := range primes { + total = total * comb(n+cnt-1, n-1) % mod + } + ans[idx] = int(total) + } + return ans +} + +func primeFactors(n int) []int { + factors := []int{} + p := 2 + for p*p <= n { + count := 0 + for n%p == 0 { + count++ + n /= p + } + if count > 0 { + factors = append(factors, count) + } + p++ + } + if n > 1 { + factors = append(factors, 1) + } + return factors +} + +func comb(n, r int) int64 { + if r > n-r { + r = n - r + } + var result int64 = 1 + for i := 1; i <= r; i++ { result = result * int64(n-i+1) % 1000000007 * modPow(int64(i), 1000000005) % 1000000007 } + return result +} + +func modPow(a, e int64) int64 { var r int64 = 1; for e > 0 { if e&1 == 1 { r = r*a%1000000007 }; a = a*a%1000000007; e >>= 1 }; return r } diff --git a/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.java b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.java new file mode 100644 index 00000000..c1a29c7b --- /dev/null +++ b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.java @@ -0,0 +1,42 @@ +class Solution { + private static final int MOD = 1_000_000_007; + + public int[] waysToFillArray(int[][] queries) { + int[] ans = new int[queries.length]; + for (int i = 0; i < queries.length; i++) { + int n = queries[i][0]; + int k = queries[i][1]; + + java.util.Map factors = primeFactors(k); + long total = 1; + for (int cnt : factors.values()) { + total = total * comb(n + cnt - 1, n - 1) % MOD; + } + ans[i] = (int) total; + } + return ans; + } + + private java.util.Map primeFactors(int n) { + java.util.Map map = new java.util.HashMap<>(); + int p = 2; + while (p * p <= n) { + while (n % p == 0) { + map.put(p, map.getOrDefault(p, 0) + 1); + n /= p; + } + p++; + } + if (n > 1) map.put(n, map.getOrDefault(n, 0) + 1); + return map; + } + + private long comb(int n, int r) { + r = Math.min(r, n - r); + long result = 1; + for (int i = 1; i <= r; i++) result = result * (n - i + 1) % MOD * modPow(i, MOD - 2) % MOD; + return result; + } + + private long modPow(long a, long e) { long r = 1; while (e > 0) { if ((e & 1) != 0) r = r * a % MOD; a = a * a % MOD; e >>= 1; } return r; } +} diff --git a/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.kt b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.kt new file mode 100644 index 00000000..d55ee944 --- /dev/null +++ b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.kt @@ -0,0 +1,42 @@ +class Solution { + private val MOD = 1_000_000_007 + + fun waysToFillArray(queries: Array): IntArray { + val result = IntArray(queries.size) + queries.forEachIndexed { idx, q -> + val n = q[0] + val k = q[1] + val factors = primeFactors(k) + var total = 1L + for (cnt in factors.values) { + total = total * comb(n + cnt - 1, n - 1) % MOD + } + result[idx] = total.toInt() + } + return result + } + + private fun primeFactors(n: Int): HashMap { + val map = HashMap() + var num = n + var p = 2 + while (p * p <= num) { + while (num % p == 0) { + map[p] = (map[p] ?: 0) + 1 + num /= p + } + p++ + } + if (num > 1) map[num] = (map[num] ?: 0) + 1 + return map + } + + private fun comb(n: Int, r: Int): Long { + val rr = minOf(r, n - r) + var result = 1L + for (i in 1..rr) result = result * (n - i + 1) % MOD * modPow(i.toLong(), MOD - 2) % MOD + return result + } + + private fun modPow(base: Long, exponent: Int): Long { var a = base; var e = exponent; var r = 1L; while (e > 0) { if (e and 1 == 1) r = r * a % MOD; a = a * a % MOD; e = e ushr 1 }; return r } +} diff --git a/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.py b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.py new file mode 100644 index 00000000..437441c3 --- /dev/null +++ b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.py @@ -0,0 +1,26 @@ +import collections +import math + + +class Solution: + def waysToFillArray(self, queries: List[List[int]]) -> List[int]: + def primes(n): + ret = [] + p = 2 + while p * p <= n: + while n % p == 0: + ret.append(p) + n //= p + p += 1 + if n != 1: + ret.append(n) + return ret + + ans = [] + for q in queries: + a = 1 + prime_count = collections.Counter(primes(q[1])) + for p, c in prime_count.items(): + a *= math.comb(q[0] + c - 1, q[0] - 1) + ans.append(a % (10**9 + 7)) + return ans diff --git a/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.py2 b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.py2 new file mode 100644 index 00000000..88053361 --- /dev/null +++ b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.py2 @@ -0,0 +1,36 @@ +class Solution(object): + def waysToFillArray(self, queries): + """ + :type queries: List[List[int]] + :rtype: List[int] + """ + MOD = 10**9 + 7 + from collections import Counter + + def get_primes(n): + result = [] + p = 2 + while p * p <= n: + while n % p == 0: + result.append(p) + n //= p + p += 1 + if n > 1: + result.append(n) + return result + + def comb(n, r): + r = min(r, n - r) + result = 1 + for i in xrange(1, r + 1): + result = result * (n - i + 1) // i + return result + + ans = [] + for n, k in queries: + factors = Counter(get_primes(k)) + total = 1 + for c in factors.values(): + total = total * comb(n + c - 1, n - 1) % MOD + ans.append(int(total)) + return ans diff --git a/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.rb b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.rb new file mode 100644 index 00000000..4cad39fa --- /dev/null +++ b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.rb @@ -0,0 +1,39 @@ +# @param {Integer[][]} queries +# @return {Integer[]} +def ways_to_fill_array(queries) + mod = 10**9 + 7 + result = [] + + queries.each do |n, k| + factors = prime_factors(k) + total = 1 + factors.each do |_, cnt| + total = total * comb(n + cnt - 1, n - 1) % mod + end + result << total + end + result +end + +def prime_factors(n) + counts = Hash.new(0) + p = 2 + while p * p <= n + while n % p == 0 + counts[p] += 1 + n /= p + end + p += 1 + end + counts[n] += 1 if n > 1 + counts +end + +def comb(n, r) + r = [r, n - r].min + result = 1 + (1..r).each do |i| + result = result * (n - i + 1) / i + end + result +end diff --git a/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.rs b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.rs new file mode 100644 index 00000000..0b0d7fe1 --- /dev/null +++ b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.rs @@ -0,0 +1,49 @@ +impl Solution { + pub fn ways_to_fill_array(queries: Vec>) -> Vec { + const MOD: i64 = 1_000_000_007; + + fn prime_factors(n: i32) -> std::collections::HashMap { + let mut map = std::collections::HashMap::new(); + let mut num = n; + let mut p = 2; + while p * p <= num { + while num % p == 0 { + *map.entry(p).or_insert(0) += 1; + num /= p; + } + p += 1; + } + if num > 1 { + *map.entry(num).or_insert(0) += 1; + } + map + } + + fn comb(n: i32, r: i32) -> i64 { + let mut result = 1i64; + let rr = std::cmp::min(r, n - r); + for i in 1..=rr { + result = result * (n - i + 1) as i64 % MOD; + result = result * mod_pow(i as i64, MOD - 2) % MOD; + } + result + } + + fn mod_pow(mut a: i64, mut e: i64) -> i64 { + let mut r = 1i64; + while e > 0 { if e & 1 == 1 { r = r * a % MOD; } a = a * a % MOD; e >>= 1; } + r + } + + queries.iter().map(|q| { + let n = q[0]; + let k = q[1]; + let factors = prime_factors(k); + let mut total: i64 = 1; + for cnt in factors.values() { + total = total * comb(n + cnt - 1, n - 1) % MOD; + } + total as i32 + }).collect() + } +} diff --git a/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.swift b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.swift new file mode 100644 index 00000000..ab9ad0a3 --- /dev/null +++ b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.swift @@ -0,0 +1,47 @@ +class Solution { + let mod = 1_000_000_007 + + func waysToFillArray(_ queries: [[Int]]) -> [Int] { + var result = [Int]() + + for q in queries { + let n = q[0] + let k = q[1] + let factors = primeFactors(k) + var total = 1 + for (_, cnt) in factors { + total = total * comb(n + cnt - 1, n - 1) % mod + } + result.append(total) + } + return result + } + + private func primeFactors(_ n: Int) -> [Int: Int] { + var num = n + var dict = [Int: Int]() + var p = 2 + while p * p <= num { + while num % p == 0 { + dict[p, default: 0] += 1 + num /= p + } + p += 1 + } + if num > 1 { + dict[num, default: 0] += 1 + } + return dict + } + + private func comb(_ n: Int, _ r: Int) -> Int { + var rr = r + if rr > n - rr { rr = n - rr } + var result = 1 + if rr == 0 { return 1 } + for i in 1...rr { result = result * (n - i + 1) % mod * modPow(i, mod - 2) % mod } + return result + } + + private func modPow(_ base: Int, _ exponent: Int) -> Int { var a = base, e = exponent, r = 1; while e > 0 { if e & 1 == 1 { r = r * a % mod }; a = a * a % mod; e >>= 1 }; return r } +} diff --git a/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.ts b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.ts new file mode 100644 index 00000000..61257849 --- /dev/null +++ b/tests/1501-2000/1735. count-ways-to-make-array-with-product/sol.ts @@ -0,0 +1,48 @@ +function waysToFillArray(queries: number[][]): number[] { + const MOD = 1_000_000_007; + + function primeFactors(n: number): Map { + const map = new Map(); + let p = 2; + while (p * p <= n) { + while (n % p === 0) { + map.set(p, (map.get(p) || 0) + 1); + n = Math.floor(n / p); + } + p++; + } + if (n > 1) map.set(n, (map.get(n) || 0) + 1); + return map; + } + + function pow(a: bigint, e: bigint): bigint { + let result = 1n; + while (e > 0n) { + if (e % 2n === 1n) result = (result * a) % BigInt(MOD); + a = (a * a) % BigInt(MOD); + e = e / 2n; + } + return result; + } + function comb(n: number, r: number): number { + r = Math.min(r, n - r); + let result = 1n; + for (let i = 1; i <= r; i++) + result = + (((result * BigInt(n - i + 1)) % BigInt(MOD)) * + pow(BigInt(i), BigInt(MOD - 2))) % + BigInt(MOD); + return Number(result); + } + + const result: number[] = []; + for (const [n, k] of queries) { + const factors = primeFactors(k); + let total = 1n; + for (const cnt of factors.values()) { + total = (total * BigInt(comb(n + cnt - 1, n - 1))) % BigInt(MOD); + } + result.push(Number(total)); + } + return result; +} diff --git a/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/manifest.yaml b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/manifest.yaml new file mode 100644 index 00000000..1ab93b31 --- /dev/null +++ b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/manifest.yaml @@ -0,0 +1,204 @@ +entry: + id: 1736 + title: "latest-time-by-replacing-hidden-digits" + params: + time: + type: string + call: + cpp: "Solution().maximumTime({time})" + rust: "Solution::maximum_time({time})" + python3: "Solution().maximumTime({time})" + python2: "Solution().maximumTime({time})" + ruby: "maximum_time({time})" + java: "new Solution().maximumTime({time})" + csharp: "new Solution().MaximumTime({time})" + kotlin: "Solution().maximumTime({time})" + go: "maximumTime({time})" + dart: "Solution().maximumTime({time})" + swift: "Solution().maximumTime({time})" + typescript: "maximumTime({time})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(time, {result})" + checker: | + class Checker: + def check(self, time, result): + best = None + for hour in range(24): + for minute in range(60): + candidate = f"{hour:02d}:{minute:02d}" + if all(a == '?' or a == b for a, b in zip(time, candidate)): + best = candidate + return result == best + +seed: 1736 + +tests: + - name: "all-hidden" + in: + time: "??:??" + out: "23:59" + - name: "example-two" + in: + time: "2?:?0" + out: "23:50" + - name: "example-three" + in: + time: "0?:3?" + out: "09:39" + - name: "example-four" + in: + time: "1?:22" + out: "19:22" + - name: "fixed-midnight" + in: + time: "00:00" + out: "00:00" + - name: "fixed-latest" + in: + time: "23:59" + out: "23:59" + - name: "hour-first-hidden" + in: + time: "?3:45" + out: "23:45" + - name: "hour-first-hidden-low-second" + in: + time: "?0:00" + out: "20:00" + - name: "hour-first-hidden-high-second" + in: + time: "?9:59" + out: "19:59" + - name: "hour-second-hidden-zero-prefix" + in: + time: "0?:00" + out: "09:00" + - name: "hour-second-hidden-one-prefix" + in: + time: "1?:00" + out: "19:00" + - name: "hour-second-hidden-two-prefix" + in: + time: "2?:00" + out: "23:00" + - name: "both-hour-digits-hidden" + in: + time: "??:00" + out: "23:00" + - name: "minute-tens-hidden" + in: + time: "12:?5" + out: "12:55" + - name: "minute-ones-hidden" + in: + time: "12:5?" + out: "12:59" + - name: "both-minute-digits-hidden" + in: + time: "12:??" + out: "12:59" + - name: "all-hidden-zero-hour-context" + in: + time: "0?:??" + out: "09:59" + - name: "all-hidden-one-hour-context" + in: + time: "1?:??" + out: "19:59" + - name: "all-hidden-two-hour-context" + in: + time: "2?:??" + out: "23:59" + - name: "fixed-hour-zero" + in: + time: "00:??" + out: "00:59" + - name: "fixed-hour-nine" + in: + time: "09:??" + out: "09:59" + - name: "fixed-hour-ten" + in: + time: "10:??" + out: "10:59" + - name: "fixed-hour-nineteen" + in: + time: "19:??" + out: "19:59" + - name: "fixed-hour-twenty" + in: + time: "20:??" + out: "20:59" + - name: "fixed-hour-twenty-three" + in: + time: "23:??" + out: "23:59" + - name: "fixed-minute-zero" + in: + time: "??:01" + out: "23:01" + - name: "fixed-minute-nine" + in: + time: "??:09" + out: "23:09" + - name: "fixed-minute-ten" + in: + time: "??:10" + out: "23:10" + - name: "fixed-minute-fifty" + in: + time: "??:50" + out: "23:50" + - name: "fixed-minute-fifty-nine" + in: + time: "??:59" + out: "23:59" + - name: "mixed-low" + in: + time: "?0:?0" + out: "20:50" + - name: "mixed-high" + in: + time: "?9:5?" + out: "19:59" + - name: "restricted-hour" + in: + time: "2?:4?" + out: "23:49" + - name: "restricted-hour-tens" + in: + time: "?3:??" + out: "23:59" + - name: "near-midnight" + in: + time: "2?:5?" + out: "23:59" + - name: "first-hour-digit-zero-boundary" + in: + time: "?0:??" + out: "20:59" + - name: "first-hour-digit-one-boundary" + in: + time: "?1:??" + out: "21:59" + - name: "second-hour-digit-zero-boundary" + in: + time: "1?:0?" + out: "19:09" + - name: "minute-tens-zero-boundary" + in: + time: "23:0?" + out: "23:09" + - name: "minute-ones-zero-boundary" + in: + time: "23:?0" + out: "23:50" diff --git a/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.cpp b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.cpp new file mode 100644 index 00000000..80853996 --- /dev/null +++ b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + string maximumTime(string time) { + string ret = ""; + for (int i = 0; i < time.length(); i++) { + char c = time[i]; + if (c == '?') { + if (i == 0) { + if (time[i+1] == '?') { + ret += '2'; + } else if (time[i+1] >= '0' && time[i+1] <= '3') { + ret += '2'; + } else { + ret += '1'; + } + } else if (i == 1) { + if (time[i-1] == '?') { + ret += '3'; + } else if (time[i-1] == '0' || time[i-1] == '1') { + ret += '9'; + } else { + ret += '3'; + } + } else if (i == 3) { + ret += '5'; + } else if (i == 4) { + ret += '9'; + } + } else { + ret += c; + } + } + return ret; + } +}; diff --git a/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.cs b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.cs new file mode 100644 index 00000000..13d40532 --- /dev/null +++ b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.cs @@ -0,0 +1,34 @@ +public class Solution { + public string MaximumTime(string time) { + string ret = ""; + for (int i = 0; i < time.Length; i++) { + char c = time[i]; + if (c == '?') { + if (i == 0) { + if (time[i+1] == '?') { + ret += '2'; + } else if (time[i+1] >= '0' && time[i+1] <= '3') { + ret += '2'; + } else { + ret += '1'; + } + } else if (i == 1) { + if (time[i-1] == '?') { + ret += '3'; + } else if (time[i-1] == '0' || time[i-1] == '1') { + ret += '9'; + } else { + ret += '3'; + } + } else if (i == 3) { + ret += '5'; + } else if (i == 4) { + ret += '9'; + } + } else { + ret += c; + } + } + return ret; + } +} diff --git a/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.dart b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.dart new file mode 100644 index 00000000..5fe5dda3 --- /dev/null +++ b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.dart @@ -0,0 +1,34 @@ +class Solution { + String maximumTime(String time) { + String ret = ''; + for (int i = 0; i < time.length; i++) { + String c = time[i]; + if (c == '?') { + if (i == 0) { + if (time[i+1] == '?') { + ret += '2'; + } else if ('0123'.contains(time[i+1])) { + ret += '2'; + } else { + ret += '1'; + } + } else if (i == 1) { + if (time[i-1] == '?') { + ret += '3'; + } else if (time[i-1] == '0' || time[i-1] == '1') { + ret += '9'; + } else { + ret += '3'; + } + } else if (i == 3) { + ret += '5'; + } else if (i == 4) { + ret += '9'; + } + } else { + ret += c; + } + } + return ret; + } +} diff --git a/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.go b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.go new file mode 100644 index 00000000..ced43123 --- /dev/null +++ b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.go @@ -0,0 +1,32 @@ +func maximumTime(time string) string { + ret := "" + for i := 0; i < len(time); i++ { + c := time[i] + if c == '?' { + if i == 0 { + if time[i+1] == '?' { + ret += "2" + } else if time[i+1] >= '0' && time[i+1] <= '3' { + ret += "2" + } else { + ret += "1" + } + } else if i == 1 { + if time[i-1] == '?' { + ret += "3" + } else if time[i-1] == '0' || time[i-1] == '1' { + ret += "9" + } else { + ret += "3" + } + } else if i == 3 { + ret += "5" + } else if i == 4 { + ret += "9" + } + } else { + ret += string(c) + } + } + return ret +} diff --git a/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.java b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.java new file mode 100644 index 00000000..ea502c83 --- /dev/null +++ b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.java @@ -0,0 +1,35 @@ +class Solution { + public String maximumTime(String time) { + int len = time.length(); + StringBuilder ret = new StringBuilder(); + for (int i = 0; i < len; i++) { + char c = time.charAt(i); + if (c == '?') { + if (i == 0) { + if (time.charAt(i+1) == '?') { + ret.append('2'); + } else if (time.charAt(i+1) >= '0' && time.charAt(i+1) <= '3') { + ret.append('2'); + } else { + ret.append('1'); + } + } else if (i == 1) { + if (time.charAt(i-1) == '?') { + ret.append('3'); + } else if (time.charAt(i-1) == '0' || time.charAt(i-1) == '1') { + ret.append('9'); + } else { + ret.append('3'); + } + } else if (i == 3) { + ret.append('5'); + } else if (i == 4) { + ret.append('9'); + } + } else { + ret.append(c); + } + } + return ret.toString(); + } +} diff --git a/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.kt b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.kt new file mode 100644 index 00000000..b6b6a5ff --- /dev/null +++ b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.kt @@ -0,0 +1,34 @@ +class Solution { + fun maximumTime(time: String): String { + var ret = StringBuilder() + for (i in 0 until time.length) { + val c = time[i] + if (c == '?') { + if (i == 0) { + if (time[i+1] == '?') { + ret.append('2') + } else if (time[i+1] in '0'..'3') { + ret.append('2') + } else { + ret.append('1') + } + } else if (i == 1) { + if (time[i-1] == '?') { + ret.append('3') + } else if (time[i-1] == '0' || time[i-1] == '1') { + ret.append('9') + } else { + ret.append('3') + } + } else if (i == 3) { + ret.append('5') + } else if (i == 4) { + ret.append('9') + } + } else { + ret.append(c) + } + } + return ret.toString() + } +} diff --git a/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.py b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.py new file mode 100644 index 00000000..85be9645 --- /dev/null +++ b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.py @@ -0,0 +1,35 @@ +class Solution: + def maximumTime(self, time): + time_str = time + len_time_str = len(time_str) + + ret_val = "" + + i = 0 + while i < len_time_str: + c = time_str[i] + if c == "?": + if i == 0: + if time_str[i + 1] == "?": + ret_val += "2" + elif time_str[i + 1] in ("0", "1", "2", "3"): + ret_val += "2" + else: + ret_val += "1" + elif i == 1: + if time_str[i - 1] == "?": + ret_val += "3" + elif time_str[i - 1] in ("0", "1"): + ret_val += "9" + else: + ret_val += "3" + elif i == 3: + ret_val += "5" + elif i == 4: + ret_val += "9" + else: + ret_val += c + + i += 1 + + return ret_val diff --git a/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.py2 b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.py2 new file mode 100644 index 00000000..a11217f1 --- /dev/null +++ b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.py2 @@ -0,0 +1,34 @@ +class Solution(object): + def maximumTime(self, time): + """ + :type time: str + :rtype: str + """ + len_time_str = len(time) + ret_val = '' + i = 0 + while i < len_time_str: + c = time[i] + if c == '?': + if i == 0: + if time[i+1] == '?': + ret_val += '2' + elif time[i+1] in ('0', '1', '2', '3'): + ret_val += '2' + else: + ret_val += '1' + elif i == 1: + if time[i-1] == '?': + ret_val += '3' + elif time[i-1] in ('0', '1'): + ret_val += '9' + else: + ret_val += '3' + elif i == 3: + ret_val += '5' + elif i == 4: + ret_val += '9' + else: + ret_val += c + i += 1 + return ret_val diff --git a/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.rb b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.rb new file mode 100644 index 00000000..9ff9da6a --- /dev/null +++ b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.rb @@ -0,0 +1,37 @@ +# @param {String} time +# @return {String} +def maximum_time(time) + len_time_str = time.length + ret_val = '' + i = 0 + while i < len_time_str + c = time[i] + if c == '?' + if i == 0 + if time[i+1] == '?' + ret_val += '2' + elsif ['0', '1', '2', '3'].include?(time[i+1]) + ret_val += '2' + else + ret_val += '1' + end + elsif i == 1 + if time[i-1] == '?' + ret_val += '3' + elsif ['0', '1'].include?(time[i-1]) + ret_val += '9' + else + ret_val += '3' + end + elsif i == 3 + ret_val += '5' + elsif i == 4 + ret_val += '9' + end + else + ret_val += c + end + i += 1 + end + ret_val +end diff --git a/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.rs b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.rs new file mode 100644 index 00000000..aab5cd04 --- /dev/null +++ b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.rs @@ -0,0 +1,35 @@ +impl Solution { + pub fn maximum_time(time: String) -> String { + let chars: Vec = time.chars().collect(); + let mut ret = String::new(); + for i in 0..chars.len() { + let c = chars[i]; + if c == '?' { + if i == 0 { + if chars[i+1] == '?' { + ret.push('2'); + } else if chars[i+1] >= '0' && chars[i+1] <= '3' { + ret.push('2'); + } else { + ret.push('1'); + } + } else if i == 1 { + if chars[i-1] == '?' { + ret.push('3'); + } else if chars[i-1] == '0' || chars[i-1] == '1' { + ret.push('9'); + } else { + ret.push('3'); + } + } else if i == 3 { + ret.push('5'); + } else if i == 4 { + ret.push('9'); + } + } else { + ret.push(c); + } + } + ret + } +} diff --git a/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.swift b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.swift new file mode 100644 index 00000000..848d92d7 --- /dev/null +++ b/tests/1501-2000/1736. latest-time-by-replacing-hidden-digits/sol.swift @@ -0,0 +1,35 @@ +class Solution { + func maximumTime(_ time: String) -> String { + var ret = "" + let chars = Array(time) + for i in 0.. freqA(26, 0); + vector freqB(26, 0); + + for (char ch : a) freqA[ch - 'a']++; + for (char ch : b) freqB[ch - 'a']++; + + int lenA = a.size(); + int lenB = b.size(); + int res = INT_MAX; + int sumA = 0, sumB = 0; + + for (int i = 0; i < 25; i++) { + sumA += freqA[i]; + sumB += freqB[i]; + res = min(res, lenA - sumA + sumB); + res = min(res, lenB - sumB + sumA); + } + + for (int i = 0; i < 26; i++) { + res = min(res, (lenA - freqA[i]) + (lenB - freqB[i])); + } + + return res; + } +}; diff --git a/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.cs b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.cs new file mode 100644 index 00000000..168e8b13 --- /dev/null +++ b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.cs @@ -0,0 +1,27 @@ +public class Solution { + public int MinCharacters(string a, string b) { + int[] freqA = new int[26]; + int[] freqB = new int[26]; + + foreach (char ch in a) freqA[ch - 'a']++; + foreach (char ch in b) freqB[ch - 'a']++; + + int lenA = a.Length; + int lenB = b.Length; + int res = int.MaxValue; + int sumA = 0, sumB = 0; + + for (int i = 0; i < 25; i++) { + sumA += freqA[i]; + sumB += freqB[i]; + res = Math.Min(res, lenA - sumA + sumB); + res = Math.Min(res, lenB - sumB + sumA); + } + + for (int i = 0; i < 26; i++) { + res = Math.Min(res, (lenA - freqA[i]) + (lenB - freqB[i])); + } + + return res; + } +} diff --git a/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.dart b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.dart new file mode 100644 index 00000000..4a653347 --- /dev/null +++ b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.dart @@ -0,0 +1,32 @@ +class Solution { + int minCharacters(String a, String b) { + List freqA = List.filled(26, 0); + List freqB = List.filled(26, 0); + + for (int i = 0; i < a.length; i++) { + freqA[a.codeUnitAt(i) - 97]++; + } + for (int i = 0; i < b.length; i++) { + freqB[b.codeUnitAt(i) - 97]++; + } + + int lenA = a.length; + int lenB = b.length; + int res = 1 << 30; + int sumA = 0, sumB = 0; + + for (int i = 0; i < 25; i++) { + sumA += freqA[i]; + sumB += freqB[i]; + res = res < (lenA - sumA + sumB) ? res : lenA - sumA + sumB; + res = res < (lenB - sumB + sumA) ? res : lenB - sumB + sumA; + } + + for (int i = 0; i < 26; i++) { + int temp = (lenA - freqA[i]) + (lenB - freqB[i]); + res = res < temp ? res : temp; + } + + return res; + } +} diff --git a/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.go b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.go new file mode 100644 index 00000000..afba6e27 --- /dev/null +++ b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.go @@ -0,0 +1,36 @@ +func minCharacters(a string, b string) int { + freqA := make([]int, 26) + freqB := make([]int, 26) + + for _, ch := range a { + freqA[ch-'a']++ + } + for _, ch := range b { + freqB[ch-'a']++ + } + + lenA := len(a) + lenB := len(b) + res := lenA + lenB + 1 + sumA, sumB := 0, 0 + + for i := 0; i < 25; i++ { + sumA += freqA[i] + sumB += freqB[i] + if lenA-sumA+sumB < res { + res = lenA - sumA + sumB + } + if lenB-sumB+sumA < res { + res = lenB - sumB + sumA + } + } + + for i := 0; i < 26; i++ { + temp := (lenA - freqA[i]) + (lenB - freqB[i]) + if temp < res { + res = temp + } + } + + return res +} diff --git a/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.java b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.java new file mode 100644 index 00000000..ee500186 --- /dev/null +++ b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.java @@ -0,0 +1,31 @@ +class Solution { + public int minCharacters(String a, String b) { + int[] freqA = new int[26]; + int[] freqB = new int[26]; + + for (char ch : a.toCharArray()) { + freqA[ch - 'a']++; + } + for (char ch : b.toCharArray()) { + freqB[ch - 'a']++; + } + + int lenA = a.length(); + int lenB = b.length(); + int res = Integer.MAX_VALUE; + int sumA = 0, sumB = 0; + + for (int i = 0; i < 25; i++) { + sumA += freqA[i]; + sumB += freqB[i]; + res = Math.min(res, lenA - sumA + sumB); + res = Math.min(res, lenB - sumB + sumA); + } + + for (int i = 0; i < 26; i++) { + res = Math.min(res, (lenA - freqA[i]) + (lenB - freqB[i])); + } + + return res; + } +} diff --git a/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.kt b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.kt new file mode 100644 index 00000000..d4028471 --- /dev/null +++ b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.kt @@ -0,0 +1,28 @@ +class Solution { + fun minCharacters(a: String, b: String): Int { + val freqA = IntArray(26) + val freqB = IntArray(26) + + for (ch in a) freqA[ch - 'a']++ + for (ch in b) freqB[ch - 'a']++ + + val lenA = a.length + val lenB = b.length + var res = Int.MAX_VALUE + var sumA = 0 + var sumB = 0 + + for (i in 0 until 25) { + sumA += freqA[i] + sumB += freqB[i] + res = minOf(res, lenA - sumA + sumB) + res = minOf(res, lenB - sumB + sumA) + } + + for (i in 0 until 26) { + res = minOf(res, (lenA - freqA[i]) + (lenB - freqB[i])) + } + + return res + } +} diff --git a/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.py b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.py new file mode 100644 index 00000000..bac1783e --- /dev/null +++ b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.py @@ -0,0 +1,30 @@ +class Solution(object): + def minCharacters(self, a, b): + """ + :type a: str + :type b: str + :rtype: int + """ + freq_a = [0] * 26 + freq_b = [0] * 26 + + for ch in a: + freq_a[ord(ch) - ord("a")] += 1 + for ch in b: + freq_b[ord(ch) - ord("a")] += 1 + + len_a = len(a) + len_b = len(b) + res = float("inf") + sum_a = sum_b = 0 + + for i in range(25): + sum_a += freq_a[i] + sum_b += freq_b[i] + res = min(res, len_a - sum_a + sum_b) + res = min(res, len_b - sum_b + sum_a) + + for i in range(26): + res = min(res, (len_a - freq_a[i]) + (len_b - freq_b[i])) + + return res diff --git a/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.py2 b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.py2 new file mode 100644 index 00000000..6a0dbd58 --- /dev/null +++ b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.py2 @@ -0,0 +1,30 @@ +class Solution(object): + def minCharacters(self, a, b): + """ + :type a: str + :type b: str + :rtype: int + """ + freq_a = [0] * 26 + freq_b = [0] * 26 + + for ch in a: + freq_a[ord(ch) - ord('a')] += 1 + for ch in b: + freq_b[ord(ch) - ord('a')] += 1 + + len_a = len(a) + len_b = len(b) + res = float('inf') + sum_a = sum_b = 0 + + for i in range(25): + sum_a += freq_a[i] + sum_b += freq_b[i] + res = min(res, len_a - sum_a + sum_b) + res = min(res, len_b - sum_b + sum_a) + + for i in range(26): + res = min(res, (len_a - freq_a[i]) + (len_b - freq_b[i])) + + return res diff --git a/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.rb b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.rb new file mode 100644 index 00000000..6df8ce42 --- /dev/null +++ b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.rb @@ -0,0 +1,28 @@ +# @param {String} a +# @param {String} b +# @return {Integer} +def min_characters(a, b) + freq_a = Array.new(26, 0) + freq_b = Array.new(26, 0) + + a.each_char { |ch| freq_a[ch.ord - 'a'.ord] += 1 } + b.each_char { |ch| freq_b[ch.ord - 'a'.ord] += 1 } + + len_a = a.length + len_b = b.length + res = Float::INFINITY + sum_a = 0 + sum_b = 0 + + (0...25).each do |i| + sum_a += freq_a[i] + sum_b += freq_b[i] + res = [res, len_a - sum_a + sum_b, len_b - sum_b + sum_a].min + end + + (0...26).each do |i| + res = [res, (len_a - freq_a[i]) + (len_b - freq_b[i])].min + end + + res +end diff --git a/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.rs b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.rs new file mode 100644 index 00000000..5d74d607 --- /dev/null +++ b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.rs @@ -0,0 +1,32 @@ +impl Solution { + pub fn min_characters(a: String, b: String) -> i32 { + let mut freq_a = vec![0; 26]; + let mut freq_b = vec![0; 26]; + + for ch in a.bytes() { + freq_a[(ch - b'a') as usize] += 1; + } + for ch in b.bytes() { + freq_b[(ch - b'a') as usize] += 1; + } + + let len_a = a.len(); + let len_b = b.len(); + let mut res = i32::MAX; + let mut sum_a = 0; + let mut sum_b = 0; + + for i in 0..25 { + sum_a += freq_a[i]; + sum_b += freq_b[i]; + res = res.min((len_a as i32 - sum_a + sum_b)); + res = res.min((len_b as i32 - sum_b + sum_a)); + } + + for i in 0..26 { + res = res.min((len_a as i32 - freq_a[i]) + (len_b as i32 - freq_b[i])); + } + + res + } +} diff --git a/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.swift b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.swift new file mode 100644 index 00000000..aeffbedd --- /dev/null +++ b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.swift @@ -0,0 +1,31 @@ +class Solution { + func minCharacters(_ a: String, _ b: String) -> Int { + var freqA = [Int](repeating: 0, count: 26) + var freqB = [Int](repeating: 0, count: 26) + + for ch in a.utf8 { + freqA[Int(ch) - 97] += 1 + } + for ch in b.utf8 { + freqB[Int(ch) - 97] += 1 + } + + let lenA = a.count + let lenB = b.count + var res = Int.max + var sumA = 0, sumB = 0 + + for i in 0..<25 { + sumA += freqA[i] + sumB += freqB[i] + res = min(res, lenA - sumA + sumB) + res = min(res, lenB - sumB + sumA) + } + + for i in 0..<26 { + res = min(res, (lenA - freqA[i]) + (lenB - freqB[i])) + } + + return res + } +} diff --git a/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.ts b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.ts new file mode 100644 index 00000000..c729d068 --- /dev/null +++ b/tests/1501-2000/1737. change-minimum-characters-to-satisfy-one-of-three-conditions/sol.ts @@ -0,0 +1,30 @@ +function minCharacters(a: string, b: string): number { + const freqA: number[] = new Array(26).fill(0); + const freqB: number[] = new Array(26).fill(0); + + for (const ch of a) { + freqA[ch.charCodeAt(0) - 97]++; + } + for (const ch of b) { + freqB[ch.charCodeAt(0) - 97]++; + } + + const lenA = a.length; + const lenB = b.length; + let res = Number.MAX_SAFE_INTEGER; + let sumA = 0, + sumB = 0; + + for (let i = 0; i < 25; i++) { + sumA += freqA[i]; + sumB += freqB[i]; + res = Math.min(res, lenA - sumA + sumB); + res = Math.min(res, lenB - sumB + sumA); + } + + for (let i = 0; i < 26; i++) { + res = Math.min(res, lenA - freqA[i] + (lenB - freqB[i])); + } + + return res; +} diff --git a/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/manifest.yaml b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/manifest.yaml new file mode 100644 index 00000000..5dd74a1c --- /dev/null +++ b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/manifest.yaml @@ -0,0 +1,370 @@ +entry: + id: 1738 + title: "find-kth-largest-xor-coordinate-value" + params: + matrix: + type: array + items: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().kthLargestValue({matrix}, {k})" + rust: "Solution::kth_largest_value({matrix}, {k})" + python3: "Solution().kthLargestValue({matrix}, {k})" + python2: "Solution().kthLargestValue({matrix}, {k})" + ruby: "kth_largest_value({matrix}, {k})" + java: "new Solution().kthLargestValue({matrix}, {k})" + csharp: "new Solution().KthLargestValue({matrix}, {k})" + kotlin: "Solution().kthLargestValue({matrix}, {k})" + go: "kthLargestValue({matrix}, {k})" + dart: "Solution().kthLargestValue({matrix}, {k})" + swift: "Solution().kthLargestValue({matrix}, {k})" + typescript: "kthLargestValue({matrix}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().kthLargestValue(matrix, k, {result})" + checker: | + class Checker: + def kthLargestValue(self, matrix, k, result): + if not isinstance(matrix, list) or not matrix or not isinstance(k, int): + return False + if not all(isinstance(row, list) and row for row in matrix): + return False + width = len(matrix[0]) + if any(len(row) != width or any(not isinstance(x, int) or x < 0 or x > 1000000 for x in row) for row in matrix): + return False + if k < 1 or k > len(matrix) * width or not isinstance(result, int): + return False + pref = [[0] * width for _ in matrix] + values = [] + for i, row in enumerate(matrix): + for j, value in enumerate(row): + cur = value + if i: + cur ^= pref[i - 1][j] + if j: + cur ^= pref[i][j - 1] + if i and j: + cur ^= pref[i - 1][j - 1] + pref[i][j] = cur + values.append(cur) + values.sort(reverse=True) + return result == values[k - 1] + +seed: 17381738 + +tests: + - name: example-one + in: + matrix: + - [5, 2] + - [1, 6] + k: 1 + out: 7 + - name: example-two + in: + matrix: + - [5, 2] + - [1, 6] + k: 2 + out: 5 + - name: example-three + in: + matrix: + - [5, 2] + - [1, 6] + k: 3 + out: 4 + - name: example-last + in: + matrix: + - [5, 2] + - [1, 6] + k: 4 + out: 0 + - name: single-zero + in: + matrix: + - [0] + k: 1 + out: 0 + - name: single-maximum + in: + matrix: + - [1000000] + k: 1 + out: 1000000 + - name: one-row + in: + matrix: + - [1, 2, 3, 4, 5] + k: 3 + out: 1 + - name: one-column + in: + matrix: + - [1] + - [2] + - [3] + - [4] + k: 2 + out: 3 + - name: all-zero + in: + matrix: + - [0, 0] + - [0, 0] + - [0, 0] + k: 4 + out: 0 + - name: equal-values + in: + matrix: + - [7, 7] + - [7, 7] + k: 3 + out: 0 + - name: xor-cancellation + in: + matrix: + - [1, 1] + - [1, 1] + k: 1 + out: 1 + - name: two-by-three + in: + matrix: + - [1, 2, 4] + - [8, 16, 32] + k: 4 + out: 7 + - name: three-by-two + in: + matrix: + - [3, 5] + - [7, 9] + - [11, 13] + k: 5 + out: 4 + - name: powers-of-two + in: + matrix: + - [1, 2, 4] + - [8, 16, 32] + - [64, 128, 256] + k: 1 + out: 511 + - name: high-values + in: + matrix: + - [1000000, 999999] + - [999998, 999997] + k: 2 + out: 127 + - name: alternating + in: + matrix: + - [0, 1, 0, 1] + - [1, 0, 1, 0] + - [0, 1, 0, 1] + k: 6 + out: 1 + - name: rectangular-four-by-three + in: + matrix: + - [2, 7, 1] + - [8, 2, 8] + - [1, 3, 9] + - [4, 6, 5] + k: 7 + out: 10 + - name: negative-free-bit-patterns + in: + matrix: + - [1048575, 524288] + - [262144, 131072] + k: 3 + out: 524287 + - name: five-by-one + in: + matrix: + - [10] + - [20] + - [30] + - [40] + - [50] + k: 5 + out: 0 + - name: six-by-two + in: + matrix: + - [1, 3] + - [5, 7] + - [9, 11] + - [13, 15] + - [17, 19] + - [21, 23] + k: 8 + out: 1 + - name: mixed-small + in: + matrix: + - [12, 5, 9] + - [3, 10, 6] + k: 5 + out: 0 + - name: diagonal-cancellation + in: + matrix: + - [255, 0, 255] + - [0, 255, 0] + - [255, 0, 255] + k: 9 + out: 0 + - name: max-k + in: + matrix: + - [15, 8, 3] + - [4, 12, 7] + - [9, 2, 14] + k: 9 + out: 2 + - name: wide-eight + in: + matrix: + - [1, 4, 9, 16, 25, 36, 49, 64] + k: 8 + out: 1 + - name: tall-eight + in: + matrix: + - [1] + - [4] + - [9] + - [16] + - [25] + - [36] + - [49] + - [64] + k: 4 + out: 16 + - name: repeated-large + in: + matrix: + - [65535, 65535, 65535] + - [65535, 65535, 65535] + k: 2 + out: 65535 + - name: nine-by-nine-small + in: + matrix: + - [1, 2, 3, 4, 5, 6, 7, 8, 9] + - [9, 8, 7, 6, 5, 4, 3, 2, 1] + - [2, 4, 6, 8, 1, 3, 5, 7, 9] + - [9, 7, 5, 3, 1, 8, 6, 4, 2] + - [5, 5, 5, 5, 5, 5, 5, 5, 5] + - [0, 1, 0, 1, 0, 1, 0, 1, 0] + - [8, 6, 4, 2, 9, 7, 5, 3, 1] + - [3, 1, 4, 1, 5, 9, 2, 6, 5] + - [6, 2, 7, 1, 8, 2, 8, 1, 8] + k: 40 + - name: generated-ten-by-ten + in: + matrix: + gen: "array" + len: 10 + of: + gen: "array" + len: 10 + of: + gen: "int" + min: 0 + max: 1000000 + k: 37 + - name: generated-twenty-by-twenty + in: + matrix: + gen: "array" + len: 20 + of: + gen: "array" + len: 20 + of: + gen: "int" + min: 0 + max: 1000000 + k: 211 + - name: generated-fifty-by-fifty + in: + matrix: + gen: "array" + len: 50 + of: + gen: "array" + len: 50 + of: + gen: "int" + min: 0 + max: 1000000 + k: 1234 + - name: generated-hundred-by-hundred + in: + matrix: + gen: "array" + len: 100 + of: + gen: "array" + len: 100 + of: + gen: "int" + min: 0 + max: 1000000 + k: 5000 + - name: generated-two-hundred-by-fifty + in: + matrix: + gen: "array" + len: 200 + of: + gen: "array" + len: 50 + of: + gen: "int" + min: 0 + max: 1000000 + k: 9999 + - name: two-by-two-high-bit + in: + matrix: + - [524288, 262144] + - [131072, 65536] + k: 2 + out: 786432 + - name: three-by-four-zero-border + in: + matrix: + - [0, 0, 0, 0] + - [1, 2, 4, 8] + - [16, 32, 64, 128] + k: 6 + out: 7 + - name: four-by-four-single-bit + in: + matrix: + - [1, 0, 0, 0] + - [0, 1, 0, 0] + - [0, 0, 1, 0] + - [0, 0, 0, 1] + k: 8 + out: 1 diff --git a/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.cpp b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.cpp new file mode 100644 index 00000000..c777850f --- /dev/null +++ b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int kthLargestValue(vector>& matrix, int k) { + int n = matrix.size(); + int m = matrix[0].size(); + vector> temp(n, vector(m)); + temp[0][0] = matrix[0][0]; + for (int j = 1; j < m; j++) temp[0][j] = temp[0][j-1] ^ matrix[0][j]; + for (int i = 1; i < n; i++) temp[i][0] = temp[i-1][0] ^ matrix[i][0]; + for (int i = 1; i < n; i++) { + for (int j = 1; j < m; j++) { + temp[i][j] = matrix[i][j] ^ temp[i-1][j] ^ temp[i][j-1] ^ temp[i-1][j-1]; + } + } + vector arr; + arr.reserve(n*m); + for (auto& row : temp) { + arr.insert(arr.end(), row.begin(), row.end()); + } + sort(arr.begin(), arr.end(), greater()); + return arr[k-1]; + } +}; diff --git a/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.cs b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.cs new file mode 100644 index 00000000..7be023c3 --- /dev/null +++ b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.cs @@ -0,0 +1,24 @@ +public class Solution { + public int KthLargestValue(int[][] matrix, int k) { + int n = matrix.Length; + int m = matrix[0].Length; + int[][] temp = new int[n][]; + for (int i = 0; i < n; i++) temp[i] = new int[m]; + temp[0][0] = matrix[0][0]; + for (int j = 1; j < m; j++) temp[0][j] = temp[0][j-1] ^ matrix[0][j]; + for (int i = 1; i < n; i++) temp[i][0] = temp[i-1][0] ^ matrix[i][0]; + for (int i = 1; i < n; i++) { + for (int j = 1; j < m; j++) { + temp[i][j] = matrix[i][j] ^ temp[i-1][j] ^ temp[i][j-1] ^ temp[i-1][j-1]; + } + } + List arr = new List(); + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + arr.Add(temp[i][j]); + } + } + arr.Sort((a, b) => b.CompareTo(a)); + return arr[k-1]; + } +} diff --git a/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.dart b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.dart new file mode 100644 index 00000000..a4bd66d3 --- /dev/null +++ b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.dart @@ -0,0 +1,25 @@ +class Solution { + int kthLargestValue(List> matrix, int k) { + int n = matrix.length; + int m = matrix[0].length; + List> temp = List.generate(n, (_) => List.filled(m, 0)); + temp[0][0] = matrix[0][0]; + for (int j = 1; j < m; j++) { + temp[0][j] = temp[0][j-1] ^ matrix[0][j]; + } + for (int i = 1; i < n; i++) { + temp[i][0] = temp[i-1][0] ^ matrix[i][0]; + } + for (int i = 1; i < n; i++) { + for (int j = 1; j < m; j++) { + temp[i][j] = matrix[i][j] ^ temp[i-1][j] ^ temp[i][j-1] ^ temp[i-1][j-1]; + } + } + List arr = []; + for (var row in temp) { + arr.addAll(row); + } + arr.sort((a, b) => b.compareTo(a)); + return arr[k-1]; + } +} diff --git a/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.go b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.go new file mode 100644 index 00000000..3158b2a7 --- /dev/null +++ b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.go @@ -0,0 +1,30 @@ +func kthLargestValue(matrix [][]int, k int) int { + n := len(matrix) + m := len(matrix[0]) + temp := make([][]int, n) + for i := range temp { + temp[i] = make([]int, m) + } + temp[0][0] = matrix[0][0] + for j := 1; j < m; j++ { + temp[0][j] = temp[0][j-1] ^ matrix[0][j] + } + for i := 1; i < n; i++ { + temp[i][0] = temp[i-1][0] ^ matrix[i][0] + } + for i := 1; i < n; i++ { + for j := 1; j < m; j++ { + temp[i][j] = matrix[i][j] ^ temp[i-1][j] ^ temp[i][j-1] ^ temp[i-1][j-1] + } + } + arr := make([]int, n*m) + idx := 0 + for i := 0; i < n; i++ { + for j := 0; j < m; j++ { + arr[idx] = temp[i][j] + idx++ + } + } + sort.Ints(arr) + return arr[n*m-k] +} diff --git a/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.java b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.java new file mode 100644 index 00000000..b6a81f7f --- /dev/null +++ b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.java @@ -0,0 +1,24 @@ +class Solution { + public int kthLargestValue(int[][] matrix, int k) { + int n = matrix.length; + int m = matrix[0].length; + int[][] temp = new int[n][m]; + temp[0][0] = matrix[0][0]; + for (int j = 1; j < m; j++) temp[0][j] = temp[0][j-1] ^ matrix[0][j]; + for (int i = 1; i < n; i++) temp[i][0] = temp[i-1][0] ^ matrix[i][0]; + for (int i = 1; i < n; i++) { + for (int j = 1; j < m; j++) { + temp[i][j] = matrix[i][j] ^ temp[i-1][j] ^ temp[i][j-1] ^ temp[i-1][j-1]; + } + } + int[] arr = new int[n*m]; + int idx = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + arr[idx++] = temp[i][j]; + } + } + Arrays.sort(arr); + return arr[n*m - k]; + } +} diff --git a/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.kt b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.kt new file mode 100644 index 00000000..754bc19d --- /dev/null +++ b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.kt @@ -0,0 +1,24 @@ +class Solution { + fun kthLargestValue(matrix: Array, k: Int): Int { + val n = matrix.size + val m = matrix[0].size + val temp = Array(n) { IntArray(m) } + temp[0][0] = matrix[0][0] + for (j in 1 until m) temp[0][j] = temp[0][j-1] xor matrix[0][j] + for (i in 1 until n) temp[i][0] = temp[i-1][0] xor matrix[i][0] + for (i in 1 until n) { + for (j in 1 until m) { + temp[i][j] = matrix[i][j] xor temp[i-1][j] xor temp[i][j-1] xor temp[i-1][j-1] + } + } + val arr = IntArray(n * m) + var index = 0 + for (row in temp) { + for (value in row) { + arr[index++] = value + } + } + arr.sort() + return arr[n*m - k] + } +} diff --git a/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.py b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.py new file mode 100644 index 00000000..a54c63b0 --- /dev/null +++ b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.py @@ -0,0 +1,76 @@ +class Solution: + def kthLargestValue(self, matrix: List[List[int]], k: int) -> int: + grid = matrix + n = len(grid) + m = len(grid[0]) + # the value of the n is 1000 so we need to create a temp matrix in O(n^2) only + + # --------------------------------------------------------------------------- + temp = [[0] * m for _ in range(n)] + temp[0][0] = grid[0][0] + # in XOR 0^a ====>>a always #that is why intilalising temp with 0 BESt + # ---------------------------------------------------------------------- + # ----------------------------------------- + # firstrow + for j in range(1, m): + temp[0][j] = temp[0][j - 1] ^ grid[0][j] + + # firstcolumn + for i in range(1, n): + temp[i][0] = temp[i - 1][0] ^ grid[i][0] + + # ----------------------------------------- + # filling temp + for i in range(1, n): + for j in range(1, m): + temp[i][j] = ( + grid[i][j] ^ temp[i - 1][j] ^ temp[i][j - 1] ^ temp[i - 1][j - 1] + ) + # left up diag + # --------------------------------------------------------------------------------- + # print(f"{temp=}") + + # --------------------------------------------------------------------- + arr = [] + for row in temp: + arr.extend(row) + # now either do the sorting thing in this array -->>> tc : O(n*n) *log(n*n) + # or we can use heap upto k i guess -->>> tc : O(n*n) *log(k) + + # firstly trying the sorting approach + arr.sort(reverse=True) + return arr[k - 1] # k-1 becaue in prblm they said 1 indexig stupid + # --------------------------------------------------------------------- + + # APPROACH 2 using a single pass for loop and heap simultaneously, pushing in the min heap + # ===================================================================================================== + + temp = [[0] * m for _ in range(n)] + pq = [] + # ----------------------------------------------- + for i in range(n): + for j in range(m): + temp[i][j] = grid[i][j] + + if j > 0: # firstrow + temp[i][j] ^= temp[i][j - 1] + + if i > 0: # firstcolumn + temp[i][j] ^= temp[i - 1][j] + + if i > 0 and j > 0: # inside elements + temp[i][j] ^= temp[i - 1][j - 1] # diag + + # --------------------------------------- + heapq.heappush(pq, temp[i][j]) + while len(pq) > k: + heapq.heappop(pq) + # --------------------------------------- + + return pq[0] + # --------------------------------------------------------------------------------- + + # Using MinHeap works here. + + +# ===================================================================================================== diff --git a/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.py2 b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.py2 new file mode 100644 index 00000000..2a8f6349 --- /dev/null +++ b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def kthLargestValue(self, matrix, k): + """ + :type matrix: List[List[int]] + :type k: int + :rtype: int + """ + n = len(matrix) + m = len(matrix[0]) + temp = [[0]*m for _ in range(n)] + temp[0][0] = matrix[0][0] + for j in range(1, m): + temp[0][j] = temp[0][j-1] ^ matrix[0][j] + for i in range(1, n): + temp[i][0] = temp[i-1][0] ^ matrix[i][0] + for i in range(1, n): + for j in range(1, m): + temp[i][j] = matrix[i][j] ^ temp[i-1][j] ^ temp[i][j-1] ^ temp[i-1][j-1] + arr = [] + for row in temp: + arr.extend(row) + arr.sort(reverse=True) + return arr[k-1] diff --git a/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.rb b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.rb new file mode 100644 index 00000000..aabc91e8 --- /dev/null +++ b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.rb @@ -0,0 +1,19 @@ +# @param {Integer[][]} matrix +# @param {Integer} k +# @return {Integer} +def kth_largest_value(matrix, k) + n = matrix.length + m = matrix[0].length + temp = Array.new(n) { Array.new(m, 0) } + temp[0][0] = matrix[0][0] + (1...m).each { |j| temp[0][j] = temp[0][j-1] ^ matrix[0][j] } + (1...n).each { |i| temp[i][0] = temp[i-1][0] ^ matrix[i][0] } + (1...n).each do |i| + (1...m).each do |j| + temp[i][j] = matrix[i][j] ^ temp[i-1][j] ^ temp[i][j-1] ^ temp[i-1][j-1] + end + end + arr = temp.flatten + arr.sort! { |a,b| b <=> a } + arr[k-1] +end diff --git a/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.rs b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.rs new file mode 100644 index 00000000..cd7bd6e3 --- /dev/null +++ b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn kth_largest_value(matrix: Vec>, k: i32) -> i32 { + let n = matrix.len(); + let m = matrix[0].len(); + let mut temp = vec![vec![0; m]; n]; + temp[0][0] = matrix[0][0]; + for j in 1..m { + temp[0][j] = temp[0][j-1] ^ matrix[0][j]; + } + for i in 1..n { + temp[i][0] = temp[i-1][0] ^ matrix[i][0]; + } + for i in 1..n { + for j in 1..m { + temp[i][j] = matrix[i][j] ^ temp[i-1][j] ^ temp[i][j-1] ^ temp[i-1][j-1]; + } + } + let mut arr: Vec = Vec::new(); + for row in temp.iter() { + arr.extend(row.iter()); + } + arr.sort_by(|a, b| b.cmp(a)); + arr[(k-1) as usize] + } +} diff --git a/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.swift b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.swift new file mode 100644 index 00000000..116ab7f4 --- /dev/null +++ b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.swift @@ -0,0 +1,25 @@ +class Solution { + func kthLargestValue(_ matrix: [[Int]], _ k: Int) -> Int { + let n = matrix.count + let m = matrix[0].count + var temp = Array(repeating: Array(repeating: 0, count: m), count: n) + temp[0][0] = matrix[0][0] + for j in 1..) + return arr[k-1] + } +} diff --git a/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.ts b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.ts new file mode 100644 index 00000000..acb041dd --- /dev/null +++ b/tests/1501-2000/1738. find-kth-largest-xor-coordinate-value/sol.ts @@ -0,0 +1,17 @@ +function kthLargestValue(matrix: number[][], k: number): number { + const n = matrix.length; + const m = matrix[0].length; + const temp: number[][] = Array.from({ length: n }, () => Array(m).fill(0)); + temp[0][0] = matrix[0][0]; + for (let j = 1; j < m; j++) temp[0][j] = temp[0][j - 1] ^ matrix[0][j]; + for (let i = 1; i < n; i++) temp[i][0] = temp[i - 1][0] ^ matrix[i][0]; + for (let i = 1; i < n; i++) { + for (let j = 1; j < m; j++) { + temp[i][j] = + matrix[i][j] ^ temp[i - 1][j] ^ temp[i][j - 1] ^ temp[i - 1][j - 1]; + } + } + const arr: number[] = temp.flat(); + arr.sort((a, b) => b - a); + return arr[k - 1]; +} diff --git a/tests/1501-2000/1739. building-boxes/manifest.yaml b/tests/1501-2000/1739. building-boxes/manifest.yaml new file mode 100644 index 00000000..cbd95476 --- /dev/null +++ b/tests/1501-2000/1739. building-boxes/manifest.yaml @@ -0,0 +1,204 @@ +entry: + id: 1739 + title: "building-boxes" + params: + n: + type: int + call: + cpp: "Solution().minimumBoxes({n})" + rust: "Solution::minimum_boxes({n})" + python3: "Solution().minimumBoxes({n})" + python2: "Solution().minimumBoxes({n})" + ruby: "minimum_boxes({n})" + java: "new Solution().minimumBoxes({n})" + csharp: "new Solution().MinimumBoxes({n})" + kotlin: "Solution().minimumBoxes({n})" + go: "minimumBoxes({n})" + dart: "Solution().minimumBoxes({n})" + swift: "Solution().minimumBoxes({n})" + typescript: "minimumBoxes({n})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().minimumBoxes(n, {result})" + checker: | + class Checker: + def minimumBoxes(self, n, result): + if not isinstance(n, int) or isinstance(n, bool) or n < 1 or n > 1000000000: + return False + if not isinstance(result, int) or isinstance(result, bool) or result < 1: + return False + x = 0 + while (x + 1) * (x + 2) * (x + 3) // 6 <= n: + x += 1 + full = x * (x + 1) * (x + 2) // 6 + base = x * (x + 1) // 2 + remainder = n - full + extra = 0 + layer = 1 + while remainder > 0: + extra += 1 + remainder -= layer + layer += 1 + return result == base + extra + +seed: 17391739 + +tests: + - name: minimum-one + in: + n: 1 + out: 1 + - name: two-boxes + in: + n: 2 + out: 2 + - name: example-three + in: + n: 3 + out: 3 + - name: example-four + in: + n: 4 + out: 3 + - name: five-boxes + in: + n: 5 + out: 4 + - name: six-boxes + in: + n: 6 + out: 5 + - name: seven-boxes + in: + n: 7 + out: 5 + - name: eight-boxes + in: + n: 8 + out: 6 + - name: nine-boxes + in: + n: 9 + out: 6 + - name: example-ten + in: + n: 10 + out: 6 + - name: eleven-boxes + in: + n: 11 + out: 7 + - name: twelve-boxes + in: + n: 12 + out: 8 + - name: thirteen-boxes + in: + n: 13 + out: 8 + - name: fourteen-boxes + in: + n: 14 + out: 9 + - name: fifteen-boxes + in: + n: 15 + out: 9 + - name: sixteen-boxes + in: + n: 16 + out: 9 + - name: seventeen-boxes + in: + n: 17 + out: 10 + - name: eighteen-boxes + in: + n: 18 + out: 10 + - name: nineteen-boxes + in: + n: 19 + out: 10 + - name: twenty-boxes + in: + n: 20 + out: 10 + - name: twenty-one-boxes + in: + n: 21 + out: 11 + - name: twenty-two-boxes + in: + n: 22 + out: 12 + - name: twenty-four-boxes + in: + n: 24 + out: 13 + - name: twenty-seven-boxes + in: + n: 27 + out: 14 + - name: thirty-two-boxes + in: + n: 32 + out: 15 + - name: thirty-six-boxes + in: + n: 36 + out: 16 + - name: forty-two-boxes + in: + n: 42 + out: 19 + - name: one-hundred-boxes + in: + n: 100 + out: 34 + - name: one-thousand-boxes + in: + n: 1000 + out: 161 + - name: one-million-boxes + in: + n: 1000000 + out: 16443 + - name: generated-small-boundary + in: + n: + gen: "int" + min: 1 + max: 100000 + - name: generated-medium-boundary + in: + n: + gen: "int" + min: 100000 + max: 10000000 + - name: generated-large-values + in: + n: + gen: "int" + min: 10000000 + max: 1000000000 + - name: generated-near-maximum + in: + n: + gen: "int" + min: 900000000 + max: 1000000000 + - name: generated-full-domain + in: + n: + gen: "int" + min: 1 + max: 1000000000 diff --git a/tests/1501-2000/1739. building-boxes/sol.cpp b/tests/1501-2000/1739. building-boxes/sol.cpp new file mode 100644 index 00000000..39dea310 --- /dev/null +++ b/tests/1501-2000/1739. building-boxes/sol.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int minimumBoxes(int n) { + long long lo = 0, hi = 200000, target = n; + while (lo < hi) { + long long mid = (lo + hi + 1) / 2; + if (mid * (mid + 1) * (mid + 2) / 6 <= target) lo = mid; + else hi = mid - 1; + } + long long remaining = target - lo * (lo + 1) * (lo + 2) / 6; + long long extra = 0; + while (extra * (extra + 1) / 2 < remaining) ++extra; + return (int)(lo * (lo + 1) / 2 + extra); + } +}; diff --git a/tests/1501-2000/1739. building-boxes/sol.cs b/tests/1501-2000/1739. building-boxes/sol.cs new file mode 100644 index 00000000..6bce074c --- /dev/null +++ b/tests/1501-2000/1739. building-boxes/sol.cs @@ -0,0 +1,14 @@ +public class Solution { + public int MinimumBoxes(int n) { + long lo = 0, hi = 200000, target = n; + while (lo < hi) { + long mid = (lo + hi + 1) / 2; + if (mid * (mid + 1) * (mid + 2) / 6 <= target) lo = mid; + else hi = mid - 1; + } + long remaining = target - lo * (lo + 1) * (lo + 2) / 6; + long extra = 0; + while (extra * (extra + 1) / 2 < remaining) extra++; + return (int)(lo * (lo + 1) / 2 + extra); + } +} diff --git a/tests/1501-2000/1739. building-boxes/sol.dart b/tests/1501-2000/1739. building-boxes/sol.dart new file mode 100644 index 00000000..74d40eeb --- /dev/null +++ b/tests/1501-2000/1739. building-boxes/sol.dart @@ -0,0 +1,14 @@ +class Solution { + int minimumBoxes(int n) { + int lo = 0, hi = 200000; + while (lo < hi) { + final mid = (lo + hi + 1) ~/ 2; + if (mid * (mid + 1) * (mid + 2) ~/ 6 <= n) lo = mid; + else hi = mid - 1; + } + final remaining = n - lo * (lo + 1) * (lo + 2) ~/ 6; + var extra = 0; + while (extra * (extra + 1) ~/ 2 < remaining) extra++; + return lo * (lo + 1) ~/ 2 + extra; + } +} diff --git a/tests/1501-2000/1739. building-boxes/sol.go b/tests/1501-2000/1739. building-boxes/sol.go new file mode 100644 index 00000000..4b9f4919 --- /dev/null +++ b/tests/1501-2000/1739. building-boxes/sol.go @@ -0,0 +1,15 @@ +func minimumBoxes(n int) int { + x := int(math.Cbrt(float64(6*n))) + for (x+1)*(x+2)*(x+3) <= 6*n { x++ } + for x*(x+1)*(x+2) > 6*n { x-- } + + ans := x*(x+1)/2 + n -= x*(x+1)*(x+2)/6 + k := 1 + for n > 0 { + ans++ + n -= k + k++ + } + return ans +} diff --git a/tests/1501-2000/1739. building-boxes/sol.java b/tests/1501-2000/1739. building-boxes/sol.java new file mode 100644 index 00000000..a5b14590 --- /dev/null +++ b/tests/1501-2000/1739. building-boxes/sol.java @@ -0,0 +1,14 @@ +class Solution { + public int minimumBoxes(int n) { + long lo = 0, hi = 200000, target = n; + while (lo < hi) { + long mid = (lo + hi + 1) / 2; + if (mid * (mid + 1) * (mid + 2) / 6 <= target) lo = mid; + else hi = mid - 1; + } + long remaining = target - lo * (lo + 1) * (lo + 2) / 6; + long extra = 0; + while (extra * (extra + 1) / 2 < remaining) extra++; + return (int)(lo * (lo + 1) / 2 + extra); + } +} diff --git a/tests/1501-2000/1739. building-boxes/sol.kt b/tests/1501-2000/1739. building-boxes/sol.kt new file mode 100644 index 00000000..12181602 --- /dev/null +++ b/tests/1501-2000/1739. building-boxes/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun minimumBoxes(n: Int): Int { + var lo = 0L + var hi = 200000L + val target = n.toLong() + while (lo < hi) { + val mid = (lo + hi + 1) / 2 + if (mid * (mid + 1) * (mid + 2) / 6 <= target) lo = mid else hi = mid - 1 + } + val remaining = target - lo * (lo + 1) * (lo + 2) / 6 + var extra = 0L + while (extra * (extra + 1) / 2 < remaining) extra++ + return (lo * (lo + 1) / 2 + extra).toInt() + } +} diff --git a/tests/1501-2000/1739. building-boxes/sol.py b/tests/1501-2000/1739. building-boxes/sol.py new file mode 100644 index 00000000..d0f0f254 --- /dev/null +++ b/tests/1501-2000/1739. building-boxes/sol.py @@ -0,0 +1,16 @@ +class Solution: + def minimumBoxes(self, n: int) -> int: + x = int((6.0 * n) ** (1.0 / 3.0)) + while (x + 1) * (x + 2) * (x + 3) <= 6 * n: + x += 1 + while x * (x + 1) * (x + 2) > 6 * n: + x -= 1 + + ans = x * (x + 1) // 2 + n -= x * (x + 1) * (x + 2) // 6 + k = 1 + while n > 0: + ans += 1 + n -= k + k += 1 + return ans diff --git a/tests/1501-2000/1739. building-boxes/sol.py2 b/tests/1501-2000/1739. building-boxes/sol.py2 new file mode 100644 index 00000000..0632417e --- /dev/null +++ b/tests/1501-2000/1739. building-boxes/sol.py2 @@ -0,0 +1,19 @@ +class Solution(object): + def minimumBoxes(self, n): + """ + :type n: int + :rtype: int + """ + lo, hi = 0, 200000 + while lo < hi: + mid = (lo + hi + 1) // 2 + if mid * (mid + 1) * (mid + 2) // 6 <= n: + lo = mid + else: + hi = mid - 1 + full = lo + remaining = n - full * (full + 1) * (full + 2) // 6 + extra = 0 + while extra * (extra + 1) // 2 < remaining: + extra += 1 + return full * (full + 1) // 2 + extra diff --git a/tests/1501-2000/1739. building-boxes/sol.rb b/tests/1501-2000/1739. building-boxes/sol.rb new file mode 100644 index 00000000..6270dd13 --- /dev/null +++ b/tests/1501-2000/1739. building-boxes/sol.rb @@ -0,0 +1,17 @@ +# @param {Integer} n +# @return {Integer} +def minimum_boxes(n) + x = ((6*n)**(1.0/3.0)).to_i + x += 1 while (x+1)*(x+2)*(x+3) <= 6*n + x -= 1 while x*(x+1)*(x+2) > 6*n + + ans = x*(x+1)/2 + n -= x*(x+1)*(x+2)/6 + k = 1 + while n > 0 + ans += 1 + n -= k + k += 1 + end + ans +end diff --git a/tests/1501-2000/1739. building-boxes/sol.rs b/tests/1501-2000/1739. building-boxes/sol.rs new file mode 100644 index 00000000..81569cc2 --- /dev/null +++ b/tests/1501-2000/1739. building-boxes/sol.rs @@ -0,0 +1,14 @@ +impl Solution { + pub fn minimum_boxes(n: i32) -> i32 { + let (mut lo, mut hi) = (0_i64, 200_000_i64); + let target = n as i64; + while lo < hi { + let mid = (lo + hi + 1) / 2; + if mid * (mid + 1) * (mid + 2) / 6 <= target { lo = mid; } else { hi = mid - 1; } + } + let remaining = target - lo * (lo + 1) * (lo + 2) / 6; + let mut extra = 0_i64; + while extra * (extra + 1) / 2 < remaining { extra += 1; } + (lo * (lo + 1) / 2 + extra) as i32 + } +} diff --git a/tests/1501-2000/1739. building-boxes/sol.swift b/tests/1501-2000/1739. building-boxes/sol.swift new file mode 100644 index 00000000..8aeb96aa --- /dev/null +++ b/tests/1501-2000/1739. building-boxes/sol.swift @@ -0,0 +1,18 @@ +class Solution { + func minimumBoxes(_ n: Int) -> Int { + var x = Int(pow(Double(6*n), 1.0/3.0)) + if x*(x+1)*(x+2) > 6*n { + x -= 1 + } + + var ans = x*(x+1)/2 + var remaining = n - x*(x+1)*(x+2)/6 + var k = 1 + while remaining > 0 { + ans += 1 + remaining -= k + k += 1 + } + return ans + } +} diff --git a/tests/1501-2000/1739. building-boxes/sol.ts b/tests/1501-2000/1739. building-boxes/sol.ts new file mode 100644 index 00000000..e5be6814 --- /dev/null +++ b/tests/1501-2000/1739. building-boxes/sol.ts @@ -0,0 +1,15 @@ +function minimumBoxes(n: number): number { + let x = Math.floor(Math.cbrt(6 * n)); + while ((x + 1) * (x + 2) * (x + 3) <= 6 * n) x++; + while (x * (x + 1) * (x + 2) > 6 * n) x--; + + let ans = (x * (x + 1)) / 2; + n -= (x * (x + 1) * (x + 2)) / 6; + let k = 1; + while (n > 0) { + ans++; + n -= k; + k++; + } + return ans; +} diff --git a/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/manifest.yaml b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/manifest.yaml new file mode 100644 index 00000000..388793b9 --- /dev/null +++ b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/manifest.yaml @@ -0,0 +1,261 @@ +entry: + id: 1742 + title: "maximum-number-of-balls-in-a-box" + params: + lowLimit: + type: int + highLimit: + type: int + call: + cpp: "Solution().countBalls({lowLimit}, {highLimit})" + rust: "Solution::count_balls({lowLimit}, {highLimit})" + python3: "Solution().countBalls({lowLimit}, {highLimit})" + python2: "Solution().countBalls({lowLimit}, {highLimit})" + ruby: "count_balls({lowLimit}, {highLimit})" + java: "new Solution().countBalls({lowLimit}, {highLimit})" + csharp: "new Solution().CountBalls({lowLimit}, {highLimit})" + kotlin: "Solution().countBalls({lowLimit}, {highLimit})" + go: "countBalls({lowLimit}, {highLimit})" + dart: "Solution().countBalls({lowLimit}, {highLimit})" + swift: "Solution().countBalls({lowLimit}, {highLimit})" + typescript: "countBalls({lowLimit}, {highLimit})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().countBalls(lowLimit, highLimit, {result})" + checker: | + from collections import Counter + + class Checker: + def countBalls(self, lowLimit, highLimit, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + counts = Counter() + for number in range(lowLimit, highLimit + 1): + counts[sum(int(d) for d in str(number))] += 1 + return result == max(counts.values()) + +seed: 1742 + +tests: + - name: single-one + in: + lowLimit: 1 + highLimit: 1 + out: 1 + - name: first-ten + in: + lowLimit: 1 + highLimit: 10 + out: 2 + - name: example-two + in: + lowLimit: 5 + highLimit: 15 + out: 2 + - name: example-three + in: + lowLimit: 19 + highLimit: 28 + out: 2 + - name: one-digit-range + in: + lowLimit: 2 + highLimit: 8 + out: 1 + - name: ten-only + in: + lowLimit: 10 + highLimit: 10 + out: 1 + - name: around-ninety-nine + in: + lowLimit: 98 + highLimit: 102 + out: 1 + - name: digit-boundary + in: + lowLimit: 99 + highLimit: 100 + out: 1 + - name: first-hundred + in: + lowLimit: 100 + highLimit: 109 + out: 1 + - name: first-double-count + in: + lowLimit: 100 + highLimit: 110 + out: 2 + - name: shifted-hundred + in: + lowLimit: 101 + highLimit: 110 + out: 2 + - name: crossing-one-ten + in: + lowLimit: 109 + highLimit: 119 + out: 2 + - name: uniform-tens + in: + lowLimit: 120 + highLimit: 129 + out: 1 + - name: nine-hundred-boundary + in: + lowLimit: 999 + highLimit: 1000 + out: 1 + - name: nine-hundred-window + in: + lowLimit: 990 + highLimit: 1005 + out: 1 + - name: thousand-single + in: + lowLimit: 1000 + highLimit: 1000 + out: 1 + - name: ten-thousand-boundary + in: + lowLimit: 9999 + highLimit: 10000 + out: 1 + - name: ten-thousand-window + in: + lowLimit: 9990 + highLimit: 10010 + out: 2 + - name: fixed-five-digit + in: + lowLimit: 12345 + highLimit: 12345 + out: 1 + - name: five-digit-window + in: + lowLimit: 12340 + highLimit: 12350 + out: 2 + - name: first-hundred-count + in: + lowLimit: 1 + highLimit: 100 + out: 10 + - name: first-thousand-count + in: + lowLimit: 1 + highLimit: 1000 + out: 75 + - name: maximum-domain + in: + lowLimit: 1 + highLimit: 100000 + out: 6000 + - name: top-end-window + in: + lowLimit: 99990 + highLimit: 100000 + out: 1 + - name: fixed-random-number + in: + lowLimit: 54321 + highLimit: 54321 + out: 1 + - name: fixed-random-window + in: + lowLimit: 54320 + highLimit: 54330 + out: 2 + - name: carry-window + in: + lowLimit: 999 + highLimit: 1020 + out: 3 + - name: repeated-hundred-block + in: + lowLimit: 50000 + highLimit: 50099 + out: 10 + - name: two-hundred-block + in: + lowLimit: 100 + highLimit: 199 + out: 10 + - name: nine-hundred-block + in: + lowLimit: 900 + highLimit: 999 + out: 10 + - name: ten-thousand-block + in: + lowLimit: 10000 + highLimit: 19999 + out: 670 + - name: identical-digit-window + in: + lowLimit: 22222 + highLimit: 22229 + out: 1 + - name: seven-window + in: + lowLimit: 77770 + highLimit: 77779 + out: 1 + - name: zero-heavy-window + in: + lowLimit: 80808 + highLimit: 80818 + out: 2 + - name: final-window + in: + lowLimit: 99980 + highLimit: 99999 + out: 2 + - name: generated-medium + in: + lowLimit: 1 + highLimit: + gen: "int" + min: 50000 + max: 70000 + + - name: generated-large-a + in: + lowLimit: 1 + highLimit: + gen: "int" + min: 90000 + max: 95000 + + - name: generated-large-b + in: + lowLimit: 1 + highLimit: + gen: "int" + min: 95001 + max: 99999 + + - name: generated-full + in: + lowLimit: 1 + highLimit: + gen: "int" + min: 99900 + max: 100000 + + - name: generated-lower + in: + lowLimit: 1 + highLimit: + gen: "int" + min: 25000 + max: 40000 diff --git a/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.cpp b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.cpp new file mode 100644 index 00000000..1b6f4623 --- /dev/null +++ b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int countBalls(int lowLimit, int highLimit) { + unordered_map boxCount; + int maxBalls = 0; + for (int num = lowLimit; num <= highLimit; num++) { + int box = 0; + int temp = num; + while (temp > 0) { + box += temp % 10; + temp /= 10; + } + boxCount[box]++; + maxBalls = max(maxBalls, boxCount[box]); + } + return maxBalls; + } +}; diff --git a/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.cs b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.cs new file mode 100644 index 00000000..90c3884f --- /dev/null +++ b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.cs @@ -0,0 +1,12 @@ +public class Solution { + public int CountBalls(int lowLimit, int highLimit) { + var boxCount = new Dictionary(); + int maxBalls = 0; + for (int num = lowLimit; num <= highLimit; num++) { + int box = num.ToString().Sum(c => c - '0'); + boxCount[box] = boxCount.GetValueOrDefault(box) + 1; + maxBalls = Math.Max(maxBalls, boxCount[box]); + } + return maxBalls; + } +} diff --git a/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.dart b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.dart new file mode 100644 index 00000000..08101559 --- /dev/null +++ b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.dart @@ -0,0 +1,14 @@ +class Solution { + int countBalls(int lowLimit, int highLimit) { + Map boxCount = {}; + int maxBalls = 0; + for (int num = lowLimit; num <= highLimit; num++) { + int box = num.toString().split('').map((c) => int.parse(c)).reduce((a, b) => a + b); + boxCount[box] = (boxCount[box] ?? 0) + 1; + if (boxCount[box]! > maxBalls) { + maxBalls = boxCount[box]!; + } + } + return maxBalls; + } +} diff --git a/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.go b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.go new file mode 100644 index 00000000..58a834c2 --- /dev/null +++ b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.go @@ -0,0 +1,17 @@ +func countBalls(lowLimit int, highLimit int) int { + boxCount := make(map[int]int) + maxBalls := 0 + for num := lowLimit; num <= highLimit; num++ { + box := 0 + temp := num + for temp > 0 { + box += temp % 10 + temp /= 10 + } + boxCount[box]++ + if boxCount[box] > maxBalls { + maxBalls = boxCount[box] + } + } + return maxBalls +} diff --git a/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.java b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.java new file mode 100644 index 00000000..34a03642 --- /dev/null +++ b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.java @@ -0,0 +1,17 @@ +class Solution { + public int countBalls(int lowLimit, int highLimit) { + Map boxCount = new HashMap<>(); + int maxBalls = 0; + for (int num = lowLimit; num <= highLimit; num++) { + int box = 0; + int temp = num; + while (temp > 0) { + box += temp % 10; + temp /= 10; + } + boxCount.put(box, boxCount.getOrDefault(box, 0) + 1); + maxBalls = Math.max(maxBalls, boxCount.get(box)); + } + return maxBalls; + } +} diff --git a/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.kt b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.kt new file mode 100644 index 00000000..677d7ad0 --- /dev/null +++ b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.kt @@ -0,0 +1,12 @@ +class Solution { + fun countBalls(lowLimit: Int, highLimit: Int): Int { + val boxCount = mutableMapOf() + var maxBalls = 0 + for (num in lowLimit..highLimit) { + val box = num.toString().sumOf { it - '0' } + boxCount[box] = (boxCount[box] ?: 0) + 1 + maxBalls = maxOf(maxBalls, boxCount[box]!!) + } + return maxBalls + } +} diff --git a/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.py b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.py new file mode 100644 index 00000000..1d9288eb --- /dev/null +++ b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.py @@ -0,0 +1,13 @@ +class Solution: + def countBalls(self, lowLimit: int, highLimit: int) -> int: + from collections import defaultdict + + box_count = defaultdict(int) + max_balls = 0 + + for num in range(lowLimit, highLimit + 1): + box = sum(int(digit) for digit in str(num)) + box_count[box] += 1 + max_balls = max(max_balls, box_count[box]) + + return max_balls diff --git a/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.py2 b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.py2 new file mode 100644 index 00000000..fab45049 --- /dev/null +++ b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def countBalls(self, lowLimit, highLimit): + """ + :type lowLimit: int + :type highLimit: int + :rtype: int + """ + from collections import defaultdict + box_count = defaultdict(int) + max_balls = 0 + for num in range(lowLimit, highLimit + 1): + box = sum(int(d) for d in str(num)) + box_count[box] += 1 + max_balls = max(max_balls, box_count[box]) + return max_balls diff --git a/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.rb b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.rb new file mode 100644 index 00000000..acfbb219 --- /dev/null +++ b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.rb @@ -0,0 +1,13 @@ +# @param {Integer} low_limit +# @param {Integer} high_limit +# @return {Integer} +def count_balls(low_limit, high_limit) + box_count = Hash.new(0) + max_balls = 0 + (low_limit..high_limit).each do |num| + box = num.to_s.chars.map(&:to_i).sum + box_count[box] += 1 + max_balls = [max_balls, box_count[box]].max + end + max_balls +end diff --git a/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.rs b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.rs new file mode 100644 index 00000000..3ffd670c --- /dev/null +++ b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn count_balls(low_limit: i32, high_limit: i32) -> i32 { + use std::collections::HashMap; + let mut box_count: HashMap = HashMap::new(); + let mut max_balls = 0; + for num in low_limit..=high_limit { + let box_val = num.to_string().chars().map(|c| c.to_digit(10).unwrap() as i32).sum(); + *box_count.entry(box_val).or_insert(0) += 1; + max_balls = max_balls.max(*box_count.get(&box_val).unwrap()); + } + max_balls + } +} diff --git a/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.swift b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.swift new file mode 100644 index 00000000..a1e85dd8 --- /dev/null +++ b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.swift @@ -0,0 +1,12 @@ +class Solution { + func countBalls(_ lowLimit: Int, _ highLimit: Int) -> Int { + var boxCount = [Int: Int]() + var maxBalls = 0 + for num in lowLimit...highLimit { + let box = String(num).reduce(0) { $0 + Int(String($1))! } + boxCount[box, default: 0] += 1 + maxBalls = max(maxBalls, boxCount[box]!) + } + return maxBalls + } +} diff --git a/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.ts b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.ts new file mode 100644 index 00000000..ba20d125 --- /dev/null +++ b/tests/1501-2000/1742. maximum-number-of-balls-in-a-box/sol.ts @@ -0,0 +1,12 @@ +function countBalls(lowLimit: number, highLimit: number): number { + const boxCount = new Map(); + let maxBalls = 0; + for (let num = lowLimit; num <= highLimit; num++) { + const box = String(num) + .split("") + .reduce((sum, c) => sum + Number(c), 0); + boxCount.set(box, (boxCount.get(box) ?? 0) + 1); + maxBalls = Math.max(maxBalls, boxCount.get(box)!); + } + return maxBalls; +} diff --git a/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/manifest.yaml b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/manifest.yaml new file mode 100644 index 00000000..e275dd47 --- /dev/null +++ b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/manifest.yaml @@ -0,0 +1,401 @@ +entry: + id: 1743 + title: "restore-the-array-from-adjacent-pairs" + params: + adjacentPairs: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().restoreArray({adjacentPairs})" + rust: "Solution::restore_array({adjacentPairs})" + python3: "Solution().restoreArray({adjacentPairs})" + python2: "Solution().restoreArray({adjacentPairs})" + ruby: "restore_array({adjacentPairs})" + java: "new Solution().restoreArray({adjacentPairs})" + csharp: "new Solution().RestoreArray({adjacentPairs})" + kotlin: "Solution().restoreArray({adjacentPairs})" + go: "restoreArray({adjacentPairs})" + dart: "Solution().restoreArray({adjacentPairs})" + swift: "Solution().restoreArray({adjacentPairs})" + typescript: "restoreArray({adjacentPairs})" + +judge: + type: exact + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(adjacentPairs, {result})" + checker: | + class Checker: + def check(self, adjacentPairs, result): + if not isinstance(result, list): + return False + if len(result) != len(adjacentPairs) + 1: + return False + if len(set(result)) != len(result): + return False + expected = {} + for pair in adjacentPairs: + if not isinstance(pair, list) or len(pair) != 2: + return False + a, b = pair + expected.setdefault(frozenset((a, b)), 0) + expected[frozenset((a, b))] += 1 + actual = {} + for i in range(1, len(result)): + key = frozenset((result[i - 1], result[i])) + actual[key] = actual.get(key, 0) + 1 + return actual == expected + +seed: 1743 + +tests: + - name: example-1 + in: + adjacentPairs: + - [2, 1] + - [3, 4] + - [3, 2] + - name: example-2 + in: + adjacentPairs: + - [4, -2] + - [1, 4] + - [-3, 1] + - name: example-3 + in: + adjacentPairs: + - [100000, -100000] + - name: two-negative + in: + adjacentPairs: + - [-7, -9] + - name: three-increasing + in: + adjacentPairs: + - [2, 1] + - [2, 3] + - name: three-decreasing + in: + adjacentPairs: + - [-1, -2] + - [-3, -2] + - name: shuffled-four + in: + adjacentPairs: + - [20, 30] + - [10, 20] + - [30, 40] + - name: alternating-sign + in: + adjacentPairs: + - [-2, 3] + - [5, -2] + - [3, -7] + - name: duplicate-magnitude + in: + adjacentPairs: + - [1, -1] + - [2, 1] + - [-1, -2] + - name: five-shuffled + in: + adjacentPairs: + - [8, 7] + - [5, 6] + - [9, 8] + - [6, 7] + - name: endpoint-zero + in: + adjacentPairs: + - [4, 0] + - [0, -3] + - [8, 4] + - [5, 8] + - name: six-permutation + in: + adjacentPairs: + - [3, 4] + - [1, 2] + - [5, 6] + - [2, 3] + - [4, 5] + - name: large-values + in: + adjacentPairs: + - [99999, 100000] + - [-100000, -99999] + - [0, 99999] + - [-99999, -1] + - [-1, 0] + - name: seven-shuffled + in: + adjacentPairs: + - [40, 50] + - [10, 20] + - [60, 70] + - [30, 40] + - [20, 30] + - [50, 60] + - name: powers + in: + adjacentPairs: + - [16, 8] + - [1, 2] + - [4, 8] + - [2, 4] + - name: mixed-seven + in: + adjacentPairs: + - [-10, 11] + - [7, -3] + - [11, 7] + - [-3, 0] + - [0, 4] + - [4, 9] + - name: eight-shuffled + in: + adjacentPairs: + - [6, 7] + - [2, 3] + - [0, 1] + - [4, 5] + - [1, 2] + - [3, 4] + - [5, 6] + - name: negatives-eight + in: + adjacentPairs: + - [-5, -6] + - [-1, -2] + - [-7, -8] + - [-3, -4] + - [-2, -3] + - [-6, -7] + - [-4, -5] + - name: sparse-values + in: + adjacentPairs: + - [100, 1000] + - [-500, 0] + - [1000, 5000] + - [0, 100] + - name: nine-reordered + in: + adjacentPairs: + - [4, 5] + - [7, 8] + - [1, 2] + - [0, 1] + - [6, 7] + - [3, 4] + - [2, 3] + - [5, 6] + - name: zigzag-signs + in: + adjacentPairs: + - [6, -5] + - [-3, 4] + - [2, -3] + - [-5, 2] + - [4, -1] + - name: ten-consecutive + in: + adjacentPairs: + - [8, 9] + - [1, 2] + - [6, 7] + - [3, 4] + - [0, 1] + - [9, 10] + - [2, 3] + - [5, 6] + - [4, 5] + - [7, 8] + - name: ten-negative-consecutive + in: + adjacentPairs: + - [-8, -9] + - [-1, -2] + - [-6, -7] + - [-3, -4] + - [-9, -10] + - [-2, -3] + - [-5, -6] + - [-4, -5] + - [-7, -8] + - name: repeated-zero-neighbors + in: + adjacentPairs: + - [2, 0] + - [-1, -2] + - [0, 1] + - [1, -1] + - name: eleven-reordered + in: + adjacentPairs: + - [9, 10] + - [2, 3] + - [7, 8] + - [0, 1] + - [5, 6] + - [10, 11] + - [1, 2] + - [6, 7] + - [3, 4] + - [4, 5] + - [8, 9] + - name: min-max-chain + in: + adjacentPairs: + - [-100000, -99999] + - [99998, 99999] + - [-99999, 0] + - [0, 99998] + - name: alternating-large + in: + adjacentPairs: + - [100000, -99999] + - [99997, 100000] + - [-99999, 99998] + - [99998, -100000] + - name: twelve-shuffled + in: + adjacentPairs: + - [10, 11] + - [3, 4] + - [8, 9] + - [0, 1] + - [6, 7] + - [1, 2] + - [11, 12] + - [4, 5] + - [9, 10] + - [2, 3] + - [5, 6] + - [7, 8] + - name: arithmetic-gap + in: + adjacentPairs: + - [42, 63] + - [-21, 0] + - [84, 105] + - [0, 21] + - [63, 84] + - [21, 42] + - name: alternating-endpoints + in: + adjacentPairs: + - [5, 6] + - [1, 2] + - [7, 8] + - [3, 4] + - [0, 1] + - [6, 7] + - [2, 3] + - [4, 5] + - name: thirteen-chain + in: + adjacentPairs: + - [11, 12] + - [2, 3] + - [7, 8] + - [0, 1] + - [5, 6] + - [9, 10] + - [1, 2] + - [12, 13] + - [3, 4] + - [8, 9] + - [4, 5] + - [6, 7] + - [10, 11] + - name: mixed-range-chain + in: + adjacentPairs: + - [500, 1000] + - [-2000, -1000] + - [0, 500] + - [1000, 2000] + - [-1000, 0] + - name: fourteen-shuffled + in: + adjacentPairs: + - [12, 13] + - [4, 5] + - [9, 10] + - [0, 1] + - [6, 7] + - [13, 14] + - [2, 3] + - [10, 11] + - [1, 2] + - [7, 8] + - [5, 6] + - [3, 4] + - [8, 9] + - [11, 12] + - name: fifteen-signed + in: + adjacentPairs: + - [-7, -6] + - [2, 3] + - [-1, 0] + - [6, 7] + - [-4, -3] + - [0, 1] + - [4, 5] + - [-6, -5] + - [1, 2] + - [5, 6] + - [-3, -2] + - [-5, -4] + - [-2, -1] + - [3, 4] + - name: sixteen-chain + in: + adjacentPairs: + - [14, 15] + - [2, 3] + - [8, 9] + - [0, 1] + - [6, 7] + - [12, 13] + - [4, 5] + - [10, 11] + - [1, 2] + - [7, 8] + - [3, 4] + - [9, 10] + - [5, 6] + - [11, 12] + - [13, 14] + - name: twenty-sparse + in: + adjacentPairs: + - [170, 180] + - [20, 30] + - [90, 100] + - [0, 10] + - [150, 160] + - [60, 70] + - [110, 120] + - [30, 40] + - [180, 190] + - [10, 20] + - [100, 110] + - [40, 50] + - [160, 170] + - [70, 80] + - [120, 130] + - [50, 60] + - [140, 150] + - [80, 90] + - [130, 140] diff --git a/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.cpp b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.cpp new file mode 100644 index 00000000..97d05250 --- /dev/null +++ b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + vector restoreArray(vector>& adjacentPairs) { + unordered_map xorMap; + unordered_map degree; + + for (auto& pair : adjacentPairs) { + int u = pair[0], v = pair[1]; + xorMap[u] ^= v; + xorMap[v] ^= u; + degree[u]++; + degree[v]++; + } + + int start = 0; + for (auto& [k, v] : degree) { + if (v == 1) { + start = k; + break; + } + } + + int n = adjacentPairs.size() + 1; + vector res(n); + + res[0] = start; + int prev = 0; + + for (int i = 1; i < n; i++) { + res[i] = xorMap[res[i - 1]] ^ prev; + prev = res[i - 1]; + } + + return res; + } +}; diff --git a/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.cs b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.cs new file mode 100644 index 00000000..b7c91753 --- /dev/null +++ b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.cs @@ -0,0 +1,35 @@ +public class Solution { + public int[] RestoreArray(int[][] adjacentPairs) { + var xorMap = new Dictionary(); + var degree = new Dictionary(); + + foreach (var pair in adjacentPairs) { + int u = pair[0], v = pair[1]; + xorMap[u] = xorMap.GetValueOrDefault(u) ^ v; + xorMap[v] = xorMap.GetValueOrDefault(v) ^ u; + degree[u] = degree.GetValueOrDefault(u) + 1; + degree[v] = degree.GetValueOrDefault(v) + 1; + } + + int start = 0; + foreach (var kv in degree) { + if (kv.Value == 1) { + start = kv.Key; + break; + } + } + + int n = adjacentPairs.Length + 1; + int[] res = new int[n]; + + res[0] = start; + int prev = 0; + + for (int i = 1; i < n; i++) { + res[i] = xorMap[res[i - 1]] ^ prev; + prev = res[i - 1]; + } + + return res; + } +} diff --git a/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.dart b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.dart new file mode 100644 index 00000000..149d0717 --- /dev/null +++ b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.dart @@ -0,0 +1,35 @@ +class Solution { + List restoreArray(List> adjacentPairs) { + Map xorMap = {}; + Map degree = {}; + + for (var pair in adjacentPairs) { + int u = pair[0], v = pair[1]; + xorMap[u] = (xorMap[u] ?? 0) ^ v; + xorMap[v] = (xorMap[v] ?? 0) ^ u; + degree[u] = (degree[u] ?? 0) + 1; + degree[v] = (degree[v] ?? 0) + 1; + } + + int start = 0; + degree.forEach((key, value) { + if (value == 1) { + start = key; + return; + } + }); + + int n = adjacentPairs.length + 1; + List res = List.filled(n, 0); + + res[0] = start; + int prev = 0; + + for (int i = 1; i < n; i++) { + res[i] = (xorMap[res[i - 1]] ?? 0) ^ prev; + prev = res[i - 1]; + } + + return res; + } +} diff --git a/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.go b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.go new file mode 100644 index 00000000..2b9c6b24 --- /dev/null +++ b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.go @@ -0,0 +1,33 @@ +func restoreArray(adjacentPairs [][]int) []int { + xorMap := make(map[int]int) + degree := make(map[int]int) + + for _, pair := range adjacentPairs { + u, v := pair[0], pair[1] + xorMap[u] ^= v + xorMap[v] ^= u + degree[u]++ + degree[v]++ + } + + start := 0 + for k, v := range degree { + if v == 1 { + start = k + break + } + } + + n := len(adjacentPairs) + 1 + res := make([]int, n) + + res[0] = start + prev := 0 + + for i := 1; i < n; i++ { + res[i] = xorMap[res[i-1]] ^ prev + prev = res[i-1] + } + + return res +} diff --git a/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.java b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.java new file mode 100644 index 00000000..4acac57b --- /dev/null +++ b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.java @@ -0,0 +1,35 @@ +class Solution { + public int[] restoreArray(int[][] adjacentPairs) { + Map xorMap = new HashMap<>(); + Map degree = new HashMap<>(); + + for (int[] pair : adjacentPairs) { + int u = pair[0], v = pair[1]; + xorMap.put(u, xorMap.getOrDefault(u, 0) ^ v); + xorMap.put(v, xorMap.getOrDefault(v, 0) ^ u); + degree.put(u, degree.getOrDefault(u, 0) + 1); + degree.put(v, degree.getOrDefault(v, 0) + 1); + } + + int start = 0; + for (Map.Entry entry : degree.entrySet()) { + if (entry.getValue() == 1) { + start = entry.getKey(); + break; + } + } + + int n = adjacentPairs.length + 1; + int[] res = new int[n]; + + res[0] = start; + int prev = 0; + + for (int i = 1; i < n; i++) { + res[i] = xorMap.get(res[i - 1]) ^ prev; + prev = res[i - 1]; + } + + return res; + } +} diff --git a/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.kt b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.kt new file mode 100644 index 00000000..d36932ec --- /dev/null +++ b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.kt @@ -0,0 +1,36 @@ +class Solution { + fun restoreArray(adjacentPairs: Array): IntArray { + val xorMap = mutableMapOf() + val degree = mutableMapOf() + + for (pair in adjacentPairs) { + val u = pair[0] + val v = pair[1] + xorMap[u] = xorMap.getOrDefault(u, 0) xor v + xorMap[v] = xorMap.getOrDefault(v, 0) xor u + degree[u] = degree.getOrDefault(u, 0) + 1 + degree[v] = degree.getOrDefault(v, 0) + 1 + } + + var start = 0 + for ((key, value) in degree) { + if (value == 1) { + start = key + break + } + } + + val n = adjacentPairs.size + 1 + val res = IntArray(n) + + res[0] = start + var prev = 0 + + for (i in 1 until n) { + res[i] = (xorMap[res[i - 1]] ?: 0) xor prev + prev = res[i - 1] + } + + return res + } +} diff --git a/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.py b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.py new file mode 100644 index 00000000..f69c38bf --- /dev/null +++ b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.py @@ -0,0 +1,31 @@ +class Solution: + def restoreArray(self, adjacentPairs): + from collections import defaultdict + + xorMap = defaultdict(int) + degree = defaultdict(int) + + for u, v in adjacentPairs: + xorMap[u] ^= v + xorMap[v] ^= u + degree[u] += 1 + degree[v] += 1 + + # find endpoint + start = 0 + for k in degree: + if degree[k] == 1: + start = k + break + + n = len(adjacentPairs) + 1 + res = [0] * n + + res[0] = start + prev = 0 + + for i in range(1, n): + res[i] = xorMap[res[i - 1]] ^ prev + prev = res[i - 1] + + return res diff --git a/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.py2 b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.py2 new file mode 100644 index 00000000..f4b6f0dc --- /dev/null +++ b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.py2 @@ -0,0 +1,34 @@ +class Solution(object): + def restoreArray(self, adjacentPairs): + """ + :type adjacentPairs: List[List[int]] + :rtype: List[int] + """ + from collections import defaultdict + + xor_map = defaultdict(int) + degree = defaultdict(int) + + for u, v in adjacentPairs: + xor_map[u] ^= v + xor_map[v] ^= u + degree[u] += 1 + degree[v] += 1 + + start = 0 + for k in degree: + if degree[k] == 1: + start = k + break + + n = len(adjacentPairs) + 1 + res = [0] * n + + res[0] = start + prev = 0 + + for i in range(1, n): + res[i] = xor_map[res[i - 1]] ^ prev + prev = res[i - 1] + + return res diff --git a/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.rb b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.rb new file mode 100644 index 00000000..e3cb0bc7 --- /dev/null +++ b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.rb @@ -0,0 +1,32 @@ +def restore_array(adjacent_pairs) + xor_map = Hash.new(0) + degree = Hash.new(0) + + adjacent_pairs.each do |u, v| + xor_map[u] ^= v + xor_map[v] ^= u + degree[u] += 1 + degree[v] += 1 + end + + start = 0 + degree.each do |k, v| + if v == 1 + start = k + break + end + end + + n = adjacent_pairs.length + 1 + res = Array.new(n, 0) + + res[0] = start + prev = 0 + + (1...n).each do |i| + res[i] = xor_map[res[i - 1]] ^ prev + prev = res[i - 1] + end + + res +end diff --git a/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.rs b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.rs new file mode 100644 index 00000000..eb3ff754 --- /dev/null +++ b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.rs @@ -0,0 +1,37 @@ +impl Solution { + pub fn restore_array(adjacent_pairs: Vec>) -> Vec { + use std::collections::HashMap; + let mut xor_map = HashMap::new(); + let mut degree = HashMap::new(); + + for pair in adjacent_pairs.iter() { + let u = pair[0]; + let v = pair[1]; + *xor_map.entry(u).or_insert(0) ^= v; + *xor_map.entry(v).or_insert(0) ^= u; + *degree.entry(u).or_insert(0) += 1; + *degree.entry(v).or_insert(0) += 1; + } + + let mut start = 0; + for (k, v) in degree.iter() { + if *v == 1 { + start = *k; + break; + } + } + + let n = adjacent_pairs.len() + 1; + let mut res = vec![0; n]; + + res[0] = start; + let mut prev = 0; + + for i in 1..n { + res[i] = xor_map[&res[i - 1]] ^ prev; + prev = res[i - 1]; + } + + res + } +} diff --git a/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.swift b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.swift new file mode 100644 index 00000000..954c1734 --- /dev/null +++ b/tests/1501-2000/1743. restore-the-array-from-adjacent-pairs/sol.swift @@ -0,0 +1,35 @@ +class Solution { + func restoreArray(_ adjacentPairs: [[Int]]) -> [Int] { + var xorMap: [Int: Int] = [:] + var degree: [Int: Int] = [:] + + for pair in adjacentPairs { + let u = pair[0], v = pair[1] + xorMap[u] = (xorMap[u] ?? 0) ^ v + xorMap[v] = (xorMap[v] ?? 0) ^ u + degree[u] = (degree[u] ?? 0) + 1 + degree[v] = (degree[v] ?? 0) + 1 + } + + var start = 0 + for (key, value) in degree { + if value == 1 { + start = key + break + } + } + + let n = adjacentPairs.count + 1 + var res = [Int](repeating: 0, count: n) + + res[0] = start + var prev = 0 + + for i in 1.. = new Map(); + const degree: Map = new Map(); + + for (const [u, v] of adjacentPairs) { + xorMap.set(u, (xorMap.get(u) ?? 0) ^ v); + xorMap.set(v, (xorMap.get(v) ?? 0) ^ u); + degree.set(u, (degree.get(u) ?? 0) + 1); + degree.set(v, (degree.get(v) ?? 0) + 1); + } + + let start = 0; + for (const [key, value] of degree) { + if (value === 1) { + start = key; + break; + } + } + + const n = adjacentPairs.length + 1; + const res: number[] = new Array(n).fill(0); + + res[0] = start; + let prev = 0; + + for (let i = 1; i < n; i++) { + res[i] = (xorMap.get(res[i - 1]) ?? 0) ^ prev; + prev = res[i - 1]; + } + + return res; +} diff --git a/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/manifest.yaml b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/manifest.yaml new file mode 100644 index 00000000..b3dab667 --- /dev/null +++ b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/manifest.yaml @@ -0,0 +1,487 @@ +entry: + id: 1744 + title: "can-you-eat-your-favorite-candy-on-your-favorite-day" + params: + candiesCount: + type: array + items: + type: int + queries: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().canEat({candiesCount}, {queries})" + rust: "Solution::can_eat({candiesCount}, {queries})" + python3: "Solution().canEat({candiesCount}, {queries})" + python2: "Solution().canEat({candiesCount}, {queries})" + ruby: "can_eat({candiesCount}, {queries})" + java: "new Solution().canEat({candiesCount}, {queries})" + csharp: "new Solution().CanEat({candiesCount}, {queries})" + kotlin: "Solution().canEat({candiesCount}, {queries})" + go: "canEat({candiesCount}, {queries})" + dart: "Solution().canEat({candiesCount}, {queries})" + swift: "Solution().canEat({candiesCount}, {queries})" + typescript: "canEat({candiesCount}, {queries})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().canEat(candiesCount, queries, {result})" + checker: | + class Checker: + def canEat(self, candiesCount, queries, result): + if not isinstance(result, list) or len(result) != len(queries): + return False + prefix = [0] + for x in candiesCount: + prefix.append(prefix[-1] + x) + expected = [] + for t, day, cap in queries: + d = day + 1 + expected.append((prefix[t] + cap) // cap <= d <= prefix[t + 1]) + return result == expected + +seed: 1744 + +tests: + - name: example-one + in: + candiesCount: [7, 4, 5, 3, 8] + queries: + - [0, 2, 2] + - [4, 2, 4] + - [2, 13, 1000000000] + out: [true, false, true] + - name: example-two + in: + candiesCount: [5, 2, 6, 4, 1] + queries: + - [3, 1, 2] + - [4, 10, 3] + - [3, 10, 100] + - [4, 100, 30] + - [1, 3, 1] + out: [false, true, true, false, false] + - name: first-type-day-zero + in: + candiesCount: [5] + queries: + - [0, 0, 1] + - [0, 0, 5] + out: [true, true] + - name: first-type-boundary + in: + candiesCount: [5] + queries: + - [0, 4, 1] + - [0, 5, 1] + - [0, 1, 5] + out: [true, false, true] + - name: two-types-transition + in: + candiesCount: [2, 3] + queries: + - [1, 0, 1] + - [1, 1, 1] + - [1, 2, 1] + - [1, 4, 1] + - [1, 5, 1] + out: [false, false, true, true, false] + - name: cap-one + in: + candiesCount: [1, 1, 1, 1] + queries: + - [0, 0, 1] + - [1, 1, 1] + - [2, 2, 1] + - [3, 3, 1] + - [3, 4, 1] + out: [true, true, true, true, false] + - name: cap-equals-first-type + in: + candiesCount: [4, 2, 3] + queries: + - [1, 0, 4] + - [1, 1, 4] + - [1, 3, 4] + - [2, 2, 4] + out: [false, true, true, true] + - name: large-cap + in: + candiesCount: [10, 20, 30] + queries: + - [0, 0, 1000000000] + - [1, 0, 1000000000] + - [2, 0, 1000000000] + - [2, 59, 1000000000] + - [2, 60, 1000000000] + out: [true, true, true, true, false] + - name: exact-min-day + in: + candiesCount: [3, 4, 5] + queries: + - [0, 0, 3] + - [1, 1, 3] + - [2, 2, 3] + - [2, 3, 4] + out: [true, true, true, true] + - name: exact-max-day + in: + candiesCount: [3, 4, 5] + queries: + - [0, 2, 1] + - [1, 6, 1] + - [2, 11, 1] + - [2, 12, 1] + out: [true, true, true, false] + - name: skipped-types + in: + candiesCount: [8, 1, 8, 1, 8] + queries: + - [2, 7, 2] + - [2, 8, 2] + - [3, 16, 2] + - [4, 25, 2] + out: [true, true, true, true] + - name: huge-day + in: + candiesCount: [100000, 100000, 100000] + queries: + - [0, 99999, 1] + - [1, 199999, 1] + - [2, 299999, 1] + - [2, 1000000000, 1000000000] + out: [true, true, true, false] + - name: huge-cap-one-candy + in: + candiesCount: [1, 100000, 1] + queries: + - [1, 0, 1000000000] + - [1, 1, 1000000000] + - [2, 0, 1000000000] + - [2, 100000, 1000000000] + out: [true, true, true, true] + - name: repeated-queries + in: + candiesCount: [6, 7] + queries: + - [1, 6, 2] + - [1, 6, 2] + - [1, 5, 2] + - [0, 5, 2] + out: [true, true, true, true] + - name: many-types + in: + candiesCount: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + queries: + - [0, 0, 1] + - [1, 2, 1] + - [2, 5, 2] + - [3, 9, 2] + - [4, 14, 3] + - [5, 20, 3] + - [9, 54, 5] + out: [true, true, true, true, true, true, true] + - name: alternating-caps + in: + candiesCount: [9, 9, 9, 9] + queries: + - [3, 8, 1] + - [3, 8, 2] + - [3, 8, 4] + - [3, 35, 1] + - [3, 35, 2] + - [3, 35, 4] + out: [false, false, true, true, true, true] + - name: type-zero-all-days + in: + candiesCount: [100] + queries: + - [0, 0, 100] + - [0, 1, 100] + - [0, 99, 1] + - [0, 100, 1] + out: [true, true, true, false] + - name: type-one-tight-window + in: + candiesCount: [5, 5] + queries: + - [1, 4, 1] + - [1, 5, 1] + - [1, 9, 1] + - [1, 10, 1] + - [1, 10, 2] + out: [false, true, true, false, false] + - name: mixed-boundaries + in: + candiesCount: [2, 1, 4, 2] + queries: + - [2, 2, 2] + - [2, 3, 2] + - [2, 6, 2] + - [3, 7, 2] + - [3, 8, 2] + out: [true, true, true, true, true] + - name: one-each-large-type + in: + candiesCount: [1, 1, 1, 1, 1, 1, 1, 1] + queries: + - [7, 7, 1] + - [7, 6, 1] + - [4, 4, 2] + - [6, 6, 100] + out: [true, false, true, true] + - name: all-cap-two + in: + candiesCount: [4, 4, 4, 4, 4] + queries: + - [0, 0, 2] + - [1, 2, 2] + - [2, 4, 2] + - [3, 6, 2] + - [4, 8, 2] + - [4, 9, 2] + out: [true, true, true, true, true, true] + - name: uneven-prefixes + in: + candiesCount: [10, 1, 10, 1, 10] + queries: + - [1, 9, 1] + - [1, 10, 1] + - [2, 10, 2] + - [2, 15, 2] + - [4, 31, 3] + out: [false, true, true, true, true] + - name: days-at-billion + in: + candiesCount: [100000, 100000] + queries: + - [0, 999999999, 1] + - [1, 999999999, 1] + - [1, 199999, 100000] + - [1, 1000000000, 1000000000] + out: [false, false, true, false] + - name: cap-one-billion-prefix + in: + candiesCount: [100000, 100000, 100000, 100000] + queries: + - [0, 0, 1000000000] + - [1, 0, 1000000000] + - [2, 0, 1000000000] + - [3, 0, 1000000000] + - [3, 1, 1000000000] + out: [true, true, true, true, true] + - name: long-prefix-cap-three + in: + candiesCount: [5, 5, 5, 5, 5, 5, 5, 5, 5, 5] + queries: + - [9, 14, 3] + - [9, 15, 3] + - [9, 33, 3] + - [9, 34, 3] + - [5, 18, 3] + out: [false, true, true, true, true] + - name: late-type-low-cap + in: + candiesCount: [20, 20, 20, 20] + queries: + - [3, 59, 1] + - [3, 60, 1] + - [3, 79, 1] + - [3, 80, 1] + - [2, 60, 2] + out: [false, true, true, false, false] + - name: alternating-query-types + in: + candiesCount: [3, 8, 2, 9] + queries: + - [0, 2, 1] + - [3, 10, 2] + - [1, 5, 2] + - [2, 9, 3] + - [3, 20, 1] + out: [true, true, true, true, true] + - name: maximum-values + in: + candiesCount: [100000, 100000, 100000, 100000, 100000] + queries: + - [4, 499999, 1] + - [4, 500000, 1] + - [4, 499999, 100000] + - [2, 299999, 100000] + out: [true, false, true, true] + - name: narrow-window-cap-seven + in: + candiesCount: [13, 17, 19] + queries: + - [2, 4, 7] + - [2, 6, 7] + - [2, 7, 7] + - [2, 10, 7] + - [2, 48, 7] + out: [true, true, true, true, true] + - name: several-singletons + in: + candiesCount: [1, 1, 1, 1, 1] + queries: + - [0, 0, 1] + - [2, 2, 1] + - [4, 4, 1] + - [4, 3, 2] + - [3, 4, 100] + out: [true, true, true, true, false] + - name: high-cap-late-query + in: + candiesCount: [6, 7, 8, 9] + queries: + - [3, 20, 100] + - [3, 29, 100] + - [3, 30, 1] + - [2, 19, 2] + out: [true, true, false, true] + - name: prefix-heavy + in: + candiesCount: [50, 1, 1, 1, 1, 50] + queries: + - [5, 50, 1] + - [5, 54, 1] + - [5, 103, 1] + - [5, 104, 1] + - [1, 49, 1] + out: [false, true, true, false, false] + - name: final-mixed + in: + candiesCount: [11, 2, 17, 3, 19] + queries: + - [0, 10, 1] + - [1, 11, 2] + - [2, 14, 2] + - [3, 20, 3] + - [4, 40, 2] + - [4, 51, 2] + out: [true, true, true, true, true, true] + - name: type-index-boundary + in: + candiesCount: [2, 2, 2, 2, 2, 2] + queries: + - [0, 1, 1] + - [1, 3, 1] + - [2, 5, 1] + - [5, 11, 1] + - [5, 10, 2] + out: [true, true, true, true, true] + - name: large-cap-window + in: + candiesCount: [12, 13, 14, 15] + queries: + - [1, 0, 12] + - [1, 1, 12] + - [2, 2, 13] + - [3, 4, 14] + - [3, 53, 1] + out: [false, true, true, true, true] + - name: generated-query-boundary + in: + candiesCount: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + queries: + gen: "array" + len: 100 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 1 + max: 9 + elemType: "int" + elemType: "int" + seed: 174401 + - name: generated-query-medium + in: + candiesCount: + [100000, 99999, 99998, 99997, 99996, 99995, 99994, 99993, 99992, 99991] + queries: + gen: "array" + len: 10000 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 1 + max: 9 + elemType: "int" + elemType: "int" + seed: 174402 + - name: generated-query-large + in: + candiesCount: + [100000, 99999, 99998, 99997, 99996, 99995, 99994, 99993, 99992, 99991] + queries: + gen: "array" + len: 100000 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 1 + max: 9 + elemType: "int" + elemType: "int" + seed: 174403 + - name: generated-large-prefix + in: + candiesCount: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + queries: + gen: "array" + len: 1000 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 1 + max: 99999 + elemType: "int" + elemType: "int" + seed: 174404 + - name: generated-maximum-input + in: + candiesCount: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + queries: + gen: "array" + len: 100000 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 1 + max: 99999 + elemType: "int" + elemType: "int" + seed: 174405 diff --git a/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.cpp b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.cpp new file mode 100644 index 00000000..9bd36402 --- /dev/null +++ b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + vector canEat(vector& candiesCount, vector>& queries) { + int n = candiesCount.size(); + int m = queries.size(); + vector ans(m, false); + vector psum(n + 1, 0); + for (int i = 1; i <= n; i++) { + psum[i] = psum[i - 1] + candiesCount[i - 1]; + } + for (int i = 0; i < m; i++) { + int t = queries[i][0]; + long long day = queries[i][1]; + long long cap = queries[i][2]; + long long minDays = psum[t] / cap; + long long maxDays = psum[t + 1] - 1; + ans[i] = (minDays <= day && day <= maxDays); + } + return ans; + } +}; diff --git a/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.cs b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.cs new file mode 100644 index 00000000..222b5b68 --- /dev/null +++ b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public bool[] CanEat(int[] candiesCount, int[][] queries) { + int n = candiesCount.Length; + int m = queries.Length; + bool[] ans = new bool[m]; + long[] psum = new long[n + 1]; + for (int i = 1; i <= n; i++) { + psum[i] = psum[i - 1] + candiesCount[i - 1]; + } + for (int i = 0; i < m; i++) { + int t = queries[i][0]; + long day = queries[i][1]; + long cap = queries[i][2]; + long minDays = psum[t] / cap; + long maxDays = psum[t + 1] - 1; + ans[i] = minDays <= day && day <= maxDays; + } + return ans; + } +} diff --git a/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.dart b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.dart new file mode 100644 index 00000000..d13f9c92 --- /dev/null +++ b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.dart @@ -0,0 +1,20 @@ +class Solution { + List canEat(List candiesCount, List> queries) { + int n = candiesCount.length; + int m = queries.length; + List ans = List.filled(m, false); + List psum = List.filled(n + 1, 0); + for (int i = 1; i <= n; i++) { + psum[i] = psum[i - 1] + candiesCount[i - 1]; + } + for (int i = 0; i < m; i++) { + int t = queries[i][0]; + int day = queries[i][1]; + int cap = queries[i][2]; + int minDays = psum[t] ~/ cap; + int maxDays = psum[t + 1] - 1; + ans[i] = minDays <= day && day <= maxDays; + } + return ans; + } +} diff --git a/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.go b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.go new file mode 100644 index 00000000..e33091ef --- /dev/null +++ b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.go @@ -0,0 +1,16 @@ +func canEat(candiesCount []int, queries [][]int) []bool { + n := len(candiesCount) + m := len(queries) + ans := make([]bool, m) + psum := make([]int64, n+1) + for i := 1; i <= n; i++ { + psum[i] = psum[i-1] + int64(candiesCount[i-1]) + } + for i := 0; i < m; i++ { + t, day, cap := queries[i][0], int64(queries[i][1]), int64(queries[i][2]) + minDays := psum[t] / cap + maxDays := psum[t+1] - 1 + ans[i] = minDays <= day && day <= maxDays + } + return ans +} diff --git a/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.java b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.java new file mode 100644 index 00000000..fd6248e9 --- /dev/null +++ b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.java @@ -0,0 +1,20 @@ +class Solution { + public boolean[] canEat(int[] candiesCount, int[][] queries) { + int n = candiesCount.length; + int m = queries.length; + boolean[] ans = new boolean[m]; + long[] psum = new long[n + 1]; + for (int i = 1; i <= n; i++) { + psum[i] = psum[i - 1] + candiesCount[i - 1]; + } + for (int i = 0; i < m; i++) { + int t = queries[i][0]; + long day = queries[i][1]; + long cap = queries[i][2]; + long minDays = psum[t] / cap; + long maxDays = psum[t + 1] - 1; + ans[i] = (minDays <= day && day <= maxDays); + } + return ans; + } +} diff --git a/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.kt b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.kt new file mode 100644 index 00000000..ba7605a0 --- /dev/null +++ b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun canEat(candiesCount: IntArray, queries: Array): BooleanArray { + val n = candiesCount.size + val m = queries.size + val ans = BooleanArray(m) + val psum = LongArray(n + 1) + for (i in 1..n) { + psum[i] = psum[i - 1] + candiesCount[i - 1] + } + for (i in 0 until m) { + val t = queries[i][0] + val day = queries[i][1].toLong() + val cap = queries[i][2].toLong() + val minDays = psum[t] / cap + val maxDays = psum[t + 1] - 1 + ans[i] = (minDays <= day && day <= maxDays) + } + return ans + } +} diff --git a/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.py b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.py new file mode 100644 index 00000000..d23a1477 --- /dev/null +++ b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.py @@ -0,0 +1,21 @@ +class Solution(object): + def canEat(self, candiesCount, queries): + """ + :type candiesCount: List[int] + :type queries: List[List[int]] + :rtype: List[bool] + """ + n = len(candiesCount) + m = len(queries) + ans = [False] * m + psum = [0] * (n + 1) + for i in range(1, n + 1): + psum[i] = psum[i - 1] + candiesCount[i - 1] + for i in range(m): + t, day, cap = queries[i] + day += 1 + minDays = (psum[t] + cap) // cap + maxDays = psum[t + 1] + ans[i] = minDays <= day and day <= maxDays + + return ans diff --git a/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.py2 b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.py2 new file mode 100644 index 00000000..117b73ba --- /dev/null +++ b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.py2 @@ -0,0 +1,19 @@ +class Solution(object): + def canEat(self, candiesCount, queries): + """ + :type candiesCount: List[int] + :type queries: List[List[int]] + :rtype: List[bool] + """ + n = len(candiesCount) + m = len(queries) + ans = [False] * m + psum = [0] * (n + 1) + for i in range(1, n + 1): + psum[i] = psum[i - 1] + candiesCount[i - 1] + for i in range(m): + t, day, cap = queries[i] + minDays = psum[t] // cap + maxDays = psum[t + 1] - 1 + ans[i] = (minDays <= day and day <= maxDays) + return ans diff --git a/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.rb b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.rb new file mode 100644 index 00000000..0115b570 --- /dev/null +++ b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.rb @@ -0,0 +1,20 @@ +# @param {Integer[]} candies_count +# @param {Integer[][]} queries +# @return {Boolean[]} +def can_eat(candies_count, queries) + n = candies_count.length + m = queries.length + ans = Array.new(m, false) + psum = Array.new(n + 1, 0) + for i in 1..n + psum[i] = psum[i - 1] + candies_count[i - 1] + end + for i in 0...m + t, day, cap = queries[i] + day += 1 + min_days = psum[t] / cap + 1 + max_days = psum[t + 1] + ans[i] = (min_days <= day && day <= max_days) + end + ans +end diff --git a/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.rs b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.rs new file mode 100644 index 00000000..127e3b96 --- /dev/null +++ b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn can_eat(candies_count: Vec, queries: Vec>) -> Vec { + let n = candies_count.len(); + let m = queries.len(); + let mut ans = vec![false; m]; + let mut psum = vec![0i64; n + 1]; + for i in 1..=n { + psum[i] = psum[i - 1] + candies_count[i - 1] as i64; + } + for i in 0..m { + let t = queries[i][0] as usize; + let day = queries[i][1] as i64; + let cap = queries[i][2] as i64; + let min_days = psum[t] / cap; + let max_days = psum[t + 1] - 1; + ans[i] = min_days <= day && day <= max_days; + } + ans + } +} diff --git a/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.swift b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.swift new file mode 100644 index 00000000..e2a45cab --- /dev/null +++ b/tests/1501-2000/1744. can-you-eat-your-favorite-candy-on-your-favorite-day/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func canEat(_ candiesCount: [Int], _ queries: [[Int]]) -> [Bool] { + let n = candiesCount.count + let m = queries.count + var ans = [Bool](repeating: false, count: m) + var psum = [Int](repeating: 0, count: n + 1) + for i in 1...n { + psum[i] = psum[i - 1] + candiesCount[i - 1] + } + for i in 0..> pal(n, vector(n, false)); + for (int i = 0; i < n; i++) pal[i][i] = true; + for (int length = 2; length <= n; length++) { + for (int i = 0; i <= n-length; i++) { + int j = i+length-1; + if (s[i]==s[j] && (length==2 || pal[i+1][j-1])) { + pal[i][j] = true; + } + } + } + for (int i = 0; i < n-2; i++) { + if (pal[0][i]) { + for (int j = i+1; j < n-1; j++) { + if (pal[i+1][j] && pal[j+1][n-1]) return true; + } + } + } + return false; + } +}; diff --git a/tests/1501-2000/1745. palindrome-partitioning-iv/sol.cs b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.cs new file mode 100644 index 00000000..ed503b14 --- /dev/null +++ b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.cs @@ -0,0 +1,26 @@ +public class Solution { + public bool CheckPartitioning(string s) { + int n = s.Length; + bool[][] pal = new bool[n][]; + for (int i = 0; i < n; i++) { + pal[i] = new bool[n]; + pal[i][i] = true; + } + for (int length = 2; length <= n; length++) { + for (int i = 0; i <= n - length; i++) { + int j = i + length - 1; + if (s[i] == s[j] && (length == 2 || pal[i+1][j-1])) { + pal[i][j] = true; + } + } + } + for (int i = 0; i < n - 2; i++) { + if (pal[0][i]) { + for (int j = i + 1; j < n - 1; j++) { + if (pal[i+1][j] && pal[j+1][n-1]) return true; + } + } + } + return false; + } +} diff --git a/tests/1501-2000/1745. palindrome-partitioning-iv/sol.dart b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.dart new file mode 100644 index 00000000..39bc6257 --- /dev/null +++ b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.dart @@ -0,0 +1,23 @@ +class Solution { + bool checkPartitioning(String s) { + int n = s.length; + List> pal = List.generate(n, (_) => List.filled(n, false)); + for (int i = 0; i < n; i++) pal[i][i] = true; + for (int length = 2; length <= n; length++) { + for (int i = 0; i <= n - length; i++) { + int j = i + length - 1; + if (s[i] == s[j] && (length == 2 || pal[i+1][j-1])) { + pal[i][j] = true; + } + } + } + for (int i = 0; i < n - 2; i++) { + if (pal[0][i]) { + for (int j = i + 1; j < n - 1; j++) { + if (pal[i+1][j] && pal[j+1][n-1]) return true; + } + } + } + return false; + } +} diff --git a/tests/1501-2000/1745. palindrome-partitioning-iv/sol.go b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.go new file mode 100644 index 00000000..b85d6fac --- /dev/null +++ b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.go @@ -0,0 +1,26 @@ +func checkPartitioning(s string) bool { + n := len(s) + pal := make([][]bool, n) + for i := range pal { + pal[i] = make([]bool, n) + pal[i][i] = true + } + for length := 2; length <= n; length++ { + for i := 0; i <= n-length; i++ { + j := i+length-1 + if s[i]==s[j] && (length==2 || pal[i+1][j-1]) { + pal[i][j] = true + } + } + } + for i := 0; i < n-2; i++ { + if pal[0][i] { + for j := i+1; j < n-1; j++ { + if pal[i+1][j] && pal[j+1][n-1] { + return true + } + } + } + } + return false +} diff --git a/tests/1501-2000/1745. palindrome-partitioning-iv/sol.java b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.java new file mode 100644 index 00000000..60d122c8 --- /dev/null +++ b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.java @@ -0,0 +1,23 @@ +class Solution { + public boolean checkPartitioning(String s) { + int n = s.length(); + boolean[][] pal = new boolean[n][n]; + for (int i = 0; i < n; i++) pal[i][i] = true; + for (int length = 2; length <= n; length++) { + for (int i = 0; i <= n-length; i++) { + int j = i+length-1; + if (s.charAt(i)==s.charAt(j) && (length==2 || pal[i+1][j-1])) { + pal[i][j] = true; + } + } + } + for (int i = 0; i < n-2; i++) { + if (pal[0][i]) { + for (int j = i+1; j < n-1; j++) { + if (pal[i+1][j] && pal[j+1][n-1]) return true; + } + } + } + return false; + } +} diff --git a/tests/1501-2000/1745. palindrome-partitioning-iv/sol.kt b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.kt new file mode 100644 index 00000000..fe50128f --- /dev/null +++ b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.kt @@ -0,0 +1,23 @@ +class Solution { + fun checkPartitioning(s: String): Boolean { + val n = s.length + val pal = Array(n) { BooleanArray(n) } + for (i in 0 until n) pal[i][i] = true + for (length in 2..n) { + for (i in 0..n-length) { + val j = i+length-1 + if (s[i]==s[j] && (length==2 || pal[i+1][j-1])) { + pal[i][j] = true + } + } + } + for (i in 0 until n-2) { + if (pal[0][i]) { + for (j in i+1 until n-1) { + if (pal[i+1][j] && pal[j+1][n-1]) return true + } + } + } + return false + } +} diff --git a/tests/1501-2000/1745. palindrome-partitioning-iv/sol.py b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.py new file mode 100644 index 00000000..9cb1e496 --- /dev/null +++ b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.py @@ -0,0 +1,17 @@ +class Solution: + def checkPartitioning(self, s: str) -> bool: + n = len(s) + pal = [[False] * n for _ in range(n)] + for i in range(n): + pal[i][i] = True + for length in range(2, n + 1): + for i in range(n - length + 1): + j = i + length - 1 + if s[i] == s[j] and (length == 2 or pal[i + 1][j - 1]): + pal[i][j] = True + for i in range(n - 2): + if pal[0][i]: + for j in range(i + 1, n - 1): + if pal[i + 1][j] and pal[j + 1][n - 1]: + return True + return False diff --git a/tests/1501-2000/1745. palindrome-partitioning-iv/sol.py2 b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.py2 new file mode 100644 index 00000000..7c44c078 --- /dev/null +++ b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def checkPartitioning(self, s): + """ + :type s: str + :rtype: bool + """ + n = len(s) + pal = [[False]*n for _ in range(n)] + for i in range(n): + pal[i][i] = True + for length in range(2, n+1): + for i in range(n-length+1): + j = i+length-1 + if s[i]==s[j] and (length==2 or pal[i+1][j-1]): + pal[i][j] = True + for i in range(n-2): + if pal[0][i]: + for j in range(i+1, n-1): + if pal[i+1][j] and pal[j+1][n-1]: + return True + return False diff --git a/tests/1501-2000/1745. palindrome-partitioning-iv/sol.rb b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.rb new file mode 100644 index 00000000..eac00dde --- /dev/null +++ b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.rb @@ -0,0 +1,23 @@ +# @param {String} s +# @return {Boolean} +def check_partitioning(s) + n = s.length + pal = Array.new(n) { Array.new(n, false) } + (0...n).each { |i| pal[i][i] = true } + (2..n).each do |length| + (0..n-length).each do |i| + j = i+length-1 + if s[i] == s[j] && (length == 2 || pal[i+1][j-1]) + pal[i][j] = true + end + end + end + (0...n-2).each do |i| + if pal[0][i] + (i+1...n-1).each do |j| + return true if pal[i+1][j] && pal[j+1][n-1] + end + end + end + false +end diff --git a/tests/1501-2000/1745. palindrome-partitioning-iv/sol.rs b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.rs new file mode 100644 index 00000000..f7fc0926 --- /dev/null +++ b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.rs @@ -0,0 +1,28 @@ +impl Solution { + pub fn check_partitioning(s: String) -> bool { + let s: Vec = s.chars().collect(); + let n = s.len(); + let mut pal = vec![vec![false; n]; n]; + for i in 0..n { + pal[i][i] = true; + } + for length in 2..=n { + for i in 0..=n-length { + let j = i + length - 1; + if s[i] == s[j] && (length == 2 || pal[i+1][j-1]) { + pal[i][j] = true; + } + } + } + for i in 0..n-2 { + if pal[0][i] { + for j in i+1..n-1 { + if pal[i+1][j] && pal[j+1][n-1] { + return true; + } + } + } + } + false + } +} diff --git a/tests/1501-2000/1745. palindrome-partitioning-iv/sol.swift b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.swift new file mode 100644 index 00000000..ceb64312 --- /dev/null +++ b/tests/1501-2000/1745. palindrome-partitioning-iv/sol.swift @@ -0,0 +1,28 @@ +class Solution { + func checkPartitioning(_ s: String) -> Bool { + let n = s.count + var pal = [[Bool]](repeating: [Bool](repeating: false, count: n), count: n) + let chars = Array(s) + for i in 0.. + new Array(n).fill(false), + ); + for (let i = 0; i < n; i++) pal[i][i] = true; + for (let length = 2; length <= n; length++) { + for (let i = 0; i <= n - length; i++) { + const j = i + length - 1; + if (s[i] === s[j] && (length === 2 || pal[i + 1][j - 1])) { + pal[i][j] = true; + } + } + } + for (let i = 0; i < n - 2; i++) { + if (pal[0][i]) { + for (let j = i + 1; j < n - 1; j++) { + if (pal[i + 1][j] && pal[j + 1][n - 1]) return true; + } + } + } + return false; +} diff --git a/tests/1501-2000/1748. sum-of-unique-elements/manifest.yaml b/tests/1501-2000/1748. sum-of-unique-elements/manifest.yaml new file mode 100644 index 00000000..037bc260 --- /dev/null +++ b/tests/1501-2000/1748. sum-of-unique-elements/manifest.yaml @@ -0,0 +1,231 @@ +entry: + id: 1748 + title: "sum-of-unique-elements" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().sumOfUnique({nums})" + rust: "Solution::sum_of_unique({nums})" + python3: "Solution().sumOfUnique({nums})" + python2: "Solution().sumOfUnique({nums})" + ruby: "sum_of_unique({nums})" + java: "new Solution().sumOfUnique({nums})" + csharp: "new Solution().SumOfUnique({nums})" + kotlin: "Solution().sumOfUnique({nums})" + go: "sumOfUnique({nums})" + dart: "Solution().sumOfUnique({nums})" + swift: "Solution().sumOfUnique({nums})" + typescript: "sumOfUnique({nums})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().sumOfUnique(nums, {result})" + checker: | + from collections import Counter + + class Checker: + def sumOfUnique(self, nums, result): + counts = Counter(nums) + expected = sum(value for value in nums if counts[value] == 1) + return result == expected +seed: 1748 +tests: + - name: example-one + in: + nums: [1, 2, 3, 2] + out: 4 + - name: example-two-all-same + in: + nums: [1, 1, 1, 1, 1] + out: 0 + - name: example-three-all-unique + in: + nums: [1, 2, 3, 4, 5] + out: 15 + - name: single-minimum + in: + nums: [1] + out: 1 + - name: single-maximum + in: + nums: [100] + out: 100 + - name: pair-equal + in: + nums: [7, 7] + out: 0 + - name: pair-distinct + in: + nums: [1, 100] + out: 101 + - name: two-pairs + in: + nums: [1, 1, 100, 100] + out: 0 + - name: one-unique-among-pairs + in: + nums: [4, 4, 8, 8, 99] + out: 99 + - name: repeated-middle + in: + nums: [1, 2, 2, 3, 4, 4, 5] + out: 9 + - name: repeated-extremes + in: + nums: [1, 1, 2, 3, 4, 100, 100] + out: 9 + - name: all-values-same-frequency-two + in: + nums: [1, 2, 3, 1, 2, 3] + out: 0 + - name: one-value-three-times + in: + nums: [42, 42, 42, 1, 100] + out: 101 + - name: alternating-duplicates + in: + nums: [1, 2, 1, 3, 2, 4] + out: 7 + - name: descending-unique + in: + nums: [10, 9, 8, 7, 6, 5] + out: 45 + - name: boundary-values + in: + nums: [1, 100, 1, 50] + out: 150 + - name: four-unique-one-pair + in: + nums: [2, 4, 6, 8, 10, 10] + out: 20 + - name: nested-frequency-pattern + in: + nums: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5] + out: 6 + - name: all-one + in: + nums: [1, 1, 1, 1, 1, 1, 1] + out: 0 + - name: all-hundred + in: + nums: [100, 100, 100, 100] + out: 0 + - name: max-length-unique + in: + nums: + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] + out: 210 + - name: max-length-pairs + in: + nums: [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10] + out: 0 + - name: max-length-one-unique + in: + nums: [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 100] + out: 100 + - name: max-length-three-groups + in: + nums: [1, 2, 3, 1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9, 7, 8, 9, 10, 100] + out: 110 + - name: mixed-low-values + in: + nums: [1, 3, 1, 5, 7, 3, 9, 11, 5, 13] + out: 40 + - name: mixed-high-values + in: + nums: [91, 92, 91, 93, 94, 95, 94, 96, 97, 98] + out: 571 + - name: duplicate-value-at-every-other-position + in: + nums: [50, 1, 50, 2, 50, 3, 50, 4, 5] + out: 15 + - name: several-frequency-two + in: + nums: [1, 1, 2, 2, 3, 3, 4, 5, 6, 7] + out: 22 + - name: long-run-with-tail + in: + nums: [8, 8, 8, 8, 8, 9, 9, 9, 10, 11, 12, 13] + out: 46 + - name: repeated-one-and-unique-boundaries + in: + nums: [1, 100, 100, 100, 2, 3, 4, 5, 6] + out: 21 + - name: many-unique-with-one-triple + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10] + out: 45 + - name: values-cover-range + in: + nums: [1, 25, 50, 75, 100, 25, 75] + out: 151 + - name: duplicate-singleton-cancelled + in: + nums: [12, 12, 13, 14, 15, 15, 16, 17] + out: 60 + - name: four-occurrence-noise + in: + nums: [20, 20, 20, 20, 1, 2, 3, 4, 5, 6] + out: 21 + - name: generated-small + in: + nums: + gen: "array" + len: 1 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + elemType: "int" + - name: generated-medium + in: + nums: + gen: "array" + len: 25 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + elemType: "int" + - name: generated-dense + in: + nums: + gen: "array" + len: 60 + of: + gen: "int" + min: 1 + max: 10 + distinct: false + elemType: "int" + - name: generated-full-range + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + elemType: "int" + - name: generated-heavy-duplicates + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 3 + distinct: false + elemType: "int" diff --git a/tests/1501-2000/1748. sum-of-unique-elements/sol.cpp b/tests/1501-2000/1748. sum-of-unique-elements/sol.cpp new file mode 100644 index 00000000..ac854c9b --- /dev/null +++ b/tests/1501-2000/1748. sum-of-unique-elements/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int sumOfUnique(vector& nums) { + int s=0; + for(int i:nums){ + int count=0; + for(int j:nums){ + if(j==i) count++; + } + if(count==1) s+=i; + } + return s; + } +}; diff --git a/tests/1501-2000/1748. sum-of-unique-elements/sol.cs b/tests/1501-2000/1748. sum-of-unique-elements/sol.cs new file mode 100644 index 00000000..0db83777 --- /dev/null +++ b/tests/1501-2000/1748. sum-of-unique-elements/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public int SumOfUnique(int[] nums) { + int s=0; + foreach(int i in nums){ + int count=0; + foreach(int j in nums){ + if(j==i) count++; + } + if(count==1) s+=i; + } + return s; + } +} diff --git a/tests/1501-2000/1748. sum-of-unique-elements/sol.dart b/tests/1501-2000/1748. sum-of-unique-elements/sol.dart new file mode 100644 index 00000000..2a61ddec --- /dev/null +++ b/tests/1501-2000/1748. sum-of-unique-elements/sol.dart @@ -0,0 +1,9 @@ +class Solution { + int sumOfUnique(List nums) { + int s=0; + for(int i in nums){ + if(nums.where((x)=>x==i).length==1) s+=i; + } + return s; + } +} diff --git a/tests/1501-2000/1748. sum-of-unique-elements/sol.go b/tests/1501-2000/1748. sum-of-unique-elements/sol.go new file mode 100644 index 00000000..a0aeb82b --- /dev/null +++ b/tests/1501-2000/1748. sum-of-unique-elements/sol.go @@ -0,0 +1,11 @@ +func sumOfUnique(nums []int) int { + s:=0 + for _,i:=range nums{ + count:=0 + for _,j:=range nums{ + if j==i{count++} + } + if count==1{s+=i} + } + return s +} diff --git a/tests/1501-2000/1748. sum-of-unique-elements/sol.java b/tests/1501-2000/1748. sum-of-unique-elements/sol.java new file mode 100644 index 00000000..f861b670 --- /dev/null +++ b/tests/1501-2000/1748. sum-of-unique-elements/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int sumOfUnique(int[] nums) { + int s=0; + for(int i=0;i) -> i32 { + let mut s=0; + for &i in &nums{ + if nums.iter().filter(|&&x| x==i).count()==1{ + s+=i; + } + } + s + } +} diff --git a/tests/1501-2000/1748. sum-of-unique-elements/sol.swift b/tests/1501-2000/1748. sum-of-unique-elements/sol.swift new file mode 100644 index 00000000..97355dc6 --- /dev/null +++ b/tests/1501-2000/1748. sum-of-unique-elements/sol.swift @@ -0,0 +1,9 @@ +class Solution { + func sumOfUnique(_ nums: [Int]) -> Int { + var s=0 + for i in nums{ + if nums.filter{$0==i}.count==1{s+=i} + } + return s + } +} diff --git a/tests/1501-2000/1748. sum-of-unique-elements/sol.ts b/tests/1501-2000/1748. sum-of-unique-elements/sol.ts new file mode 100644 index 00000000..e73171fd --- /dev/null +++ b/tests/1501-2000/1748. sum-of-unique-elements/sol.ts @@ -0,0 +1,7 @@ +function sumOfUnique(nums: number[]): number { + let s = 0; + for (let i of nums) { + if (nums.filter((x) => x === i).length === 1) s += i; + } + return s; +} diff --git a/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/manifest.yaml b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/manifest.yaml new file mode 100644 index 00000000..b357f759 --- /dev/null +++ b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/manifest.yaml @@ -0,0 +1,231 @@ +entry: + id: 1749 + title: "maximum-absolute-sum-of-any-subarray" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().maxAbsoluteSum({nums})" + rust: "Solution::max_absolute_sum({nums})" + python3: "Solution().maxAbsoluteSum({nums})" + python2: "Solution().maxAbsoluteSum({nums})" + ruby: "max_absolute_sum({nums})" + java: "new Solution().maxAbsoluteSum({nums})" + csharp: "new Solution().MaxAbsoluteSum({nums})" + kotlin: "Solution().maxAbsoluteSum({nums})" + go: "maxAbsoluteSum({nums})" + dart: "Solution().maxAbsoluteSum({nums})" + swift: "Solution().maxAbsoluteSum({nums})" + typescript: "maxAbsoluteSum({nums})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(nums, {result})" + checker: | + class Checker: + def check(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + prefix = 0 + low = 0 + high = 0 + expected = 0 + for value in nums: + prefix += value + expected = max(expected, prefix - low, high - prefix) + low = min(low, prefix) + high = max(high, prefix) + return result == expected + +seed: 1749 + +tests: + - name: example-one + in: + nums: [1, -3, 2, 3, -4] + out: 5 + - name: example-two + in: + nums: [2, -5, 1, -4, 3, -2] + out: 8 + - name: single-positive + in: + nums: [7] + out: 7 + - name: single-negative + in: + nums: [-7] + out: 7 + - name: single-zero + in: + nums: [0] + out: 0 + - name: all-zero + in: + nums: [0, 0, 0, 0, 0] + out: 0 + - name: all-positive + in: + nums: [1, 2, 3, 4, 5] + out: 15 + - name: all-negative + in: + nums: [-1, -2, -3, -4, -5] + out: 15 + - name: alternating-balanced + in: + nums: [5, -5, 5, -5] + out: 5 + - name: positive-run-with-noise + in: + nums: [-2, 4, 6, -1, 3, -20, 2] + out: 20 + - name: negative-run-with-noise + in: + nums: [2, -4, -6, 1, -3, 20, -2] + out: 20 + - name: cancellation + in: + nums: [10, -10, 10, -10, 10] + out: 10 + - name: large-positive-bound + in: + nums: [10000, 10000, 10000] + out: 30000 + - name: large-negative-bound + in: + nums: [-10000, -10000, -10000] + out: 30000 + - name: opposite-extremes + in: + nums: [10000, -10000, -10000, 10000] + out: 20000 + - name: best-middle-positive + in: + nums: [-8, 3, 4, 5, -9] + out: 12 + - name: best-middle-negative + in: + nums: [8, -3, -4, -5, 9] + out: 12 + - name: separated-peaks + in: + nums: [6, 6, -20, 7, 7] + out: 20 + - name: one-element-best + in: + nums: [-1, 2, -3, 1] + out: 3 + - name: prefix-positive + in: + nums: [4, -1, -1, -1] + out: 4 + - name: suffix-negative + in: + nums: [1, 1, 1, -5] + out: 5 + - name: mixed-small + in: + nums: [-2, 1, -2, 1, -2] + out: 4 + - name: repeated-blocks + in: + nums: [3, 3, -6, -3, -3, 6] + out: 12 + - name: near-intuition-trap + in: + nums: [4, -10, 4, 4, -10, 4] + out: 12 + - name: maximal-length-small-pattern + in: + nums: [1, -1, 1, -1, 1, -1, 1, -1, 1, -1] + out: 1 + - name: uneven-alternation + in: + nums: [-4, 1, 1, 1, 1, -4] + out: 4 + - name: two-element-positive + in: + nums: [9999, 1] + out: 10000 + - name: two-element-negative + in: + nums: [-9999, -1] + out: 10000 + - name: bounds-with-zero + in: + nums: [10000, 0, -10000, -10000] + out: 20000 + - name: long-static + in: + nums: [2, 2, 2, 2, -3, -3, -3, 1, 1, 1, 1, -2, -2, -2, -2] + out: 13 + - name: generated-positive + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 0 + max: 10000 + distinct: false + sorted: false + elemType: "int" + - name: generated-negative + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: -10000 + max: 0 + distinct: false + sorted: false + elemType: "int" + - name: generated-balanced + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: -10000 + max: 10000 + distinct: false + sorted: false + elemType: "int" + - name: generated-small-range + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: -2 + max: 2 + distinct: false + sorted: false + elemType: "int" + - name: generated-extreme-mix + in: + nums: + gen: "array" + len: 75000 + of: + gen: "int" + min: -10000 + max: 10000 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.cpp b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.cpp new file mode 100644 index 00000000..8a6a2c87 --- /dev/null +++ b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int maxAbsoluteSum(vector& nums) { + int prefix_sum = 0; + int min_prefix_sum = 0; + int max_prefix_sum = 0; + int max_absolute_sum = 0; + + for (int num : nums) { + prefix_sum += num; + + max_absolute_sum = max(max_absolute_sum, abs(prefix_sum - min_prefix_sum)); + max_absolute_sum = max(max_absolute_sum, abs(prefix_sum - max_prefix_sum)); + + min_prefix_sum = min(min_prefix_sum, prefix_sum); + max_prefix_sum = max(max_prefix_sum, prefix_sum); + } + + return max_absolute_sum; + } +}; diff --git a/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.cs b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.cs new file mode 100644 index 00000000..a7f2210c --- /dev/null +++ b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public int MaxAbsoluteSum(int[] nums) { + int prefixSum = 0; + int minPrefixSum = 0; + int maxPrefixSum = 0; + int maxAbsoluteSum = 0; + + foreach (int num in nums) { + prefixSum += num; + + maxAbsoluteSum = Math.Max(maxAbsoluteSum, Math.Abs(prefixSum - minPrefixSum)); + maxAbsoluteSum = Math.Max(maxAbsoluteSum, Math.Abs(prefixSum - maxPrefixSum)); + + minPrefixSum = Math.Min(minPrefixSum, prefixSum); + maxPrefixSum = Math.Max(maxPrefixSum, prefixSum); + } + + return maxAbsoluteSum; + } +} diff --git a/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.dart b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.dart new file mode 100644 index 00000000..114d58b0 --- /dev/null +++ b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.dart @@ -0,0 +1,20 @@ +class Solution { + int maxAbsoluteSum(List nums) { + int prefixSum = 0; + int minPrefixSum = 0; + int maxPrefixSum = 0; + int maxAbsoluteSum = 0; + + for (int num in nums) { + prefixSum += num; + + maxAbsoluteSum = max(maxAbsoluteSum, (prefixSum - minPrefixSum).abs()); + maxAbsoluteSum = max(maxAbsoluteSum, (prefixSum - maxPrefixSum).abs()); + + minPrefixSum = min(minPrefixSum, prefixSum); + maxPrefixSum = max(maxPrefixSum, prefixSum); + } + + return maxAbsoluteSum; + } +} diff --git a/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.go b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.go new file mode 100644 index 00000000..02f3ac3a --- /dev/null +++ b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.go @@ -0,0 +1,26 @@ +func maxAbsoluteSum(nums []int) int { + prefixSum := 0 + minPrefixSum := 0 + maxPrefixSum := 0 + maxAbsoluteSum := 0 + + for _, num := range nums { + prefixSum += num + + if diff := prefixSum - minPrefixSum; diff > maxAbsoluteSum { + maxAbsoluteSum = diff + } + if diff := prefixSum - maxPrefixSum; -diff > maxAbsoluteSum { + maxAbsoluteSum = -diff + } + + if prefixSum < minPrefixSum { + minPrefixSum = prefixSum + } + if prefixSum > maxPrefixSum { + maxPrefixSum = prefixSum + } + } + + return maxAbsoluteSum +} diff --git a/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.java b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.java new file mode 100644 index 00000000..fb83c239 --- /dev/null +++ b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.java @@ -0,0 +1,20 @@ +class Solution { + public int maxAbsoluteSum(int[] nums) { + int prefixSum = 0; + int minPrefixSum = 0; + int maxPrefixSum = 0; + int maxAbsoluteSum = 0; + + for (int num : nums) { + prefixSum += num; + + maxAbsoluteSum = Math.max(maxAbsoluteSum, Math.abs(prefixSum - minPrefixSum)); + maxAbsoluteSum = Math.max(maxAbsoluteSum, Math.abs(prefixSum - maxPrefixSum)); + + minPrefixSum = Math.min(minPrefixSum, prefixSum); + maxPrefixSum = Math.max(maxPrefixSum, prefixSum); + } + + return maxAbsoluteSum; + } +} diff --git a/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.kt b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.kt new file mode 100644 index 00000000..c00999e1 --- /dev/null +++ b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun maxAbsoluteSum(nums: IntArray): Int { + var prefixSum = 0 + var minPrefixSum = 0 + var maxPrefixSum = 0 + var maxAbsoluteSum = 0 + + for (num in nums) { + prefixSum += num + + maxAbsoluteSum = maxOf(maxAbsoluteSum, abs(prefixSum - minPrefixSum)) + maxAbsoluteSum = maxOf(maxAbsoluteSum, abs(prefixSum - maxPrefixSum)) + + minPrefixSum = minOf(minPrefixSum, prefixSum) + maxPrefixSum = maxOf(maxPrefixSum, prefixSum) + } + + return maxAbsoluteSum + } +} diff --git a/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.py b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.py new file mode 100644 index 00000000..8cca07af --- /dev/null +++ b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.py @@ -0,0 +1,19 @@ +class Solution: + def maxAbsoluteSum(self, nums): + prefix_sum = 0 + min_prefix_sum = 0 + max_prefix_sum = 0 + max_absolute_sum = 0 + + for num in nums: + prefix_sum += num # Update prefix sum + + # Update max_absolute_sum + max_absolute_sum = max(max_absolute_sum, abs(prefix_sum - min_prefix_sum)) + max_absolute_sum = max(max_absolute_sum, abs(prefix_sum - max_prefix_sum)) + + # Update min_prefix_sum and max_prefix_sum + min_prefix_sum = min(min_prefix_sum, prefix_sum) + max_prefix_sum = max(max_prefix_sum, prefix_sum) + + return max_absolute_sum diff --git a/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.py2 b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.py2 new file mode 100644 index 00000000..e632934a --- /dev/null +++ b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def maxAbsoluteSum(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + prefix_sum = 0 + min_prefix_sum = 0 + max_prefix_sum = 0 + max_absolute_sum = 0 + + for num in nums: + prefix_sum += num + + max_absolute_sum = max(max_absolute_sum, abs(prefix_sum - min_prefix_sum)) + max_absolute_sum = max(max_absolute_sum, abs(prefix_sum - max_prefix_sum)) + + min_prefix_sum = min(min_prefix_sum, prefix_sum) + max_prefix_sum = max(max_prefix_sum, prefix_sum) + + return max_absolute_sum diff --git a/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.rb b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.rb new file mode 100644 index 00000000..acc11dc4 --- /dev/null +++ b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.rb @@ -0,0 +1,20 @@ +# @param {Integer[]} nums +# @return {Integer} +def max_absolute_sum(nums) + prefix_sum = 0 + min_prefix_sum = 0 + max_prefix_sum = 0 + max_absolute_sum = 0 + + nums.each do |num| + prefix_sum += num + + max_absolute_sum = [max_absolute_sum, (prefix_sum - min_prefix_sum).abs].max + max_absolute_sum = [max_absolute_sum, (prefix_sum - max_prefix_sum).abs].max + + min_prefix_sum = [min_prefix_sum, prefix_sum].min + max_prefix_sum = [max_prefix_sum, prefix_sum].max + end + + max_absolute_sum +end diff --git a/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.rs b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.rs new file mode 100644 index 00000000..ae8ce615 --- /dev/null +++ b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn max_absolute_sum(nums: Vec) -> i32 { + let mut prefix_sum = 0; + let mut min_prefix_sum = 0; + let mut max_prefix_sum = 0; + let mut max_absolute_sum = 0; + + for num in nums { + prefix_sum += num; + + max_absolute_sum = max_absolute_sum.max((prefix_sum - min_prefix_sum).abs()); + max_absolute_sum = max_absolute_sum.max((prefix_sum - max_prefix_sum).abs()); + + min_prefix_sum = min_prefix_sum.min(prefix_sum); + max_prefix_sum = max_prefix_sum.max(prefix_sum); + } + + max_absolute_sum + } +} diff --git a/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.swift b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.swift new file mode 100644 index 00000000..160e5471 --- /dev/null +++ b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func maxAbsoluteSum(_ nums: [Int]) -> Int { + var prefixSum = 0 + var minPrefixSum = 0 + var maxPrefixSum = 0 + var maxAbsoluteSum = 0 + + for num in nums { + prefixSum += num + + maxAbsoluteSum = max(maxAbsoluteSum, abs(prefixSum - minPrefixSum)) + maxAbsoluteSum = max(maxAbsoluteSum, abs(prefixSum - maxPrefixSum)) + + minPrefixSum = min(minPrefixSum, prefixSum) + maxPrefixSum = max(maxPrefixSum, prefixSum) + } + + return maxAbsoluteSum + } +} diff --git a/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.ts b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.ts new file mode 100644 index 00000000..681b9bd2 --- /dev/null +++ b/tests/1501-2000/1749. maximum-absolute-sum-of-any-subarray/sol.ts @@ -0,0 +1,24 @@ +function maxAbsoluteSum(nums: number[]): number { + let prefixSum = 0; + let minPrefixSum = 0; + let maxPrefixSum = 0; + let maxAbsoluteSum = 0; + + for (const num of nums) { + prefixSum += num; + + maxAbsoluteSum = Math.max( + maxAbsoluteSum, + Math.abs(prefixSum - minPrefixSum), + ); + maxAbsoluteSum = Math.max( + maxAbsoluteSum, + Math.abs(prefixSum - maxPrefixSum), + ); + + minPrefixSum = Math.min(minPrefixSum, prefixSum); + maxPrefixSum = Math.max(maxPrefixSum, prefixSum); + } + + return maxAbsoluteSum; +} diff --git a/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/manifest.yaml b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/manifest.yaml new file mode 100644 index 00000000..a42c577e --- /dev/null +++ b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/manifest.yaml @@ -0,0 +1,205 @@ +entry: + id: 1750 + title: "minimum-length-of-string-after-deleting-similar-ends" + params: + s: + type: string + call: + cpp: "Solution().minimumLength({s})" + rust: "Solution::minimum_length({s})" + python3: "Solution().minimumLength({s})" + python2: "Solution().minimumLength({s})" + ruby: "minimum_length({s})" + java: "new Solution().minimumLength({s})" + csharp: "new Solution().MinimumLength({s})" + kotlin: "Solution().minimumLength({s})" + go: "minimumLength({s})" + dart: "Solution().minimumLength({s})" + swift: "Solution().minimumLength({s})" + typescript: "minimumLength({s})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minimumLength(s, {result})" + checker: | + class Checker: + def minimumLength(self, s, result): + i, j = 0, len(s) - 1 + while i < j and s[i] == s[j]: + ch = s[i] + while i <= j and s[i] == ch: + i += 1 + while i < j and s[j] == ch: + j -= 1 + expected = max(0, j - i + 1) + return result == expected + +seed: 1750 + +tests: + - name: two-different + in: + s: "ca" + out: 2 + - name: example-zero + in: + s: "cabaabac" + out: 0 + - name: example-three + in: + s: "aabccabba" + out: 3 + - name: single-a + in: + s: "a" + out: 1 + - name: single-b + in: + s: "b" + out: 1 + - name: equal-pair + in: + s: "aa" + out: 0 + - name: different-pair + in: + s: "ab" + out: 2 + - name: three-equal + in: + s: "aaa" + out: 0 + - name: three-palindrome + in: + s: "aba" + out: 1 + - name: three-mismatch + in: + s: "abc" + out: 3 + - name: four-equal + in: + s: "bbbb" + out: 0 + - name: four-alternating + in: + s: "abab" + out: 4 + - name: nested-a + in: + s: "aaba" + out: 1 + - name: nested-b + in: + s: "baab" + out: 0 + - name: opposite-runs + in: + s: "aaabbb" + out: 6 + - name: removable-runs + in: + s: "aaabaaa" + out: 1 + - name: center-two + in: + s: "aaacaa" + out: 1 + - name: center-three + in: + s: "aaabcaaa" + out: 2 + - name: all-three-runs + in: + s: "aaabbbccc" + out: 9 + - name: full-cascade + in: + s: "aaabbbcccbbbaaa" + out: 0 + - name: cascade-leaves-one + in: + s: "aaabcccbbaaa" + out: 0 + - name: mismatch-after-prefix + in: + s: "aabbccaa" + out: 4 + - name: alternating-palindrome + in: + s: "abcba" + out: 1 + - name: repeated-palindrome + in: + s: "abccba" + out: 0 + - name: repeated-middle + in: + s: "abcccba" + out: 0 + - name: unequal-runs + in: + s: "aaaaabbbbaaaa" + out: 0 + - name: unequal-runs-center + in: + s: "aaaaabbbbbaaa" + out: 0 + - name: a-b-a-c-a + in: + s: "abaca" + out: 3 + - name: c-b-a-b-c + in: + s: "cbabc" + out: 1 + - name: no-removal-long + in: + s: "abcabcabc" + out: 9 + - name: nested-three + in: + s: "aaabccbaaa" + out: 0 + - name: generated-small + in: + s: + gen: "str" + len: 20 + alphabet: "abc" + seed: 175001 + - name: generated-medium + in: + s: + gen: "str" + len: 1000 + alphabet: "abc" + seed: 175002 + - name: generated-large-binary + in: + s: + gen: "str" + len: 50000 + alphabet: "ab" + seed: 175003 + - name: generated-large-ternary + in: + s: + gen: "str" + len: 100000 + alphabet: "abc" + seed: 175004 + - name: generated-max-unary + in: + s: + gen: "str" + len: 100000 + alphabet: "c" + seed: 175005 diff --git a/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.cpp b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.cpp new file mode 100644 index 00000000..5c82462a --- /dev/null +++ b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int minimumLength(string s) { + int left = 0; + int right = s.length() - 1; + while (left < right && s[left] == s[right]) { + char ch = s[left]; + while (left <= right && s[left] == ch) { + left++; + } + while (left <= right && s[right] == ch) { + right--; + } + } + return max(0, right - left + 1); + } +}; diff --git a/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.cs b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.cs new file mode 100644 index 00000000..f0cdaf9e --- /dev/null +++ b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public int MinimumLength(string s) { + int left = 0; + int right = s.Length - 1; + while (left < right && s[left] == s[right]) { + char ch = s[left]; + while (left <= right && s[left] == ch) { + left++; + } + while (left <= right && s[right] == ch) { + right--; + } + } + return Math.Max(0, right - left + 1); + } +} diff --git a/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.dart b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.dart new file mode 100644 index 00000000..83d94f28 --- /dev/null +++ b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.dart @@ -0,0 +1,16 @@ +class Solution { + int minimumLength(String s) { + int left = 0; + int right = s.length - 1; + while (left < right && s[left] == s[right]) { + String ch = s[left]; + while (left <= right && s[left] == ch) { + left++; + } + while (left <= right && s[right] == ch) { + right--; + } + } + return (right - left + 1) < 0 ? 0 : right - left + 1; + } +} diff --git a/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.go b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.go new file mode 100644 index 00000000..53795fd9 --- /dev/null +++ b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.go @@ -0,0 +1,17 @@ +func minimumLength(s string) int { + left := 0 + right := len(s) - 1 + for left < right && s[left] == s[right] { + ch := s[left] + for left <= right && s[left] == ch { + left++ + } + for left <= right && s[right] == ch { + right-- + } + } + if right-left+1 < 0 { + return 0 + } + return right - left + 1 +} diff --git a/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.java b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.java new file mode 100644 index 00000000..70189f5a --- /dev/null +++ b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.java @@ -0,0 +1,16 @@ +class Solution { + public int minimumLength(String s) { + int left = 0; + int right = s.length() - 1; + while (left < right && s.charAt(left) == s.charAt(right)) { + char ch = s.charAt(left); + while (left <= right && s.charAt(left) == ch) { + left++; + } + while (left <= right && s.charAt(right) == ch) { + right--; + } + } + return Math.max(0, right - left + 1); + } +} diff --git a/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.kt b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.kt new file mode 100644 index 00000000..3d33c4ea --- /dev/null +++ b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun minimumLength(s: String): Int { + var left = 0 + var right = s.length - 1 + while (left < right && s[left] == s[right]) { + val ch = s[left] + while (left <= right && s[left] == ch) { + left++ + } + while (left <= right && s[right] == ch) { + right-- + } + } + return maxOf(0, right - left + 1) + } +} diff --git a/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.py b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.py new file mode 100644 index 00000000..16d77e56 --- /dev/null +++ b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.py @@ -0,0 +1,10 @@ +class Solution: + def minimumLength(self, s: str) -> int: + left, right = 0, len(s) - 1 + while left < right and s[left] == s[right]: + ch = s[left] + while left <= right and s[left] == ch: + left += 1 + while left <= right and s[right] == ch: + right -= 1 + return max(0, right - left + 1) diff --git a/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.py2 b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.py2 new file mode 100644 index 00000000..b9052b5d --- /dev/null +++ b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def minimumLength(self, s): + """ + :type s: str + :rtype: int + """ + left, right = 0, len(s) - 1 + while left < right and s[left] == s[right]: + ch = s[left] + while left <= right and s[left] == ch: + left += 1 + while left <= right and s[right] == ch: + right -= 1 + return max(0, right - left + 1) diff --git a/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.rb b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.rb new file mode 100644 index 00000000..4cca81fb --- /dev/null +++ b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.rb @@ -0,0 +1,16 @@ +# @param {String} s +# @return {Integer} +def minimum_length(s) + left = 0 + right = s.length - 1 + while left < right && s[left] == s[right] + ch = s[left] + while left <= right && s[left] == ch + left += 1 + end + while left <= right && s[right] == ch + right -= 1 + end + end + return [0, right - left + 1].max +end diff --git a/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.rs b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.rs new file mode 100644 index 00000000..8b183f8b --- /dev/null +++ b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn minimum_length(s: String) -> i32 { + let s_bytes = s.as_bytes(); + let mut left = 0; + let mut right = s.len() as i32 - 1; + while left < right && s_bytes[left as usize] == s_bytes[right as usize] { + let ch = s_bytes[left as usize]; + while left <= right && s_bytes[left as usize] == ch { + left += 1; + } + while left <= right && s_bytes[right as usize] == ch { + right -= 1; + } + } + (right - left + 1).max(0) + } +} diff --git a/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.swift b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.swift new file mode 100644 index 00000000..1c07c9e8 --- /dev/null +++ b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.swift @@ -0,0 +1,17 @@ +class Solution { + func minimumLength(_ s: String) -> Int { + var left = 0 + var right = s.count - 1 + let chars = Array(s) + while left < right && chars[left] == chars[right] { + let ch = chars[left] + while left <= right && chars[left] == ch { + left += 1 + } + while left <= right && chars[right] == ch { + right -= 1 + } + } + return max(0, right - left + 1) + } +} diff --git a/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.ts b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.ts new file mode 100644 index 00000000..7b30bc6a --- /dev/null +++ b/tests/1501-2000/1750. minimum-length-of-string-after-deleting-similar-ends/sol.ts @@ -0,0 +1,14 @@ +function minimumLength(s: string): number { + let left = 0; + let right = s.length - 1; + while (left < right && s[left] === s[right]) { + const ch = s[left]; + while (left <= right && s[left] === ch) { + left++; + } + while (left <= right && s[right] === ch) { + right--; + } + } + return Math.max(0, right - left + 1); +} diff --git a/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/manifest.yaml b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/manifest.yaml new file mode 100644 index 00000000..881492f1 --- /dev/null +++ b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/manifest.yaml @@ -0,0 +1,432 @@ +entry: + id: 1751 + title: "maximum-number-of-events-that-can-be-attended-ii" + params: + events: + type: array + items: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().maxValue({events}, {k})" + rust: "Solution::max_value({events}, {k})" + python3: "Solution().maxValue({events}, {k})" + python2: "Solution().maxValue({events}, {k})" + ruby: "max_value({events}, {k})" + java: "new Solution().maxValue({events}, {k})" + csharp: "new Solution().MaxValue({events}, {k})" + kotlin: "Solution().maxValue({events}, {k})" + go: "maxValue({events}, {k})" + dart: "Solution().maxValue({events}, {k})" + swift: "Solution().maxValue({events}, {k})" + typescript: "maxValue({events}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 5000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().maxValue(events, k, {result})" + checker: | + from bisect import bisect_left + + class Checker: + def maxValue(self, events, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not isinstance(events, list) or not isinstance(k, int) or isinstance(k, bool): + return False + if not 1 <= k <= len(events): + return False + es = [] + for event in events: + if not isinstance(event, list) or len(event) != 3: + return False + start, end, value = event + if any(not isinstance(x, int) or isinstance(x, bool) for x in event): + return False + if not (1 <= start <= end <= 1000000000 and 1 <= value <= 1000000): + return False + es.append((start, end, value)) + es.sort(key=lambda event: event[1]) + n = len(es) + ends = [event[1] for event in es] + previous = [bisect_left(ends, start, 0, i) for i, (start, _, _) in enumerate(es)] + best_without_current = [0] * (n + 1) + for used in range(1, k + 1): + best_with_limit = [0] * (n + 1) + for i, (_, _, value) in enumerate(es, 1): + best_with_limit[i] = max( + best_with_limit[i - 1], + best_without_current[previous[i - 1]] + value, + ) + best_without_current = best_with_limit + return result == best_without_current[n] + +seed: 1751 + +tests: + - name: example-one + in: + events: + - [1, 2, 4] + - [3, 4, 3] + - [2, 3, 1] + k: 2 + out: 7 + - name: example-two + in: + events: + - [1, 2, 4] + - [3, 4, 3] + - [2, 3, 10] + k: 2 + out: 10 + - name: example-three + in: + events: + - [1, 1, 1] + - [2, 2, 2] + - [3, 3, 3] + - [4, 4, 4] + k: 3 + out: 9 + - name: one-event + in: + events: + - [1, 1, 100] + k: 1 + out: 100 + - name: k-one + in: + events: + - [1, 2, 5] + - [2, 3, 100] + - [4, 5, 7] + k: 1 + out: 100 + - name: all-overlap + in: + events: + - [1, 10, 4] + - [2, 9, 20] + - [3, 8, 7] + - [1, 10, 19] + k: 4 + out: 20 + - name: all-compatible + in: + events: + - [1, 1, 2] + - [2, 2, 4] + - [3, 3, 6] + - [4, 4, 8] + k: 4 + out: 20 + - name: inclusive-boundary + in: + events: + - [1, 2, 50] + - [2, 2, 100] + - [3, 3, 4] + k: 2 + out: 104 + - name: boundary-chain + in: + events: + - [1, 1, 10] + - [1, 2, 20] + - [2, 3, 30] + - [3, 4, 40] + - [5, 5, 50] + k: 3 + out: 110 + - name: choose-two-gaps + in: + events: + - [1, 2, 8] + - [4, 5, 9] + - [7, 8, 10] + - [2, 6, 30] + k: 2 + out: 40 + - name: negative-looking-days + in: + events: + - [1, 1000000000, 1] + - [1, 1, 999999] + - [2, 2, 999998] + k: 2 + out: 1999997 + - name: large-values + in: + events: + - [1, 1, 1000000] + - [2, 2, 1000000] + - [3, 3, 999999] + k: 3 + out: 2999999 + - name: duplicate-events + in: + events: + - [2, 5, 7] + - [2, 5, 8] + - [2, 5, 20] + - [6, 7, 3] + k: 2 + out: 23 + - name: nested-intervals + in: + events: + - [1, 10, 100] + - [2, 9, 60] + - [3, 8, 70] + - [11, 11, 5] + k: 2 + out: 105 + - name: sort-by-end-needed + in: + events: + - [8, 9, 10] + - [1, 3, 5] + - [4, 7, 20] + - [2, 5, 100] + k: 2 + out: 110 + - name: zero-gap-choice + in: + events: + - [1, 1, 1] + - [2, 4, 2] + - [5, 5, 3] + - [6, 9, 4] + k: 2 + out: 7 + - name: one-day-conflicts + in: + events: + - [5, 5, 11] + - [5, 5, 12] + - [6, 6, 13] + - [7, 7, 14] + k: 2 + out: 27 + - name: skip-low-value + in: + events: + - [1, 2, 1] + - [3, 4, 100] + - [5, 6, 1] + - [1, 6, 101] + k: 3 + out: 102 + - name: three-disjoint + in: + events: + - [1, 2, 10] + - [4, 5, 20] + - [7, 8, 30] + - [10, 11, 40] + k: 3 + out: 90 + - name: long-and-short + in: + events: + - [1, 10, 40] + - [1, 3, 15] + - [4, 6, 16] + - [7, 10, 17] + - [11, 12, 1] + k: 3 + out: 48 + - name: same-starts + in: + events: + - [1, 1, 2] + - [1, 2, 5] + - [1, 3, 9] + - [4, 4, 10] + k: 2 + out: 19 + - name: same-ends + in: + events: + - [1, 4, 2] + - [2, 4, 100] + - [3, 4, 3] + - [5, 6, 4] + k: 2 + out: 104 + - name: k-larger-than-useful + in: + events: + - [1, 2, 4] + - [2, 3, 9] + - [4, 5, 8] + k: 3 + out: 17 + - name: sparse-days + in: + events: + - [1, 100, 4] + - [101, 200, 8] + - [201, 300, 16] + - [150, 250, 100] + k: 2 + out: 104 + - name: huge-day-values + in: + events: + - [999999990, 999999991, 12] + - [999999992, 999999999, 13] + - [1, 999999989, 20] + k: 2 + out: 33 + - name: six-events + in: + events: + - [1, 2, 3] + - [3, 4, 20] + - [5, 6, 4] + - [2, 5, 30] + - [7, 8, 5] + - [9, 10, 40] + k: 3 + out: 75 + - name: alternating-overlaps + in: + events: + - [1, 4, 10] + - [2, 2, 5] + - [3, 5, 20] + - [6, 7, 8] + - [5, 6, 50] + k: 2 + out: 60 + - name: best-three-of-four + in: + events: + - [1, 1, 10] + - [2, 2, 20] + - [3, 3, 30] + - [4, 4, 40] + k: 3 + out: 90 + - name: exact-two-required-not + in: + events: + - [1, 10, 100] + - [2, 2, 1] + - [11, 11, 2] + - [12, 12, 3] + k: 4 + out: 105 + - name: large-disjoint-chain + in: + events: + - [1, 2, 100] + - [4, 5, 101] + - [7, 8, 102] + - [10, 11, 103] + - [13, 14, 104] + - [16, 17, 105] + - [19, 20, 106] + - [22, 23, 107] + - [25, 26, 108] + - [28, 29, 109] + - [31, 32, 110] + - [34, 35, 111] + - [37, 38, 112] + - [40, 41, 113] + - [43, 44, 114] + - [46, 47, 115] + - [49, 50, 116] + - [52, 53, 117] + - [55, 56, 118] + - [58, 59, 119] + k: 10 + out: 1145 + - name: large-overlapping-window + in: + events: + - [1, 100, 1000] + - [2, 101, 999] + - [3, 102, 998] + - [4, 103, 997] + - [5, 104, 996] + - [6, 105, 995] + - [7, 106, 994] + - [8, 107, 993] + - [9, 108, 992] + - [10, 109, 991] + - [11, 110, 990] + - [12, 111, 989] + - [13, 112, 988] + - [14, 113, 987] + - [15, 114, 986] + - [16, 115, 985] + - [17, 116, 984] + - [18, 117, 983] + - [19, 118, 982] + - [20, 119, 981] + k: 20 + out: 1000 + - name: high-day-chain + in: + events: + - [999999900, 999999901, 10] + - [999999902, 999999903, 20] + - [999999904, 999999905, 30] + - [999999906, 999999907, 40] + - [999999908, 999999909, 50] + - [999999910, 999999911, 60] + - [999999912, 999999913, 70] + - [999999914, 999999915, 80] + - [999999916, 999999917, 90] + - [999999918, 999999919, 100] + k: 5 + out: 400 + - name: many-identical-intervals + in: + events: + - [100, 200, 1] + - [100, 200, 2] + - [100, 200, 3] + - [100, 200, 4] + - [100, 200, 5] + - [100, 200, 6] + - [100, 200, 7] + - [100, 200, 8] + - [100, 200, 9] + - [201, 201, 100] + k: 2 + out: 109 + - name: mixed-large-values + in: + events: + - [1, 50, 1000000] + - [51, 100, 999999] + - [101, 150, 999998] + - [25, 75, 200000] + - [76, 125, 300000] + - [126, 175, 400000] + - [176, 200, 500000] + k: 3 + out: 2999997 + - name: choose-best-two-separated + in: + events: + - [1, 10, 50] + - [11, 20, 60] + - [21, 30, 70] + - [5, 15, 200] + - [16, 25, 1] + k: 2 + out: 270 diff --git a/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.cpp b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.cpp new file mode 100644 index 00000000..4950e0f0 --- /dev/null +++ b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + int maxValue(vector>& events, int k) { + sort(events.begin(), events.end(), [](const vector& a, const vector& b) { + return a[1] < b[1]; + }); + int n = events.size(); + vector> dp(n + 1, vector(k + 1, 0)); + + for (int i = 1; i <= n; i++) { + int start = events[i - 1][0]; + int value = events[i - 1][2]; + int prev = findLastNonOverlapping(events, i - 1, start); + for (int j = 1; j <= k; j++) { + dp[i][j] = max(dp[i - 1][j], dp[prev + 1][j - 1] + value); + } + } + return dp[n][k]; + } + +private: + int findLastNonOverlapping(vector>& events, int right, int targetStart) { + int left = 0; + int res = -1; + while (left <= right) { + int mid = (left + right) / 2; + if (events[mid][1] < targetStart) { + res = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + return res; + } +}; diff --git a/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.cs b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.cs new file mode 100644 index 00000000..a67bf05f --- /dev/null +++ b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.cs @@ -0,0 +1,32 @@ +public class Solution { + public int MaxValue(int[][] events, int k) { + Array.Sort(events, (a, b) => a[1].CompareTo(b[1])); + int n = events.Length; + int[,] dp = new int[n + 1, k + 1]; + + for (int i = 1; i <= n; i++) { + int start = events[i - 1][0]; + int value = events[i - 1][2]; + int prev = FindLastNonOverlapping(events, i - 1, start); + for (int j = 1; j <= k; j++) { + dp[i, j] = Math.Max(dp[i - 1, j], dp[prev + 1, j - 1] + value); + } + } + return dp[n, k]; + } + + private int FindLastNonOverlapping(int[][] events, int right, int targetStart) { + int left = 0; + int res = -1; + while (left <= right) { + int mid = (left + right) / 2; + if (events[mid][1] < targetStart) { + res = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + return res; + } +} diff --git a/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.dart b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.dart new file mode 100644 index 00000000..8247247e --- /dev/null +++ b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.dart @@ -0,0 +1,34 @@ +class Solution { + int maxValue(List> events, int k) { + events.sort((a, b) => a[1].compareTo(b[1])); + int n = events.length; + List> dp = List.generate(n + 1, (_) => List.filled(k + 1, 0)); + + for (int i = 1; i <= n; i++) { + int start = events[i - 1][0]; + int value = events[i - 1][2]; + int prev = findLastNonOverlapping(events, i - 1, start); + for (int j = 1; j <= k; j++) { + dp[i][j] = dp[i - 1][j] > dp[prev + 1][j - 1] + value + ? dp[i - 1][j] + : dp[prev + 1][j - 1] + value; + } + } + return dp[n][k]; + } + + int findLastNonOverlapping(List> events, int right, int targetStart) { + int left = 0; + int res = -1; + while (left <= right) { + int mid = (left + right) ~/ 2; + if (events[mid][1] < targetStart) { + res = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + return res; + } +} diff --git a/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.go b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.go new file mode 100644 index 00000000..86b082fd --- /dev/null +++ b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.go @@ -0,0 +1,40 @@ +func maxValue(events [][]int, k int) int { + sort.Slice(events, func(i, j int) bool { + return events[i][1] < events[j][1] + }) + n := len(events) + dp := make([][]int, n+1) + for i := range dp { + dp[i] = make([]int, k+1) + } + + for i := 1; i <= n; i++ { + start := events[i-1][0] + value := events[i-1][2] + prev := findLastNonOverlapping(events, i-1, start) + for j := 1; j <= k; j++ { + take := dp[prev+1][j-1] + value + if dp[i-1][j] > take { + dp[i][j] = dp[i-1][j] + } else { + dp[i][j] = take + } + } + } + return dp[n][k] +} + +func findLastNonOverlapping(events [][]int, right int, targetStart int) int { + left := 0 + res := -1 + for left <= right { + mid := (left + right) / 2 + if events[mid][1] < targetStart { + res = mid + left = mid + 1 + } else { + right = mid - 1 + } + } + return res +} diff --git a/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.java b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.java new file mode 100644 index 00000000..1e593b17 --- /dev/null +++ b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.java @@ -0,0 +1,31 @@ +class Solution { + public int maxValue(int[][] events, int k) { + Arrays.sort(events, (a, b) -> a[1] - b[1]); + int n = events.length; + int[][] dp = new int[n + 1][k + 1]; + + for (int i = 1; i <= n; i++) { + int start = events[i - 1][0]; + int value = events[i - 1][2]; + int prev = findLastNonOverlapping(events, i - 1, start); + for (int j = 1; j <= k; j++) { + dp[i][j] = Math.max(dp[i - 1][j], dp[prev + 1][j - 1] + value); + } + } + return dp[n][k]; + } + + private int findLastNonOverlapping(int[][] events, int right, int targetStart) { + int left = 0, res = -1; + while (left <= right) { + int mid = (left + right) / 2; + if (events[mid][1] < targetStart) { + res = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + return res; + } +} diff --git a/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.kt b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.kt new file mode 100644 index 00000000..977d50e6 --- /dev/null +++ b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.kt @@ -0,0 +1,33 @@ +class Solution { + fun maxValue(events: Array, k: Int): Int { + events.sortBy { it[1] } + val n = events.size + val dp = Array(n + 1) { IntArray(k + 1) } + + for (i in 1..n) { + val start = events[i - 1][0] + val value = events[i - 1][2] + val prev = findLastNonOverlapping(events, i - 1, start) + for (j in 1..k) { + dp[i][j] = maxOf(dp[i - 1][j], dp[prev + 1][j - 1] + value) + } + } + return dp[n][k] + } + + private fun findLastNonOverlapping(events: Array, right: Int, targetStart: Int): Int { + var left = 0 + var res = -1 + var r = right + while (left <= r) { + val mid = (left + r) / 2 + if (events[mid][1] < targetStart) { + res = mid + left = mid + 1 + } else { + r = mid - 1 + } + } + return res + } +} diff --git a/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.py b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.py new file mode 100644 index 00000000..6e2a62fc --- /dev/null +++ b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.py @@ -0,0 +1,41 @@ +from bisect import bisect_right + + +class Solution: + def maxValue(self, events, k): + # Step 1: Sort events by end time + events.sort(key=lambda x: x[1]) + n = len(events) + + # Step 2: Extract start times separately for binary search + start_times = [e[0] for e in events] + + # Step 3: Initialize DP table + dp = [[0] * (k + 1) for _ in range(n + 1)] + + # Step 4: Loop through each event + for i in range(1, n + 1): + start, end, value = events[i - 1] + + # Step 5: Binary search for last non-overlapping event + prev = self.findLastNonOverlapping(events, i - 1, start) + + for j in range(1, k + 1): + # Option 1: skip current event + # Option 2: take current event and add to prev best + dp[i][j] = max(dp[i - 1][j], dp[prev + 1][j - 1] + value) + + # Step 6: Return final answer + return dp[n][k] + + def findLastNonOverlapping(self, events, right, targetStart): + left = 0 + res = -1 + while left <= right: + mid = (left + right) // 2 + if events[mid][1] < targetStart: + res = mid + left = mid + 1 + else: + right = mid - 1 + return res diff --git a/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.py2 b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.py2 new file mode 100644 index 00000000..71723f79 --- /dev/null +++ b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.py2 @@ -0,0 +1,30 @@ +class Solution(object): + def maxValue(self, events, k): + """ + :type events: List[List[int]] + :type k: int + :rtype: int + """ + events.sort(key=lambda x: x[1]) + n = len(events) + start_times = [e[0] for e in events] + dp = [[0] * (k + 1) for _ in range(n + 1)] + + for i in range(1, n + 1): + start, end, value = events[i - 1] + prev = self.findLastNonOverlapping(events, i - 1, start) + for j in range(1, k + 1): + dp[i][j] = max(dp[i - 1][j], dp[prev + 1][j - 1] + value) + return dp[n][k] + + def findLastNonOverlapping(self, events, right, targetStart): + left = 0 + res = -1 + while left <= right: + mid = (left + right) // 2 + if events[mid][1] < targetStart: + res = mid + left = mid + 1 + else: + right = mid - 1 + return res diff --git a/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.rb b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.rb new file mode 100644 index 00000000..a8165635 --- /dev/null +++ b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.rb @@ -0,0 +1,33 @@ +# @param {Integer[][]} events +# @param {Integer} k +# @return {Integer} +def max_value(events, k) + events.sort_by! { |e| e[1] } + n = events.length + dp = Array.new(n + 1) { Array.new(k + 1, 0) } + + (1..n).each do |i| + start_time = events[i - 1][0] + value = events[i - 1][2] + prev = find_last_non_overlapping(events, i - 1, start_time) + (1..k).each do |j| + dp[i][j] = [dp[i - 1][j], dp[prev + 1][j - 1] + value].max + end + end + dp[n][k] +end + +def find_last_non_overlapping(events, right, target_start) + left = 0 + res = -1 + while left <= right + mid = (left + right) / 2 + if events[mid][1] < target_start + res = mid + left = mid + 1 + else + right = mid - 1 + end + end + res +end diff --git a/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.rs b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.rs new file mode 100644 index 00000000..a44371cc --- /dev/null +++ b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.rs @@ -0,0 +1,36 @@ +impl Solution { + pub fn max_value(events: Vec>, k: i32) -> i32 { + let mut events = events; + events.sort_by_key(|e| e[1]); + let n = events.len(); + let k = k as usize; + let mut dp = vec![vec![0; k + 1]; n + 1]; + + for i in 1..=n { + let start = events[i - 1][0]; + let value = events[i - 1][2]; + let prev = Self::find_last_non_overlapping(&events, i - 1, start); + for j in 1..=k { + dp[i][j] = dp[i - 1][j].max(dp[prev][j - 1] + value); + } + } + dp[n][k] + } + + fn find_last_non_overlapping(events: &Vec>, right: usize, target_start: i32) -> usize { + let mut left = 0; + let mut res = 0; + let mut r = right; + while left <= r { + let mid = (left + r) / 2; + if events[mid][1] < target_start { + res = mid + 1; + left = mid + 1; + } else { + if mid == 0 { break; } + r = mid - 1; + } + } + res + } +} diff --git a/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.swift b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.swift new file mode 100644 index 00000000..ecf0c38f --- /dev/null +++ b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.swift @@ -0,0 +1,33 @@ +class Solution { + func maxValue(_ events: [[Int]], _ k: Int) -> Int { + let sortedEvents = events.sorted { $0[1] < $1[1] } + let n = sortedEvents.count + var dp = Array(repeating: Array(repeating: 0, count: k + 1), count: n + 1) + + for i in 1...n { + let start = sortedEvents[i - 1][0] + let value = sortedEvents[i - 1][2] + let prev = findLastNonOverlapping(sortedEvents, i - 1, start) + for j in 1...k { + dp[i][j] = max(dp[i - 1][j], dp[prev + 1][j - 1] + value) + } + } + return dp[n][k] + } + + private func findLastNonOverlapping(_ events: [[Int]], _ right: Int, _ targetStart: Int) -> Int { + var left = 0 + var res = -1 + var r = right + while left <= r { + let mid = (left + r) / 2 + if events[mid][1] < targetStart { + res = mid + left = mid + 1 + } else { + r = mid - 1 + } + } + return res + } +} diff --git a/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.ts b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.ts new file mode 100644 index 00000000..58f9fd32 --- /dev/null +++ b/tests/1501-2000/1751. maximum-number-of-events-that-can-be-attended-ii/sol.ts @@ -0,0 +1,36 @@ +function maxValue(events: number[][], k: number): number { + events.sort((a, b) => a[1] - b[1]); + const n = events.length; + const dp: number[][] = Array.from({ length: n + 1 }, () => + Array(k + 1).fill(0), + ); + + for (let i = 1; i <= n; i++) { + const start = events[i - 1][0]; + const value = events[i - 1][2]; + const prev = findLastNonOverlapping(events, i - 1, start); + for (let j = 1; j <= k; j++) { + dp[i][j] = Math.max(dp[i - 1][j], dp[prev + 1][j - 1] + value); + } + } + return dp[n][k]; +} + +function findLastNonOverlapping( + events: number[][], + right: number, + targetStart: number, +): number { + let left = 0; + let res = -1; + while (left <= right) { + const mid = Math.floor((left + right) / 2); + if (events[mid][1] < targetStart) { + res = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + return res; +} diff --git a/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/manifest.yaml b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/manifest.yaml new file mode 100644 index 00000000..6e39ce0c --- /dev/null +++ b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/manifest.yaml @@ -0,0 +1,217 @@ +entry: + id: 1752 + title: "check-if-array-is-sorted-and-rotated" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().check({nums})" + rust: "Solution::check({nums})" + python3: "Solution().check({nums})" + python2: "Solution().check({nums})" + ruby: "check({nums})" + java: "new Solution().check({nums})" + csharp: "new Solution().Check({nums})" + kotlin: "Solution().check({nums})" + go: "check({nums})" + dart: "Solution().check({nums})" + swift: "Solution().check({nums})" + typescript: "check({nums})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(nums, {result})" + checker: | + class Checker: + def check(self, nums, result): + if not isinstance(result, bool): + return False + drops = sum(nums[i] > nums[(i + 1) % len(nums)] for i in range(len(nums))) + return result == (drops <= 1) + +seed: 1752 + +tests: + - name: example-1 + in: + nums: [3, 4, 5, 1, 2] + out: true + - name: example-2 + in: + nums: [2, 1, 3, 4] + out: false + - name: example-3 + in: + nums: [1, 2, 3] + out: true + - name: singleton + in: + nums: [7] + out: true + - name: two-equal + in: + nums: [5, 5] + out: true + - name: two-increasing + in: + nums: [1, 2] + out: true + - name: two-decreasing-is-rotation + in: + nums: [2, 1] + out: true + - name: all-equal + in: + nums: [4, 4, 4, 4, 4] + out: true + - name: already-sorted + in: + nums: [1, 2, 3, 4, 5, 6] + out: true + - name: sorted-with-duplicates + in: + nums: [1, 2, 2, 3, 3, 4] + out: true + - name: rotation-with-duplicates + in: + nums: [3, 3, 4, 1, 2, 2] + out: true + - name: rotation-at-last-element + in: + nums: [6, 1, 2, 3, 4, 5] + out: true + - name: rotation-with-equal-boundary + in: + nums: [2, 3, 3, 1, 1, 2] + out: true + - name: one-drop-equal-boundary + in: + nums: [2, 2, 3, 1, 2] + out: true + - name: two-drops + in: + nums: [3, 1, 2, 1] + out: false + - name: descending-three + in: + nums: [3, 2, 1] + out: false + - name: valley-not-rotation + in: + nums: [2, 3, 1, 4] + out: false + - name: duplicate-break + in: + nums: [1, 2, 1, 1] + out: true + - name: values-at-lower-bound + in: + nums: [1, 1, 1, 1, 1, 1] + out: true + - name: values-at-upper-bound + in: + nums: [100, 100, 100, 100] + out: true + - name: mixed-boundary-rotation + in: + nums: [100, 1, 1, 50, 100] + out: true + - name: mixed-boundary-invalid + in: + nums: [100, 1, 50, 1, 100] + out: false + - name: long-sorted + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + out: true + - name: long-rotation + in: + nums: [8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7] + out: true + - name: long-invalid + in: + nums: [8, 9, 10, 3, 12, 13, 14, 15, 1, 2, 4, 5, 6, 7, 11] + out: false + - name: repeated-block-rotation + in: + nums: [3, 4, 4, 1, 2, 2, 3] + out: true + - name: repeated-block-invalid + in: + nums: [3, 4, 2, 1, 2, 3, 4] + out: false + - name: near-sorted-valid + in: + nums: [2, 3, 4, 5, 1] + out: true + - name: near-sorted-invalid + in: + nums: [2, 4, 3, 5, 1] + out: false + - name: alternating-invalid + in: + nums: [1, 3, 2, 4, 3, 5] + out: false + - name: wide-rotation + in: + nums: [50, 60, 70, 80, 90, 100, 1, 10, 20, 30, 40] + out: true + - name: generator-small + in: + nums: + gen: "array" + len: 10 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + - name: generator-medium + in: + nums: + gen: "array" + len: 30 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + - name: generator-max-values + in: + nums: + gen: "array" + len: 90 + of: + gen: "int" + min: 90 + max: 100 + elemType: "int" + - name: generator-uniform + in: + nums: + gen: "array" + len: 75 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + - name: generator-full + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" diff --git a/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.cpp b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.cpp new file mode 100644 index 00000000..2f388b4e --- /dev/null +++ b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + bool check(vector& nums) { + int n = nums.size(); + int count = 0; + for (int i = 0; i < n; i++) { + if (nums[i] > nums[(i + 1) % n]) { + count++; + } + } + return count <= 1; + } +}; diff --git a/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.cs b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.cs new file mode 100644 index 00000000..9711d14d --- /dev/null +++ b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.cs @@ -0,0 +1,12 @@ +public class Solution { + public bool Check(int[] nums) { + int n = nums.Length; + int count = 0; + for (int i = 0; i < n; i++) { + if (nums[i] > nums[(i + 1) % n]) { + count++; + } + } + return count <= 1; + } +} diff --git a/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.dart b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.dart new file mode 100644 index 00000000..6b244afb --- /dev/null +++ b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.dart @@ -0,0 +1,12 @@ +class Solution { + bool check(List nums) { + int n = nums.length; + int count = 0; + for (int i = 0; i < n; i++) { + if (nums[i] > nums[(i + 1) % n]) { + count++; + } + } + return count <= 1; + } +} diff --git a/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.go b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.go new file mode 100644 index 00000000..070cf2d7 --- /dev/null +++ b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.go @@ -0,0 +1,10 @@ +func check(nums []int) bool { + n := len(nums) + count := 0 + for i := 0; i < n; i++ { + if nums[i] > nums[(i+1)%n] { + count++ + } + } + return count <= 1 +} diff --git a/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.java b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.java new file mode 100644 index 00000000..f375b94e --- /dev/null +++ b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.java @@ -0,0 +1,12 @@ +class Solution { + public boolean check(int[] nums) { + int n = nums.length; + int count = 0; + for (int i = 0; i < n; i++) { + if (nums[i] > nums[(i + 1) % n]) { + count++; + } + } + return count <= 1; + } +} diff --git a/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.kt b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.kt new file mode 100644 index 00000000..a7bfe805 --- /dev/null +++ b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.kt @@ -0,0 +1,12 @@ +class Solution { + fun check(nums: IntArray): Boolean { + val n = nums.size + var count = 0 + for (i in 0 until n) { + if (nums[i] > nums[(i + 1) % n]) { + count++ + } + } + return count <= 1 + } +} diff --git a/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.py b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.py new file mode 100644 index 00000000..814f87d8 --- /dev/null +++ b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.py @@ -0,0 +1,11 @@ +class Solution: + def check(self, nums): + + n = len(nums) + count = 0 + + for i in range(n): + if nums[i] > nums[(i + 1) % n]: + count += 1 + + return count <= 1 diff --git a/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.py2 b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.py2 new file mode 100644 index 00000000..ced0ad29 --- /dev/null +++ b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def check(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + n = len(nums) + count = 0 + for i in range(n): + if nums[i] > nums[(i + 1) % n]: + count += 1 + return count <= 1 diff --git a/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.rb b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.rb new file mode 100644 index 00000000..dd108d1a --- /dev/null +++ b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.rb @@ -0,0 +1,10 @@ +# @param {Integer[]} nums +# @return {Boolean} +def check(nums) + n = nums.length + count = 0 + (0...n).each do |i| + count += 1 if nums[i] > nums[(i + 1) % n] + end + count <= 1 +end diff --git a/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.rs b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.rs new file mode 100644 index 00000000..9161dc6b --- /dev/null +++ b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.rs @@ -0,0 +1,12 @@ +impl Solution { + pub fn check(nums: Vec) -> bool { + let n = nums.len(); + let mut count = 0; + for i in 0..n { + if nums[i] > nums[(i + 1) % n] { + count += 1; + } + } + count <= 1 + } +} diff --git a/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.swift b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.swift new file mode 100644 index 00000000..690e0971 --- /dev/null +++ b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.swift @@ -0,0 +1,12 @@ +class Solution { + func check(_ nums: [Int]) -> Bool { + let n = nums.count + var count = 0 + for i in 0.. nums[(i + 1) % n] { + count += 1 + } + } + return count <= 1 + } +} diff --git a/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.ts b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.ts new file mode 100644 index 00000000..a417b17c --- /dev/null +++ b/tests/1501-2000/1752. check-if-array-is-sorted-and-rotated/sol.ts @@ -0,0 +1,10 @@ +function check(nums: number[]): boolean { + const n = nums.length; + let count = 0; + for (let i = 0; i < n; i++) { + if (nums[i] > nums[(i + 1) % n]) { + count++; + } + } + return count <= 1; +} diff --git a/tests/1501-2000/1753. maximum-score-from-removing-stones/manifest.yaml b/tests/1501-2000/1753. maximum-score-from-removing-stones/manifest.yaml new file mode 100644 index 00000000..5e617a0a --- /dev/null +++ b/tests/1501-2000/1753. maximum-score-from-removing-stones/manifest.yaml @@ -0,0 +1,304 @@ +entry: + id: 1753 + title: "maximum-score-from-removing-stones" + params: + a: + type: int + b: + type: int + c: + type: int + call: + cpp: "Solution().maximumScore({a}, {b}, {c})" + rust: "Solution::maximum_score({a}, {b}, {c})" + python3: "Solution().maximumScore({a}, {b}, {c})" + python2: "Solution().maximumScore({a}, {b}, {c})" + ruby: "maximum_score({a}, {b}, {c})" + java: "new Solution().maximumScore({a}, {b}, {c})" + csharp: "new Solution().MaximumScore({a}, {b}, {c})" + kotlin: "Solution().maximumScore({a}, {b}, {c})" + go: "maximumScore({a}, {b}, {c})" + dart: "Solution().maximumScore({a}, {b}, {c})" + swift: "Solution().maximumScore({a}, {b}, {c})" + typescript: "maximumScore({a}, {b}, {c})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maximumScore(a, b, c, {result})" + checker: | + class Checker: + def maximumScore(self, a, b, c, result): + expected = min(a + b + c - max(a, b, c), (a + b + c) // 2) + return result == expected + +seed: 1753 + +tests: + - name: "minimum-all-one" + in: + a: 1 + b: 1 + c: 1 + out: 1 + - name: "one-pile-dominates" + in: + a: 1 + b: 1 + c: 100000 + out: 2 + - name: "balanced-small" + in: + a: 2 + b: 2 + c: 2 + out: 3 + - name: "example-one" + in: + a: 2 + b: 4 + c: 6 + out: 6 + - name: "example-two" + in: + a: 4 + b: 4 + c: 6 + out: 7 + - name: "example-three" + in: + a: 1 + b: 8 + c: 8 + out: 8 + - name: "small-even-near-balanced" + in: + a: 2 + b: 3 + c: 3 + out: 4 + - name: "ascending-near-equal" + in: + a: 3 + b: 4 + c: 5 + out: 6 + - name: "descending-near-equal" + in: + a: 5 + b: 4 + c: 3 + out: 6 + - name: "two-piles-equal" + in: + a: 7 + b: 7 + c: 1 + out: 7 + - name: "two-piles-with-extra" + in: + a: 7 + b: 7 + c: 2 + out: 8 + - name: "dominant-threshold" + in: + a: 3 + b: 4 + c: 10 + out: 7 + - name: "dominant-just-over" + in: + a: 3 + b: 4 + c: 8 + out: 7 + - name: "dominant-just-under" + in: + a: 3 + b: 4 + c: 6 + out: 6 + - name: "all-ten" + in: + a: 10 + b: 10 + c: 10 + out: 15 + - name: "powers-of-two" + in: + a: 16 + b: 8 + c: 4 + out: 12 + - name: "large-balanced" + in: + a: 100000 + b: 100000 + c: 100000 + out: 150000 + - name: "large-two-piles" + in: + a: 100000 + b: 100000 + c: 1 + out: 100000 + - name: "large-dominant" + in: + a: 1 + b: 99999 + c: 100000 + out: 100000 + - name: "large-dominant-overflow" + in: + a: 50000 + b: 50000 + c: 100000 + out: 100000 + - name: "odd-total-balanced" + in: + a: 5 + b: 6 + c: 7 + out: 9 + - name: "even-total-balanced" + in: + a: 5 + b: 6 + c: 8 + out: 9 + - name: "one-one-medium" + in: + a: 1 + b: 1 + c: 50 + out: 2 + - name: "small-skew" + in: + a: 1 + b: 2 + c: 3 + out: 3 + - name: "medium-skew" + in: + a: 9 + b: 1 + c: 1 + out: 2 + - name: "medium-skew-two" + in: + a: 9 + b: 2 + c: 2 + out: 4 + - name: "equal-four" + in: + a: 4 + b: 4 + c: 4 + out: 6 + - name: "equal-five" + in: + a: 5 + b: 5 + c: 5 + out: 7 + - name: "close-large" + in: + a: 99998 + b: 99999 + c: 100000 + out: 149998 + - name: "two-small-one-large" + in: + a: 12 + b: 13 + c: 100 + out: 25 + - name: "mixed-values" + in: + a: 17 + b: 29 + c: 41 + out: 43 + - name: "generator-small" + in: + a: + gen: "int" + min: 1 + max: 100 + b: + gen: "int" + min: 1 + max: 100 + c: + gen: "int" + min: 1 + max: 100 + seed: 175301 + - name: "generator-medium" + in: + a: + gen: "int" + min: 1 + max: 10000 + b: + gen: "int" + min: 1 + max: 10000 + c: + gen: "int" + min: 1 + max: 10000 + seed: 175302 + - name: "generator-large" + in: + a: + gen: "int" + min: 1 + max: 100000 + b: + gen: "int" + min: 1 + max: 100000 + c: + gen: "int" + min: 1 + max: 100000 + seed: 175303 + - name: "generator-large-skew-capable" + in: + a: + gen: "int" + min: 1 + max: 100000 + b: + gen: "int" + min: 1 + max: 100000 + c: + gen: "int" + min: 1 + max: 100000 + seed: 175304 + - name: "generator-boundary" + in: + a: + gen: "int" + min: 99900 + max: 100000 + b: + gen: "int" + min: 99900 + max: 100000 + c: + gen: "int" + min: 99900 + max: 100000 + seed: 175305 diff --git a/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.cpp b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.cpp new file mode 100644 index 00000000..53103130 --- /dev/null +++ b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.cpp @@ -0,0 +1,7 @@ +class Solution { +public: + int maximumScore(int a, int b, int c) { + int sum = a + b + c; + return min(sum - max(a, max(b, c)), sum / 2); + } +}; diff --git a/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.cs b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.cs new file mode 100644 index 00000000..a527012c --- /dev/null +++ b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.cs @@ -0,0 +1,6 @@ +public class Solution { + public int MaximumScore(int a, int b, int c) { + int sum = a + b + c; + return Math.Min(sum - Math.Max(a, Math.Max(b, c)), sum / 2); + } +} diff --git a/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.dart b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.dart new file mode 100644 index 00000000..a46ee9d4 --- /dev/null +++ b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.dart @@ -0,0 +1,8 @@ +class Solution { + int maximumScore(int a, int b, int c) { + int sum = a + b + c; + return (sum - [a, b, c].reduce((x, y) => x > y ? x : y)) < (sum ~/ 2) + ? sum - [a, b, c].reduce((x, y) => x > y ? x : y) + : sum ~/ 2; + } +} diff --git a/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.go b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.go new file mode 100644 index 00000000..d435ed7b --- /dev/null +++ b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.go @@ -0,0 +1,14 @@ +func maximumScore(a int, b int, c int) int { + sum := a + b + c + max := a + if b > max { + max = b + } + if c > max { + max = c + } + if sum - max < sum / 2 { + return sum - max + } + return sum / 2 +} diff --git a/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.java b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.java new file mode 100644 index 00000000..c878e95a --- /dev/null +++ b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.java @@ -0,0 +1,6 @@ +class Solution { + public int maximumScore(int a, int b, int c) { + int sum = a + b + c; + return Math.min(sum - Math.max(a, Math.max(b, c)), sum / 2); + } +} diff --git a/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.kt b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.kt new file mode 100644 index 00000000..cb56d9c9 --- /dev/null +++ b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.kt @@ -0,0 +1,6 @@ +class Solution { + fun maximumScore(a: Int, b: Int, c: Int): Int { + val sum = a + b + c + return minOf(sum - maxOf(a, b, c), sum / 2) + } +} diff --git a/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.py b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.py new file mode 100644 index 00000000..21e97f1d --- /dev/null +++ b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.py @@ -0,0 +1,3 @@ +class Solution: + def maximumScore(self, a: int, b: int, c: int) -> int: + return min(a + b + c - max(a, b, c), (a + b + c) // 2) diff --git a/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.py2 b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.py2 new file mode 100644 index 00000000..3b87a036 --- /dev/null +++ b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.py2 @@ -0,0 +1,9 @@ +class Solution(object): + def maximumScore(self, a, b, c): + """ + :type a: int + :type b: int + :type c: int + :rtype: int + """ + return min(a + b + c - max(a, b, c), (a + b + c) // 2) diff --git a/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.rb b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.rb new file mode 100644 index 00000000..2741c3bf --- /dev/null +++ b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.rb @@ -0,0 +1,7 @@ +# @param {Integer} a +# @param {Integer} b +# @param {Integer} c +# @return {Integer} +def maximum_score(a, b, c) + [a + b + c - [a, b, c].max, (a + b + c) / 2].min +end diff --git a/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.rs b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.rs new file mode 100644 index 00000000..b19ab61a --- /dev/null +++ b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.rs @@ -0,0 +1,6 @@ +impl Solution { + pub fn maximum_score(a: i32, b: i32, c: i32) -> i32 { + let sum = a + b + c; + std::cmp::min(sum - std::cmp::max(a, std::cmp::max(b, c)), sum / 2) + } +} diff --git a/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.swift b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.swift new file mode 100644 index 00000000..6fb1c633 --- /dev/null +++ b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.swift @@ -0,0 +1,6 @@ +class Solution { + func maximumScore(_ a: Int, _ b: Int, _ c: Int) -> Int { + let sum = a + b + c + return min(sum - max(a, b, c), sum / 2) + } +} diff --git a/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.ts b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.ts new file mode 100644 index 00000000..64d29ebe --- /dev/null +++ b/tests/1501-2000/1753. maximum-score-from-removing-stones/sol.ts @@ -0,0 +1,4 @@ +function maximumScore(a: number, b: number, c: number): number { + const sum = a + b + c; + return Math.min(sum - Math.max(a, b, c), Math.floor(sum / 2)); +} diff --git a/tests/1501-2000/1754. largest-merge-of-two-strings/manifest.yaml b/tests/1501-2000/1754. largest-merge-of-two-strings/manifest.yaml new file mode 100644 index 00000000..262259e6 --- /dev/null +++ b/tests/1501-2000/1754. largest-merge-of-two-strings/manifest.yaml @@ -0,0 +1,262 @@ +entry: + id: 1754 + title: "largest-merge-of-two-strings" + params: + word1: + type: string + word2: + type: string + call: + cpp: "Solution().largestMerge({word1}, {word2})" + rust: "Solution::largest_merge({word1}, {word2})" + python3: "Solution().largestMerge({word1}, {word2})" + python2: "Solution().largestMerge({word1}, {word2})" + ruby: "largest_merge({word1}, {word2})" + java: "new Solution().largestMerge({word1}, {word2})" + csharp: "new Solution().LargestMerge({word1}, {word2})" + kotlin: "Solution().largestMerge({word1}, {word2})" + go: "largestMerge({word1}, {word2})" + dart: "Solution().largestMerge({word1}, {word2})" + swift: "Solution().largestMerge({word1}, {word2})" + typescript: "largestMerge({word1}, {word2})" + +judge: + type: "exact" + +limits: + time_ms: 5000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().largestMerge(word1, word2, {result})" + checker: | + class Checker: + def largestMerge(self, word1, word2, result): + i = 0 + j = 0 + expected = [] + while i < len(word1) and j < len(word2): + if word1[i:] >= word2[j:]: + expected.append(word1[i]) + i += 1 + else: + expected.append(word2[j]) + j += 1 + expected.extend(word1[i:]) + expected.extend(word2[j:]) + return result == ''.join(expected) + +seed: 1754 + +tests: + - name: example-one + in: + word1: "cabaa" + word2: "bcaaa" + out: "cbcabaaaaa" + - name: example-two + in: + word1: "abcabc" + word2: "abdcaba" + out: "abdcabcabcaba" + - name: one-character-greater + in: + word1: "b" + word2: "a" + out: "ba" + - name: one-character-less + in: + word1: "a" + word2: "b" + out: "ba" + - name: equal-singletons + in: + word1: "a" + word2: "a" + out: "aa" + - name: word1-empty-not-allowed + in: + word1: "z" + word2: "a" + out: "za" + - name: reverse-alphabet + in: + word1: "abc" + word2: "xyz" + out: "xyzabc" + - name: alternating-letters + in: + word1: "abab" + word2: "baba" + out: "babababa" + - name: long-equal-prefix-word1-wins + in: + word1: "abcz" + word2: "abcx" + out: "abczabcx" + - name: long-equal-prefix-word2-wins + in: + word1: "abcx" + word2: "abcz" + out: "abczabcx" + - name: repeated-a + in: + word1: "aaaa" + word2: "aaa" + out: "aaaaaaa" + - name: repeated-z + in: + word1: "zz" + word2: "zzz" + out: "zzzzz" + - name: suffix-decides + in: + word1: "ba" + word2: "b" + out: "bba" + - name: suffix-decides-other + in: + word1: "b" + word2: "ba" + out: "bba" + - name: nested-choice + in: + word1: "cac" + word2: "caa" + out: "ccacaa" + - name: all-different + in: + word1: "ace" + word2: "bdf" + out: "bdface" + - name: descending-word1 + in: + word1: "zyx" + word2: "abc" + out: "zyxabc" + - name: descending-word2 + in: + word1: "abc" + word2: "zyx" + out: "zyxabc" + - name: shared-middle + in: + word1: "azaz" + word2: "azay" + out: "azazazay" + - name: repeated-prefix + in: + word1: "ababac" + word2: "ababab" + out: "ababacababab" + - name: short-and-long + in: + word1: "m" + word2: "lmnop" + out: "mlmnop" + - name: long-and-short + in: + word1: "mnopq" + word2: "m" + out: "mnopqm" + - name: mixed-case-lower + in: + word1: "azby" + word2: "aybz" + out: "azbyaybz" + - name: four-way-tie + in: + word1: "aaaa" + word2: "aaaa" + out: "aaaaaaaa" + - name: high-tail + in: + word1: "ccca" + word2: "cccz" + out: "ccczccca" + - name: alternating-high + in: + word1: "azazaz" + word2: "zazaza" + out: "zazazazazaza" + - name: boundary-b + in: + word1: "bba" + word2: "bab" + out: "bbbaba" + - name: palindrome-like + in: + word1: "abcba" + word2: "bacab" + out: "bacabcbaba" + - name: numeric-looking-letters + in: + word1: "mnop" + word2: "mnoq" + out: "mnoqmnop" + - name: one-word-dominates + in: + word1: "zxywv" + word2: "abcde" + out: "zxywvabcde" + - name: tie-then-tail + in: + word1: "aaaaab" + word2: "aaaaac" + out: "aaaaacaaaaab" + - name: generator-small + in: + word1: + gen: "str" + len: 1 + alphabet: "abcz" + word2: + gen: "str" + len: 1 + alphabet: "abcz" + seed: 175401 + - name: generator-medium + in: + word1: + gen: "str" + len: 20 + alphabet: "abcde" + word2: + gen: "str" + len: 23 + alphabet: "abcde" + seed: 175402 + - name: generator-ties + in: + word1: + gen: "str" + len: 100 + alphabet: "ab" + word2: + gen: "str" + len: 100 + alphabet: "ab" + seed: 175403 + - name: generator-large + in: + word1: + gen: "str" + len: 1000 + alphabet: "amz" + word2: + gen: "str" + len: 1000 + alphabet: "amz" + seed: 175404 + - name: generator-maximum + in: + word1: + gen: "str" + len: 3000 + alphabet: "abyz" + word2: + gen: "str" + len: 3000 + alphabet: "abyz" + seed: 175405 diff --git a/tests/1501-2000/1754. largest-merge-of-two-strings/sol.cpp b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.cpp new file mode 100644 index 00000000..26697328 --- /dev/null +++ b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + string largestMerge(string word1, string word2) { + string res; + int i = 0, j = 0; + while (i < word1.length() && j < word2.length()) { + if (word1[i] > word2[j]) { + res += word1[i]; + i++; + } else if (word1[i] < word2[j]) { + res += word2[j]; + j++; + } else { + int p = i, q = j; + while (p < word1.length() && q < word2.length() && word1[p] == word2[q]) { + p++; + q++; + } + if (q == word2.length() || (p < word1.length() && word1[p] > word2[q])) { + res += word1[i]; + i++; + } else { + res += word2[j]; + j++; + } + } + } + while (i < word1.length()) { + res += word1[i]; + i++; + } + while (j < word2.length()) { + res += word2[j]; + j++; + } + return res; + } +}; diff --git a/tests/1501-2000/1754. largest-merge-of-two-strings/sol.cs b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.cs new file mode 100644 index 00000000..69662e5b --- /dev/null +++ b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.cs @@ -0,0 +1,37 @@ +public class Solution { + public string LargestMerge(string word1, string word2) { + var res = new StringBuilder(); + int i = 0, j = 0; + while (i < word1.Length && j < word2.Length) { + if (word1[i] > word2[j]) { + res.Append(word1[i]); + i++; + } else if (word1[i] < word2[j]) { + res.Append(word2[j]); + j++; + } else { + int p = i, q = j; + while (p < word1.Length && q < word2.Length && word1[p] == word2[q]) { + p++; + q++; + } + if (q == word2.Length || (p < word1.Length && word1[p] > word2[q])) { + res.Append(word1[i]); + i++; + } else { + res.Append(word2[j]); + j++; + } + } + } + while (i < word1.Length) { + res.Append(word1[i]); + i++; + } + while (j < word2.Length) { + res.Append(word2[j]); + j++; + } + return res.ToString(); + } +} diff --git a/tests/1501-2000/1754. largest-merge-of-two-strings/sol.dart b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.dart new file mode 100644 index 00000000..3a63f72b --- /dev/null +++ b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.dart @@ -0,0 +1,37 @@ +class Solution { + String largestMerge(String word1, String word2) { + final StringBuffer res = StringBuffer(); + int i = 0, j = 0; + while (i < word1.length && j < word2.length) { + if (word1.codeUnitAt(i) > word2.codeUnitAt(j)) { + res.writeCharCode(word1.codeUnitAt(i)); + i++; + } else if (word1.codeUnitAt(i) < word2.codeUnitAt(j)) { + res.writeCharCode(word2.codeUnitAt(j)); + j++; + } else { + int p = i, q = j; + while (p < word1.length && q < word2.length && word1.codeUnitAt(p) == word2.codeUnitAt(q)) { + p++; + q++; + } + if (q == word2.length || (p < word1.length && word1.codeUnitAt(p) > word2.codeUnitAt(q))) { + res.writeCharCode(word1.codeUnitAt(i)); + i++; + } else { + res.writeCharCode(word2.codeUnitAt(j)); + j++; + } + } + } + while (i < word1.length) { + res.writeCharCode(word1.codeUnitAt(i)); + i++; + } + while (j < word2.length) { + res.writeCharCode(word2.codeUnitAt(j)); + j++; + } + return res.toString(); + } +} diff --git a/tests/1501-2000/1754. largest-merge-of-two-strings/sol.go b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.go new file mode 100644 index 00000000..53ad8936 --- /dev/null +++ b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.go @@ -0,0 +1,35 @@ +func largestMerge(word1 string, word2 string) string { + res := []byte{} + i, j := 0, 0 + for i < len(word1) && j < len(word2) { + if word1[i] > word2[j] { + res = append(res, word1[i]) + i++ + } else if word1[i] < word2[j] { + res = append(res, word2[j]) + j++ + } else { + p, q := i, j + for p < len(word1) && q < len(word2) && word1[p] == word2[q] { + p++ + q++ + } + if q == len(word2) || (p < len(word1) && word1[p] > word2[q]) { + res = append(res, word1[i]) + i++ + } else { + res = append(res, word2[j]) + j++ + } + } + } + for i < len(word1) { + res = append(res, word1[i]) + i++ + } + for j < len(word2) { + res = append(res, word2[j]) + j++ + } + return string(res) +} diff --git a/tests/1501-2000/1754. largest-merge-of-two-strings/sol.java b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.java new file mode 100644 index 00000000..7b68039f --- /dev/null +++ b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.java @@ -0,0 +1,37 @@ +class Solution { + public String largestMerge(String word1, String word2) { + StringBuilder res = new StringBuilder(); + int i = 0, j = 0; + while (i < word1.length() && j < word2.length()) { + if (word1.charAt(i) > word2.charAt(j)) { + res.append(word1.charAt(i)); + i++; + } else if (word1.charAt(i) < word2.charAt(j)) { + res.append(word2.charAt(j)); + j++; + } else { + int p = i, q = j; + while (p < word1.length() && q < word2.length() && word1.charAt(p) == word2.charAt(q)) { + p++; + q++; + } + if (q == word2.length() || (p < word1.length() && word1.charAt(p) > word2.charAt(q))) { + res.append(word1.charAt(i)); + i++; + } else { + res.append(word2.charAt(j)); + j++; + } + } + } + while (i < word1.length()) { + res.append(word1.charAt(i)); + i++; + } + while (j < word2.length()) { + res.append(word2.charAt(j)); + j++; + } + return res.toString(); + } +} diff --git a/tests/1501-2000/1754. largest-merge-of-two-strings/sol.kt b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.kt new file mode 100644 index 00000000..01f6225f --- /dev/null +++ b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.kt @@ -0,0 +1,39 @@ +class Solution { + fun largestMerge(word1: String, word2: String): String { + val res = StringBuilder() + var i = 0 + var j = 0 + while (i < word1.length && j < word2.length) { + if (word1[i] > word2[j]) { + res.append(word1[i]) + i++ + } else if (word1[i] < word2[j]) { + res.append(word2[j]) + j++ + } else { + var p = i + var q = j + while (p < word1.length && q < word2.length && word1[p] == word2[q]) { + p++ + q++ + } + if (q == word2.length || (p < word1.length && word1[p] > word2[q])) { + res.append(word1[i]) + i++ + } else { + res.append(word2[j]) + j++ + } + } + } + while (i < word1.length) { + res.append(word1[i]) + i++ + } + while (j < word2.length) { + res.append(word2[j]) + j++ + } + return res.toString() + } +} diff --git a/tests/1501-2000/1754. largest-merge-of-two-strings/sol.py b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.py new file mode 100644 index 00000000..8584d0f9 --- /dev/null +++ b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.py @@ -0,0 +1,35 @@ +class Solution(object): + def largestMerge(self, word1, word2): + res = [] + i, j = 0, 0 + while i < len(word1) and j < len(word2): + if word1[i] > word2[j]: + res.append(word1[i]) + i += 1 + elif word1[i] < word2[j]: + res.append(word2[j]) + j += 1 + else: + p, q = i, j + while p < len(word1) and q < len(word2) and word1[p] == word2[q]: + p += 1 + q += 1 + if q == len(word2) or (p < len(word1) and word1[p] > word2[q]): + res.append(word1[i]) + i += 1 + else: + res.append(word2[j]) + j += 1 + + while i < len(word1): + res += word1[i] + i += 1 + while j < len(word2): + res += word2[j] + j += 1 + return "".join(res) + """ + :type word1: str + :type word2: str + :rtype: str + """ diff --git a/tests/1501-2000/1754. largest-merge-of-two-strings/sol.py2 b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.py2 new file mode 100644 index 00000000..816f01a2 --- /dev/null +++ b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.py2 @@ -0,0 +1,29 @@ +class Solution(object): + def largestMerge(self, word1, word2): + res = [] + i,j = 0,0 + while i < len(word1) and j < len(word2): + if word1[i] > word2[j]: + res.append(word1[i]) + i += 1 + elif word1[i] < word2[j]: + res.append(word2[j]) + j += 1 + else: + p,q = i,j + while p < len(word1) and q < len(word2) and word1[p] == word2[q]: + p += 1 + q += 1 + if q == len(word2) or (p < len(word1) and word1[p] > word2[q]): + res.append(word1[i]) + i += 1 + else: + res.append(word2[j]) + j += 1 + while i < len(word1): + res.append(word1[i]) + i += 1 + while j < len(word2): + res.append(word2[j]) + j += 1 + return ''.join(res) diff --git a/tests/1501-2000/1754. largest-merge-of-two-strings/sol.rb b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.rb new file mode 100644 index 00000000..b8884bee --- /dev/null +++ b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.rb @@ -0,0 +1,40 @@ +# @param {String} word1 +# @param {String} word2 +# @return {String} +def largest_merge(word1, word2) + res = [] + i = 0 + j = 0 + while i < word1.length && j < word2.length + if word1[i] > word2[j] + res << word1[i] + i += 1 + elsif word1[i] < word2[j] + res << word2[j] + j += 1 + else + p = i + q = j + while p < word1.length && q < word2.length && word1[p] == word2[q] + p += 1 + q += 1 + end + if q == word2.length || (p < word1.length && word1[p] > word2[q]) + res << word1[i] + i += 1 + else + res << word2[j] + j += 1 + end + end + end + while i < word1.length + res << word1[i] + i += 1 + end + while j < word2.length + res << word2[j] + j += 1 + end + res.join +end diff --git a/tests/1501-2000/1754. largest-merge-of-two-strings/sol.rs b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.rs new file mode 100644 index 00000000..a059ad8a --- /dev/null +++ b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.rs @@ -0,0 +1,41 @@ +impl Solution { + pub fn largest_merge(word1: String, word2: String) -> String { + let w1: Vec = word1.chars().collect(); + let w2: Vec = word2.chars().collect(); + let mut res = String::new(); + let mut i = 0; + let mut j = 0; + while i < w1.len() && j < w2.len() { + if w1[i] > w2[j] { + res.push(w1[i]); + i += 1; + } else if w1[i] < w2[j] { + res.push(w2[j]); + j += 1; + } else { + let mut p = i; + let mut q = j; + while p < w1.len() && q < w2.len() && w1[p] == w2[q] { + p += 1; + q += 1; + } + if q == w2.len() || (p < w1.len() && w1[p] > w2[q]) { + res.push(w1[i]); + i += 1; + } else { + res.push(w2[j]); + j += 1; + } + } + } + while i < w1.len() { + res.push(w1[i]); + i += 1; + } + while j < w2.len() { + res.push(w2[j]); + j += 1; + } + res + } +} diff --git a/tests/1501-2000/1754. largest-merge-of-two-strings/sol.swift b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.swift new file mode 100644 index 00000000..c84495f8 --- /dev/null +++ b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.swift @@ -0,0 +1,39 @@ +class Solution { + func largestMerge(_ word1: String, _ word2: String) -> String { + var res = "" + var i = word1.startIndex + var j = word2.startIndex + while i < word1.endIndex && j < word2.endIndex { + if word1[i] > word2[j] { + res.append(word1[i]) + i = word1.index(after: i) + } else if word1[i] < word2[j] { + res.append(word2[j]) + j = word2.index(after: j) + } else { + var p = i + var q = j + while p < word1.endIndex && q < word2.endIndex && word1[p] == word2[q] { + p = word1.index(after: p) + q = word2.index(after: q) + } + if q == word2.endIndex || (p < word1.endIndex && word1[p] > word2[q]) { + res.append(word1[i]) + i = word1.index(after: i) + } else { + res.append(word2[j]) + j = word2.index(after: j) + } + } + } + while i < word1.endIndex { + res.append(word1[i]) + i = word1.index(after: i) + } + while j < word2.endIndex { + res.append(word2[j]) + j = word2.index(after: j) + } + return res + } +} diff --git a/tests/1501-2000/1754. largest-merge-of-two-strings/sol.ts b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.ts new file mode 100644 index 00000000..d87e74d0 --- /dev/null +++ b/tests/1501-2000/1754. largest-merge-of-two-strings/sol.ts @@ -0,0 +1,37 @@ +function largestMerge(word1: string, word2: string): string { + let res = ""; + let i = 0, + j = 0; + while (i < word1.length && j < word2.length) { + if (word1[i] > word2[j]) { + res += word1[i]; + i++; + } else if (word1[i] < word2[j]) { + res += word2[j]; + j++; + } else { + let p = i, + q = j; + while (p < word1.length && q < word2.length && word1[p] === word2[q]) { + p++; + q++; + } + if (q === word2.length || (p < word1.length && word1[p] > word2[q])) { + res += word1[i]; + i++; + } else { + res += word2[j]; + j++; + } + } + } + while (i < word1.length) { + res += word1[i]; + i++; + } + while (j < word2.length) { + res += word2[j]; + j++; + } + return res; +} diff --git a/tests/1501-2000/1755. closest-subsequence-sum/manifest.yaml b/tests/1501-2000/1755. closest-subsequence-sum/manifest.yaml new file mode 100644 index 00000000..d93cf8bb --- /dev/null +++ b/tests/1501-2000/1755. closest-subsequence-sum/manifest.yaml @@ -0,0 +1,275 @@ +entry: + id: 1755 + title: closest-subsequence-sum + params: + nums: + type: array + items: + type: int + goal: + type: int + call: + cpp: "Solution().minAbsDifference({nums}, {goal})" + rust: "Solution::min_abs_difference({nums}, {goal})" + python3: "Solution().minAbsDifference({nums}, {goal})" + python2: "Solution().minAbsDifference({nums}, {goal})" + ruby: "min_abs_difference({nums}, {goal})" + java: "new Solution().minAbsDifference({nums}, {goal})" + csharp: "new Solution().MinAbsDifference({nums}, {goal})" + kotlin: "Solution().minAbsDifference({nums}, {goal})" + go: "minAbsDifference({nums}, {goal})" + dart: "Solution().minAbsDifference({nums}, {goal})" + swift: "Solution().minAbsDifference({nums}, {goal})" + typescript: "minAbsDifference({nums}, {goal})" +judge: + type: exact +limits: + time_ms: 10000 + memory_mb: 512 +oracle: + python3: + call: "Checker().check(nums, goal, {result})" + checker: | + class Checker: + def check(self, nums, goal, result): + if not isinstance(result, int) or isinstance(result, bool) or result < 0: + return False + def sums(values): + out = [0] + for value in values: + out += [x + value for x in out] + return out + mid = len(nums) // 2 + left = sorted(sums(nums[:mid])) + right = sorted(sums(nums[mid:])) + best = abs(goal) + j = len(right) - 1 + for value in left: + while j > 0 and right[j - 1] >= goal - value: + j -= 1 + best = min(best, abs(value + right[j] - goal)) + if j > 0: + best = min(best, abs(value + right[j - 1] - goal)) + return result == best +seed: 1755 +tests: + - name: example-one + in: + nums: [5, -7, 3, 5] + goal: 6 + out: 0 + - name: example-two + in: + nums: [7, -9, 15, -2] + goal: -5 + out: 1 + - name: example-three + in: + nums: [1, 2, 3] + goal: -7 + out: 7 + - name: one-positive-hit + in: + nums: [8] + goal: 8 + out: 0 + - name: one-negative + in: + nums: [-8] + goal: 3 + out: 3 + - name: empty-subsequence-best + in: + nums: [4, 9] + goal: 0 + out: 0 + - name: all-negative + in: + nums: [-10, -4, -7] + goal: -12 + out: 1 + - name: all-positive + in: + nums: [2, 5, 11] + goal: 14 + out: 1 + - name: duplicates + in: + nums: [3, 3, 3, 3] + goal: 7 + out: 1 + - name: cancellation + in: + nums: [-5, 5, -5, 5] + goal: 1 + out: 1 + - name: exact-single + in: + nums: [12, -4, 9] + goal: -4 + out: 0 + - name: exact-combination + in: + nums: [6, 10, 15, -2] + goal: 13 + out: 0 + - name: far-positive-goal + in: + nums: [1, 2, 4] + goal: 100 + out: 93 + - name: far-negative-goal + in: + nums: [-1, -2, -4] + goal: -100 + out: 93 + - name: zero-values + in: + nums: [0, 0, 0] + goal: 5 + out: 5 + - name: large-values + in: + nums: [10000000, -10000000, 9999999] + goal: 1000000 + out: 1000000 + - name: mixed-six + in: + nums: [17, -23, 31, -11, 8, 4] + goal: 19 + out: 1 + - name: mixed-seven + in: + nums: [-20, 14, 6, 9, -3, 2, 1] + goal: -1 + out: 0 + - name: parity-gap + in: + nums: [2, 4, 8] + goal: 7 + out: 1 + - name: negative-and-zero + in: + nums: [-9, 0, 4] + goal: -6 + out: 1 + - name: powers + in: + nums: [1, 2, 4, 8, 16, 32] + goal: 37 + out: 0 + - name: repeated-negative + in: + nums: [-6, -6, -6, -6, -6] + goal: -17 + out: 1 + - name: narrow-near-goal + in: + nums: [101, -100, 51, -49] + goal: 2 + out: 0 + - name: large-goal + in: + nums: [10000000, 10000000, -1] + goal: 20000000 + out: 0 + - name: negative-large-goal + in: + nums: [-10000000, -10000000, 1] + goal: -19999999 + out: 0 + - name: eleven-mixed + in: + nums: [3, -1, 7, 12, -9, 4, 15, -6, 2, 8, -11] + goal: 20 + out: 0 + - name: twelve-mixed + in: + nums: [-5, 13, -8, 21, -3, 6, 10, -14, 2, 9, -1, 4] + goal: 33 + out: 0 + - name: generator-small + in: + nums: + gen: array + len: 20 + of: + gen: int + min: -10000000 + max: 10000000 + elemType: int + goal: + gen: int + min: -1000000000 + max: 1000000000 + - name: exact-powers + in: + nums: [1, 2, 4] + goal: 6 + out: 0 + - name: exact-negative-powers + in: + nums: [-1, -2, -4] + goal: -6 + out: 0 + - name: two-element-near + in: + nums: [5, 10] + goal: 12 + out: 2 + - name: generator-medium + in: + nums: + gen: array + len: 30 + of: + gen: int + min: -1000000 + max: 1000000 + elemType: int + goal: + gen: int + min: -1000000000 + max: 1000000000 + - name: generator-large-values + in: + nums: + gen: array + len: 40 + of: + gen: int + min: -10000000 + max: 10000000 + elemType: int + goal: + gen: int + min: -1000000000 + max: 1000000000 + - name: generator-biased-positive + in: + nums: + gen: array + len: 40 + of: + gen: int + min: 0 + max: 10000000 + elemType: int + goal: + gen: int + min: -1000000000 + max: 1000000000 + - name: generator-biased-negative + in: + nums: + gen: array + len: 40 + of: + gen: int + min: -10000000 + max: 0 + elemType: int + goal: + gen: int + min: -1000000000 + max: 1000000000 diff --git a/tests/1501-2000/1755. closest-subsequence-sum/sol.cpp b/tests/1501-2000/1755. closest-subsequence-sum/sol.cpp new file mode 100644 index 00000000..90598367 --- /dev/null +++ b/tests/1501-2000/1755. closest-subsequence-sum/sol.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int minAbsDifference(vector& nums, int goal) { + auto sums = [](const vector& values) { + vector result = {0}; + for (int value : values) { + int currentLen = result.size(); + for (int i = 0; i < currentLen; i++) { + result.push_back(result[i] + value); + } + } + return result; + }; + int mid = nums.size() / 2; + vector left = sums(vector(nums.begin(), nums.begin() + mid)); + vector right = sums(vector(nums.begin() + mid, nums.end())); + sort(left.begin(), left.end()); + sort(right.begin(), right.end()); + int answer = abs(goal); + int j = right.size() - 1; + for (int value : left) { + while (j > 0 && right[j - 1] >= goal - value) { + j--; + } + answer = min(answer, abs(value + right[j] - goal)); + if (j > 0) { + answer = min(answer, abs(value + right[j - 1] - goal)); + } + } + return answer; + } +}; diff --git a/tests/1501-2000/1755. closest-subsequence-sum/sol.cs b/tests/1501-2000/1755. closest-subsequence-sum/sol.cs new file mode 100644 index 00000000..b840d477 --- /dev/null +++ b/tests/1501-2000/1755. closest-subsequence-sum/sol.cs @@ -0,0 +1,31 @@ +public class Solution { + public int MinAbsDifference(int[] nums, int goal) { + Func> sums = (values) => { + var result = new List { 0 }; + foreach (var value in values) { + int currentLen = result.Count; + for (int i = 0; i < currentLen; i++) { + result.Add(result[i] + value); + } + } + return result; + }; + int mid = nums.Length / 2; + var left = sums(nums.Take(mid).ToArray()); + var right = sums(nums.Skip(mid).ToArray()); + left.Sort(); + right.Sort(); + int answer = Math.Abs(goal); + int j = right.Count - 1; + foreach (int value in left) { + while (j > 0 && right[j - 1] >= goal - value) { + j--; + } + answer = Math.Min(answer, Math.Abs(value + right[j] - goal)); + if (j > 0) { + answer = Math.Min(answer, Math.Abs(value + right[j - 1] - goal)); + } + } + return answer; + } +} diff --git a/tests/1501-2000/1755. closest-subsequence-sum/sol.dart b/tests/1501-2000/1755. closest-subsequence-sum/sol.dart new file mode 100644 index 00000000..f31f3f30 --- /dev/null +++ b/tests/1501-2000/1755. closest-subsequence-sum/sol.dart @@ -0,0 +1,30 @@ +class Solution { + int minAbsDifference(List nums, int goal) { + List sums(List values) { + List result = [0]; + for (int value in values) { + int currentLen = result.length; + for (int i = 0; i < currentLen; i++) { + result.add(result[i] + value); + } + } + return result; + } + + int mid = nums.length ~/ 2; + List left = sums(nums.sublist(0, mid))..sort(); + List right = sums(nums.sublist(mid))..sort(); + int answer = goal.abs(); + int j = right.length - 1; + for (int value in left) { + while (j > 0 && right[j - 1] >= goal - value) { + j--; + } + answer = [answer, (value + right[j] - goal).abs()].reduce((a, b) => a < b ? a : b); + if (j > 0) { + answer = [answer, (value + right[j - 1] - goal).abs()].reduce((a, b) => a < b ? a : b); + } + } + return answer; + } +} diff --git a/tests/1501-2000/1755. closest-subsequence-sum/sol.go b/tests/1501-2000/1755. closest-subsequence-sum/sol.go new file mode 100644 index 00000000..2f5bd71b --- /dev/null +++ b/tests/1501-2000/1755. closest-subsequence-sum/sol.go @@ -0,0 +1,43 @@ +func minAbsDifference(nums []int, goal int) int { + sums := func(values []int) []int { + result := []int{0} + for _, value := range values { + currentLen := len(result) + for i := 0; i < currentLen; i++ { + result = append(result, result[i]+value) + } + } + return result + } + mid := len(nums) / 2 + left := sums(nums[:mid]) + right := sums(nums[mid:]) + sort.Ints(left) + sort.Ints(right) + answer := abs(goal) + j := len(right) - 1 + for _, value := range left { + for j > 0 && right[j-1] >= goal-value { + j-- + } + answer = min(answer, abs(value+right[j]-goal)) + if j > 0 { + answer = min(answer, abs(value+right[j-1]-goal)) + } + } + return answer +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} diff --git a/tests/1501-2000/1755. closest-subsequence-sum/sol.java b/tests/1501-2000/1755. closest-subsequence-sum/sol.java new file mode 100644 index 00000000..ff5f936d --- /dev/null +++ b/tests/1501-2000/1755. closest-subsequence-sum/sol.java @@ -0,0 +1,32 @@ +class Solution { + public int minAbsDifference(int[] nums, int goal) { + java.util.List leftSums = new java.util.ArrayList<>(); + java.util.List rightSums = new java.util.ArrayList<>(); + int mid = nums.length / 2; + generateSums(nums, 0, mid, 0, leftSums); + generateSums(nums, mid, nums.length, 0, rightSums); + java.util.Collections.sort(leftSums); + java.util.Collections.sort(rightSums); + int answer = Math.abs(goal); + int j = rightSums.size() - 1; + for (int value : leftSums) { + while (j > 0 && rightSums.get(j - 1) >= goal - value) { + j--; + } + answer = Math.min(answer, Math.abs(value + rightSums.get(j) - goal)); + if (j > 0) { + answer = Math.min(answer, Math.abs(value + rightSums.get(j - 1) - goal)); + } + } + return answer; + } + + private void generateSums(int[] nums, int start, int end, int current, java.util.List result) { + if (start == end) { + result.add(current); + return; + } + generateSums(nums, start + 1, end, current, result); + generateSums(nums, start + 1, end, current + nums[start], result); + } +} diff --git a/tests/1501-2000/1755. closest-subsequence-sum/sol.kt b/tests/1501-2000/1755. closest-subsequence-sum/sol.kt new file mode 100644 index 00000000..865cee0d --- /dev/null +++ b/tests/1501-2000/1755. closest-subsequence-sum/sol.kt @@ -0,0 +1,29 @@ +class Solution { + fun minAbsDifference(nums: IntArray, goal: Int): Int { + fun sums(values: List): MutableList { + val result = mutableListOf(0) + for (value in values) { + val size = result.size + for (i in 0 until size) { + result.add(result[i] + value) + } + } + return result + } + val mid = nums.size / 2 + val left = sums(nums.take(mid)).sorted() + val right = sums(nums.drop(mid)).sorted() + var answer = Math.abs(goal) + var j = right.size - 1 + for (value in left) { + while (j > 0 && right[j - 1] >= goal - value) { + j-- + } + answer = Math.min(answer, Math.abs(value + right[j] - goal)) + if (j > 0) { + answer = Math.min(answer, Math.abs(value + right[j - 1] - goal)) + } + } + return answer + } +} diff --git a/tests/1501-2000/1755. closest-subsequence-sum/sol.py b/tests/1501-2000/1755. closest-subsequence-sum/sol.py new file mode 100644 index 00000000..0737dde1 --- /dev/null +++ b/tests/1501-2000/1755. closest-subsequence-sum/sol.py @@ -0,0 +1,20 @@ +class Solution: + def minAbsDifference(self, nums, goal): + def sums(values): + result = [0] + for value in values: + result += [x + value for x in result] + return result + + mid = len(nums) // 2 + left = sorted(sums(nums[:mid])) + right = sorted(sums(nums[mid:])) + answer = abs(goal) + j = len(right) - 1 + for value in left: + while j > 0 and right[j - 1] >= goal - value: + j -= 1 + answer = min(answer, abs(value + right[j] - goal)) + if j > 0: + answer = min(answer, abs(value + right[j - 1] - goal)) + return answer diff --git a/tests/1501-2000/1755. closest-subsequence-sum/sol.py2 b/tests/1501-2000/1755. closest-subsequence-sum/sol.py2 new file mode 100644 index 00000000..72511059 --- /dev/null +++ b/tests/1501-2000/1755. closest-subsequence-sum/sol.py2 @@ -0,0 +1,24 @@ +class Solution(object): + def minAbsDifference(self, nums, goal): + """ + :type nums: List[int] + :type goal: int + :rtype: int + """ + def sums(values): + result = [0] + for value in values: + result += [x + value for x in result] + return result + mid = len(nums) // 2 + left = sorted(sums(nums[:mid])) + right = sorted(sums(nums[mid:])) + answer = abs(goal) + j = len(right) - 1 + for value in left: + while j > 0 and right[j - 1] >= goal - value: + j -= 1 + answer = min(answer, abs(value + right[j] - goal)) + if j > 0: + answer = min(answer, abs(value + right[j - 1] - goal)) + return answer diff --git a/tests/1501-2000/1755. closest-subsequence-sum/sol.rb b/tests/1501-2000/1755. closest-subsequence-sum/sol.rb new file mode 100644 index 00000000..a4975f04 --- /dev/null +++ b/tests/1501-2000/1755. closest-subsequence-sum/sol.rb @@ -0,0 +1,27 @@ +# @param {Integer[]} nums +# @param {Integer} goal +# @return {Integer} +def min_abs_difference(nums, goal) + sums = lambda do |values| + result = [0] + values.each do |value| + result += result.map { |x| x + value } + end + result + end + mid = nums.length / 2 + left = sums.call(nums[0...mid]).sort + right = sums.call(nums[mid..-1]).sort + answer = (goal).abs + j = right.length - 1 + left.each do |value| + while j > 0 && right[j - 1] >= goal - value + j -= 1 + end + answer = [answer, (value + right[j] - goal).abs].min + if j > 0 + answer = [answer, (value + right[j - 1] - goal).abs].min + end + end + answer +end diff --git a/tests/1501-2000/1755. closest-subsequence-sum/sol.rs b/tests/1501-2000/1755. closest-subsequence-sum/sol.rs new file mode 100644 index 00000000..cdf304bc --- /dev/null +++ b/tests/1501-2000/1755. closest-subsequence-sum/sol.rs @@ -0,0 +1,31 @@ +impl Solution { + pub fn min_abs_difference(nums: Vec, goal: i32) -> i32 { + fn sums(values: &[i32]) -> Vec { + let mut result = vec![0]; + for &value in values { + let current_len = result.len(); + for i in 0..current_len { + result.push(result[i] + value); + } + } + result + } + let mid = nums.len() / 2; + let mut left = sums(&nums[..mid]); + let mut right = sums(&nums[mid..]); + left.sort(); + right.sort(); + let mut answer = (goal).abs(); + let mut j = right.len() - 1; + for &value in &left { + while j > 0 && right[j - 1] >= goal - value { + j -= 1; + } + answer = answer.min((value + right[j] - goal).abs()); + if j > 0 { + answer = answer.min((value + right[j - 1] - goal).abs()); + } + } + answer + } +} diff --git a/tests/1501-2000/1755. closest-subsequence-sum/sol.swift b/tests/1501-2000/1755. closest-subsequence-sum/sol.swift new file mode 100644 index 00000000..489c7f2e --- /dev/null +++ b/tests/1501-2000/1755. closest-subsequence-sum/sol.swift @@ -0,0 +1,29 @@ +class Solution { + func minAbsDifference(_ nums: [Int], _ goal: Int) -> Int { + func sums(_ values: [Int]) -> [Int] { + var result = [0] + for value in values { + let currentCount = result.count + for i in 0.. 0 && right[j - 1] >= goal - value { + j -= 1 + } + answer = min(answer, abs(value + right[j] - goal)) + if j > 0 { + answer = min(answer, abs(value + right[j - 1] - goal)) + } + } + return answer + } +} diff --git a/tests/1501-2000/1755. closest-subsequence-sum/sol.ts b/tests/1501-2000/1755. closest-subsequence-sum/sol.ts new file mode 100644 index 00000000..aa7662e5 --- /dev/null +++ b/tests/1501-2000/1755. closest-subsequence-sum/sol.ts @@ -0,0 +1,27 @@ +function minAbsDifference(nums: number[], goal: number): number { + const sums = (values: number[]): number[] => { + const result: number[] = [0]; + for (const value of values) { + const currentLen = result.length; + for (let i = 0; i < currentLen; i++) { + result.push(result[i] + value); + } + } + return result; + }; + const mid = Math.floor(nums.length / 2); + const left = sums(nums.slice(0, mid)).sort((a, b) => a - b); + const right = sums(nums.slice(mid)).sort((a, b) => a - b); + let answer = Math.abs(goal); + let j = right.length - 1; + for (const value of left) { + while (j > 0 && right[j - 1] >= goal - value) { + j--; + } + answer = Math.min(answer, Math.abs(value + right[j] - goal)); + if (j > 0) { + answer = Math.min(answer, Math.abs(value + right[j - 1] - goal)); + } + } + return answer; +} diff --git a/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/manifest.yaml b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/manifest.yaml new file mode 100644 index 00000000..ea734adf --- /dev/null +++ b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/manifest.yaml @@ -0,0 +1,219 @@ +entry: + id: 1758 + title: "minimum-changes-to-make-alternating-binary-string" + params: + s: + type: string + call: + cpp: "Solution().minOperations({s})" + rust: "Solution::min_operations({s})" + python3: "Solution().minOperations({s})" + python2: "Solution().minOperations({s})" + ruby: "min_operations({s})" + java: "new Solution().minOperations({s})" + csharp: "new Solution().MinOperations({s})" + kotlin: "Solution().minOperations({s})" + go: "minOperations({s})" + dart: "Solution().minOperations({s})" + swift: "Solution().minOperations({s})" + typescript: "minOperations({s})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minOperations(s, {result})" + checker: | + class Checker: + def minOperations(self, s, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not isinstance(s, str) or not (1 <= len(s) <= 10000): + return False + mismatches = 0 + for i, ch in enumerate(s): + if ch == str(i % 2): + mismatches += 1 + return result == min(mismatches, len(s) - mismatches) + +seed: 1758 + +tests: + - name: example-0100 + in: + s: "0100" + out: 1 + - name: example-10 + in: + s: "10" + out: 0 + - name: example-1111 + in: + s: "1111" + out: 2 + - name: single-zero + in: + s: "0" + out: 0 + - name: single-one + in: + s: "1" + out: 0 + - name: alternating-even-zero-first + in: + s: "0101010101" + out: 0 + - name: alternating-even-one-first + in: + s: "1010101010" + out: 0 + - name: alternating-odd-zero-first + in: + s: "0101010" + out: 0 + - name: alternating-odd-one-first + in: + s: "1010101" + out: 0 + - name: all-zero-two + in: + s: "00" + out: 1 + - name: all-one-three + in: + s: "111" + out: 1 + - name: all-zero-ten + in: + s: "0000000000" + out: 5 + - name: all-one-nine + in: + s: "111111111" + out: 4 + - name: one-flip-from-alternating + in: + s: "0110101" + out: 2 + - name: two-flips-from-alternating + in: + s: "11001010" + out: 2 + - name: repeated-pairs-zero-first + in: + s: "00110011" + out: 4 + - name: repeated-pairs-one-first + in: + s: "11001100" + out: 4 + - name: runs-at-ends + in: + s: "0010100" + out: 2 + - name: central-run + in: + s: "01000101" + out: 1 + - name: mostly-zero + in: + s: "0001000001" + out: 3 + - name: mostly-one + in: + s: "1110111110" + out: 3 + - name: palindrome-even + in: + s: "01100110" + out: 4 + - name: palindrome-odd + in: + s: "0100010" + out: 1 + - name: alternating-prefix-bad-suffix + in: + s: "010101111" + out: 2 + - name: alternating-suffix-bad-prefix + in: + s: "000101010" + out: 1 + - name: boundary-single-mismatch + in: + s: "1010101001" + out: 2 + - name: balanced-mismatches + in: + s: "00110100" + out: 3 + - name: long-zero-run + in: + s: "010000000101010" + out: 3 + - name: long-one-run + in: + s: "101111111010101" + out: 3 + - name: alternating-with-end-changes + in: + s: "1101010110" + out: 3 + - name: asymmetric-runs + in: + s: "000111000111" + out: 4 + - name: near-max-pattern + in: + s: "01010101010101010101010101010101010101010101010101" + out: 0 + - name: near-max-inverted-pattern + in: + s: "10101010101010101010101010101010101010101010101010" + out: 0 + - name: alternating-block-boundary + in: + s: "0101010110101010" + out: 8 + - name: alternating-with-two-adjacent-errors + in: + s: "101011001010" + out: 2 + - name: generator-all-zero + in: + s: + gen: "str" + len: 10000 + alphabet: "0" + - name: generator-all-one + in: + s: + gen: "str" + len: 9999 + alphabet: "1" + - name: generator-binary-random-a + in: + s: + gen: "str" + len: 10000 + alphabet: "01" + seed: 1758003 + - name: generator-binary-random-b + in: + s: + gen: "str" + len: 9998 + alphabet: "01" + seed: 1758004 + - name: generator-binary-random-c + in: + s: + gen: "str" + len: 8191 + alphabet: "01" + seed: 1758005 diff --git a/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.cpp b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.cpp new file mode 100644 index 00000000..a8ec93b6 --- /dev/null +++ b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int minOperations(string s) { + int c = 0, j = 0, n = s.length(); + for (char ch : s) { + if (ch - '0' == j) { + c++; + } + j ^= 1; + } + return min(c, n - c); + } +}; diff --git a/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.cs b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.cs new file mode 100644 index 00000000..49189858 --- /dev/null +++ b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.cs @@ -0,0 +1,12 @@ +public class Solution { + public int MinOperations(string s) { + int c = 0, j = 0, n = s.Length; + foreach (char ch in s) { + if (ch - '0' == j) { + c++; + } + j ^= 1; + } + return Math.Min(c, n - c); + } +} diff --git a/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.dart b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.dart new file mode 100644 index 00000000..3afc0a14 --- /dev/null +++ b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.dart @@ -0,0 +1,12 @@ +class Solution { + int minOperations(String s) { + int c = 0, j = 0, n = s.length; + for (int i = 0; i < n; i++) { + if (s.codeUnitAt(i) - 48 == j) { + c++; + } + j ^= 1; + } + return c < n - c ? c : n - c; + } +} diff --git a/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.go b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.go new file mode 100644 index 00000000..fa01b117 --- /dev/null +++ b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.go @@ -0,0 +1,15 @@ +func minOperations(s string) int { + c := 0 + j := 0 + n := len(s) + for _, ch := range s { + if int(ch-'0') == j { + c++ + } + j ^= 1 + } + if c < n-c { + return c + } + return n - c +} diff --git a/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.java b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.java new file mode 100644 index 00000000..b8e2e22c --- /dev/null +++ b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.java @@ -0,0 +1,12 @@ +class Solution { + public int minOperations(String s) { + int c = 0, j = 0, n = s.length(); + for (char ch : s.toCharArray()) { + if (ch - '0' == j) { + c++; + } + j ^= 1; + } + return Math.min(c, n - c); + } +} diff --git a/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.kt b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.kt new file mode 100644 index 00000000..ba1b2478 --- /dev/null +++ b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun minOperations(s: String): Int { + var c = 0 + var j = 0 + val n = s.length + for (ch in s) { + if (ch - '0' == j) { + c++ + } + j = j xor 1 + } + return minOf(c, n - c) + } +} diff --git a/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.py b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.py new file mode 100644 index 00000000..dcdfb51a --- /dev/null +++ b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.py @@ -0,0 +1,8 @@ +class Solution: + def minOperations(self, s: str) -> int: + c, j, n = 0, 0, len(s) + for ch in s: + if int(ch) == j: + c += 1 + j ^= 1 + return min(c, n - c) diff --git a/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.py2 b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.py2 new file mode 100644 index 00000000..2254a16e --- /dev/null +++ b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def minOperations(self, s): + """ + :type s: str + :rtype: int + """ + c = 0 + j = 0 + n = len(s) + for ch in s: + if int(ch) == j: + c += 1 + j ^= 1 + return min(c, n - c) diff --git a/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.rb b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.rb new file mode 100644 index 00000000..85777fd4 --- /dev/null +++ b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.rb @@ -0,0 +1,14 @@ +# @param {String} s +# @return {Integer} +def min_operations(s) + c = 0 + j = 0 + n = s.length + s.each_char do |ch| + if ch.to_i == j + c += 1 + end + j ^= 1 + end + [c, n - c].min +end diff --git a/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.rs b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.rs new file mode 100644 index 00000000..5515f15a --- /dev/null +++ b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn min_operations(s: String) -> i32 { + let mut c = 0; + let mut j = 0; + let n = s.len() as i32; + for ch in s.chars() { + let digit = ch.to_digit(10).unwrap() as i32; + if digit == j { + c += 1; + } + j ^= 1; + } + std::cmp::min(c, n - c) + } +} diff --git a/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.swift b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.swift new file mode 100644 index 00000000..e7a4d3f6 --- /dev/null +++ b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func minOperations(_ s: String) -> Int { + var c = 0 + var j = 0 + let n = s.count + for ch in s { + if ch == "0" && j == 0 { + c += 1 + } else if ch == "1" && j == 1 { + c += 1 + } + j ^= 1 + } + return min(c, n - c) + } +} diff --git a/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.ts b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.ts new file mode 100644 index 00000000..7b72eb0c --- /dev/null +++ b/tests/1501-2000/1758. minimum-changes-to-make-alternating-binary-string/sol.ts @@ -0,0 +1,12 @@ +function minOperations(s: string): number { + let c = 0, + j = 0, + n = s.length; + for (let ch of s) { + if (Number(ch) === j) { + c++; + } + j ^= 1; + } + return Math.min(c, n - c); +} diff --git a/tests/1501-2000/1759. count-number-of-homogenous-substrings/manifest.yaml b/tests/1501-2000/1759. count-number-of-homogenous-substrings/manifest.yaml new file mode 100644 index 00000000..6a7e7206 --- /dev/null +++ b/tests/1501-2000/1759. count-number-of-homogenous-substrings/manifest.yaml @@ -0,0 +1,204 @@ +entry: + id: 1759 + title: "count-number-of-homogenous-substrings" + params: + s: + type: string + call: + cpp: "Solution().countHomogenous({s})" + rust: "Solution::count_homogenous({s})" + python3: "Solution().countHomogenous({s})" + python2: "Solution().countHomogenous({s})" + ruby: "count_homogenous({s})" + java: "new Solution().countHomogenous({s})" + csharp: "new Solution().CountHomogenous({s})" + kotlin: "Solution().countHomogenous({s})" + go: "countHomogenous({s})" + dart: "Solution().countHomogenous({s})" + swift: "Solution().countHomogenous({s})" + typescript: "countHomogenous({s})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().countHomogenous(s, {result})" + checker: | + class Checker: + def countHomogenous(self, s, result): + mod = 1000000007 + total = 0 + run = 0 + previous = None + for ch in s: + if ch == previous: + run += 1 + else: + run = 1 + previous = ch + total = (total + run) % mod + return result == total + +seed: 1759 + +tests: + - name: example-abbcccaa + in: + s: "abbcccaa" + out: 13 + - name: example-xy + in: + s: "xy" + out: 2 + - name: example-zzzzz + in: + s: "zzzzz" + out: 15 + - name: single-a + in: + s: "a" + out: 1 + - name: single-z + in: + s: "z" + out: 1 + - name: two-equal + in: + s: "aa" + out: 3 + - name: two-different + in: + s: "az" + out: 2 + - name: three-equal + in: + s: "bbb" + out: 6 + - name: alternating + in: + s: "ababab" + out: 6 + - name: two-runs + in: + s: "aaabbbb" + out: 16 + - name: many-runs + in: + s: "aabbccdd" + out: 12 + - name: mixed-runs + in: + s: "aabcccbb" + out: 13 + - name: all-alphabet + in: + s: "abcdefghijklmnopqrstuvwxyz" + out: 26 + - name: reverse-alphabet + in: + s: "zyxwvutsrqponmlkjihgfedcba" + out: 26 + - name: three-long-runs + in: + s: "aaaaabbbbbccccc" + out: 45 + - name: uneven-runs + in: + s: "aabbbbbcc" + out: 21 + - name: isolated-middle + in: + s: "aaaaabaaaaa" + out: 31 + - name: repeated-pattern + in: + s: "aabbbaaabbb" + out: 21 + - name: long-first-run + in: + s: "aaaaaaaaaabc" + out: 57 + - name: long-last-run + in: + s: "abcbbbbbbbbb" + out: 48 + - name: alternating-runs + in: + s: "aaabbaaabbbaa" + out: 24 + - name: single-char-runs + in: + s: "abcdefghij" + out: 10 + - name: palindrome-runs + in: + s: "aaabcccbaaa" + out: 20 + - name: dense-a-runs + in: + s: "aabaaabaaab" + out: 18 + - name: four-equal-blocks + in: + s: "aaaabbbbccccdddd" + out: 40 + - name: five-equal-blocks + in: + s: "aaaaabbbbbcccccdddddeeeee" + out: 75 + - name: long-balanced + in: + s: "aaaaabbbbbbaaaaa" + out: 51 + - name: one-long-run + in: + s: "qwertyyyyyyyy" + out: 41 + - name: alternating-uppercase-free + in: + s: "azazazazazaz" + out: 12 + - name: edge-character-runs + in: + s: "zzzaazzz" + out: 15 + - name: generator-small + in: + s: + gen: "str" + len: 20 + alphabet: "abc" + seed: 1759001 + - name: generator-medium + in: + s: + gen: "str" + len: 1000 + alphabet: "abcd" + seed: 1759002 + - name: generator-large-binary + in: + s: + gen: "str" + len: 50000 + alphabet: "ab" + seed: 1759003 + - name: generator-max-ternary + in: + s: + gen: "str" + len: 100000 + alphabet: "abc" + seed: 1759004 + - name: generator-max-unary + in: + s: + gen: "str" + len: 100000 + alphabet: "z" + seed: 1759005 diff --git a/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.cpp b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.cpp new file mode 100644 index 00000000..4a5428c6 --- /dev/null +++ b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int countHomogenous(string s) { + const int mod = 1000000007; + int n = s.length(); + long long res = 1; + int cnt = 1; + for (int i = 1; i < n; i++) { + if (s[i] != s[i - 1]) { + cnt = 0; + } + cnt++; + res = (res + cnt) % mod; + } + return (int) res; + } +}; diff --git a/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.cs b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.cs new file mode 100644 index 00000000..e5727680 --- /dev/null +++ b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public int CountHomogenous(string s) { + const int mod = 1000000007; + int n = s.Length; + long res = 1; + int cnt = 1; + for (int i = 1; i < n; i++) { + if (s[i] != s[i - 1]) { + cnt = 0; + } + cnt++; + res = (res + cnt) % mod; + } + return (int) res; + } +} diff --git a/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.dart b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.dart new file mode 100644 index 00000000..538c3c9e --- /dev/null +++ b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.dart @@ -0,0 +1,16 @@ +class Solution { + int countHomogenous(String s) { + const int mod = 1000000007; + int n = s.length; + int res = 1; + int cnt = 1; + for (int i = 1; i < n; i++) { + if (s[i] != s[i - 1]) { + cnt = 0; + } + cnt++; + res = (res + cnt) % mod; + } + return res; + } +} diff --git a/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.go b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.go new file mode 100644 index 00000000..ae42a350 --- /dev/null +++ b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.go @@ -0,0 +1,14 @@ +func countHomogenous(s string) int { + mod := int64(1000000007) + n := len(s) + res := int64(1) + cnt := 1 + for i := 1; i < n; i++ { + if s[i] != s[i-1] { + cnt = 0 + } + cnt++ + res = (res + int64(cnt)) % mod + } + return int(res) +} diff --git a/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.java b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.java new file mode 100644 index 00000000..d0d0f73b --- /dev/null +++ b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.java @@ -0,0 +1,16 @@ +class Solution { + public int countHomogenous(String s) { + long mod = 1_000_000_007L; + int n = s.length(); + long res = 1; + int cnt = 1; + for (int i = 1; i < n; i++) { + if (s.charAt(i) != s.charAt(i - 1)) { + cnt = 0; + } + cnt++; + res = (res + cnt) % mod; + } + return (int) res; + } +} diff --git a/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.kt b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.kt new file mode 100644 index 00000000..f07f7dcb --- /dev/null +++ b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun countHomogenous(s: String): Int { + val mod = 1_000_000_007L + val n = s.length + var res = 1L + var cnt = 1 + for (i in 1 until n) { + if (s[i] != s[i - 1]) { + cnt = 0 + } + cnt++ + res = (res + cnt) % mod + } + return res.toInt() + } +} diff --git a/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.py b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.py new file mode 100644 index 00000000..ac8fd412 --- /dev/null +++ b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.py @@ -0,0 +1,11 @@ +class Solution: + def countHomogenous(self, s: str) -> int: + MOD = 1e9 + 7 + n = len(s) + res = cnt = 1 + for i in range(1, n): + if s[i] != s[i - 1]: + cnt = 0 + cnt += 1 + res = (res + cnt) % MOD + return int(res) diff --git a/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.py2 b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.py2 new file mode 100644 index 00000000..a8fe194e --- /dev/null +++ b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def countHomogenous(self, s): + """ + :type s: str + :rtype: int + """ + MOD = 10**9 + 7 + n = len(s) + res = cnt = 1 + for i in range(1, n): + if s[i] != s[i - 1]: + cnt = 0 + cnt += 1 + res = (res + cnt) % MOD + return res diff --git a/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.rb b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.rb new file mode 100644 index 00000000..ad750b6a --- /dev/null +++ b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.rb @@ -0,0 +1,16 @@ +# @param {String} s +# @return {Integer} +def count_homogenous(s) + mod = 10**9 + 7 + n = s.length + res = 1 + cnt = 1 + (1...n).each do |i| + if s[i] != s[i - 1] + cnt = 0 + end + cnt += 1 + res = (res + cnt) % mod + end + res +end diff --git a/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.rs b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.rs new file mode 100644 index 00000000..36979e78 --- /dev/null +++ b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn count_homogenous(s: String) -> i32 { + let modulus = 1_000_000_007i64; + let n = s.len(); + let chars: Vec = s.chars().collect(); + let mut res = 1i64; + let mut cnt = 1; + for i in 1..n { + if chars[i] != chars[i - 1] { + cnt = 0; + } + cnt += 1; + res = (res + cnt as i64) % modulus; + } + res as i32 + } +} diff --git a/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.swift b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.swift new file mode 100644 index 00000000..7a6d2cbc --- /dev/null +++ b/tests/1501-2000/1759. count-number-of-homogenous-substrings/sol.swift @@ -0,0 +1,17 @@ +class Solution { + func countHomogenous(_ s: String) -> Int { + let mod = 1_000_000_007 + let chars = Array(s) + let n = chars.count + var res = 1 + var cnt = 1 + for i in 1..& nums, int maxOperations) { + int lo = 1, hi = *max_element(nums.begin(), nums.end()); + while (lo < hi) { + int mid = lo + (hi - lo) / 2; + long long needed = 0; + for (int x : nums) { + needed += (x - 1) / mid; + } + if (needed <= maxOperations) { + hi = mid; + } else { + lo = mid + 1; + } + } + return lo; + } +}; diff --git a/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.cs b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.cs new file mode 100644 index 00000000..004080c3 --- /dev/null +++ b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public int MinimumSize(int[] nums, int maxOperations) { + int lo = 1, hi = nums.Max(); + while (lo < hi) { + int mid = lo + (hi - lo) / 2; + long needed = 0; + foreach (int x in nums) { + needed += (x - 1) / mid; + } + if (needed <= maxOperations) { + hi = mid; + } else { + lo = mid + 1; + } + } + return lo; + } +} diff --git a/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.dart b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.dart new file mode 100644 index 00000000..bd69008f --- /dev/null +++ b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.dart @@ -0,0 +1,18 @@ +class Solution { + int minimumSize(List nums, int maxOperations) { + int lo = 1, hi = nums.reduce((a, b) => a > b ? a : b); + while (lo < hi) { + int mid = (lo + hi) ~/ 2; + int needed = 0; + for (int x in nums) { + needed += (x - 1) ~/ mid; + } + if (needed <= maxOperations) { + hi = mid; + } else { + lo = mid + 1; + } + } + return lo; + } +} diff --git a/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.go b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.go new file mode 100644 index 00000000..ec2c7fb6 --- /dev/null +++ b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.go @@ -0,0 +1,19 @@ +func minimumSize(nums []int, maxOperations int) int { + lo, hi := 1, 0 + for _, x := range nums { + if x > hi { hi = x } + } + for lo < hi { + mid := (lo + hi) / 2 + needed := 0 + for _, x := range nums { + needed += (x - 1) / mid + } + if needed <= maxOperations { + hi = mid + } else { + lo = mid + 1 + } + } + return lo +} diff --git a/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.java b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.java new file mode 100644 index 00000000..8b7d8c05 --- /dev/null +++ b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.java @@ -0,0 +1,14 @@ +class Solution { + public int minimumSize(int[] nums, int maxOperations) { + int lo = 1, hi = 0; + for (int x : nums) hi = Math.max(hi, x); + while (lo < hi) { + int mid = lo + (hi - lo) / 2; + long needed = 0; + for (int x : nums) needed += (x - 1) / mid; + if (needed <= maxOperations) hi = mid; + else lo = mid + 1; + } + return lo; + } +} diff --git a/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.kt b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.kt new file mode 100644 index 00000000..0a9e1ffa --- /dev/null +++ b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun minimumSize(nums: IntArray, maxOperations: Int): Int { + var lo = 1 + var hi = nums.max()!! + while (lo < hi) { + val mid = (lo + hi) / 2 + var needed = 0L + for (x in nums) needed += (x - 1) / mid + if (needed <= maxOperations) hi = mid + else lo = mid + 1 + } + return lo + } +} diff --git a/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.py b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.py new file mode 100644 index 00000000..796f0f7d --- /dev/null +++ b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.py @@ -0,0 +1,26 @@ +class Solution: + def minimumSize(self, nums, maxOperations): + lo, hi = 1, max(nums) + while lo < hi: + mid = (lo + hi) // 2 + needed = sum((x - 1) // mid for x in nums) + if needed <= maxOperations: + hi = mid + else: + lo = mid + 1 + return lo + + def test(): + sol = Solution() + + # Basic case + assert sol.minimumSize([9], 2) == 3 + + # Multiple bags + assert sol.minimumSize([2, 4, 8, 2], 4) == 2 + + # No operations allowed + assert sol.minimumSize([7, 17], 0) == 17 + + # Large values + assert sol.minimumSize([1000000000], 1) == 500000000 diff --git a/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.py2 b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.py2 new file mode 100644 index 00000000..826e1fc6 --- /dev/null +++ b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def minimumSize(self, nums, maxOperations): + """ + :type nums: List[int] + :type maxOperations: int + :rtype: int + """ + lo, hi = 1, max(nums) + while lo < hi: + mid = (lo + hi) // 2 + needed = sum((x - 1) // mid for x in nums) + if needed <= maxOperations: + hi = mid + else: + lo = mid + 1 + return lo diff --git a/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.rb b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.rb new file mode 100644 index 00000000..4f3eb17a --- /dev/null +++ b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.rb @@ -0,0 +1,16 @@ +# @param {Integer[]} nums +# @param {Integer} max_operations +# @return {Integer} +def minimum_size(nums, max_operations) + lo, hi = 1, nums.max + while lo < hi + mid = (lo + hi) / 2 + needed = nums.sum { |x| (x - 1) / mid } + if needed <= max_operations + hi = mid + else + lo = mid + 1 + end + end + lo +end diff --git a/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.rs b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.rs new file mode 100644 index 00000000..2b414eca --- /dev/null +++ b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn minimum_size(nums: Vec, max_operations: i32) -> i32 { + let mut lo = 1; + let mut hi = *nums.iter().max().unwrap(); + while lo < hi { + let mid = (lo + hi) / 2; + let needed: i64 = nums.iter().map(|&x| ((x - 1) / mid) as i64).sum(); + if needed <= max_operations as i64 { + hi = mid; + } else { + lo = mid + 1; + } + } + lo + } +} diff --git a/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.swift b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.swift new file mode 100644 index 00000000..e160f320 --- /dev/null +++ b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.swift @@ -0,0 +1,19 @@ +class Solution { + func minimumSize(_ nums: [Int], _ maxOperations: Int) -> Int { + var lo = 1 + var hi = nums.max()! + while lo < hi { + let mid = (lo + hi) / 2 + var needed = 0 + for x in nums { + needed += (x - 1) / mid + } + if needed <= maxOperations { + hi = mid + } else { + lo = mid + 1 + } + } + return lo + } +} diff --git a/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.ts b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.ts new file mode 100644 index 00000000..7ff13098 --- /dev/null +++ b/tests/1501-2000/1760. minimum-limit-of-balls-in-a-bag/sol.ts @@ -0,0 +1,17 @@ +function minimumSize(nums: number[], maxOperations: number): number { + let lo = 1; + let hi = Math.max(...nums); + while (lo < hi) { + const mid = Math.floor((lo + hi) / 2); + let needed = 0; + for (const x of nums) { + needed += Math.floor((x - 1) / mid); + } + if (needed <= maxOperations) { + hi = mid; + } else { + lo = mid + 1; + } + } + return lo; +} diff --git a/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/manifest.yaml b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/manifest.yaml new file mode 100644 index 00000000..bcfbee44 --- /dev/null +++ b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/manifest.yaml @@ -0,0 +1,338 @@ +entry: + id: 1761 + title: "minimum-degree-of-a-connected-trio-in-a-graph" + params: + n: + type: int + edges: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().minTrioDegree({n}, {edges})" + rust: "Solution::min_trio_degree({n}, {edges})" + python3: "Solution().minTrioDegree({n}, {edges})" + python2: "Solution().minTrioDegree({n}, {edges})" + ruby: "min_trio_degree({n}, {edges})" + java: "new Solution().minTrioDegree({n}, {edges})" + csharp: "new Solution().MinTrioDegree({n}, {edges})" + kotlin: "Solution().minTrioDegree({n}, {edges})" + go: "minTrioDegree({n}, {edges})" + dart: "Solution().minTrioDegree({n}, {edges})" + swift: "Solution().minTrioDegree({n}, {edges})" + typescript: "minTrioDegree({n}, {edges})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().minTrioDegree(n, edges, {result})" + checker: | + class Checker: + def minTrioDegree(self, n, edges, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + adj = [[False] * (n + 1) for _ in range(n + 1)] + deg = [0] * (n + 1) + for edge in edges: + if not isinstance(edge, list) or len(edge) != 2: + return False + u, v = edge + if not (1 <= u <= n and 1 <= v <= n and u != v): + return False + if not adj[u][v]: + adj[u][v] = adj[v][u] = True + deg[u] += 1 + deg[v] += 1 + best = None + for a in range(1, n + 1): + for b in range(a + 1, n + 1): + if not adj[a][b]: + continue + for c in range(b + 1, n + 1): + if adj[a][c] and adj[b][c]: + value = deg[a] + deg[b] + deg[c] - 6 + best = value if best is None else min(best, value) + return result == (-1 if best is None else best) + +seed: 1761 + +tests: + - name: "example_one" + in: + n: 6 + edges: [[1, 2], [1, 3], [3, 2], [4, 1], [5, 2], [3, 6]] + out: 3 + - name: "example_two" + in: + n: 7 + edges: [[1, 3], [4, 1], [4, 3], [2, 5], [5, 6], [6, 7], [7, 5], [2, 6]] + out: 0 + - name: "minimum_n_triangle" + in: + n: 3 + edges: [[1, 2], [2, 3], [1, 3]] + out: 0 + - name: "minimum_n_no_trio" + in: + n: 3 + edges: [[1, 2], [2, 3]] + out: -1 + - name: "single_edge" + in: + n: 4 + edges: [[1, 4]] + out: -1 + - name: "path_four" + in: + n: 4 + edges: [[1, 2], [2, 3], [3, 4]] + out: -1 + - name: "star_six" + in: + n: 6 + edges: [[1, 2], [1, 3], [1, 4], [1, 5], [1, 6]] + out: -1 + - name: "triangle_one_leaf" + in: + n: 4 + edges: [[1, 2], [2, 3], [1, 3], [3, 4]] + out: 1 + - name: "triangle_two_leaves" + in: + n: 5 + edges: [[1, 2], [2, 3], [1, 3], [1, 4], [2, 5]] + out: 2 + - name: "triangle_all_three_leaves" + in: + n: 6 + edges: [[1, 2], [2, 3], [1, 3], [1, 4], [2, 5], [3, 6]] + out: 3 + - name: "triangle_extra_edges_between_leaves" + in: + n: 6 + edges: [[1, 2], [1, 3], [2, 3], [1, 4], [2, 5], [3, 6], [4, 5], [5, 6]] + out: 3 + - name: "two_disjoint_triangles" + in: + n: 6 + edges: [[1, 2], [2, 3], [1, 3], [4, 5], [5, 6], [4, 6]] + out: 0 + - name: "two_triangles_with_bridge" + in: + n: 6 + edges: [[1, 2], [2, 3], [1, 3], [4, 5], [5, 6], [4, 6], [3, 4]] + out: 1 + - name: "two_triangles_shared_vertex" + in: + n: 5 + edges: [[1, 2], [2, 3], [1, 3], [1, 4], [4, 5], [1, 5]] + out: 2 + - name: "two_triangles_shared_edge" + in: + n: 4 + edges: [[1, 2], [1, 3], [2, 3], [1, 4], [2, 4]] + out: 2 + - name: "three_triangles_chain" + in: + n: 7 + edges: + [[1, 2], [2, 3], [1, 3], [3, 4], [4, 5], [3, 5], [5, 6], [6, 7], [5, 7]] + out: 2 + - name: "complete_four" + in: + n: 4 + edges: [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] + out: 3 + - name: "complete_five" + in: + n: 5 + edges: + [ + [1, 2], + [1, 3], + [1, 4], + [1, 5], + [2, 3], + [2, 4], + [2, 5], + [3, 4], + [3, 5], + [4, 5], + ] + out: 6 + - name: "complete_six" + in: + n: 6 + edges: + [ + [1, 2], + [1, 3], + [1, 4], + [1, 5], + [1, 6], + [2, 3], + [2, 4], + [2, 5], + [2, 6], + [3, 4], + [3, 5], + [3, 6], + [4, 5], + [4, 6], + [5, 6], + ] + out: 9 + - name: "complete_seven" + in: + n: 7 + edges: + [ + [1, 2], + [1, 3], + [1, 4], + [1, 5], + [1, 6], + [1, 7], + [2, 3], + [2, 4], + [2, 5], + [2, 6], + [2, 7], + [3, 4], + [3, 5], + [3, 6], + [3, 7], + [4, 5], + [4, 6], + [4, 7], + [5, 6], + [5, 7], + [6, 7], + ] + out: 12 + - name: "triangle_with_isolated_nodes" + in: + n: 8 + edges: [[4, 5], [5, 6], [4, 6]] + out: 0 + - name: "triangle_with_disconnected_edges" + in: + n: 8 + edges: [[1, 2], [2, 3], [1, 3], [4, 5], [6, 7], [7, 8]] + out: 0 + - name: "triangle_with_long_tail" + in: + n: 8 + edges: [[1, 2], [2, 3], [1, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8]] + out: 1 + - name: "triangle_with_two_extra_chords" + in: + n: 7 + edges: + [[1, 2], [2, 3], [1, 3], [1, 4], [2, 5], [3, 6], [4, 5], [5, 6], [6, 7]] + out: 3 + - name: "four_cycle_no_trio" + in: + n: 4 + edges: [[1, 2], [2, 3], [3, 4], [4, 1]] + out: -1 + - name: "five_cycle_no_trio" + in: + n: 5 + edges: [[1, 2], [2, 3], [3, 4], [4, 5], [5, 1]] + out: -1 + - name: "almost_complete_four" + in: + n: 4 + edges: [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4]] + out: 2 + - name: "triangle_with_dense_outside" + in: + n: 6 + edges: + [[1, 2], [2, 3], [1, 3], [4, 5], [4, 6], [5, 6], [1, 4], [2, 5], [3, 6]] + out: 3 + - name: "two_trios_different_degree" + in: + n: 7 + edges: + [ + [1, 2], + [2, 3], + [1, 3], + [1, 4], + [2, 4], + [1, 5], + [2, 5], + [3, 6], + [3, 7], + [6, 7], + ] + out: 2 + - name: "triangle_with_one_unrelated_edge" + in: + n: 6 + edges: [[2, 3], [3, 4], [2, 4], [5, 6]] + out: 0 + - name: "two_triangles_and_tail_edges" + in: + n: 9 + edges: + [[1, 2], [2, 3], [1, 3], [4, 5], [5, 6], [4, 6], [1, 7], [7, 8], [8, 9]] + out: 0 + - name: "dense_six_without_one_edge" + in: + n: 6 + edges: + [ + [1, 2], + [1, 3], + [1, 4], + [1, 5], + [1, 6], + [2, 3], + [2, 4], + [2, 5], + [2, 6], + [3, 4], + [3, 5], + [3, 6], + [4, 5], + [4, 6], + ] + out: 8 + - name: "triangle_with_many_isolates" + in: + n: 20 + edges: [[10, 11], [11, 12], [10, 12]] + out: 0 + - name: "no_trio_bipartite" + in: + n: 8 + edges: + [ + [1, 5], + [1, 6], + [2, 5], + [2, 6], + [3, 7], + [3, 8], + [4, 7], + [4, 8], + [1, 7], + [2, 8], + ] + out: -1 + - name: "triangle_with_two_external_edges" + in: + n: 5 + edges: [[1, 2], [2, 3], [1, 3], [3, 4], [3, 5]] + out: 2 diff --git a/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.cpp b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.cpp new file mode 100644 index 00000000..bb3e778a --- /dev/null +++ b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int minTrioDegree(int n, vector>& edges) { + vector> adj(n+1, vector(n+1,0)); + vector deg(n+1,0); + for (auto& e : edges) { + adj[e[0]][e[1]] = 1; + adj[e[1]][e[0]] = 1; + deg[e[0]]++; + deg[e[1]]++; + } + int ans = INT_MAX; + for (auto& e : edges) { + int u = e[0], v = e[1]; + for (int w=1; w<=n; w++) { + if (adj[u][w] && adj[v][w]) { + ans = min(ans, deg[u]+deg[v]+deg[w]-6); + } + } + } + return ans==INT_MAX ? -1 : ans; + } +}; diff --git a/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.cs b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.cs new file mode 100644 index 00000000..8217ed74 --- /dev/null +++ b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public int MinTrioDegree(int n, int[][] edges) { + int[,] adj = new int[n+1,n+1]; + int[] deg = new int[n+1]; + foreach (var e in edges) { + adj[e[0],e[1]] = 1; + adj[e[1],e[0]] = 1; + deg[e[0]]++; + deg[e[1]]++; + } + int ans = int.MaxValue; + foreach (var e in edges) { + int u=e[0], v=e[1]; + for (int w=1; w<=n; w++) { + if (adj[u,w]==1 && adj[v,w]==1) { + ans = Math.Min(ans, deg[u]+deg[v]+deg[w]-6); + } + } + } + return ans==int.MaxValue ? -1 : ans; + } +} diff --git a/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.dart b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.dart new file mode 100644 index 00000000..9e0fce4b --- /dev/null +++ b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.dart @@ -0,0 +1,23 @@ +class Solution { + int minTrioDegree(int n, List> edges) { + List> adj = List.generate(n+1, (_) => List.filled(n+1, 0)); + List deg = List.filled(n+1, 0); + for (var e in edges) { + adj[e[0]][e[1]] = 1; + adj[e[1]][e[0]] = 1; + deg[e[0]]++; + deg[e[1]]++; + } + int ans = 1 << 30; + for (var e in edges) { + int u = e[0], v = e[1]; + for (int w = 1; w <= n; w++) { + if (adj[u][w] == 1 && adj[v][w] == 1) { + int val = deg[u] + deg[v] + deg[w] - 6; + if (val < ans) ans = val; + } + } + } + return ans == (1 << 30) ? -1 : ans; + } +} diff --git a/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.go b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.go new file mode 100644 index 00000000..8367fe62 --- /dev/null +++ b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.go @@ -0,0 +1,29 @@ +func minTrioDegree(n int, edges [][]int) int { + adj := make([][]int, n+1) + for i := range adj { + adj[i] = make([]int, n+1) + } + deg := make([]int, n+1) + for _, e := range edges { + adj[e[0]][e[1]] = 1 + adj[e[1]][e[0]] = 1 + deg[e[0]]++ + deg[e[1]]++ + } + ans := int(^uint(0) >> 1) // max int + for _, e := range edges { + u, v := e[0], e[1] + for w := 1; w <= n; w++ { + if adj[u][w] == 1 && adj[v][w] == 1 { + val := deg[u] + deg[v] + deg[w] - 6 + if val < ans { + ans = val + } + } + } + } + if ans == int(^uint(0) >> 1) { + return -1 + } + return ans +} diff --git a/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.java b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.java new file mode 100644 index 00000000..8a3e5b4f --- /dev/null +++ b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.java @@ -0,0 +1,22 @@ +class Solution { + public int minTrioDegree(int n, int[][] edges) { + int[][] adj = new int[n+1][n+1]; + int[] deg = new int[n+1]; + for (int[] e : edges) { + adj[e[0]][e[1]]=1; + adj[e[1]][e[0]]=1; + deg[e[0]]++; + deg[e[1]]++; + } + int ans = Integer.MAX_VALUE; + for (int[] e : edges) { + int u=e[0], v=e[1]; + for (int w=1; w<=n; w++) { + if (adj[u][w]==1 && adj[v][w]==1) { + ans = Math.min(ans, deg[u]+deg[v]+deg[w]-6); + } + } + } + return ans==Integer.MAX_VALUE ? -1 : ans; + } +} diff --git a/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.kt b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.kt new file mode 100644 index 00000000..17397787 --- /dev/null +++ b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.kt @@ -0,0 +1,22 @@ +class Solution { + fun minTrioDegree(n: Int, edges: Array): Int { + val adj = Array(n+1) { IntArray(n+1) } + val deg = IntArray(n+1) + for (e in edges) { + adj[e[0]][e[1]]=1 + adj[e[1]][e[0]]=1 + deg[e[0]]++ + deg[e[1]]++ + } + var ans = Int.MAX_VALUE + for (e in edges) { + val u=e[0]; val v=e[1] + for (w in 1..n) { + if (adj[u][w]==1 && adj[v][w]==1) { + ans = minOf(ans, deg[u]+deg[v]+deg[w]-6) + } + } + } + return if (ans==Int.MAX_VALUE) -1 else ans + } +} diff --git a/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.py b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.py new file mode 100644 index 00000000..396793bf --- /dev/null +++ b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.py @@ -0,0 +1,39 @@ +import numpy as np + + +class Solution: + def minTrioDegree(self, n: int, edges: List[List[int]]) -> int: + # 1. Memory-Efficient Adjacency Matrix + # uint8 is used to keep the footprint small for the N x N matrix + adj = np.zeros((n + 1, n + 1), dtype=np.uint8) + degrees = np.zeros(n + 1, dtype=int) + + for u, v in edges: + adj[u, v] = adj[v, u] = 1 + degrees[u] += 1 + degrees[v] += 1 + + min_degree = float("inf") + + # 2. Vectorized Trio Search + # We iterate over edges to ensure we only check nodes that are connected + for u, v in edges: + # Create a boolean mask of common neighbors 'w' + # A common neighbor exists where both adj[u] and adj[v] have a 1 + common_mask = (adj[u] & adj[v]) == 1 + + # If any common neighbors exist, calculate degrees in a vectorized batch + if np.any(common_mask): + # Pull all degrees of 'w' nodes without a Python loop + w_degrees = degrees[common_mask] + + # Formula: (deg(u)-2) + (deg(v)-2) + (deg(w)-2) + # Simplified: deg(u) + deg(v) + deg(w) - 6 + trio_degrees = (degrees[u] + degrees[v] + w_degrees) - 6 + + # Update the global minimum using NumPy's optimized min() + current_min = np.min(trio_degrees) + if current_min < min_degree: + min_degree = current_min + + return int(min_degree) if min_degree != float("inf") else -1 diff --git a/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.py2 b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.py2 new file mode 100644 index 00000000..c4aa9b2d --- /dev/null +++ b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.py2 @@ -0,0 +1,19 @@ +class Solution(object): + def minTrioDegree(self, n, edges): + """ + :type n: int + :type edges: List[List[int]] + :rtype: int + """ + adj = [[0]*(n+1) for _ in range(n+1)] + deg = [0]*(n+1) + for u,v in edges: + adj[u][v]=adj[v][u]=1 + deg[u]+=1 + deg[v]+=1 + ans = float('inf') + for u,v in edges: + for w in range(1,n+1): + if adj[u][w] and adj[v][w]: + ans = min(ans, deg[u]+deg[v]+deg[w]-6) + return -1 if ans==float('inf') else ans diff --git a/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.rb b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.rb new file mode 100644 index 00000000..b3622252 --- /dev/null +++ b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.rb @@ -0,0 +1,22 @@ +# @param {Integer} n +# @param {Integer[][]} edges +# @return {Integer} +def min_trio_degree(n, edges) + adj = Array.new(n+1) { Array.new(n+1,0) } + deg = Array.new(n+1,0) + edges.each do |u,v| + adj[u][v]=1 + adj[v][u]=1 + deg[u]+=1 + deg[v]+=1 + end + ans = Float::INFINITY + edges.each do |u,v| + (1..n).each do |w| + if adj[u][w]==1 && adj[v][w]==1 + ans = [ans, deg[u]+deg[v]+deg[w]-6].min + end + end + end + ans==Float::INFINITY ? -1 : ans +end diff --git a/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.rs b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.rs new file mode 100644 index 00000000..6a5e8d6c --- /dev/null +++ b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn min_trio_degree(n: i32, edges: Vec>) -> i32 { + let n = n as usize; + let mut adj = vec![vec![0i32; n+1]; n+1]; + let mut deg = vec![0i32; n+1]; + for e in &edges { + let u = e[0] as usize; + let v = e[1] as usize; + adj[u][v] = 1; + adj[v][u] = 1; + deg[u] += 1; + deg[v] += 1; + } + let mut ans = i32::MAX; + for e in &edges { + let u = e[0] as usize; + let v = e[1] as usize; + for w in 1..=n { + if adj[u][w] == 1 && adj[v][w] == 1 { + ans = ans.min(deg[u] + deg[v] + deg[w] - 6); + } + } + } + if ans == i32::MAX { -1 } else { ans } + } +} diff --git a/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.swift b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.swift new file mode 100644 index 00000000..00739251 --- /dev/null +++ b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.swift @@ -0,0 +1,22 @@ +class Solution { + func minTrioDegree(_ n: Int, _ edges: [[Int]]) -> Int { + var adj = Array(repeating: Array(repeating: 0, count: n+1), count: n+1) + var deg = Array(repeating: 0, count: n+1) + for e in edges { + adj[e[0]][e[1]] = 1 + adj[e[1]][e[0]] = 1 + deg[e[0]] += 1 + deg[e[1]] += 1 + } + var ans = Int.max + for e in edges { + let u = e[0], v = e[1] + for w in 1...n { + if adj[u][w] == 1 && adj[v][w] == 1 { + ans = min(ans, deg[u] + deg[v] + deg[w] - 6) + } + } + } + return ans == Int.max ? -1 : ans + } +} diff --git a/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.ts b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.ts new file mode 100644 index 00000000..76133f51 --- /dev/null +++ b/tests/1501-2000/1761. minimum-degree-of-a-connected-trio-in-a-graph/sol.ts @@ -0,0 +1,21 @@ +function minTrioDegree(n: number, edges: number[][]): number { + const adj: number[][] = Array.from({ length: n + 1 }, () => + Array(n + 1).fill(0), + ); + const deg: number[] = Array(n + 1).fill(0); + for (const [u, v] of edges) { + adj[u][v] = 1; + adj[v][u] = 1; + deg[u]++; + deg[v]++; + } + let ans = Number.MAX_SAFE_INTEGER; + for (const [u, v] of edges) { + for (let w = 1; w <= n; w++) { + if (adj[u][w] === 1 && adj[v][w] === 1) { + ans = Math.min(ans, deg[u] + deg[v] + deg[w] - 6); + } + } + } + return ans === Number.MAX_SAFE_INTEGER ? -1 : ans; +} diff --git a/tests/1501-2000/1763. longest-nice-substring/manifest.yaml b/tests/1501-2000/1763. longest-nice-substring/manifest.yaml new file mode 100644 index 00000000..1dc6a276 --- /dev/null +++ b/tests/1501-2000/1763. longest-nice-substring/manifest.yaml @@ -0,0 +1,204 @@ +entry: + id: 1763 + title: "longest-nice-substring" + params: + s: + type: string + call: + cpp: "Solution().longestNiceSubstring({s})" + rust: "Solution::longest_nice_substring({s})" + python3: "Solution().longestNiceSubstring({s})" + python2: "Solution().longestNiceSubstring({s})" + ruby: "longest_nice_substring({s})" + java: "new Solution().longestNiceSubstring({s})" + csharp: "new Solution().LongestNiceSubstring({s})" + kotlin: "Solution().longestNiceSubstring({s})" + go: "longestNiceSubstring({s})" + dart: "Solution().longestNiceSubstring({s})" + swift: "Solution().longestNiceSubstring({s})" + typescript: "longestNiceSubstring({s})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(s, {result})" + checker: | + class Checker: + def check(self, s, result): + best = '' + for i in range(len(s)): + present = set() + for j in range(i, len(s)): + present.add(s[j]) + ok = True + for ch in present: + if ch.swapcase() not in present: + ok = False + break + if ok and j - i + 1 > len(best): + best = s[i:j + 1] + return result == best + +seed: 1763 + +tests: + - name: example-yazaay + in: + s: "YazaAay" + out: "aAa" + - name: example-bb + in: + s: "Bb" + out: "Bb" + - name: example-single + in: + s: "c" + out: "" + - name: empty-impossible-single + in: + s: "A" + out: "" + - name: pair-lower-upper + in: + s: "aA" + out: "aA" + - name: pair-reversed + in: + s: "Aa" + out: "Aa" + - name: all-nice-repeated + in: + s: "aAbBaB" + out: "aAbBaB" + - name: split-by-bad-character + in: + s: "aAbcCB" + out: "aAbcCB" + - name: longest-right-side + in: + s: "xYyZz" + out: "YyZz" + - name: earliest-tie + in: + s: "aAbBcCd" + out: "aAbBcC" + - name: earliest-equal-pairs + in: + s: "aAbBcCdDe" + out: "aAbBcCdD" + - name: nested-valid-segments + in: + s: "xAaBbYy" + out: "AaBbYy" + - name: bad-lowercase-middle + in: + s: "AaXxqBb" + out: "AaXx" + - name: bad-uppercase-middle + in: + s: "AaQbBq" + out: "AaQbBq" + - name: repeated-pairs + in: + s: "aAaAbBbB" + out: "aAaAbBbB" + - name: reversed-repeated-pairs + in: + s: "AaBbCc" + out: "AaBbCc" + - name: only-bad + in: + s: "abcdef" + out: "" + - name: only-uppercase + in: + s: "ABCDEF" + out: "" + - name: alternating-valid-invalid + in: + s: "aAbcCdD" + out: "cCdD" + - name: one-letter-valid-region + in: + s: "qAaQ" + out: "qAaQ" + - name: valid-at-end + in: + s: "mnopPON" + out: "nopPON" + - name: valid-at-start + in: + s: "AaXYZ" + out: "Aa" + - name: three-letter-pairs + in: + s: "aAbBcCz" + out: "aAbBcC" + - name: case-mixed-valid + in: + s: "aBcCbA" + out: "aBcCbA" + - name: duplicate-invalid-symbol + in: + s: "aAxxBb" + out: "aA" + - name: bad-symbol-after-valid + in: + s: "aAbBcCq" + out: "aAbBcC" + - name: bad-symbol-before-valid + in: + s: "qAaBbCc" + out: "AaBbCc" + - name: two-tied-long-runs + in: + s: "aAbBcCdEfF" + out: "aAbBcC" + - name: long-valid-run + in: + s: "aAbBcCdDeEfFgGhH" + out: "aAbBcCdDeEfFgGhH" + - name: punctuation-not-allowed + in: + s: "Aa!Bb" + out: "Aa" + - name: single-valid-pair-inside + in: + s: "xyzZyY" + out: "yzZyY" + - name: generated-small + in: + s: + gen: "str" + len: 1 + alphabet: "aAbBcx" + - name: generated-medium + in: + s: + gen: "str" + len: 20 + alphabet: "aAbBcCdDeEq" + - name: generated-dense + in: + s: + gen: "str" + len: 60 + alphabet: "aAbBcCdDeEfF" + - name: generated-near-limit + in: + s: + gen: "str" + len: 99 + alphabet: "aAbBcCdDeExY" + - name: generated-max + in: + s: + gen: "str" + len: 100 + alphabet: "aAbBcCdDeEfFgGz" diff --git a/tests/1501-2000/1763. longest-nice-substring/sol.cpp b/tests/1501-2000/1763. longest-nice-substring/sol.cpp new file mode 100644 index 00000000..7ad3ff2e --- /dev/null +++ b/tests/1501-2000/1763. longest-nice-substring/sol.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + string longestNiceSubstring(string s) { + int len_s = s.length(); + if (len_s <= 1) return ""; + + unordered_map charToFreqMap; + for (char c : s) { + charToFreqMap[c]++; + } + + bool isBroken = false; + int i = 0; + while (i < s.length()) { + char ch = s[i]; + if (islower(ch) && charToFreqMap.count(toupper(ch))) { + // pass + } else if (isupper(ch) && charToFreqMap.count(tolower(ch))) { + // pass + } else { + isBroken = true; + break; + } + i++; + } + + if (!isBroken) return s; + + string longestNiceSubstr1 = longestNiceSubstring(s.substr(0, i)); + string longestNiceSubstr2 = longestNiceSubstring(s.substr(i + 1)); + + return longestNiceSubstr1.length() >= longestNiceSubstr2.length() ? longestNiceSubstr1 : longestNiceSubstr2; + } +}; diff --git a/tests/1501-2000/1763. longest-nice-substring/sol.cs b/tests/1501-2000/1763. longest-nice-substring/sol.cs new file mode 100644 index 00000000..c54e6ab8 --- /dev/null +++ b/tests/1501-2000/1763. longest-nice-substring/sol.cs @@ -0,0 +1,33 @@ +public class Solution { + public string LongestNiceSubstring(string s) { + int len_s = s.Length; + if (len_s <= 1) return ""; + + Dictionary charToFreqMap = new Dictionary(); + foreach (char c in s) { + charToFreqMap[c] = charToFreqMap.GetValueOrDefault(c, 0) + 1; + } + + bool isBroken = false; + int i = 0; + while (i < s.Length) { + char ch = s[i]; + if (char.IsLower(ch) && charToFreqMap.ContainsKey(char.ToUpper(ch))) { + // pass + } else if (char.IsUpper(ch) && charToFreqMap.ContainsKey(char.ToLower(ch))) { + // pass + } else { + isBroken = true; + break; + } + i++; + } + + if (!isBroken) return s; + + string longestNiceSubstr1 = LongestNiceSubstring(s.Substring(0, i)); + string longestNiceSubstr2 = LongestNiceSubstring(s.Substring(i + 1)); + + return longestNiceSubstr1.Length >= longestNiceSubstr2.Length ? longestNiceSubstr1 : longestNiceSubstr2; + } +} diff --git a/tests/1501-2000/1763. longest-nice-substring/sol.dart b/tests/1501-2000/1763. longest-nice-substring/sol.dart new file mode 100644 index 00000000..4d2befbb --- /dev/null +++ b/tests/1501-2000/1763. longest-nice-substring/sol.dart @@ -0,0 +1,33 @@ +class Solution { + String longestNiceSubstring(String s) { + int lenS = s.length; + if (lenS <= 1) return ""; + + Map charToFreqMap = {}; + for (int i = 0; i < s.length; i++) { + charToFreqMap[s[i]] = (charToFreqMap[s[i]] ?? 0) + 1; + } + + bool isBroken = false; + int i = 0; + while (i < s.length) { + String ch = s[i]; + if (ch.codeUnitAt(0) >= 97 && ch.codeUnitAt(0) <= 122 && charToFreqMap.containsKey(ch.toUpperCase())) { + // pass + } else if (ch.codeUnitAt(0) >= 65 && ch.codeUnitAt(0) <= 90 && charToFreqMap.containsKey(ch.toLowerCase())) { + // pass + } else { + isBroken = true; + break; + } + i++; + } + + if (!isBroken) return s; + + String longestNiceSubstr1 = longestNiceSubstring(s.substring(0, i)); + String longestNiceSubstr2 = longestNiceSubstring(s.substring(i + 1)); + + return longestNiceSubstr1.length >= longestNiceSubstr2.length ? longestNiceSubstr1 : longestNiceSubstr2; + } +} diff --git a/tests/1501-2000/1763. longest-nice-substring/sol.go b/tests/1501-2000/1763. longest-nice-substring/sol.go new file mode 100644 index 00000000..7feb2735 --- /dev/null +++ b/tests/1501-2000/1763. longest-nice-substring/sol.go @@ -0,0 +1,40 @@ +func longestNiceSubstring(s string) string { + lenS := len(s) + if lenS <= 1 { + return "" + } + + charToFreqMap := make(map[byte]int) + for i := 0; i < len(s); i++ { + charToFreqMap[s[i]]++ + } + + isBroken := false + i := 0 + for i < len(s) { + ch := s[i] + if (ch >= 'a' && ch <= 'z' && charToFreqMap[ch-32] > 0) { + // pass + } else if (ch >= 'A' && ch <= 'Z' && charToFreqMap[ch+32] > 0) { + // pass + } else { + isBroken = true + break + } + i++ + } + + if !isBroken { + return s + } + + longestNiceSubstr1 := longestNiceSubstring(s[:i]) + if i+1 < len(s) { + longestNiceSubstr2 := longestNiceSubstring(s[i+1:]) + if len(longestNiceSubstr1) >= len(longestNiceSubstr2) { + return longestNiceSubstr1 + } + return longestNiceSubstr2 + } + return longestNiceSubstr1 +} diff --git a/tests/1501-2000/1763. longest-nice-substring/sol.java b/tests/1501-2000/1763. longest-nice-substring/sol.java new file mode 100644 index 00000000..097d1573 --- /dev/null +++ b/tests/1501-2000/1763. longest-nice-substring/sol.java @@ -0,0 +1,33 @@ +class Solution { + public String longestNiceSubstring(String s) { + int len_s = s.length(); + if (len_s <= 1) return ""; + + java.util.HashMap charToFreqMap = new java.util.HashMap<>(); + for (char c : s.toCharArray()) { + charToFreqMap.put(c, charToFreqMap.getOrDefault(c, 0) + 1); + } + + boolean isBroken = false; + int i = 0; + while (i < s.length()) { + char ch = s.charAt(i); + if (Character.isLowerCase(ch) && charToFreqMap.containsKey(Character.toUpperCase(ch))) { + // pass + } else if (Character.isUpperCase(ch) && charToFreqMap.containsKey(Character.toLowerCase(ch))) { + // pass + } else { + isBroken = true; + break; + } + i++; + } + + if (!isBroken) return s; + + String longestNiceSubstr1 = longestNiceSubstring(s.substring(0, i)); + String longestNiceSubstr2 = longestNiceSubstring(s.substring(i + 1)); + + return longestNiceSubstr1.length() >= longestNiceSubstr2.length() ? longestNiceSubstr1 : longestNiceSubstr2; + } +} diff --git a/tests/1501-2000/1763. longest-nice-substring/sol.kt b/tests/1501-2000/1763. longest-nice-substring/sol.kt new file mode 100644 index 00000000..70171c02 --- /dev/null +++ b/tests/1501-2000/1763. longest-nice-substring/sol.kt @@ -0,0 +1,33 @@ +class Solution { + fun longestNiceSubstring(s: String): String { + val lenS = s.length + if (lenS <= 1) return "" + + val charToFreqMap = HashMap() + for (c in s) { + charToFreqMap[c] = charToFreqMap.getOrDefault(c, 0) + 1 + } + + var isBroken = false + var i = 0 + while (i < s.length) { + val ch = s[i] + if (ch.isLowerCase() && charToFreqMap.containsKey(ch.uppercaseChar())) { + // pass + } else if (ch.isUpperCase() && charToFreqMap.containsKey(ch.lowercaseChar())) { + // pass + } else { + isBroken = true + break + } + i++ + } + + if (!isBroken) return s + + val longestNiceSubstr1 = longestNiceSubstring(s.substring(0, i)) + val longestNiceSubstr2 = longestNiceSubstring(s.substring(i + 1)) + + return if (longestNiceSubstr1.length >= longestNiceSubstr2.length) longestNiceSubstr1 else longestNiceSubstr2 + } +} diff --git a/tests/1501-2000/1763. longest-nice-substring/sol.py b/tests/1501-2000/1763. longest-nice-substring/sol.py new file mode 100644 index 00000000..181e16f2 --- /dev/null +++ b/tests/1501-2000/1763. longest-nice-substring/sol.py @@ -0,0 +1,35 @@ +from collections import defaultdict + + +class Solution: + def longestNiceSubstring(self, s): + len_s = len(s) + if len_s <= 1: + return "" + + char_to_freq_map = defaultdict(int) + for c in s: + char_to_freq_map[c] += 1 + + is_broken = False + i = 0 + while i < len(s): + if s[i].islower() and s[i].upper() in char_to_freq_map.keys(): + pass + elif s[i].isupper() and s[i].lower() in char_to_freq_map.keys(): + pass + else: + is_broken = True + break + i += 1 + + if not is_broken: + return s + + longest_nice_substr_1 = self.longestNiceSubstring(s[:i]) + longest_nice_substr_2 = self.longestNiceSubstring(s[i + 1 :]) + + if len(longest_nice_substr_1) >= len(longest_nice_substr_2): + return longest_nice_substr_1 + else: + return longest_nice_substr_2 diff --git a/tests/1501-2000/1763. longest-nice-substring/sol.py2 b/tests/1501-2000/1763. longest-nice-substring/sol.py2 new file mode 100644 index 00000000..95f5c59a --- /dev/null +++ b/tests/1501-2000/1763. longest-nice-substring/sol.py2 @@ -0,0 +1,36 @@ +class Solution(object): + def longestNiceSubstring(self, s): + """ + :type s: str + :rtype: str + """ + len_s = len(s) + if len_s <= 1: + return '' + + char_to_freq_map = {} + for c in s: + char_to_freq_map[c] = char_to_freq_map.get(c, 0) + 1 + + is_broken = False + i = 0 + while (i < len(s)): + if s[i].islower() and s[i].upper() in char_to_freq_map: + pass + elif s[i].isupper() and s[i].lower() in char_to_freq_map: + pass + else: + is_broken = True + break + i += 1 + + if not is_broken: + return s + + longest_nice_substr_1 = self.longestNiceSubstring(s[:i]) + longest_nice_substr_2 = self.longestNiceSubstring(s[i+1:]) + + if len(longest_nice_substr_1)>=len(longest_nice_substr_2): + return longest_nice_substr_1 + else: + return longest_nice_substr_2 diff --git a/tests/1501-2000/1763. longest-nice-substring/sol.rb b/tests/1501-2000/1763. longest-nice-substring/sol.rb new file mode 100644 index 00000000..6c3194be --- /dev/null +++ b/tests/1501-2000/1763. longest-nice-substring/sol.rb @@ -0,0 +1,32 @@ +# @param {String} s +# @return {String} +def longest_nice_substring(s) + len_s = s.length + return '' if len_s <= 1 + + char_to_freq_map = {} + s.each_char do |c| + char_to_freq_map[c] = char_to_freq_map.fetch(c, 0) + 1 + end + + is_broken = false + i = 0 + while (i < s.length) + if s[i] =~ /[a-z]/ && char_to_freq_map.key?(s[i].upcase) + # pass + elsif s[i] =~ /[A-Z]/ && char_to_freq_map.key?(s[i].downcase) + # pass + else + is_broken = true + break + end + i += 1 + end + + return s unless is_broken + + longest_nice_substr_1 = longest_nice_substring(s[0...i]) + longest_nice_substr_2 = longest_nice_substring(s[(i+1)..-1] || '') + + longest_nice_substr_1.length >= longest_nice_substr_2.length ? longest_nice_substr_1 : longest_nice_substr_2 +end diff --git a/tests/1501-2000/1763. longest-nice-substring/sol.rs b/tests/1501-2000/1763. longest-nice-substring/sol.rs new file mode 100644 index 00000000..69f22032 --- /dev/null +++ b/tests/1501-2000/1763. longest-nice-substring/sol.rs @@ -0,0 +1,45 @@ +impl Solution { + pub fn longest_nice_substring(s: String) -> String { + let len_s = s.len(); + if len_s <= 1 { + return String::new(); + } + + let mut char_to_freq_map = std::collections::HashMap::new(); + for c in s.chars() { + *char_to_freq_map.entry(c).or_insert(0) += 1; + } + + let mut is_broken = false; + let mut i = 0; + let chars: Vec = s.chars().collect(); + while (i < chars.len()) { + let ch = chars[i]; + if ch.is_lowercase() && char_to_freq_map.contains_key(&ch.to_uppercase().next().unwrap()) { + // pass + } else if ch.is_uppercase() && char_to_freq_map.contains_key(&ch.to_lowercase().next().unwrap()) { + // pass + } else { + is_broken = true; + break; + } + i += 1; + } + + if !is_broken { + return s; + } + + let left = &s[..i]; + let right = if i + 1 <= s.len() { &s[i+1..] } else { "" }; + + let longest_nice_substr_1 = Self::longest_nice_substring(left.to_string()); + let longest_nice_substr_2 = Self::longest_nice_substring(right.to_string()); + + if longest_nice_substr_1.len() >= longest_nice_substr_2.len() { + longest_nice_substr_1 + } else { + longest_nice_substr_2 + } + } +} diff --git a/tests/1501-2000/1763. longest-nice-substring/sol.swift b/tests/1501-2000/1763. longest-nice-substring/sol.swift new file mode 100644 index 00000000..bc70da5e --- /dev/null +++ b/tests/1501-2000/1763. longest-nice-substring/sol.swift @@ -0,0 +1,39 @@ +class Solution { + func longestNiceSubstring(_ s: String) -> String { + let lenS = s.count + if lenS <= 1 { return "" } + + var charToFreqMap: [Character: Int] = [:] + for c in s { + charToFreqMap[c, default: 0] += 1 + } + + var isBroken = false + var i = 0 + let chars = Array(s) + while (i < chars.count) { + let ch = chars[i] + if ch.isLowercase && charToFreqMap[ch.uppercased().first!] != nil { + // pass + } else if ch.isUppercase && charToFreqMap[ch.lowercased().first!] != nil { + // pass + } else { + isBroken = true + break + } + i += 1 + } + + if !isBroken { return s } + + let index = chars.index(chars.startIndex, offsetBy: i) + let stringArray = Array(s) + let left = String(stringArray[0..= longestNiceSubstr2.count ? longestNiceSubstr1 : longestNiceSubstr2 + } +} diff --git a/tests/1501-2000/1763. longest-nice-substring/sol.ts b/tests/1501-2000/1763. longest-nice-substring/sol.ts new file mode 100644 index 00000000..b56be276 --- /dev/null +++ b/tests/1501-2000/1763. longest-nice-substring/sol.ts @@ -0,0 +1,33 @@ +function longestNiceSubstring(s: string): string { + const lenS = s.length; + if (lenS <= 1) return ""; + + const charToFreqMap: Map = new Map(); + for (const c of s) { + charToFreqMap.set(c, (charToFreqMap.get(c) || 0) + 1); + } + + let isBroken = false; + let i = 0; + while (i < s.length) { + const ch = s[i]; + if (ch >= "a" && ch <= "z" && charToFreqMap.has(ch.toUpperCase())) { + // pass + } else if (ch >= "A" && ch <= "Z" && charToFreqMap.has(ch.toLowerCase())) { + // pass + } else { + isBroken = true; + break; + } + i++; + } + + if (!isBroken) return s; + + const longestNiceSubstr1 = longestNiceSubstring(s.substring(0, i)); + const longestNiceSubstr2 = longestNiceSubstring(s.substring(i + 1)); + + return longestNiceSubstr1.length >= longestNiceSubstr2.length + ? longestNiceSubstr1 + : longestNiceSubstr2; +} diff --git a/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/manifest.yaml b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/manifest.yaml new file mode 100644 index 00000000..c828255b --- /dev/null +++ b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/manifest.yaml @@ -0,0 +1,284 @@ +entry: + id: 1764 + title: "form-array-by-concatenating-subarrays-of-another-array" + params: + groups: + type: array + items: + type: array + items: + type: int + nums: + type: array + items: + type: int + call: + cpp: "Solution().canChoose({groups}, {nums})" + rust: "Solution::can_choose({groups}, {nums})" + python3: "Solution().canChoose({groups}, {nums})" + python2: "Solution().canChoose({groups}, {nums})" + ruby: "can_choose({groups}, {nums})" + java: "new Solution().canChoose({groups}, {nums})" + csharp: "new Solution().CanChoose({groups}, {nums})" + kotlin: "Solution().canChoose({groups}, {nums})" + go: "canChoose({groups}, {nums})" + dart: "Solution().canChoose({groups}, {nums})" + swift: "Solution().canChoose({groups}, {nums})" + typescript: "canChoose({groups}, {nums})" + +judge: + type: exact + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().canChoose(groups, nums, {result})" + checker: | + class Checker: + def canChoose(self, groups, nums, result): + i = 0 + expected = True + for group in groups: + found = False + while i + len(group) <= len(nums): + if nums[i:i + len(group)] == group: + i += len(group) + found = True + break + i += 1 + if not found: + expected = False + break + return isinstance(result, bool) and result == expected + +seed: 1764 + +tests: + - name: examples-1 + in: + groups: [[1, -1, -1], [3, -2, 0]] + nums: [1, -1, 0, 1, -1, -1, 3, -2, 0] + out: true + - name: examples-2-order + in: + groups: [[10, -2], [1, 2, 3, 4]] + nums: [1, 2, 3, 4, 10, -2] + out: false + - name: examples-3-overlap + in: + groups: [[1, 2, 3], [3, 4]] + nums: [7, 7, 1, 2, 3, 4, 7, 7] + out: false + - name: one-group-exact + in: + groups: [[5, 6, 7]] + nums: [5, 6, 7] + out: true + - name: one-group-inside + in: + groups: [[5, 6]] + nums: [0, 5, 6, 9] + out: true + - name: one-group-missing + in: + groups: [[5, 6]] + nums: [0, 5, 7, 6] + out: false + - name: empty-gap + in: + groups: [[1], [3]] + nums: [1, 2, 3] + out: true + - name: adjacent-groups + in: + groups: [[1, 2], [3, 4]] + nums: [1, 2, 3, 4] + out: true + - name: repeated-groups + in: + groups: [[2], [2], [2]] + nums: [2, 2, 2] + out: true + - name: repeated-insufficient + in: + groups: [[2], [2], [2]] + nums: [2, 2] + out: false + - name: repeated-with-noise + in: + groups: [[2], [2]] + nums: [2, 9, 2] + out: true + - name: negative-values + in: + groups: [[-3, -2], [0, -1]] + nums: [8, -3, -2, 5, 0, -1] + out: true + - name: large-values + in: + groups: [[10000000], [-10000000]] + nums: [10000000, -10000000] + out: true + - name: large-values-reversed + in: + groups: [[10000000], [-10000000]] + nums: [-10000000, 10000000] + out: false + - name: prefix-match-then-valid + in: + groups: [[1, 2], [3]] + nums: [1, 9, 1, 2, 3] + out: true + - name: prefix-match-wrong-order + in: + groups: [[1, 2], [3]] + nums: [1, 2, 9, 3] + out: true + - name: group-prefix-conflict + in: + groups: [[1, 2, 3], [2, 3]] + nums: [1, 2, 3, 2, 3] + out: true + - name: overlapping-only + in: + groups: [[1, 2], [2, 3]] + nums: [1, 2, 3] + out: false + - name: trailing-unused + in: + groups: [[4], [5]] + nums: [0, 4, 0, 5, 0] + out: true + - name: no-space-after-first + in: + groups: [[4, 5], [6]] + nums: [4, 5] + out: false + - name: many-singletons + in: + groups: [[1], [3], [5], [7], [9]] + nums: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + out: true + - name: singleton-order-fail + in: + groups: [[1], [3], [5]] + nums: [5, 3, 1] + out: false + - name: duplicate-long-group + in: + groups: [[1, 1, 2], [1, 1, 2]] + nums: [1, 1, 2, 0, 1, 1, 2] + out: true + - name: duplicate-long-insufficient + in: + groups: [[1, 1, 2], [1, 1, 2]] + nums: [1, 1, 2, 0, 1, 2] + out: false + - name: group-at-end + in: + groups: [[0, 0], [9, 8, 7]] + nums: [1, 2, 3, 0, 0, 4, 9, 8, 7] + out: true + - name: first-group-at-end-impossible + in: + groups: [[9, 8], [7]] + nums: [7, 9, 8] + out: false + - name: all-negative + in: + groups: [[-1, -2], [-3, -4]] + nums: [-1, -2, -3, -4] + out: true + - name: mismatch-last-element + in: + groups: [[1, 2, 3], [4, 5]] + nums: [1, 2, 9, 4, 5] + out: false + - name: later-valid-occurrence + in: + groups: [[1, 2], [4]] + nums: [1, 9, 1, 2, 4] + out: true + - name: later-occurrence-would-overlap + in: + groups: [[1, 2], [2, 3]] + nums: [1, 2, 1, 2, 3] + out: true + - name: all-values-equal + in: + groups: [[3, 3], [3, 3], [3]] + nums: [3, 3, 3, 3, 3] + out: true + - name: generated-no-match + in: + groups: [[10000000, 9999999], [8888888]] + nums: + gen: array + len: 1000 + of: + gen: int + min: -10000000 + max: 10000000 + elemType: int + judge: + type: exact + seed: 176401 + - name: generated-singletons + in: + groups: [[10000000], [-10000000]] + nums: + gen: array + len: 1000 + of: + gen: int + min: -10000000 + max: 10000000 + elemType: int + judge: + type: exact + seed: 176402 + - name: generated-long-pattern + in: + groups: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] + nums: + gen: array + len: 1000 + of: + gen: int + min: -10000000 + max: 10000000 + elemType: int + judge: + type: exact + seed: 176403 + - name: generated-negative-pattern + in: + groups: [[-1, -2, -3], [4, 5]] + nums: + gen: array + len: 1000 + of: + gen: int + min: -10000000 + max: 10000000 + elemType: int + judge: + type: exact + seed: 176404 + - name: generated-repeated-pattern + in: + groups: [[0, 0, 0], [1, 1]] + nums: + gen: array + len: 1000 + of: + gen: int + min: -10000000 + max: 10000000 + elemType: int + judge: + type: exact + seed: 176405 diff --git a/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.cpp b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.cpp new file mode 100644 index 00000000..413a4338 --- /dev/null +++ b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + bool canChoose(vector>& groups, vector& nums) { + int i = 0; + for (auto& group : groups) { + bool found = false; + while (i + group.size() <= nums.size()) { + bool match = true; + for (int j = 0; j < group.size(); j++) { + if (nums[i + j] != group[j]) { + match = false; + break; + } + } + if (match) { + i += group.size(); + found = true; + break; + } else { + i++; + } + } + if (!found) return false; + } + return true; + } +}; diff --git a/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.cs b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.cs new file mode 100644 index 00000000..bbe42577 --- /dev/null +++ b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.cs @@ -0,0 +1,26 @@ +public class Solution { + public bool CanChoose(int[][] groups, int[] nums) { + int i = 0; + foreach (var group in groups) { + bool found = false; + while (i + group.Length <= nums.Length) { + bool match = true; + for (int j = 0; j < group.Length; j++) { + if (nums[i + j] != group[j]) { + match = false; + break; + } + } + if (match) { + i += group.Length; + found = true; + break; + } else { + i++; + } + } + if (!found) return false; + } + return true; + } +} diff --git a/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.dart b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.dart new file mode 100644 index 00000000..1e775b80 --- /dev/null +++ b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.dart @@ -0,0 +1,26 @@ +class Solution { + bool canChoose(List> groups, List nums) { + int i = 0; + for (var group in groups) { + bool found = false; + while (i + group.length <= nums.length) { + bool match = true; + for (int j = 0; j < group.length; j++) { + if (nums[i + j] != group[j]) { + match = false; + break; + } + } + if (match) { + i += group.length; + found = true; + break; + } else { + i++; + } + } + if (!found) return false; + } + return true; + } +} diff --git a/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.go b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.go new file mode 100644 index 00000000..3f682a3b --- /dev/null +++ b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.go @@ -0,0 +1,26 @@ +func canChoose(groups [][]int, nums []int) bool { + i := 0 + for _, group := range groups { + found := false + for i + len(group) <= len(nums) { + match := true + for j := 0; j < len(group); j++ { + if nums[i+j] != group[j] { + match = false + break + } + } + if match { + i += len(group) + found = true + break + } else { + i++ + } + } + if !found { + return false + } + } + return true +} diff --git a/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.java b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.java new file mode 100644 index 00000000..b94af72b --- /dev/null +++ b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.java @@ -0,0 +1,26 @@ +class Solution { + public boolean canChoose(int[][] groups, int[] nums) { + int i = 0; + for (int[] group : groups) { + boolean found = false; + while (i + group.length <= nums.length) { + boolean match = true; + for (int j = 0; j < group.length; j++) { + if (nums[i + j] != group[j]) { + match = false; + break; + } + } + if (match) { + i += group.length; + found = true; + break; + } else { + i++; + } + } + if (!found) return false; + } + return true; + } +} diff --git a/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.kt b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.kt new file mode 100644 index 00000000..b10cc119 --- /dev/null +++ b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.kt @@ -0,0 +1,26 @@ +class Solution { + fun canChoose(groups: Array, nums: IntArray): Boolean { + var i = 0 + for (group in groups) { + var found = false + while (i + group.size <= nums.size) { + var match = true + for (j in group.indices) { + if (nums[i + j] != group[j]) { + match = false + break + } + } + if (match) { + i += group.size + found = true + break + } else { + i++ + } + } + if (!found) return false + } + return true + } +} diff --git a/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.py b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.py new file mode 100644 index 00000000..1c8c8c54 --- /dev/null +++ b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.py @@ -0,0 +1,20 @@ +class Solution(object): + def canChoose(self, groups, nums): + """ + :type groups: List[List[int]] + :type nums: List[int] + :rtype: bool + """ + i = 0 + for group in groups: + found = False + while i + len(group) <= len(nums): + if nums[i : i + len(group)] == group: + i += len(group) + found = True + break + else: + i += 1 + if not found: + return False + return True diff --git a/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.py2 b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.py2 new file mode 100644 index 00000000..80e60d5b --- /dev/null +++ b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def canChoose(self, groups, nums): + """ + :type groups: List[List[int]] + :type nums: List[int] + :rtype: bool + """ + i = 0 + for group in groups: + found = False + while i + len(group) <= len(nums): + if nums[i:i + len(group)] == group: + i += len(group) + found = True + break + else: + i += 1 + if not found: + return False + return True diff --git a/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.rb b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.rb new file mode 100644 index 00000000..6ea58632 --- /dev/null +++ b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.rb @@ -0,0 +1,20 @@ +# @param {Integer[][]} groups +# @param {Integer[]} nums +# @return {Boolean} +def can_choose(groups, nums) + i = 0 + groups.each do |group| + found = false + while i + group.length <= nums.length + if nums[i, group.length] == group + i += group.length + found = true + break + else + i += 1 + end + end + return false unless found + end + true +end diff --git a/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.rs b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.rs new file mode 100644 index 00000000..d82ca0bb --- /dev/null +++ b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.rs @@ -0,0 +1,28 @@ +impl Solution { + pub fn can_choose(groups: Vec>, nums: Vec) -> bool { + let mut i = 0; + for group in groups { + let mut found = false; + while i + group.len() <= nums.len() { + let mut match_all = true; + for j in 0..group.len() { + if nums[i + j] != group[j] { + match_all = false; + break; + } + } + if match_all { + i += group.len(); + found = true; + break; + } else { + i += 1; + } + } + if !found { + return false; + } + } + true + } +} diff --git a/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.swift b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.swift new file mode 100644 index 00000000..d1072ee0 --- /dev/null +++ b/tests/1501-2000/1764. form-array-by-concatenating-subarrays-of-another-array/sol.swift @@ -0,0 +1,28 @@ +class Solution { + func canChoose(_ groups: [[Int]], _ nums: [Int]) -> Bool { + var i = 0 + for group in groups { + var found = false + while i + group.count <= nums.count { + var match = true + for j in 0.. 0: + return False + for di, dj in ((1, 0), (0, 1)): + ni, nj = i + di, j + dj + if ni < r and nj < c and abs(result[i][j] - result[ni][nj]) > 1: + return False + return True + +seed: 1765 + +tests: + - name: example-1 + in: + isWater: + - [0, 1] + - [0, 0] + - name: example-2 + in: + isWater: + - [0, 0, 1] + - [1, 0, 0] + - [0, 0, 0] + - name: one-water-single-row + in: + isWater: + - [0, 0, 0, 1, 0, 0, 0] + - name: one-water-single-column + in: + isWater: + - [0] + - [0] + - [1] + - [0] + - [0] + - name: all-water-1x1 + in: + isWater: + - [1] + - name: all-water-2x4 + in: + isWater: + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - name: corner-water-4x4 + in: + isWater: + - [1, 0, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - name: opposite-corners + in: + isWater: + - [1, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 1] + - name: vertical-stripe + in: + isWater: + - [0, 1, 0, 0] + - [0, 0, 0, 0] + - [0, 1, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - name: horizontal-stripe + in: + isWater: + - [0, 0, 0, 0, 0] + - [1, 1, 1, 1, 1] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - name: checker-3x3 + in: + isWater: + - [1, 0, 1] + - [0, 1, 0] + - [1, 0, 1] + - name: checker-4x5 + in: + isWater: + - [1, 0, 1, 0, 1] + - [0, 1, 0, 1, 0] + - [1, 0, 1, 0, 1] + - [0, 1, 0, 1, 0] + - name: central-water-5x5 + in: + isWater: + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 1, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - name: cross-water + in: + isWater: + - [0, 0, 1, 0, 0] + - [0, 0, 1, 0, 0] + - [1, 1, 1, 1, 1] + - [0, 0, 1, 0, 0] + - [0, 0, 1, 0, 0] + - name: ring-water + in: + isWater: + - [1, 1, 1, 1, 1] + - [1, 0, 0, 0, 1] + - [1, 0, 0, 0, 1] + - [1, 0, 0, 0, 1] + - [1, 1, 1, 1, 1] + - name: diagonal-water-6 + in: + isWater: + - [1, 0, 0, 0, 0, 0] + - [0, 1, 0, 0, 0, 0] + - [0, 0, 1, 0, 0, 0] + - [0, 0, 0, 1, 0, 0] + - [0, 0, 0, 0, 1, 0] + - [0, 0, 0, 0, 0, 1] + - name: sparse-2x7 + in: + isWater: + - [0, 0, 0, 1, 0, 0, 0] + - [1, 0, 0, 0, 0, 0, 1] + - name: sparse-7x2 + in: + isWater: + - [0, 1] + - [0, 0] + - [0, 0] + - [1, 0] + - [0, 0] + - [0, 0] + - [0, 1] + - name: two-islands + in: + isWater: + - [0, 0, 0, 0, 0, 0] + - [0, 1, 1, 0, 0, 0] + - [0, 0, 0, 0, 1, 0] + - [0, 0, 0, 0, 1, 0] + - name: dense-water + in: + isWater: + - [1, 1, 0, 1, 1] + - [1, 0, 0, 0, 1] + - [0, 0, 0, 0, 0] + - [1, 0, 0, 0, 1] + - [1, 1, 0, 1, 1] + - name: tall-9x3 + in: + isWater: + - [0, 0, 1] + - [0, 0, 0] + - [0, 1, 0] + - [0, 0, 0] + - [1, 0, 0] + - [0, 0, 0] + - [0, 0, 1] + - [0, 0, 0] + - [0, 1, 0] + - name: wide-3x9 + in: + isWater: + - [0, 0, 1, 0, 0, 0, 0, 0, 1] + - [0, 1, 0, 0, 0, 1, 0, 0, 0] + - [0, 0, 0, 0, 1, 0, 0, 1, 0] + - name: alternating-rows + in: + isWater: + - [1, 0, 1, 0, 1, 0] + - [0, 0, 0, 0, 0, 0] + - [0, 1, 0, 1, 0, 1] + - [0, 0, 0, 0, 0, 0] + - [1, 0, 1, 0, 1, 0] + - name: water-border + in: + isWater: + - [1, 1, 1, 1, 1, 1] + - [1, 0, 0, 0, 0, 1] + - [1, 0, 0, 0, 0, 1] + - [1, 1, 1, 1, 1, 1] + - name: one-hole + in: + isWater: + - [1, 1, 1] + - [1, 0, 1] + - [1, 1, 1] + - name: zigzag-water + in: + isWater: + - [1, 0, 0, 0, 0] + - [0, 0, 1, 0, 0] + - [0, 0, 0, 0, 1] + - [0, 0, 1, 0, 0] + - [1, 0, 0, 0, 0] + - name: nine-by-nine + in: + isWater: + - [0, 0, 0, 0, 1, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 1, 0, 0, 0, 1, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0] + - [1, 0, 0, 0, 0, 0, 0, 0, 1] + - [0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 1, 0, 0, 0, 1, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 1, 0, 0, 0, 0] + - name: all-land-except-center + in: + isWater: + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 1, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - name: 10x4-corners + in: + isWater: + - [1, 0, 0, 1] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - [1, 0, 0, 1] + - name: 4x10-middle + in: + isWater: + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 1, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 1, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: 12x1-center + in: + isWater: + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [1] + - [0] + - [0] + - [0] + - [0] + - [0] + - name: 1x12-many-water + in: + isWater: + - [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1] + - name: 7x7-diagonal-and-center + in: + isWater: + - [1, 0, 0, 0, 0, 0, 1] + - [0, 1, 0, 0, 0, 1, 0] + - [0, 0, 1, 0, 1, 0, 0] + - [0, 0, 0, 1, 0, 0, 0] + - [0, 0, 1, 0, 1, 0, 0] + - [0, 1, 0, 0, 0, 1, 0] + - [1, 0, 0, 0, 0, 0, 1] + - name: 15x2-alternating + in: + isWater: + - [1, 0] + - [0, 0] + - [0, 1] + - [0, 0] + - [1, 0] + - [0, 0] + - [0, 1] + - [0, 0] + - [1, 0] + - [0, 0] + - [0, 1] + - [0, 0] + - [1, 0] + - [0, 0] + - [0, 1] + - name: 20x3-spaced + in: + isWater: + - [1, 0, 0] + - [0, 0, 0] + - [0, 0, 1] + - [0, 0, 0] + - [0, 1, 0] + - [0, 0, 0] + - [1, 0, 0] + - [0, 0, 0] + - [0, 0, 1] + - [0, 0, 0] + - [0, 1, 0] + - [0, 0, 0] + - [1, 0, 0] + - [0, 0, 0] + - [0, 0, 1] + - [0, 0, 0] + - [0, 1, 0] + - [0, 0, 0] + - [1, 0, 0] + - [0, 0, 0] + - name: 25x1-end-water + in: + isWater: + - [1] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - [0] + - name: 30x30-periodic + in: + isWater: + - [ + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + - [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] diff --git a/tests/1501-2000/1765. map-of-highest-peak/sol.cpp b/tests/1501-2000/1765. map-of-highest-peak/sol.cpp new file mode 100644 index 00000000..f223bcdc --- /dev/null +++ b/tests/1501-2000/1765. map-of-highest-peak/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + vector> highestPeak(vector>& isWater) { + int r = isWater.size(); + int c = isWater[0].size(); + vector> height(r, vector(c, 1000000000)); + + for (int i = 0; i < r; ++i) { + for (int j = 0; j < c; ++j) { + if (isWater[i][j] == 1) { + height[i][j] = 0; + } else { + if (i > 0) height[i][j] = min(height[i][j], height[i - 1][j] + 1); + if (j > 0) height[i][j] = min(height[i][j], height[i][j - 1] + 1); + } + } + } + + for (int i = r - 1; i >= 0; --i) { + for (int j = c - 1; j >= 0; --j) { + if (i < r - 1) height[i][j] = min(height[i][j], height[i + 1][j] + 1); + if (j < c - 1) height[i][j] = min(height[i][j], height[i][j + 1] + 1); + } + } + + return height; + } +}; diff --git a/tests/1501-2000/1765. map-of-highest-peak/sol.cs b/tests/1501-2000/1765. map-of-highest-peak/sol.cs new file mode 100644 index 00000000..05e742eb --- /dev/null +++ b/tests/1501-2000/1765. map-of-highest-peak/sol.cs @@ -0,0 +1,31 @@ +public class Solution { + public int[][] HighestPeak(int[][] isWater) { + int r = isWater.Length; + int c = isWater[0].Length; + int[][] height = new int[r][]; + for (int i = 0; i < r; i++) { + height[i] = new int[c]; + Array.Fill(height[i], 1000000000); + } + + for (int i = 0; i < r; i++) { + for (int j = 0; j < c; j++) { + if (isWater[i][j] == 1) { + height[i][j] = 0; + } else { + if (i > 0) height[i][j] = Math.Min(height[i][j], height[i - 1][j] + 1); + if (j > 0) height[i][j] = Math.Min(height[i][j], height[i][j - 1] + 1); + } + } + } + + for (int i = r - 1; i >= 0; i--) { + for (int j = c - 1; j >= 0; j--) { + if (i < r - 1) height[i][j] = Math.Min(height[i][j], height[i + 1][j] + 1); + if (j < c - 1) height[i][j] = Math.Min(height[i][j], height[i][j + 1] + 1); + } + } + + return height; + } +} diff --git a/tests/1501-2000/1765. map-of-highest-peak/sol.dart b/tests/1501-2000/1765. map-of-highest-peak/sol.dart new file mode 100644 index 00000000..05d35c5a --- /dev/null +++ b/tests/1501-2000/1765. map-of-highest-peak/sol.dart @@ -0,0 +1,27 @@ +class Solution { + List> highestPeak(List> isWater) { + int r = isWater.length; + int c = isWater[0].length; + List> height = List.generate(r, (_) => List.filled(c, 1 << 30)); + + for (int i = 0; i < r; i++) { + for (int j = 0; j < c; j++) { + if (isWater[i][j] == 1) { + height[i][j] = 0; + } else { + if (i > 0) height[i][j] = (height[i][j] < height[i - 1][j] + 1) ? height[i][j] : height[i - 1][j] + 1; + if (j > 0) height[i][j] = (height[i][j] < height[i][j - 1] + 1) ? height[i][j] : height[i][j - 1] + 1; + } + } + } + + for (int i = r - 1; i >= 0; i--) { + for (int j = c - 1; j >= 0; j--) { + if (i < r - 1) height[i][j] = (height[i][j] < height[i + 1][j] + 1) ? height[i][j] : height[i + 1][j] + 1; + if (j < c - 1) height[i][j] = (height[i][j] < height[i][j + 1] + 1) ? height[i][j] : height[i][j + 1] + 1; + } + } + + return height; + } +} diff --git a/tests/1501-2000/1765. map-of-highest-peak/sol.go b/tests/1501-2000/1765. map-of-highest-peak/sol.go new file mode 100644 index 00000000..42887753 --- /dev/null +++ b/tests/1501-2000/1765. map-of-highest-peak/sol.go @@ -0,0 +1,40 @@ +func highestPeak(isWater [][]int) [][]int { + r := len(isWater) + c := len(isWater[0]) + height := make([][]int, r) + inf := 1000000000 + for i := 0; i < r; i++ { + height[i] = make([]int, c) + for j := 0; j < c; j++ { + height[i][j] = inf + } + } + + for i := 0; i < r; i++ { + for j := 0; j < c; j++ { + if isWater[i][j] == 1 { + height[i][j] = 0 + } else { + if i > 0 && height[i-1][j]+1 < height[i][j] { + height[i][j] = height[i-1][j] + 1 + } + if j > 0 && height[i][j-1]+1 < height[i][j] { + height[i][j] = height[i][j-1] + 1 + } + } + } + } + + for i := r - 1; i >= 0; i-- { + for j := c - 1; j >= 0; j-- { + if i < r-1 && height[i+1][j]+1 < height[i][j] { + height[i][j] = height[i+1][j] + 1 + } + if j < c-1 && height[i][j+1]+1 < height[i][j] { + height[i][j] = height[i][j+1] + 1 + } + } + } + + return height +} diff --git a/tests/1501-2000/1765. map-of-highest-peak/sol.java b/tests/1501-2000/1765. map-of-highest-peak/sol.java new file mode 100644 index 00000000..0cbec3b4 --- /dev/null +++ b/tests/1501-2000/1765. map-of-highest-peak/sol.java @@ -0,0 +1,28 @@ +class Solution { + public int[][] highestPeak(int[][] isWater) { + int r = isWater.length; + int c = isWater[0].length; + int[][] height = new int[r][c]; + for (int[] row : height) java.util.Arrays.fill(row, 1000000000); + + for (int i = 0; i < r; i++) { + for (int j = 0; j < c; j++) { + if (isWater[i][j] == 1) { + height[i][j] = 0; + } else { + if (i > 0) height[i][j] = Math.min(height[i][j], height[i - 1][j] + 1); + if (j > 0) height[i][j] = Math.min(height[i][j], height[i][j - 1] + 1); + } + } + } + + for (int i = r - 1; i >= 0; i--) { + for (int j = c - 1; j >= 0; j--) { + if (i < r - 1) height[i][j] = Math.min(height[i][j], height[i + 1][j] + 1); + if (j < c - 1) height[i][j] = Math.min(height[i][j], height[i][j + 1] + 1); + } + } + + return height; + } +} diff --git a/tests/1501-2000/1765. map-of-highest-peak/sol.kt b/tests/1501-2000/1765. map-of-highest-peak/sol.kt new file mode 100644 index 00000000..1d62a3e9 --- /dev/null +++ b/tests/1501-2000/1765. map-of-highest-peak/sol.kt @@ -0,0 +1,27 @@ +class Solution { + fun highestPeak(isWater: Array): Array { + val r = isWater.size + val c = isWater[0].size + val height = Array(r) { IntArray(c) { 1_000_000_000 } } + + for (i in 0 until r) { + for (j in 0 until c) { + if (isWater[i][j] == 1) { + height[i][j] = 0 + } else { + if (i > 0) height[i][j] = minOf(height[i][j], height[i - 1][j] + 1) + if (j > 0) height[i][j] = minOf(height[i][j], height[i][j - 1] + 1) + } + } + } + + for (i in r - 1 downTo 0) { + for (j in c - 1 downTo 0) { + if (i < r - 1) height[i][j] = minOf(height[i][j], height[i + 1][j] + 1) + if (j < c - 1) height[i][j] = minOf(height[i][j], height[i][j + 1] + 1) + } + } + + return height + } +} diff --git a/tests/1501-2000/1765. map-of-highest-peak/sol.py b/tests/1501-2000/1765. map-of-highest-peak/sol.py new file mode 100644 index 00000000..068dcf1c --- /dev/null +++ b/tests/1501-2000/1765. map-of-highest-peak/sol.py @@ -0,0 +1,24 @@ +class Solution: + def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: + R = len(isWater) + C = len(isWater[0]) + height = [[float("inf")] * C for _ in range(R)] + + for i in range(R): + for j in range(C): + if isWater[i][j] == 1: + height[i][j] = 0 + else: + if i > 0: + height[i][j] = min(height[i][j], height[i - 1][j] + 1) + if j > 0: + height[i][j] = min(height[i][j], height[i][j - 1] + 1) + + for i in range(R - 1, -1, -1): + for j in range(C - 1, -1, -1): + if i < R - 1: + height[i][j] = min(height[i][j], height[i + 1][j] + 1) + if j < C - 1: + height[i][j] = min(height[i][j], height[i][j + 1] + 1) + + return height diff --git a/tests/1501-2000/1765. map-of-highest-peak/sol.py2 b/tests/1501-2000/1765. map-of-highest-peak/sol.py2 new file mode 100644 index 00000000..1d5dded8 --- /dev/null +++ b/tests/1501-2000/1765. map-of-highest-peak/sol.py2 @@ -0,0 +1,28 @@ +class Solution(object): + def highestPeak(self, isWater): + """ + :type isWater: List[List[int]] + :rtype: List[List[int]] + """ + R = len(isWater) + C = len(isWater[0]) + height = [[float('inf')] * C for _ in range(R)] + + for i in range(R): + for j in range(C): + if isWater[i][j] == 1: + height[i][j] = 0 + else: + if i > 0: + height[i][j] = min(height[i][j], height[i - 1][j] + 1) + if j > 0: + height[i][j] = min(height[i][j], height[i][j - 1] + 1) + + for i in range(R - 1, -1, -1): + for j in range(C - 1, -1, -1): + if i < R - 1: + height[i][j] = min(height[i][j], height[i + 1][j] + 1) + if j < C - 1: + height[i][j] = min(height[i][j], height[i][j + 1] + 1) + + return height diff --git a/tests/1501-2000/1765. map-of-highest-peak/sol.rb b/tests/1501-2000/1765. map-of-highest-peak/sol.rb new file mode 100644 index 00000000..7723c46e --- /dev/null +++ b/tests/1501-2000/1765. map-of-highest-peak/sol.rb @@ -0,0 +1,27 @@ +# @param {Integer[][]} is_water +# @return {Integer[][]} +def highest_peak(is_water) + r = is_water.length + c = is_water[0].length + height = Array.new(r) { Array.new(c, Float::INFINITY) } + + (0...r).each do |i| + (0...c).each do |j| + if is_water[i][j] == 1 + height[i][j] = 0 + else + height[i][j] = [height[i][j], height[i - 1][j] + 1].min if i > 0 + height[i][j] = [height[i][j], height[i][j - 1] + 1].min if j > 0 + end + end + end + + (0...r).reverse_each do |i| + (0...c).reverse_each do |j| + height[i][j] = [height[i][j], height[i + 1][j] + 1].min if i < r - 1 + height[i][j] = [height[i][j], height[i][j + 1] + 1].min if j < c - 1 + end + end + + height +end diff --git a/tests/1501-2000/1765. map-of-highest-peak/sol.rs b/tests/1501-2000/1765. map-of-highest-peak/sol.rs new file mode 100644 index 00000000..f9b8214b --- /dev/null +++ b/tests/1501-2000/1765. map-of-highest-peak/sol.rs @@ -0,0 +1,27 @@ +impl Solution { + pub fn highest_peak(is_water: Vec>) -> Vec> { + let r = is_water.len(); + let c = is_water[0].len(); + let mut height = vec![vec![1_000_000_000i32; c]; r]; + + for i in 0..r { + for j in 0..c { + if is_water[i][j] == 1 { + height[i][j] = 0; + } else { + if i > 0 { height[i][j] = height[i][j].min(height[i - 1][j] + 1); } + if j > 0 { height[i][j] = height[i][j].min(height[i][j - 1] + 1); } + } + } + } + + for i in (0..r).rev() { + for j in (0..c).rev() { + if i < r - 1 { height[i][j] = height[i][j].min(height[i + 1][j] + 1); } + if j < c - 1 { height[i][j] = height[i][j].min(height[i][j + 1] + 1); } + } + } + + height + } +} diff --git a/tests/1501-2000/1765. map-of-highest-peak/sol.swift b/tests/1501-2000/1765. map-of-highest-peak/sol.swift new file mode 100644 index 00000000..4b722a8a --- /dev/null +++ b/tests/1501-2000/1765. map-of-highest-peak/sol.swift @@ -0,0 +1,27 @@ +class Solution { + func highestPeak(_ isWater: [[Int]]) -> [[Int]] { + let r = isWater.count + let c = isWater[0].count + var height = [[Int]](repeating: [Int](repeating: 1_000_000_000, count: c), count: r) + + for i in 0.. 0 { height[i][j] = min(height[i][j], height[i - 1][j] + 1) } + if j > 0 { height[i][j] = min(height[i][j], height[i][j - 1] + 1) } + } + } + } + + for i in stride(from: r - 1, through: 0, by: -1) { + for j in stride(from: c - 1, through: 0, by: -1) { + if i < r - 1 { height[i][j] = min(height[i][j], height[i + 1][j] + 1) } + if j < c - 1 { height[i][j] = min(height[i][j], height[i][j + 1] + 1) } + } + } + + return height + } +} diff --git a/tests/1501-2000/1765. map-of-highest-peak/sol.ts b/tests/1501-2000/1765. map-of-highest-peak/sol.ts new file mode 100644 index 00000000..5d71ccbc --- /dev/null +++ b/tests/1501-2000/1765. map-of-highest-peak/sol.ts @@ -0,0 +1,29 @@ +function highestPeak(isWater: number[][]): number[][] { + const r = isWater.length; + const c = isWater[0].length; + const height: number[][] = Array.from({ length: r }, () => + Array(c).fill(Number.MAX_SAFE_INTEGER), + ); + + for (let i = 0; i < r; i++) { + for (let j = 0; j < c; j++) { + if (isWater[i][j] === 1) { + height[i][j] = 0; + } else { + if (i > 0) height[i][j] = Math.min(height[i][j], height[i - 1][j] + 1); + if (j > 0) height[i][j] = Math.min(height[i][j], height[i][j - 1] + 1); + } + } + } + + for (let i = r - 1; i >= 0; i--) { + for (let j = c - 1; j >= 0; j--) { + if (i < r - 1) + height[i][j] = Math.min(height[i][j], height[i + 1][j] + 1); + if (j < c - 1) + height[i][j] = Math.min(height[i][j], height[i][j + 1] + 1); + } + } + + return height; +} diff --git a/tests/1501-2000/1766. tree-of-coprimes/manifest.yaml b/tests/1501-2000/1766. tree-of-coprimes/manifest.yaml new file mode 100644 index 00000000..2e7256a5 --- /dev/null +++ b/tests/1501-2000/1766. tree-of-coprimes/manifest.yaml @@ -0,0 +1,803 @@ +entry: + id: 1766 + title: tree-of-coprimes + params: + nums: + type: array + items: + type: int + edges: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().getCoprimes({nums}, {edges})" + rust: "Solution::get_coprimes({nums}, {edges})" + python3: "Solution().getCoprimes({nums}, {edges})" + python2: "Solution().getCoprimes({nums}, {edges})" + ruby: "get_coprimes({nums}, {edges})" + java: "new Solution().getCoprimes({nums}, {edges})" + csharp: "new Solution().GetCoprimes({nums}, {edges})" + kotlin: "Solution().getCoprimes({nums}, {edges})" + go: "getCoprimes({nums}, {edges})" + dart: "Solution().getCoprimes({nums}, {edges})" + swift: "Solution().getCoprimes({nums}, {edges})" + typescript: "getCoprimes({nums}, {edges})" + +judge: + type: exact + +limits: + time_ms: 5000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().getCoprimes(nums, edges, {result})" + checker: | + import math + + class Checker: + def getCoprimes(self, nums, edges, result): + n = len(nums) + if not isinstance(result, list) or len(result) != n: + return False + adj = [[] for _ in range(n)] + if len(edges) != n - 1: + return False + for edge in edges: + if not isinstance(edge, list) or len(edge) != 2: + return False + u, v = edge + if not (0 <= u < n and 0 <= v < n and u != v): + return False + adj[u].append(v) + adj[v].append(u) + expected = [-1] * n + stack = [(0, -1, [])] + while stack: + node, parent, path = stack.pop() + for ancestor in reversed(path): + if math.gcd(nums[node], nums[ancestor]) == 1: + expected[node] = ancestor + break + next_path = path + [node] + for child in reversed(adj[node]): + if child != parent: + stack.append((child, node, next_path)) + return result == expected + +seed: 1766 + +tests: + - name: example-one + in: + nums: [2, 3, 3, 2] + edges: + - [0, 1] + - [1, 2] + - [1, 3] + - name: example-two + in: + nums: [5, 6, 10, 2, 3, 6, 15] + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - name: single-root + in: + nums: [1] + edges: [] + - name: two-coprime + in: + nums: [2, 3] + edges: + - [0, 1] + - name: two-equal + in: + nums: [7, 7] + edges: + - [0, 1] + - name: all-ones-chain + in: + nums: [1, 1, 1, 1, 1] + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - name: all-fifty-star + in: + nums: [50, 50, 50, 50, 50, 50] + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - name: alternating-chain + in: + nums: [6, 10, 15, 7, 14, 9, 21, 2] + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - name: prime-chain + in: + nums: [2, 3, 5, 7, 11, 13, 17, 19] + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - name: repeated-prime-factors + in: + nums: [30, 6, 10, 15, 21, 14, 35] + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - name: balanced-eight + in: + nums: [6, 35, 10, 21, 14, 15, 22, 49] + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [3, 7] + - name: coprime-root + in: + nums: [1, 50, 25, 49, 2, 3, 5] + edges: + - [0, 1] + - [1, 2] + - [1, 3] + - [2, 4] + - [2, 5] + - [3, 6] + - name: root-fifty + in: + nums: [50, 10, 3, 25, 7, 14] + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - name: deep-duplicates + in: + nums: [2, 4, 8, 16, 32, 3, 6, 12, 24, 48] + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - name: branch-prime-rescue + in: + nums: [30, 6, 10, 7, 14, 15, 11, 22, 13] + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [3, 6] + - [4, 7] + - [5, 8] + - name: value-one-leaves + in: + nums: [42, 6, 10, 1, 1, 15, 1] + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - name: max-value-mix + in: + nums: [50, 49, 48, 47, 46, 45, 44, 43, 42] + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [3, 7] + - [5, 8] + - name: skewed-right + in: + nums: [9, 27, 18, 25, 5, 10, 7, 14, 11, 22] + edges: + - [0, 1] + - [0, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - name: balanced-fifteen + in: + nums: [30, 6, 10, 15, 21, 14, 22, 35, 7, 11, 13, 5, 17, 19, 23] + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [3, 7] + - [3, 8] + - [4, 9] + - [4, 10] + - [5, 11] + - [5, 12] + - [6, 13] + - [6, 14] + - name: chain-twenty + in: + nums: + [ + 2, + 4, + 6, + 8, + 10, + 12, + 14, + 16, + 18, + 20, + 22, + 24, + 26, + 28, + 30, + 32, + 34, + 36, + 38, + 40, + ] + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [11, 12] + - [12, 13] + - [13, 14] + - [14, 15] + - [15, 16] + - [16, 17] + - [17, 18] + - [18, 19] + - name: star-twenty + in: + nums: + [30, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + - [0, 7] + - [0, 8] + - [0, 9] + - [0, 10] + - [0, 11] + - [0, 12] + - [0, 13] + - [0, 14] + - [0, 15] + - [0, 16] + - [0, 17] + - [0, 18] + - [0, 19] + - name: zigzag-thirty + in: + nums: + [ + 6, + 35, + 10, + 21, + 14, + 15, + 22, + 49, + 26, + 39, + 34, + 33, + 38, + 25, + 46, + 27, + 50, + 29, + 42, + 31, + 30, + 37, + 44, + 41, + 48, + 43, + 32, + 45, + 36, + 47, + ] + edges: + - [0, 1] + - [1, 2] + - [1, 3] + - [3, 4] + - [3, 5] + - [5, 6] + - [5, 7] + - [7, 8] + - [7, 9] + - [9, 10] + - [9, 11] + - [11, 12] + - [11, 13] + - [13, 14] + - [13, 15] + - [15, 16] + - [15, 17] + - [17, 18] + - [17, 19] + - [19, 20] + - [19, 21] + - [21, 22] + - [21, 23] + - [23, 24] + - [23, 25] + - [25, 26] + - [25, 27] + - [27, 28] + - [27, 29] + - name: repeated-seven-tree + in: + nums: [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7] + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [3, 7] + - [3, 8] + - [4, 9] + - [5, 10] + - [6, 11] + - name: coprime-everywhere + in: + nums: [47, 43, 41, 37, 31, 29, 23, 19, 17, 13, 11, 7] + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - name: mixed-factors-fourteen + in: + nums: [12, 18, 25, 49, 35, 22, 33, 26, 39, 17, 29, 46, 47, 50] + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [3, 7] + - [4, 8] + - [5, 9] + - [6, 10] + - [7, 11] + - [8, 12] + - [9, 13] + - name: chain-thirty-five + in: + nums: + [ + 50, + 45, + 40, + 35, + 30, + 25, + 20, + 15, + 10, + 5, + 2, + 3, + 7, + 11, + 13, + 17, + 19, + 23, + 29, + 31, + 37, + 41, + 43, + 47, + 49, + 1, + 6, + 14, + 21, + 28, + 33, + 39, + 44, + 46, + 48, + ] + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [11, 12] + - [12, 13] + - [13, 14] + - [14, 15] + - [15, 16] + - [16, 17] + - [17, 18] + - [18, 19] + - [19, 20] + - [20, 21] + - [21, 22] + - [22, 23] + - [23, 24] + - [24, 25] + - [25, 26] + - [26, 27] + - [27, 28] + - [28, 29] + - [29, 30] + - [30, 31] + - [31, 32] + - [32, 33] + - [33, 34] + - name: branch-thirty + in: + nums: + [ + 6, + 10, + 15, + 21, + 14, + 22, + 35, + 7, + 33, + 26, + 39, + 17, + 46, + 25, + 29, + 50, + 31, + 37, + 41, + 43, + 47, + 49, + 5, + 11, + 13, + 19, + 23, + 27, + 30, + 34, + ] + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 4] + - [1, 5] + - [2, 6] + - [2, 7] + - [3, 8] + - [3, 9] + - [4, 10] + - [5, 11] + - [6, 12] + - [7, 13] + - [8, 14] + - [9, 15] + - [10, 16] + - [11, 17] + - [12, 18] + - [13, 19] + - [14, 20] + - [15, 21] + - [16, 22] + - [17, 23] + - [18, 24] + - [19, 25] + - [20, 26] + - [21, 27] + - [22, 28] + - [23, 29] + - name: values-one-to-fifty + in: + nums: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + ] + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [3, 7] + - [3, 8] + - [4, 9] + - [4, 10] + - [5, 11] + - [5, 12] + - [6, 13] + - [6, 14] + - [7, 15] + - [7, 16] + - [8, 17] + - [8, 18] + - [9, 19] + - [9, 20] + - [10, 21] + - [10, 22] + - [11, 23] + - [11, 24] + - [12, 25] + - [12, 26] + - [13, 27] + - [13, 28] + - [14, 29] + - [14, 30] + - [15, 31] + - [16, 32] + - [17, 33] + - [18, 34] + - [19, 35] + - [20, 36] + - [21, 37] + - [22, 38] + - [23, 39] + - [24, 40] + - [25, 41] + - [26, 42] + - [27, 43] + - [28, 44] + - [29, 45] + - [30, 46] + - [31, 47] + - [32, 48] + - [33, 49] + - name: sparse-coprime-branches + in: + nums: [48, 16, 24, 30, 7, 11, 13, 17, 19, 23] + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 4] + - [1, 5] + - [2, 6] + - [2, 7] + - [3, 8] + - [3, 9] + - name: all-two-chain + in: + nums: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [11, 12] + - [12, 13] + - [13, 14] + - name: isolated-coprime-resets + in: + nums: [18, 6, 35, 10, 7, 14, 11, 22, 13, 26, 17, 34] + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - name: balanced-sixteen-repeats + in: + nums: [12, 25, 18, 35, 6, 49, 10, 21, 14, 22, 15, 33, 26, 39, 17, 46] + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [3, 7] + - [3, 8] + - [4, 9] + - [4, 10] + - [5, 11] + - [5, 12] + - [6, 13] + - [6, 14] + - [7, 15] + - name: prime-and-composite-star + in: + nums: [42, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + - [0, 7] + - [0, 8] + - [0, 9] + - [0, 10] + - [0, 11] + - name: alternating-branch-depth + in: + nums: + [30, 6, 5, 10, 7, 15, 11, 14, 13, 21, 17, 22, 19, 26, 23, 34, 29, 38] + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [3, 7] + - [4, 8] + - [5, 9] + - [6, 10] + - [7, 11] + - [8, 12] + - [9, 13] + - [10, 14] + - [11, 15] + - [12, 16] + - [13, 17] + - name: all-six-chain + in: + nums: [6, 6, 6, 6, 6, 6, 6, 6, 6, 6] + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] diff --git a/tests/1501-2000/1766. tree-of-coprimes/sol.cpp b/tests/1501-2000/1766. tree-of-coprimes/sol.cpp new file mode 100644 index 00000000..5e8c4c43 --- /dev/null +++ b/tests/1501-2000/1766. tree-of-coprimes/sol.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + vector getCoprimes(vector& nums, vector>& edges) { + int n = nums.size(); + vector> adj(n); + for (auto& e : edges) { + adj[e[0]].push_back(e[1]); + adj[e[1]].push_back(e[0]); + } + vector ans(n, -1); + vector depth(n, 0); + vector ancestorByValue(51, -1); + dfs(0, 0, 0, nums, adj, ans, depth, ancestorByValue); + return ans; + } + + void dfs(int node, int prev, int dep, vector& nums, vector>& adj, vector& ans, vector& depth, vector& ancestorByValue) { + depth[node] = dep; + int best = INT_MAX; + int bestAnc = -1; + for (int i = 1; i <= 50; i++) { + if (gcd(i, nums[node]) == 1) { + int anc = ancestorByValue[i]; + if (anc != -1) { + int diff = dep - depth[anc]; + if (diff < best) { + best = diff; + bestAnc = anc; + } + } + } + } + ans[node] = bestAnc; + int prevState = ancestorByValue[nums[node]]; + ancestorByValue[nums[node]] = node; + for (int v : adj[node]) { + if (v != prev) dfs(v, node, dep + 1, nums, adj, ans, depth, ancestorByValue); + } + ancestorByValue[nums[node]] = prevState; + } + + int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +}; diff --git a/tests/1501-2000/1766. tree-of-coprimes/sol.cs b/tests/1501-2000/1766. tree-of-coprimes/sol.cs new file mode 100644 index 00000000..e8980f2d --- /dev/null +++ b/tests/1501-2000/1766. tree-of-coprimes/sol.cs @@ -0,0 +1,52 @@ +public class Solution { + public int[] GetCoprimes(int[] nums, int[][] edges) { + int n = nums.Length; + List> adj = new List>(); + for (int i = 0; i < n; i++) adj.Add(new List()); + foreach (var e in edges) { + adj[e[0]].Add(e[1]); + adj[e[1]].Add(e[0]); + } + int[] ans = new int[n]; + Array.Fill(ans, -1); + int[] depth = new int[n]; + int[] ancestorByValue = new int[51]; + Array.Fill(ancestorByValue, -1); + Dfs(0, 0, 0, nums, adj, ans, depth, ancestorByValue); + return ans; + } + + private void Dfs(int node, int prev, int dep, int[] nums, List> adj, int[] ans, int[] depth, int[] ancestorByValue) { + depth[node] = dep; + int best = int.MaxValue; + int bestAnc = -1; + for (int i = 1; i <= 50; i++) { + if (Gcd(i, nums[node]) == 1) { + int anc = ancestorByValue[i]; + if (anc != -1) { + int diff = dep - depth[anc]; + if (diff < best) { + best = diff; + bestAnc = anc; + } + } + } + } + ans[node] = bestAnc; + int prevState = ancestorByValue[nums[node]]; + ancestorByValue[nums[node]] = node; + foreach (var v in adj[node]) { + if (v != prev) Dfs(v, node, dep + 1, nums, adj, ans, depth, ancestorByValue); + } + ancestorByValue[nums[node]] = prevState; + } + + private int Gcd(int a, int b) { + while (b != 0) { + int t = a % b; + a = b; + b = t; + } + return a; + } +} diff --git a/tests/1501-2000/1766. tree-of-coprimes/sol.dart b/tests/1501-2000/1766. tree-of-coprimes/sol.dart new file mode 100644 index 00000000..b55d0672 --- /dev/null +++ b/tests/1501-2000/1766. tree-of-coprimes/sol.dart @@ -0,0 +1,50 @@ +class Solution { + List getCoprimes(List nums, List> edges) { + int n = nums.length; + List> adj = List.generate(n, (_) => []); + for (var e in edges) { + adj[e[0]].add(e[1]); + adj[e[1]].add(e[0]); + } + List ans = List.filled(n, -1); + List depth = List.filled(n, 0); + List ancestorByValue = List.filled(51, -1); + + void dfs(int node, int prev, int dep) { + depth[node] = dep; + int best = 1 << 30; + int bestAnc = -1; + for (int i = 1; i <= 50; i++) { + if (gcd(i, nums[node]) == 1) { + int anc = ancestorByValue[i]; + if (anc != -1) { + int diff = dep - depth[anc]; + if (diff < best) { + best = diff; + bestAnc = anc; + } + } + } + } + ans[node] = bestAnc; + int prevState = ancestorByValue[nums[node]]; + ancestorByValue[nums[node]] = node; + for (var v in adj[node]) { + if (v != prev) dfs(v, node, dep + 1); + } + ancestorByValue[nums[node]] = prevState; + } + + dfs(0, 0, 0); + return ans; + } + + int gcd(int a, int b) { + while (b != 0) { + int t = a % b; + a = b; + b = t; + } + return a; + } +} diff --git a/tests/1501-2000/1766. tree-of-coprimes/sol.go b/tests/1501-2000/1766. tree-of-coprimes/sol.go new file mode 100644 index 00000000..a1347fdc --- /dev/null +++ b/tests/1501-2000/1766. tree-of-coprimes/sol.go @@ -0,0 +1,53 @@ +func getCoprimes(nums []int, edges [][]int) []int { + n := len(nums) + adj := make([][]int, n) + for _, e := range edges { + adj[e[0]] = append(adj[e[0]], e[1]) + adj[e[1]] = append(adj[e[1]], e[0]) + } + ans := make([]int, n) + for i := range ans { + ans[i] = -1 + } + depth := make([]int, n) + ancestorByValue := make([]int, 51) + for i := range ancestorByValue { + ancestorByValue[i] = -1 + } + var dfs func(node, prev, dep int) + dfs = func(node, prev, dep int) { + depth[node] = dep + best := int(^uint(0) >> 1) + bestAnc := -1 + for i := 1; i <= 50; i++ { + if gcd(i, nums[node]) == 1 { + anc := ancestorByValue[i] + if anc != -1 { + diff := dep - depth[anc] + if diff < best { + best = diff + bestAnc = anc + } + } + } + } + ans[node] = bestAnc + prevState := ancestorByValue[nums[node]] + ancestorByValue[nums[node]] = node + for _, v := range adj[node] { + if v != prev { + dfs(v, node, dep+1) + } + } + ancestorByValue[nums[node]] = prevState + } + dfs(0, 0, 0) + return ans +} + +func gcd(a, b int) int { + for b != 0 { + a, b = b, a%b + } + return a +} diff --git a/tests/1501-2000/1766. tree-of-coprimes/sol.java b/tests/1501-2000/1766. tree-of-coprimes/sol.java new file mode 100644 index 00000000..5e55e48d --- /dev/null +++ b/tests/1501-2000/1766. tree-of-coprimes/sol.java @@ -0,0 +1,47 @@ +class Solution { + public int[] getCoprimes(int[] nums, int[][] edges) { + int n = nums.length; + List> adj = new ArrayList<>(); + for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); + for (int[] e : edges) { + adj.get(e[0]).add(e[1]); + adj.get(e[1]).add(e[0]); + } + int[] ans = new int[n]; + Arrays.fill(ans, -1); + int[] depth = new int[n]; + int[] ancestorByValue = new int[51]; + Arrays.fill(ancestorByValue, -1); + dfs(0, 0, 0, nums, adj, ans, depth, ancestorByValue); + return ans; + } + + private void dfs(int node, int prev, int dep, int[] nums, List> adj, int[] ans, int[] depth, int[] ancestorByValue) { + depth[node] = dep; + int best = Integer.MAX_VALUE; + int bestAnc = -1; + for (int i = 1; i <= 50; i++) { + if (gcd(i, nums[node]) == 1) { + int anc = ancestorByValue[i]; + if (anc != -1) { + int diff = dep - depth[anc]; + if (diff < best) { + best = diff; + bestAnc = anc; + } + } + } + } + ans[node] = bestAnc; + int prevState = ancestorByValue[nums[node]]; + ancestorByValue[nums[node]] = node; + for (int v : adj.get(node)) { + if (v != prev) dfs(v, node, dep + 1, nums, adj, ans, depth, ancestorByValue); + } + ancestorByValue[nums[node]] = prevState; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} diff --git a/tests/1501-2000/1766. tree-of-coprimes/sol.kt b/tests/1501-2000/1766. tree-of-coprimes/sol.kt new file mode 100644 index 00000000..bb33db0b --- /dev/null +++ b/tests/1501-2000/1766. tree-of-coprimes/sol.kt @@ -0,0 +1,42 @@ +class Solution { + fun getCoprimes(nums: IntArray, edges: Array): IntArray { + val n = nums.size + val adj = Array(n) { mutableListOf() } + for (e in edges) { + adj[e[0]].add(e[1]) + adj[e[1]].add(e[0]) + } + val ans = IntArray(n) { -1 } + val depth = IntArray(n) + val ancestorByValue = IntArray(51) { -1 } + dfs(0, 0, 0, nums, adj, ans, depth, ancestorByValue) + return ans + } + + private fun dfs(node: Int, prev: Int, dep: Int, nums: IntArray, adj: Array>, ans: IntArray, depth: IntArray, ancestorByValue: IntArray) { + depth[node] = dep + var best = Int.MAX_VALUE + var bestAnc = -1 + for (i in 1..50) { + if (gcd(i, nums[node]) == 1) { + val anc = ancestorByValue[i] + if (anc != -1) { + val diff = dep - depth[anc] + if (diff < best) { + best = diff + bestAnc = anc + } + } + } + } + ans[node] = bestAnc + val prevState = ancestorByValue[nums[node]] + ancestorByValue[nums[node]] = node + for (v in adj[node]) { + if (v != prev) dfs(v, node, dep + 1, nums, adj, ans, depth, ancestorByValue) + } + ancestorByValue[nums[node]] = prevState + } + + private fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) +} diff --git a/tests/1501-2000/1766. tree-of-coprimes/sol.py b/tests/1501-2000/1766. tree-of-coprimes/sol.py new file mode 100644 index 00000000..27b9961d --- /dev/null +++ b/tests/1501-2000/1766. tree-of-coprimes/sol.py @@ -0,0 +1,36 @@ +class Solution: + def getCoprimes(self, nums: List[int], edges: List[List[int]]) -> List[int]: + n = len(nums) + + adj = [[] for i in range(n)] + for u, v in edges: + adj[u].append(v) + adj[v].append(u) + + ans = [-1 for i in range(n)] + depth = [0 for i in range(n)] + ancestorByValue = [-1 for _ in range(51)] + + def dfs(node, prev, dep): + depth[node] = dep + + t = float("inf") + for i in range(1, 51): + if math.gcd(i, nums[node]) == 1: + if ancestorByValue[i] != -1: + diff = depth[node] - depth[ancestorByValue[i]] + if diff < t: + ans[node] = ancestorByValue[i] + t = diff + + prev_state = ancestorByValue[nums[node]] + ancestorByValue[nums[node]] = node + + for v in adj[node]: + if v != prev: + dfs(v, node, dep + 1) + + ancestorByValue[nums[node]] = prev_state + + dfs(0, 0, 0) + return ans diff --git a/tests/1501-2000/1766. tree-of-coprimes/sol.py2 b/tests/1501-2000/1766. tree-of-coprimes/sol.py2 new file mode 100644 index 00000000..b42d9371 --- /dev/null +++ b/tests/1501-2000/1766. tree-of-coprimes/sol.py2 @@ -0,0 +1,45 @@ +class Solution(object): + def getCoprimes(self, nums, edges): + """ + :type nums: List[int] + :type edges: List[List[int]] + :rtype: List[int] + """ + import math + n = len(nums) + adj = [[] for _ in range(n)] + for u, v in edges: + adj[u].append(v) + adj[v].append(u) + + ans = [-1] * n + depth = [0] * n + ancestorByValue = [-1] * 51 + + def gcd(a, b): + while b: + a, b = b, a % b + return a + + def dfs(node, prev, dep): + depth[node] = dep + best = float('inf') + best_anc = -1 + for i in range(1, 51): + if gcd(i, nums[node]) == 1: + if ancestorByValue[i] != -1: + diff = dep - depth[ancestorByValue[i]] + if diff < best: + best = diff + best_anc = ancestorByValue[i] + ans[node] = best_anc + + prev_state = ancestorByValue[nums[node]] + ancestorByValue[nums[node]] = node + for v in adj[node]: + if v != prev: + dfs(v, node, dep + 1) + ancestorByValue[nums[node]] = prev_state + + dfs(0, 0, 0) + return ans diff --git a/tests/1501-2000/1766. tree-of-coprimes/sol.rb b/tests/1501-2000/1766. tree-of-coprimes/sol.rb new file mode 100644 index 00000000..b95eec4a --- /dev/null +++ b/tests/1501-2000/1766. tree-of-coprimes/sol.rb @@ -0,0 +1,47 @@ +# @param {Integer[]} nums +# @param {Integer[][]} edges +# @return {Integer[]} +def get_coprimes(nums, edges) + require 'set' + n = nums.length + adj = Array.new(n) { [] } + edges.each do |u, v| + adj[u] << v + adj[v] << u + end + + ans = Array.new(n, -1) + depth = Array.new(n, 0) + ancestor_by_value = Array.new(51, -1) + + gcd = ->(a, b) { b == 0 ? a : gcd.call(b, a % b) } + + dfs = ->(node, prev, dep) do + depth[node] = dep + best = Float::INFINITY + best_anc = -1 + (1..50).each do |i| + if gcd.call(i, nums[node]) == 1 + anc = ancestor_by_value[i] + if anc != -1 + diff = dep - depth[anc] + if diff < best + best = diff + best_anc = anc + end + end + end + end + ans[node] = best_anc + + prev_state = ancestor_by_value[nums[node]] + ancestor_by_value[nums[node]] = node + adj[node].each do |v| + dfs.call(v, node, dep + 1) if v != prev + end + ancestor_by_value[nums[node]] = prev_state + end + + dfs.call(0, 0, 0) + ans +end diff --git a/tests/1501-2000/1766. tree-of-coprimes/sol.rs b/tests/1501-2000/1766. tree-of-coprimes/sol.rs new file mode 100644 index 00000000..c2619862 --- /dev/null +++ b/tests/1501-2000/1766. tree-of-coprimes/sol.rs @@ -0,0 +1,46 @@ +impl Solution { + pub fn get_coprimes(nums: Vec, edges: Vec>) -> Vec { + let n = nums.len(); + let mut adj = vec![Vec::new(); n]; + for e in &edges { + adj[e[0] as usize].push(e[1] as usize); + adj[e[1] as usize].push(e[0] as usize); + } + let mut ans = vec![-1; n]; + let mut depth = vec![0; n]; + let mut ancestor_by_value = vec![-1i32; 51]; + Self::dfs(0, 0, 0, &nums, &adj, &mut ans, &mut depth, &mut ancestor_by_value); + ans + } + + fn dfs(node: usize, prev: usize, dep: i32, nums: &Vec, adj: &Vec>, ans: &mut Vec, depth: &mut Vec, ancestor_by_value: &mut Vec) { + depth[node] = dep; + let mut best = i32::MAX; + let mut best_anc = -1; + for i in 1..=50 { + if Self::gcd(i, nums[node]) == 1 { + let anc = ancestor_by_value[i as usize]; + if anc != -1 { + let diff = dep - depth[anc as usize]; + if diff < best { + best = diff; + best_anc = anc; + } + } + } + } + ans[node] = best_anc; + let prev_state = ancestor_by_value[nums[node] as usize]; + ancestor_by_value[nums[node] as usize] = node as i32; + for &v in &adj[node] { + if v != prev { + Self::dfs(v, node, dep + 1, nums, adj, ans, depth, ancestor_by_value); + } + } + ancestor_by_value[nums[node] as usize] = prev_state; + } + + fn gcd(a: i32, b: i32) -> i32 { + if b == 0 { a } else { Self::gcd(b, a % b) } + } +} diff --git a/tests/1501-2000/1766. tree-of-coprimes/sol.swift b/tests/1501-2000/1766. tree-of-coprimes/sol.swift new file mode 100644 index 00000000..4435e6a6 --- /dev/null +++ b/tests/1501-2000/1766. tree-of-coprimes/sol.swift @@ -0,0 +1,47 @@ +class Solution { + func getCoprimes(_ nums: [Int], _ edges: [[Int]]) -> [Int] { + let n = nums.count + var adj = [[Int]](repeating: [], count: n) + for e in edges { + adj[e[0]].append(e[1]) + adj[e[1]].append(e[0]) + } + var ans = [Int](repeating: -1, count: n) + var depth = [Int](repeating: 0, count: n) + var ancestorByValue = [Int](repeating: -1, count: 51) + + func gcd(_ a: Int, _ b: Int) -> Int { + return b == 0 ? a : gcd(b, a % b) + } + + func dfs(_ node: Int, _ prev: Int, _ dep: Int) { + depth[node] = dep + var best = Int.max + var bestAnc = -1 + for i in 1...50 { + if gcd(i, nums[node]) == 1 { + let anc = ancestorByValue[i] + if anc != -1 { + let diff = dep - depth[anc] + if diff < best { + best = diff + bestAnc = anc + } + } + } + } + ans[node] = bestAnc + let prevState = ancestorByValue[nums[node]] + ancestorByValue[nums[node]] = node + for v in adj[node] { + if v != prev { + dfs(v, node, dep + 1) + } + } + ancestorByValue[nums[node]] = prevState + } + + dfs(0, 0, 0) + return ans + } +} diff --git a/tests/1501-2000/1766. tree-of-coprimes/sol.ts b/tests/1501-2000/1766. tree-of-coprimes/sol.ts new file mode 100644 index 00000000..3cbd45e7 --- /dev/null +++ b/tests/1501-2000/1766. tree-of-coprimes/sol.ts @@ -0,0 +1,43 @@ +function getCoprimes(nums: number[], edges: number[][]): number[] { + const n = nums.length; + const adj: number[][] = Array.from({ length: n }, () => []); + for (const [u, v] of edges) { + adj[u].push(v); + adj[v].push(u); + } + const ans: number[] = new Array(n).fill(-1); + const depth: number[] = new Array(n).fill(0); + const ancestorByValue: number[] = new Array(51).fill(-1); + + function gcd(a: number, b: number): number { + return b === 0 ? a : gcd(b, a % b); + } + + function dfs(node: number, prev: number, dep: number): void { + depth[node] = dep; + let best = Number.MAX_SAFE_INTEGER; + let bestAnc = -1; + for (let i = 1; i <= 50; i++) { + if (gcd(i, nums[node]) === 1) { + const anc = ancestorByValue[i]; + if (anc !== -1) { + const diff = dep - depth[anc]; + if (diff < best) { + best = diff; + bestAnc = anc; + } + } + } + } + ans[node] = bestAnc; + const prevState = ancestorByValue[nums[node]]; + ancestorByValue[nums[node]] = node; + for (const v of adj[node]) { + if (v !== prev) dfs(v, node, dep + 1); + } + ancestorByValue[nums[node]] = prevState; + } + + dfs(0, 0, 0); + return ans; +} diff --git a/tests/1501-2000/1768. merge-strings-alternately/manifest.yaml b/tests/1501-2000/1768. merge-strings-alternately/manifest.yaml new file mode 100644 index 00000000..8d3d9dd0 --- /dev/null +++ b/tests/1501-2000/1768. merge-strings-alternately/manifest.yaml @@ -0,0 +1,231 @@ +entry: + id: 1768 + title: "merge-strings-alternately" + params: + word1: + type: string + word2: + type: string + call: + cpp: "Solution().mergeAlternately({word1}, {word2})" + rust: "Solution::merge_alternately({word1}, {word2})" + python3: "Solution().mergeAlternately({word1}, {word2})" + python2: "Solution().mergeAlternately({word1}, {word2})" + ruby: "merge_alternately({word1}, {word2})" + java: "new Solution().mergeAlternately({word1}, {word2})" + csharp: "new Solution().MergeAlternately({word1}, {word2})" + kotlin: "Solution().mergeAlternately({word1}, {word2})" + go: "mergeAlternately({word1}, {word2})" + dart: "Solution().mergeAlternately({word1}, {word2})" + swift: "Solution().mergeAlternately({word1}, {word2})" + typescript: "mergeAlternately({word1}, {word2})" +judge: + type: "exact" +limits: + time_ms: 1000 + memory_mb: 256 +oracle: + python3: + call: "Checker().mergeAlternately(word1, word2, {result})" + checker: | + class Checker: + def mergeAlternately(self, word1, word2, result): + expected = [] + for i in range(max(len(word1), len(word2))): + if i < len(word1): + expected.append(word1[i]) + if i < len(word2): + expected.append(word2[i]) + return result == "".join(expected) +seed: 1768 +tests: + - name: example-equal + in: + word1: "abc" + word2: "pqr" + out: "apbqcr" + - name: example-second-longer + in: + word1: "ab" + word2: "pqrs" + out: "apbqrs" + - name: example-first-longer + in: + word1: "abcd" + word2: "pq" + out: "apbqcd" + - name: one-one + in: + word1: "a" + word2: "b" + out: "ab" + - name: one-two-first + in: + word1: "a" + word2: "bc" + out: "abc" + - name: two-one-second + in: + word1: "ab" + word2: "c" + out: "acb" + - name: equal-two + in: + word1: "hi" + word2: "yo" + out: "hyio" + - name: equal-four + in: + word1: "abcd" + word2: "wxyz" + out: "awbxcydz" + - name: first-three-second-two + in: + word1: "cat" + word2: "do" + out: "cdaot" + - name: first-two-second-three + in: + word1: "go" + word2: "sun" + out: "gsoun" + - name: repeated-first + in: + word1: "aaaa" + word2: "b" + out: "abaaa" + - name: repeated-second + in: + word1: "a" + word2: "bbbb" + out: "abbbb" + - name: repeated-equal + in: + word1: "aaaa" + word2: "bbbb" + out: "abababab" + - name: all-z + in: + word1: "zzzz" + word2: "zz" + out: "zzzzzz" + - name: alphabet-equal + in: + word1: "abcde" + word2: "fghij" + out: "afbgchdiej" + - name: reverse-alphabet + in: + word1: "zyxwv" + word2: "utsrq" + out: "zuytxswrvq" + - name: vowels + in: + word1: "aeiou" + word2: "ouiea" + out: "aoeuiioeua" + - name: consonants + in: + word1: "bcdfg" + word2: "hjklm" + out: "bhcjdkflgm" + - name: alternating-pattern + in: + word1: "ababab" + word2: "cdcd" + out: "acbdacbdab" + - name: first-long-six + in: + word1: "planet" + word2: "orb" + out: "polrabnet" + - name: second-long-six + in: + word1: "orb" + word2: "planet" + out: "oprlbanet" + - name: ten-equal + in: + word1: "abcdefghij" + word2: "klmnopqrst" + out: "akblcmdneofpgqhrisjt" + - name: ten-first-longer + in: + word1: "abcdefghij" + word2: "xyz" + out: "axbyczdefghij" + - name: ten-second-longer + in: + word1: "xyz" + word2: "abcdefghij" + out: "xaybzcdefghij" + - name: palindrome-equal + in: + word1: "radar" + word2: "civic" + out: "rcaidvairc" + - name: palindrome-unequal + in: + word1: "racecar" + word2: "level" + out: "rlaecveeclar" + - name: eight-one + in: + word1: "abcdefgh" + word2: "z" + out: "azbcdefgh" + - name: one-eight + in: + word1: "z" + word2: "abcdefgh" + out: "zabcdefgh" + - name: two-digit-words + in: + word1: "oneone" + word2: "twotwo" + out: "otnweootnweo" + - name: mixed-runs + in: + word1: "aaaaabbbbb" + word2: "cccccdddddd" + out: "acacacacacbdbdbdbdbdd" + - name: q-pattern + in: + word1: "qwerty" + word2: "asdfgh" + out: "qawsedrftgyh" + - name: j-pattern + in: + word1: "jkl" + word2: "mno" + out: "jmknlo" + - name: long-first + in: + word1: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv" + word2: "z" + out: "azbcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv" + - name: long-second + in: + word1: "a" + word2: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv" + out: "aabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv" + - name: max-equal + in: + word1: "aaaaa" + word2: "bbbbb" + out: "ababababab" + - name: unicode-free-lowercase + in: + word1: "mnop" + word2: "qrstuv" + out: "mqnrosptuv" + - name: short-tail-first + in: + word1: "xyza" + word2: "k" + out: "xkyza" + - name: short-tail-second + in: + word1: "k" + word2: "xyza" + out: "kxyza" diff --git a/tests/1501-2000/1768. merge-strings-alternately/sol.cpp b/tests/1501-2000/1768. merge-strings-alternately/sol.cpp new file mode 100644 index 00000000..f741e205 --- /dev/null +++ b/tests/1501-2000/1768. merge-strings-alternately/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + string mergeAlternately(string word1, string word2) { + string merged; + int minLen = min(word1.length(), word2.length()); + for (int i = 0; i < minLen; i++) { + merged += word1[i]; + merged += word2[i]; + } + if (word1.length() > minLen) { + merged += word1.substr(minLen); + } + if (word2.length() > minLen) { + merged += word2.substr(minLen); + } + return merged; + } +}; diff --git a/tests/1501-2000/1768. merge-strings-alternately/sol.cs b/tests/1501-2000/1768. merge-strings-alternately/sol.cs new file mode 100644 index 00000000..fe2dc78f --- /dev/null +++ b/tests/1501-2000/1768. merge-strings-alternately/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public string MergeAlternately(string word1, string word2) { + var merged = new StringBuilder(); + int minLen = Math.Min(word1.Length, word2.Length); + for (int i = 0; i < minLen; i++) { + merged.Append(word1[i]).Append(word2[i]); + } + if (word1.Length > minLen) { + merged.Append(word1.Substring(minLen)); + } + if (word2.Length > minLen) { + merged.Append(word2.Substring(minLen)); + } + return merged.ToString(); + } +} diff --git a/tests/1501-2000/1768. merge-strings-alternately/sol.dart b/tests/1501-2000/1768. merge-strings-alternately/sol.dart new file mode 100644 index 00000000..d0ee294e --- /dev/null +++ b/tests/1501-2000/1768. merge-strings-alternately/sol.dart @@ -0,0 +1,13 @@ +class Solution { + String mergeAlternately(String word1, String word2) { + final result = StringBuffer(); + final limit = word1.length < word2.length ? word1.length : word2.length; + for (var i = 0; i < limit; i++) { + result.write(word1[i]); + result.write(word2[i]); + } + if (word1.length > limit) result.write(word1.substring(limit)); + if (word2.length > limit) result.write(word2.substring(limit)); + return result.toString(); + } +} diff --git a/tests/1501-2000/1768. merge-strings-alternately/sol.go b/tests/1501-2000/1768. merge-strings-alternately/sol.go new file mode 100644 index 00000000..c0847300 --- /dev/null +++ b/tests/1501-2000/1768. merge-strings-alternately/sol.go @@ -0,0 +1,17 @@ +func mergeAlternately(word1 string, word2 string) string { + merged := make([]byte, 0) + minLen := len(word1) + if len(word2) < minLen { + minLen = len(word2) + } + for i := 0; i < minLen; i++ { + merged = append(merged, word1[i], word2[i]) + } + if len(word1) > minLen { + merged = append(merged, word1[minLen:]...) + } + if len(word2) > minLen { + merged = append(merged, word2[minLen:]...) + } + return string(merged) +} diff --git a/tests/1501-2000/1768. merge-strings-alternately/sol.java b/tests/1501-2000/1768. merge-strings-alternately/sol.java new file mode 100644 index 00000000..71ca7241 --- /dev/null +++ b/tests/1501-2000/1768. merge-strings-alternately/sol.java @@ -0,0 +1,16 @@ +class Solution { + public String mergeAlternately(String word1, String word2) { + StringBuilder merged = new StringBuilder(); + int minLen = Math.min(word1.length(), word2.length()); + for (int i = 0; i < minLen; i++) { + merged.append(word1.charAt(i)).append(word2.charAt(i)); + } + if (word1.length() > minLen) { + merged.append(word1.substring(minLen)); + } + if (word2.length() > minLen) { + merged.append(word2.substring(minLen)); + } + return merged.toString(); + } +} diff --git a/tests/1501-2000/1768. merge-strings-alternately/sol.kt b/tests/1501-2000/1768. merge-strings-alternately/sol.kt new file mode 100644 index 00000000..e0ffda12 --- /dev/null +++ b/tests/1501-2000/1768. merge-strings-alternately/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun mergeAlternately(word1: String, word2: String): String { + val merged = StringBuilder() + val minLen = minOf(word1.length, word2.length) + for (i in 0 until minLen) { + merged.append(word1[i]).append(word2[i]) + } + if (word1.length > minLen) { + merged.append(word1.substring(minLen)) + } + if (word2.length > minLen) { + merged.append(word2.substring(minLen)) + } + return merged.toString() + } +} diff --git a/tests/1501-2000/1768. merge-strings-alternately/sol.py b/tests/1501-2000/1768. merge-strings-alternately/sol.py new file mode 100644 index 00000000..1102aa48 --- /dev/null +++ b/tests/1501-2000/1768. merge-strings-alternately/sol.py @@ -0,0 +1,11 @@ +class Solution: + def mergeAlternately(self, word1: str, word2: str) -> str: + merged = [] + + for a, b in zip(word1, word2): + merged.append(a + b) + + merged.append(word1[len(word2) :]) + merged.append(word2[len(word1) :]) + + return "".join(merged) diff --git a/tests/1501-2000/1768. merge-strings-alternately/sol.py2 b/tests/1501-2000/1768. merge-strings-alternately/sol.py2 new file mode 100644 index 00000000..9d8583e4 --- /dev/null +++ b/tests/1501-2000/1768. merge-strings-alternately/sol.py2 @@ -0,0 +1,13 @@ +class Solution(object): + def mergeAlternately(self, word1, word2): + """ + :type word1: str + :type word2: str + :rtype: str + """ + merged = [] + for a, b in zip(word1, word2): + merged.append(a + b) + merged.append(word1[len(word2):]) + merged.append(word2[len(word1):]) + return "".join(merged) diff --git a/tests/1501-2000/1768. merge-strings-alternately/sol.rb b/tests/1501-2000/1768. merge-strings-alternately/sol.rb new file mode 100644 index 00000000..0123687d --- /dev/null +++ b/tests/1501-2000/1768. merge-strings-alternately/sol.rb @@ -0,0 +1,13 @@ +# @param {String} word1 +# @param {String} word2 +# @return {String} +def merge_alternately(word1, word2) + merged = [] + min_len = [word1.length, word2.length].min + min_len.times do |i| + merged << word1[i, 1] + word2[i, 1] + end + merged << word1[word2.length..-1] if word1.length > word2.length + merged << word2[word1.length..-1] if word2.length > word1.length + merged.join +end diff --git a/tests/1501-2000/1768. merge-strings-alternately/sol.rs b/tests/1501-2000/1768. merge-strings-alternately/sol.rs new file mode 100644 index 00000000..ee49c524 --- /dev/null +++ b/tests/1501-2000/1768. merge-strings-alternately/sol.rs @@ -0,0 +1,27 @@ +impl Solution { + pub fn merge_alternately(word1: String, word2: String) -> String { + let mut merged = String::new(); + let mut chars1 = word1.chars(); + let mut chars2 = word2.chars(); + loop { + match (chars1.next(), chars2.next()) { + (Some(c1), Some(c2)) => { + merged.push(c1); + merged.push(c2); + } + (Some(c1), None) => { + merged.push(c1); + merged.push_str(chars1.as_str()); + break; + } + (None, Some(c2)) => { + merged.push(c2); + merged.push_str(chars2.as_str()); + break; + } + (None, None) => break, + } + } + merged + } +} diff --git a/tests/1501-2000/1768. merge-strings-alternately/sol.swift b/tests/1501-2000/1768. merge-strings-alternately/sol.swift new file mode 100644 index 00000000..5256d4a0 --- /dev/null +++ b/tests/1501-2000/1768. merge-strings-alternately/sol.swift @@ -0,0 +1,19 @@ +class Solution { + func mergeAlternately(_ word1: String, _ word2: String) -> String { + var merged = "" + let chars1 = Array(word1) + let chars2 = Array(word2) + let minLen = min(chars1.count, chars2.count) + for i in 0.. minLen { + merged.append(contentsOf: chars1[minLen...]) + } + if chars2.count > minLen { + merged.append(contentsOf: chars2[minLen...]) + } + return merged + } +} diff --git a/tests/1501-2000/1768. merge-strings-alternately/sol.ts b/tests/1501-2000/1768. merge-strings-alternately/sol.ts new file mode 100644 index 00000000..8e9f214f --- /dev/null +++ b/tests/1501-2000/1768. merge-strings-alternately/sol.ts @@ -0,0 +1,14 @@ +function mergeAlternately(word1: string, word2: string): string { + const merged: string[] = []; + const minLen = Math.min(word1.length, word2.length); + for (let i = 0; i < minLen; i++) { + merged.push(word1[i] + word2[i]); + } + if (word1.length > minLen) { + merged.push(word1.slice(minLen)); + } + if (word2.length > minLen) { + merged.push(word2.slice(minLen)); + } + return merged.join(""); +} diff --git a/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/manifest.yaml b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/manifest.yaml new file mode 100644 index 00000000..0c3d51ee --- /dev/null +++ b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/manifest.yaml @@ -0,0 +1,207 @@ +entry: + id: 1769 + title: "minimum-number-of-operations-to-move-all-balls-to-each-box" + params: + boxes: + type: string + call: + cpp: "Solution().minOperations({boxes})" + rust: "Solution::min_operations({boxes})" + python3: "Solution().minOperations({boxes})" + python2: "Solution().minOperations({boxes})" + ruby: "min_operations({boxes})" + java: "new Solution().minOperations({boxes})" + csharp: "new Solution().MinOperations({boxes})" + kotlin: "Solution().minOperations({boxes})" + go: "minOperations({boxes})" + dart: "Solution().minOperations({boxes})" + swift: "Solution().minOperations({boxes})" + typescript: "minOperations({boxes})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minOperations(boxes, {result})" + checker: | + class Checker: + def minOperations(self, boxes, result): + if not isinstance(boxes, str) or any(c not in '01' for c in boxes): + return False + expected = [] + for target in range(len(boxes)): + expected.append(sum(abs(i - target) for i, c in enumerate(boxes) if c == '1')) + return result == expected + +seed: 1769 + +tests: + - name: example-110 + in: + boxes: "110" + out: [1, 1, 3] + - name: example-001011 + in: + boxes: "001011" + out: [11, 8, 5, 4, 3, 4] + - name: single-zero + in: + boxes: "0" + out: [0] + - name: single-one + in: + boxes: "1" + out: [0] + - name: two-zeroes + in: + boxes: "00" + out: [0, 0] + - name: two-ones + in: + boxes: "11" + out: [1, 1] + - name: alternating-five + in: + boxes: "10101" + out: [6, 5, 4, 5, 6] + - name: alternating-six + in: + boxes: "010101" + out: [9, 6, 5, 4, 5, 6] + - name: one-at-left + in: + boxes: "100000" + out: [0, 1, 2, 3, 4, 5] + - name: one-at-right + in: + boxes: "000001" + out: [5, 4, 3, 2, 1, 0] + - name: all-zero-seven + in: + boxes: "0000000" + out: [0, 0, 0, 0, 0, 0, 0] + - name: all-one-seven + in: + boxes: "1111111" + out: [21, 16, 13, 12, 13, 16, 21] + - name: centered-one + in: + boxes: "00100" + out: [2, 1, 0, 1, 2] + - name: centered-three + in: + boxes: "01110" + out: [6, 3, 2, 3, 6] + - name: separated-pair + in: + boxes: "10001" + out: [4, 4, 4, 4, 4] + - name: separated-triple + in: + boxes: "10000100001" + out: [15, 14, 13, 12, 11, 10, 11, 12, 13, 14, 15] + - name: leading-run + in: + boxes: "1110000" + out: [3, 2, 3, 6, 9, 12, 15] + - name: trailing-run + in: + boxes: "0000111" + out: [15, 12, 9, 6, 3, 2, 3] + - name: two-blocks + in: + boxes: "110011" + out: [10, 8, 8, 8, 8, 10] + - name: sparse-eight + in: + boxes: "10010001" + out: [10, 9, 8, 7, 8, 9, 10, 11] + - name: nine-alternating + in: + boxes: "101010101" + out: [20, 17, 14, 13, 12, 13, 14, 17, 20] + - name: nine-offset + in: + boxes: "010101010" + out: [16, 12, 10, 8, 8, 8, 10, 12, 16] + - name: middle-block + in: + boxes: "00111100" + out: [14, 10, 6, 4, 4, 6, 10, 14] + - name: isolated-middle + in: + boxes: "00010000" + out: [3, 2, 1, 0, 1, 2, 3, 4] + - name: ten-single-block + in: + boxes: "0000010000" + out: [5, 4, 3, 2, 1, 0, 1, 2, 3, 4] + - name: ten-two-ends + in: + boxes: "1000000001" + out: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9] + - name: dense-nine + in: + boxes: "111011111" + out: [33, 27, 23, 21, 19, 19, 21, 25, 31] + - name: sparse-twelve + in: + boxes: "100010001000" + out: [12, 11, 10, 9, 8, 9, 10, 11, 12, 15, 18, 21] + - name: alternating-twelve + in: + boxes: "010101010101" + out: [36, 30, 26, 22, 20, 18, 18, 18, 20, 22, 26, 30] + - name: long-left-block + in: + boxes: "111110000000" + out: [10, 7, 6, 7, 10, 15, 20, 25, 30, 35, 40, 45] + - name: long-right-block + in: + boxes: "000000011111" + out: [45, 40, 35, 30, 25, 20, 15, 10, 7, 6, 7, 10] + - name: generated-short + in: + boxes: + gen: "str" + len: 17 + alphabet: "01" + judge: + type: "exact" + - name: generated-medium + in: + boxes: + gen: "str" + len: 64 + alphabet: "01" + judge: + type: "exact" + - name: generated-large-balanced + in: + boxes: + gen: "str" + len: 500 + alphabet: "01" + judge: + type: "exact" + - name: generated-large-sparse + in: + boxes: + gen: "str" + len: 1500 + alphabet: "0001" + judge: + type: "exact" + - name: generated-maximum + in: + boxes: + gen: "str" + len: 2000 + alphabet: "01" + judge: + type: "exact" diff --git a/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.cpp b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.cpp new file mode 100644 index 00000000..327b8048 --- /dev/null +++ b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + vector minOperations(string boxes) { + int n = boxes.length(); + vector distances(n, 0); + + int prefixCount = 0; + int prefixSum = 0; + + for (int i = 0; i < n; i++) { + distances[i] = prefixCount * i - prefixSum; + if (boxes[i] == '1') { + prefixCount++; + prefixSum += i; + } + } + + int suffixCount = 0; + int suffixSum = 0; + + for (int i = n - 1; i >= 0; i--) { + distances[i] += suffixSum - suffixCount * i; + if (boxes[i] == '1') { + suffixCount++; + suffixSum += i; + } + } + + return distances; + } +}; diff --git a/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.cs b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.cs new file mode 100644 index 00000000..fc02f7d3 --- /dev/null +++ b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.cs @@ -0,0 +1,30 @@ +public class Solution { + public int[] MinOperations(string boxes) { + int n = boxes.Length; + int[] distances = new int[n]; + + int prefixCount = 0; + int prefixSum = 0; + + for (int i = 0; i < n; i++) { + distances[i] = prefixCount * i - prefixSum; + if (boxes[i] == '1') { + prefixCount++; + prefixSum += i; + } + } + + int suffixCount = 0; + int suffixSum = 0; + + for (int i = n - 1; i >= 0; i--) { + distances[i] += suffixSum - suffixCount * i; + if (boxes[i] == '1') { + suffixCount++; + suffixSum += i; + } + } + + return distances; + } +} diff --git a/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.dart b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.dart new file mode 100644 index 00000000..c3d905c2 --- /dev/null +++ b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.dart @@ -0,0 +1,30 @@ +class Solution { + List minOperations(String boxes) { + int n = boxes.length; + List distances = List.filled(n, 0); + + int prefixCount = 0; + int prefixSum = 0; + + for (int i = 0; i < n; i++) { + distances[i] = prefixCount * i - prefixSum; + if (boxes[i] == '1') { + prefixCount++; + prefixSum += i; + } + } + + int suffixCount = 0; + int suffixSum = 0; + + for (int i = n - 1; i >= 0; i--) { + distances[i] += suffixSum - suffixCount * i; + if (boxes[i] == '1') { + suffixCount++; + suffixSum += i; + } + } + + return distances; + } +} diff --git a/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.go b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.go new file mode 100644 index 00000000..df097a10 --- /dev/null +++ b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.go @@ -0,0 +1,28 @@ +func minOperations(boxes string) []int { + n := len(boxes) + distances := make([]int, n) + + prefixCount := 0 + prefixSum := 0 + + for i := 0; i < n; i++ { + distances[i] = prefixCount*i - prefixSum + if boxes[i] == '1' { + prefixCount++ + prefixSum += i + } + } + + suffixCount := 0 + suffixSum := 0 + + for i := n - 1; i >= 0; i-- { + distances[i] += suffixSum - suffixCount*i + if boxes[i] == '1' { + suffixCount++ + suffixSum += i + } + } + + return distances +} diff --git a/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.java b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.java new file mode 100644 index 00000000..909aa7cc --- /dev/null +++ b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.java @@ -0,0 +1,30 @@ +class Solution { + public int[] minOperations(String boxes) { + int n = boxes.length(); + int[] distances = new int[n]; + + int prefixCount = 0; + int prefixSum = 0; + + for (int i = 0; i < n; i++) { + distances[i] = prefixCount * i - prefixSum; + if (boxes.charAt(i) == '1') { + prefixCount++; + prefixSum += i; + } + } + + int suffixCount = 0; + int suffixSum = 0; + + for (int i = n - 1; i >= 0; i--) { + distances[i] += suffixSum - suffixCount * i; + if (boxes.charAt(i) == '1') { + suffixCount++; + suffixSum += i; + } + } + + return distances; + } +} diff --git a/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.kt b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.kt new file mode 100644 index 00000000..98115dfd --- /dev/null +++ b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.kt @@ -0,0 +1,30 @@ +class Solution { + fun minOperations(boxes: String): IntArray { + val n = boxes.length + val distances = IntArray(n) + + var prefixCount = 0 + var prefixSum = 0 + + for (i in 0 until n) { + distances[i] = prefixCount * i - prefixSum + if (boxes[i] == '1') { + prefixCount++ + prefixSum += i + } + } + + var suffixCount = 0 + var suffixSum = 0 + + for (i in n - 1 downTo 0) { + distances[i] += suffixSum - suffixCount * i + if (boxes[i] == '1') { + suffixCount++ + suffixSum += i + } + } + + return distances + } +} diff --git a/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.py b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.py new file mode 100644 index 00000000..d69378fd --- /dev/null +++ b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.py @@ -0,0 +1,24 @@ +class Solution: + def minOperations(self, boxes: str) -> List[int]: + n = len(boxes) + distances = [0] * n + + prefixCount = 0 + prefixSum = 0 + + for i in range(n): + distances[i] = prefixCount * i - prefixSum + if boxes[i] == "1": + prefixCount += 1 + prefixSum += i + + suffixCount = 0 + suffixSum = 0 + + for i in range(n - 1, -1, -1): + distances[i] += suffixSum - suffixCount * i + if boxes[i] == "1": + suffixCount += 1 + suffixSum += i + + return distances diff --git a/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.py2 b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.py2 new file mode 100644 index 00000000..33ac7a9e --- /dev/null +++ b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.py2 @@ -0,0 +1,28 @@ +class Solution(object): + def minOperations(self, boxes): + """ + :type boxes: str + :rtype: List[int] + """ + n = len(boxes) + distances = [0] * n + + prefixCount = 0 + prefixSum = 0 + + for i in range(n): + distances[i] = prefixCount * i - prefixSum + if boxes[i] == '1': + prefixCount += 1 + prefixSum += i + + suffixCount = 0 + suffixSum = 0 + + for i in range(n - 1, -1, -1): + distances[i] += suffixSum - suffixCount * i + if boxes[i] == '1': + suffixCount += 1 + suffixSum += i + + return distances diff --git a/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.rb b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.rb new file mode 100644 index 00000000..06cc1339 --- /dev/null +++ b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.rb @@ -0,0 +1,30 @@ +# @param {String} boxes +# @return {Integer[]} +def min_operations(boxes) + n = boxes.length + distances = Array.new(n, 0) + + prefix_count = 0 + prefix_sum = 0 + + (0...n).each do |i| + distances[i] = prefix_count * i - prefix_sum + if boxes[i] == '1' + prefix_count += 1 + prefix_sum += i + end + end + + suffix_count = 0 + suffix_sum = 0 + + (n-1).downto(0) do |i| + distances[i] += suffix_sum - suffix_count * i + if boxes[i] == '1' + suffix_count += 1 + suffix_sum += i + end + end + + distances +end diff --git a/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.rs b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.rs new file mode 100644 index 00000000..ac469a9d --- /dev/null +++ b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.rs @@ -0,0 +1,31 @@ +impl Solution { + pub fn min_operations(boxes: String) -> Vec { + let n = boxes.len(); + let mut distances = vec![0; n]; + let chars: Vec = boxes.chars().collect(); + + let mut prefix_count = 0; + let mut prefix_sum = 0; + + for i in 0..n { + distances[i] = prefix_count * i as i32 - prefix_sum; + if chars[i] == '1' { + prefix_count += 1; + prefix_sum += i as i32; + } + } + + let mut suffix_count = 0; + let mut suffix_sum = 0; + + for i in (0..n).rev() { + distances[i] += suffix_sum - suffix_count * i as i32; + if chars[i] == '1' { + suffix_count += 1; + suffix_sum += i as i32; + } + } + + distances + } +} diff --git a/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.swift b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.swift new file mode 100644 index 00000000..36bae129 --- /dev/null +++ b/tests/1501-2000/1769. minimum-number-of-operations-to-move-all-balls-to-each-box/sol.swift @@ -0,0 +1,31 @@ +class Solution { + func minOperations(_ boxes: String) -> [Int] { + let n = boxes.count + var distances = [Int](repeating: 0, count: n) + let chars = Array(boxes) + + var prefixCount = 0 + var prefixSum = 0 + + for i in 0..= 0; i--) { + distances[i] += suffixSum - suffixCount * i; + if (boxes[i] === "1") { + suffixCount++; + suffixSum += i; + } + } + + return distances; +} diff --git a/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/manifest.yaml b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/manifest.yaml new file mode 100644 index 00000000..f53d11ff --- /dev/null +++ b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/manifest.yaml @@ -0,0 +1,274 @@ +entry: + id: 1770 + title: "maximum-score-from-performing-multiplication-operations" + params: + nums: + type: array + items: + type: int + multipliers: + type: array + items: + type: int + call: + cpp: "Solution().maximumScore({nums}, {multipliers})" + rust: "Solution::maximum_score({nums}, {multipliers})" + python3: "Solution().maximumScore({nums}, {multipliers})" + python2: "Solution().maximumScore({nums}, {multipliers})" + ruby: "maximum_score({nums}, {multipliers})" + java: "new Solution().maximumScore({nums}, {multipliers})" + csharp: "new Solution().MaximumScore({nums}, {multipliers})" + kotlin: "Solution().maximumScore({nums}, {multipliers})" + go: "maximumScore({nums}, {multipliers})" + dart: "Solution().maximumScore({nums}, {multipliers})" + swift: "Solution().maximumScore({nums}, {multipliers})" + typescript: "maximumScore({nums}, {multipliers})" + +judge: + type: "exact" + +limits: + time_ms: 5000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maximumScore(nums, multipliers, {result})" + checker: | + class Checker: + def maximumScore(self, nums, multipliers, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + n = len(nums) + m = len(multipliers) + if m < 1 or m > n: + return False + dp = [0] * (m + 1) + for i in range(m - 1, -1, -1): + nxt = [0] * (m + 1) + for left in range(i, -1, -1): + right = i - left + front = multipliers[i] * nums[left] + dp[right] + back = multipliers[i] * nums[n - 1 - right] + dp[right + 1] + nxt[right] = max(front, back) + dp = nxt + return result == dp[0] + +seed: 1770 + +tests: + - name: example-one + in: + nums: [1, 2, 3] + multipliers: [3, 2, 1] + out: 14 + - name: example-two + in: + nums: [-5, -3, -3, -2, 7, 1] + multipliers: [-10, -5, 3, 4, 6] + out: 102 + - name: single-positive + in: + nums: [7] + multipliers: [9] + out: 63 + - name: single-negative + in: + nums: [-7] + multipliers: [9] + out: -63 + - name: one-operation-front + in: + nums: [5, -100, 6] + multipliers: [2] + out: 12 + - name: one-operation-negative-multiplier + in: + nums: [-8, 3, 9] + multipliers: [-4] + out: 32 + - name: all-equal + in: + nums: [4, 4, 4, 4] + multipliers: [1, 2, 3] + out: 24 + - name: all-zero + in: + nums: [0, 0, 0, 0] + multipliers: [1000, -1000, 7] + out: 0 + - name: all-positive-increasing + in: + nums: [1, 2, 3, 4, 5] + multipliers: [1, 2, 3, 4] + out: 36 + - name: all-positive-decreasing + in: + nums: [1, 2, 3, 4, 5] + multipliers: [4, 3, 2, 1] + out: 40 + - name: all-negative + in: + nums: [-1, -2, -3, -4, -5] + multipliers: [4, 3, 2, 1] + out: -20 + - name: alternating-signs + in: + nums: [-10, 9, -8, 7, -6, 5] + multipliers: [3, -2, 4, -1] + out: 79 + - name: extremes-positive + in: + nums: [1000, -1, -2, -3, 1000] + multipliers: [1000, 1000, 1000] + out: 1999000 + - name: extremes-negative + in: + nums: [-1000, 1, 2, 3, -1000] + multipliers: [1000, 1000, 1000] + out: -995000 + - name: take-all-ascending + in: + nums: [2, 5, 1, 4] + multipliers: [3, 2, 4, 1] + out: 37 + - name: take-all-descending + in: + nums: [2, 5, 1, 4] + multipliers: [-3, 2, -4, 1] + out: 4 + - name: duplicate-extremes + in: + nums: [8, 1, 8, 1, 8] + multipliers: [5, -5, 5] + out: 75 + - name: multiplier-zero-middle + in: + nums: [10, -10, 3, 7] + multipliers: [2, 0, 3] + out: 44 + - name: negative-zero-positive + in: + nums: [-5, 0, 5] + multipliers: [-2, 0, 2] + out: 20 + - name: close-choices + in: + nums: [4, 3, 2, 1] + multipliers: [1, 10, 1] + out: 44 + - name: large-multiplier-signs + in: + nums: [-12, 11, -10, 9, -8, 7] + multipliers: [-1000, 999, -998, 997] + out: 41942 + - name: m-two + in: + nums: [5, -4, 3, -2, 1] + multipliers: [7, -6] + out: 59 + - name: m-three + in: + nums: [9, -8, 7, -6, 5, -4] + multipliers: [-3, 4, -5] + out: 88 + - name: m-near-n + in: + nums: [6, 1, 9, -2, 8, 3, -7] + multipliers: [2, -3, 4, -5, 6, -7] + out: 152 + - name: symmetric-values + in: + nums: [-2, -1, 0, 1, 2] + multipliers: [5, 4, 3, 2] + out: 12 + - name: repeated-multipliers + in: + nums: [3, 9, 1, 8, 2] + multipliers: [4, 4, 4] + out: 56 + - name: negative-repeated-multipliers + in: + nums: [-3, -9, -1, -8, -2] + multipliers: [-4, -4, -4] + out: 56 + - name: cancellation + in: + nums: [100, -100, 50, -50] + multipliers: [1, 1, -1] + out: 150 + - name: small-values + in: + nums: [-2, -1, 1, 2] + multipliers: [-2, -1, 1] + out: 7 + - name: boundary-values + in: + nums: [-1000, -999, 999, 1000] + multipliers: [-1000, 999, -998] + out: 2996002 + - name: generated-large-positive + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: "int" + multipliers: [1000] + - name: generated-large-negative + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: "int" + multipliers: [-1000] + - name: generated-long-two-ops + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: "int" + multipliers: [997, -991] + - name: generated-long-three-ops + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: "int" + multipliers: [-1000, 999, 998] + - name: generated-long-five-ops + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: "int" + multipliers: [1000, -1000, 999, -999, 998] diff --git a/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.cpp b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.cpp new file mode 100644 index 00000000..5b957099 --- /dev/null +++ b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int maximumScore(vector& nums, vector& multipliers) { + int m = multipliers.size(); + vector> dp(m + 1, vector(m + 1, -1)); + + function f = [&](int i, int j) -> int { + int k = i + j; + if (k == m) return 0; + if (dp[i][j] != -1) return dp[i][j]; + + int back = multipliers[k] * nums[nums.size() - 1 - j] + f(i, j + 1); + int front = multipliers[k] * nums[i] + f(i + 1, j); + dp[i][j] = max(front, back); + return dp[i][j]; + }; + + return f(0, 0); + } +}; diff --git a/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.cs b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.cs new file mode 100644 index 00000000..4cf0faa7 --- /dev/null +++ b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.cs @@ -0,0 +1,24 @@ +public class Solution { + public int MaximumScore(int[] nums, int[] multipliers) { + int m = multipliers.Length; + int?[][] dp = new int?[m + 1][]; + for (int i = 0; i <= m; i++) { + dp[i] = new int?[m + 1]; + } + + Func f = null; + f = (i, j) => { + int k = i + j; + if (k == m) return 0; + if (dp[i][j].HasValue) return dp[i][j].Value; + + int back = multipliers[k] * nums[nums.Length - 1 - j] + f(i, j + 1); + int front = multipliers[k] * nums[i] + f(i + 1, j); + int result = Math.Max(front, back); + dp[i][j] = result; + return result; + }; + + return f(0, 0); + } +} diff --git a/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.dart b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.dart new file mode 100644 index 00000000..262f6f37 --- /dev/null +++ b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.dart @@ -0,0 +1,20 @@ +class Solution { + int maximumScore(List nums, List multipliers) { + int m = multipliers.length; + List> dp = List.generate(m + 1, (_) => List.filled(m + 1, null)); + + int f(int i, int j) { + int k = i + j; + if (k == m) return 0; + if (dp[i][j] != null) return dp[i][j]!; + + int back = multipliers[k] * nums[nums.length - 1 - j] + f(i, j + 1); + int front = multipliers[k] * nums[i] + f(i + 1, j); + int result = front > back ? front : back; + dp[i][j] = result; + return result; + } + + return f(0, 0); + } +} diff --git a/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.go b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.go new file mode 100644 index 00000000..9b53d07d --- /dev/null +++ b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.go @@ -0,0 +1,32 @@ +func maximumScore(nums []int, multipliers []int) int { + m := len(multipliers) + dp := make([][]*int, m+1) + for i := range dp { + dp[i] = make([]*int, m+1) + } + + var f func(i, j int) int + f = func(i, j int) int { + k := i + j + if k == m { + return 0 + } + if dp[i][j] != nil { + return *dp[i][j] + } + back := multipliers[k] * nums[len(nums)-1-j] + f(i, j+1) + front := multipliers[k] * nums[i] + f(i+1, j) + result := max(front, back) + dp[i][j] = &result + return result + } + + return f(0, 0) +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} diff --git a/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.java b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.java new file mode 100644 index 00000000..65b92164 --- /dev/null +++ b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.java @@ -0,0 +1,21 @@ +class Solution { + public int maximumScore(int[] nums, int[] multipliers) { + int m = multipliers.length; + Integer[][] dp = new Integer[m + 1][m + 1]; + + java.util.function.BiFunction f = new java.util.function.BiFunction<>() { + @Override + public Integer apply(Integer i, Integer j) { + int k = i + j; + if (k == m) return 0; + if (dp[i][j] != null) return dp[i][j]; + int back = multipliers[k] * nums[nums.length - 1 - j] + apply(i, j + 1); + int front = multipliers[k] * nums[i] + apply(i + 1, j); + dp[i][j] = Math.max(front, back); + return dp[i][j]; + } + }; + + return f.apply(0, 0); + } +} diff --git a/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.kt b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.kt new file mode 100644 index 00000000..4c7589ee --- /dev/null +++ b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun maximumScore(nums: IntArray, multipliers: IntArray): Int { + val m = multipliers.size + val dp = Array(m + 1) { arrayOfNulls(m + 1) } + + fun f(i: Int, j: Int): Int { + val k = i + j + if (k == m) return 0 + dp[i][j]?.let { return it } + + val back = multipliers[k] * nums[nums.size - 1 - j] + f(i, j + 1) + val front = multipliers[k] * nums[i] + f(i + 1, j) + val result = maxOf(front, back) + dp[i][j] = result + return result + } + + return f(0, 0) + } +} diff --git a/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.py b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.py new file mode 100644 index 00000000..e83cfe2d --- /dev/null +++ b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.py @@ -0,0 +1,22 @@ +class Solution: + def maximumScore(self, nums: List[int], multipliers: List[int]) -> int: + m = len(multipliers) + dp = [[None] * (m + 1) for _ in range(m + 1)] + + def f(i, j): + k = i + j + + if k == m: + return 0 + + if dp[i][j] is not None: + return dp[i][j] + + back = multipliers[k] * nums[len(nums) - 1 - j] + f(i, j + 1) + + front = multipliers[k] * nums[i] + f(i + 1, j) + + dp[i][j] = max(front, back) + return dp[i][j] + + return f(0, 0) diff --git a/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.py2 b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.py2 new file mode 100644 index 00000000..3bd9b2df --- /dev/null +++ b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.py2 @@ -0,0 +1,15 @@ + +class Solution(object): + def maximumScore(self, nums, multipliers): + m = len(multipliers) + dp = [0] * (m + 1) + for operation in xrange(m - 1, -1, -1): + next_dp = dp[:] + for left in xrange(operation, -1, -1): + right = operation - left + next_dp[left] = max( + multipliers[operation] * nums[left] + dp[left + 1], + multipliers[operation] * nums[len(nums) - 1 - right] + dp[left], + ) + dp = next_dp + return dp[0] diff --git a/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.rb b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.rb new file mode 100644 index 00000000..22e6d564 --- /dev/null +++ b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.rb @@ -0,0 +1,20 @@ +# @param {Integer[]} nums +# @param {Integer[]} multipliers +# @return {Integer} +def maximum_score(nums, multipliers) + m = multipliers.length + dp = Array.new(m + 1) { Array.new(m + 1) } + + f = lambda do |i, j| + k = i + j + return 0 if k == m + return dp[i][j] unless dp[i][j].nil? + + back = multipliers[k] * nums[nums.length - 1 - j] + f.call(i, j + 1) + front = multipliers[k] * nums[i] + f.call(i + 1, j) + dp[i][j] = [front, back].max + dp[i][j] + end + + f.call(0, 0) +end diff --git a/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.rs b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.rs new file mode 100644 index 00000000..ace42599 --- /dev/null +++ b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn maximum_score(nums: Vec, multipliers: Vec) -> i32 { + let m = multipliers.len(); + let mut dp = vec![vec![None; m + 1]; m + 1]; + + fn f(i: usize, j: usize, nums: &Vec, multipliers: &Vec, dp: &mut Vec>>) -> i32 { + let k = i + j; + if k == multipliers.len() { return 0; } + if let Some(val) = dp[i][j] { return val; } + + let back = multipliers[k] * nums[nums.len() - 1 - j] + f(i, j + 1, nums, multipliers, dp); + let front = multipliers[k] * nums[i] + f(i + 1, j, nums, multipliers, dp); + let result = front.max(back); + dp[i][j] = Some(result); + result + } + + f(0, 0, &nums, &multipliers, &mut dp) + } +} diff --git a/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.swift b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.swift new file mode 100644 index 00000000..f318d023 --- /dev/null +++ b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func maximumScore(_ nums: [Int], _ multipliers: [Int]) -> Int { + let m = multipliers.count + var dp = [[Int?]](repeating: [Int?](repeating: nil, count: m + 1), count: m + 1) + + func f(_ i: Int, _ j: Int) -> Int { + let k = i + j + if k == m { return 0 } + if let val = dp[i][j] { return val } + + let back = multipliers[k] * nums[nums.count - 1 - j] + f(i, j + 1) + let front = multipliers[k] * nums[i] + f(i + 1, j) + let result = max(front, back) + dp[i][j] = result + return result + } + + return f(0, 0) + } +} diff --git a/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.ts b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.ts new file mode 100644 index 00000000..2618dfee --- /dev/null +++ b/tests/1501-2000/1770. maximum-score-from-performing-multiplication-operations/sol.ts @@ -0,0 +1,20 @@ +function maximumScore(nums: number[], multipliers: number[]): number { + const m = multipliers.length; + const dp: (number | null)[][] = Array.from({ length: m + 1 }, () => + Array(m + 1).fill(null), + ); + + function f(i: number, j: number): number { + const k = i + j; + if (k === m) return 0; + if (dp[i][j] !== null) return dp[i][j]!; + + const back = multipliers[k] * nums[nums.length - 1 - j] + f(i, j + 1); + const front = multipliers[k] * nums[i] + f(i + 1, j); + const result = Math.max(front, back); + dp[i][j] = result; + return result; + } + + return f(0, 0); +} diff --git a/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/manifest.yaml b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/manifest.yaml new file mode 100644 index 00000000..7ad6ec45 --- /dev/null +++ b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/manifest.yaml @@ -0,0 +1,261 @@ +entry: + id: 1771 + title: "maximize-palindrome-length-from-subsequences" + params: + word1: + type: string + word2: + type: string + call: + cpp: "Solution().longestPalindrome({word1}, {word2})" + rust: "Solution::longest_palindrome({word1}, {word2})" + python3: "Solution().longestPalindrome({word1}, {word2})" + python2: "Solution().longestPalindrome({word1}, {word2})" + ruby: "longest_palindrome({word1}, {word2})" + java: "new Solution().longestPalindrome({word1}, {word2})" + csharp: "new Solution().LongestPalindrome({word1}, {word2})" + kotlin: "Solution().longestPalindrome({word1}, {word2})" + go: "longestPalindrome({word1}, {word2})" + dart: "Solution().longestPalindrome({word1}, {word2})" + swift: "Solution().longestPalindrome({word1}, {word2})" + typescript: "longestPalindrome({word1}, {word2})" + +judge: + type: "exact" + +limits: + time_ms: 5000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().longestPalindrome(word1, word2, {result})" + checker: | + class Checker: + def longestPalindrome(self, word1, word2, result): + if not isinstance(word1, str) or not isinstance(word2, str): + return False + if not (1 <= len(word1) <= 1000 and 1 <= len(word2) <= 1000): + return False + if any(not ('a' <= c <= 'z') for c in word1 + word2): + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + word = word1 + word2 + n = len(word) + dp = [[0] * n for _ in range(n)] + best = 0 + for i in range(n - 1, -1, -1): + dp[i][i] = 1 + for j in range(i + 1, n): + if word[i] == word[j]: + dp[i][j] = dp[i + 1][j - 1] + 2 if i + 1 <= j - 1 else 2 + else: + dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]) + if i < len(word1) <= j: + best = max(best, dp[i][j]) + return result == best + +seed: 1771 + +tests: + - name: example-one + in: + word1: "cacb" + word2: "cbba" + out: 5 + - name: example-two + in: + word1: "ab" + word2: "ab" + out: 3 + - name: example-three-no-match + in: + word1: "aa" + word2: "bb" + out: 0 + - name: single-equal + in: + word1: "a" + word2: "a" + out: 2 + - name: single-different + in: + word1: "a" + word2: "b" + out: 0 + - name: two-by-two-cross + in: + word1: "ab" + word2: "ba" + out: 4 + - name: repeated-first + in: + word1: "aaa" + word2: "a" + out: 4 + - name: repeated-second + in: + word1: "a" + word2: "aaa" + out: 4 + - name: disjoint-alphabet + in: + word1: "abc" + word2: "def" + out: 0 + - name: alternating + in: + word1: "abab" + word2: "baba" + out: 8 + - name: nested-palindrome + in: + word1: "abcba" + word2: "abcba" + out: 10 + - name: cross-boundary-pair + in: + word1: "xabc" + word2: "cby" + out: 4 + - name: cross-boundary-long + in: + word1: "abcdxyz" + word2: "zyxwvut" + out: 6 + - name: one-sided-no-palindrome + in: + word1: "abcd" + word2: "efgh" + out: 0 + - name: all-same-small + in: + word1: "aaaaa" + word2: "aaaaa" + out: 10 + - name: all-same-unbalanced + in: + word1: "aaaa" + word2: "aa" + out: 6 + - name: mirrored-halves + in: + word1: "abc" + word2: "cba" + out: 6 + - name: mirrored-with-noise + in: + word1: "axbycz" + word2: "zcybxa" + out: 12 + - name: duplicate-noise + in: + word1: "aabcc" + word2: "cbbaa" + out: 9 + - name: long-first-short-second + in: + word1: "abcdefghijklmnopq" + word2: "qponmlkjihgfedcba" + out: 34 + - name: long-second-short-first + in: + word1: "mnopq" + word2: "qponmlkjihgfedcba" + out: 10 + - name: boundary-character-a + in: + word1: "zaaz" + word2: "azza" + out: 5 + - name: boundary-character-z + in: + word1: "zzab" + word2: "bazz" + out: 8 + - name: multiple-optimal-centers + in: + word1: "abca" + word2: "acba" + out: 8 + - name: sparse-match + in: + word1: "qwerty" + word2: "ytrewq" + out: 12 + - name: repeated-blocks + in: + word1: "abcabc" + word2: "cbacba" + out: 12 + - name: mostly-equal + in: + word1: "aaaaab" + word2: "baaaaa" + out: 12 + - name: distinct-letters + in: + word1: "acegik" + word2: "bdfhjl" + out: 0 + - name: alternating-noise + in: + word1: "aibicid" + word2: "dicibia" + out: 14 + - name: moderate-repeated + in: + word1: "abbacaba" + word2: "bacababb" + out: 13 + - name: generated-small + in: + word1: + gen: "str" + len: 1 + alphabet: "abc" + word2: + gen: "str" + len: 1 + alphabet: "abc" + - name: generated-medium + in: + word1: + gen: "str" + len: 20 + alphabet: "abcde" + word2: + gen: "str" + len: 20 + alphabet: "abcde" + - name: generated-dense + in: + word1: + gen: "str" + len: 100 + alphabet: "abc" + word2: + gen: "str" + len: 100 + alphabet: "abc" + - name: generated-large + in: + word1: + gen: "str" + len: 500 + alphabet: "abcdefgh" + word2: + gen: "str" + len: 500 + alphabet: "abcdefgh" + - name: generated-max + in: + word1: + gen: "str" + len: 1000 + alphabet: "abcdefghij" + word2: + gen: "str" + len: 1000 + alphabet: "abcdefghij" diff --git a/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.cpp b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.cpp new file mode 100644 index 00000000..b95f81ef --- /dev/null +++ b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int longestPalindrome(string word1, string word2) { + string word = word1 + word2; + int n = word.size(); + vector> memo(n, vector(n, -1)); + + function fn = [&](int lo, int hi) { + if (lo >= hi) return lo == hi ? 1 : 0; + if (memo[lo][hi] != -1) return memo[lo][hi]; + if (word[lo] == word[hi]) { + memo[lo][hi] = 2 + fn(lo+1, hi-1); + } else { + memo[lo][hi] = max(fn(lo+1, hi), fn(lo, hi-1)); + } + return memo[lo][hi]; + }; + + int ans = 0; + unordered_set seen; + for (int i = 0; i < word1.size(); i++) { + char c = word1[i]; + if (seen.count(c)) continue; + seen.insert(c); + int idx1 = word1.find(c); + int idx2 = word2.rfind(c); + if (idx1 != string::npos && idx2 != string::npos) { + ans = max(ans, fn(idx1, idx2 + word1.size())); + } + } + return ans; + } +}; diff --git a/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.cs b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.cs new file mode 100644 index 00000000..3b059def --- /dev/null +++ b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.cs @@ -0,0 +1,38 @@ +public class Solution { + public int LongestPalindrome(string word1, string word2) { + string word = word1 + word2; + int n = word.Length; + int[,] memo = new int[n, n]; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + memo[i, j] = -1; + } + } + + System.Func fn = null; + fn = (lo, hi) => { + if (lo >= hi) return lo == hi ? 1 : 0; + if (memo[lo, hi] != -1) return memo[lo, hi]; + if (word[lo] == word[hi]) { + memo[lo, hi] = 2 + fn(lo+1, hi-1); + } else { + memo[lo, hi] = System.Math.Max(fn(lo+1, hi), fn(lo, hi-1)); + } + return memo[lo, hi]; + }; + + int ans = 0; + var seen = new System.Collections.Generic.HashSet(); + for (int i = 0; i < word1.Length; i++) { + char c = word1[i]; + if (seen.Contains(c)) continue; + seen.Add(c); + int idx1 = word1.IndexOf(c); + int idx2 = word2.LastIndexOf(c); + if (idx1 != -1 && idx2 != -1) { + ans = System.Math.Max(ans, fn(idx1, idx2 + word1.Length)); + } + } + return ans; + } +} diff --git a/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.dart b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.dart new file mode 100644 index 00000000..66633fe4 --- /dev/null +++ b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.dart @@ -0,0 +1,32 @@ +class Solution { + int longestPalindrome(String word1, String word2) { + String word = word1 + word2; + int n = word.length; + List> memo = List.generate(n, (_) => List.filled(n, -1)); + + int fn(int lo, int hi) { + if (lo >= hi) return lo == hi ? 1 : 0; + if (memo[lo][hi] != -1) return memo[lo][hi]; + if (word[lo] == word[hi]) { + memo[lo][hi] = 2 + fn(lo+1, hi-1); + } else { + memo[lo][hi] = max(fn(lo+1, hi), fn(lo, hi-1)); + } + return memo[lo][hi]; + } + + int ans = 0; + Set seen = {}; + for (int i = 0; i < word1.length; i++) { + String c = word1[i]; + if (seen.contains(c)) continue; + seen.add(c); + int idx1 = word1.indexOf(c); + int idx2 = word2.lastIndexOf(c); + if (idx1 != -1 && idx2 != -1) { + ans = max(ans, fn(idx1, idx2 + word1.length)); + } + } + return ans; + } +} diff --git a/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.go b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.go new file mode 100644 index 00000000..ef80db1d --- /dev/null +++ b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.go @@ -0,0 +1,55 @@ +func longestPalindrome(word1 string, word2 string) int { + word := word1 + word2 + n := len(word) + memo := make([][]int, n) + for i := range memo { + memo[i] = make([]int, n) + for j := range memo[i] { + memo[i][j] = -1 + } + } + + var fn func(lo, hi int) int + fn = func(lo, hi int) int { + if lo >= hi { + if lo == hi { + return 1 + } + return 0 + } + if memo[lo][hi] != -1 { + return memo[lo][hi] + } + if word[lo] == word[hi] { + memo[lo][hi] = 2 + fn(lo+1, hi-1) + } else { + a := fn(lo+1, hi) + b := fn(lo, hi-1) + if a > b { + memo[lo][hi] = a + } else { + memo[lo][hi] = b + } + } + return memo[lo][hi] + } + + ans := 0 + seen := make(map[byte]bool) + for i := 0; i < len(word1); i++ { + c := word1[i] + if seen[c] { + continue + } + seen[c] = true + idx1 := strings.IndexByte(word1, c) + idx2 := strings.LastIndexByte(word2, c) + if idx1 != -1 && idx2 != -1 { + val := fn(idx1, idx2 + len(word1)) + if val > ans { + ans = val + } + } + } + return ans +} diff --git a/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.java b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.java new file mode 100644 index 00000000..05395a05 --- /dev/null +++ b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.java @@ -0,0 +1,29 @@ +class Solution { + public int longestPalindrome(String word1, String word2) { + String word = word1 + word2; + int n = word.length(); + int[][] memo = new int[n][n]; + for (int[] row : memo) Arrays.fill(row, -1); + int ans = 0; + + for (char c : word1.toCharArray()) { + int i = word1.indexOf(c); + int j = word2.lastIndexOf(c); + if (i != -1 && j != -1) { + ans = Math.max(ans, fn(i, j + word1.length(), word, memo)); + } + } + return ans; + } + + private int fn(int lo, int hi, String word, int[][] memo) { + if (lo >= hi) return lo == hi ? 1 : 0; + if (memo[lo][hi] != -1) return memo[lo][hi]; + if (word.charAt(lo) == word.charAt(hi)) { + memo[lo][hi] = 2 + fn(lo+1, hi-1, word, memo); + } else { + memo[lo][hi] = Math.max(fn(lo+1, hi, word, memo), fn(lo, hi-1, word, memo)); + } + return memo[lo][hi]; + } +} diff --git a/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.kt b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.kt new file mode 100644 index 00000000..9a00da31 --- /dev/null +++ b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.kt @@ -0,0 +1,28 @@ +class Solution { + fun longestPalindrome(word1: String, word2: String): Int { + val word = word1 + word2 + val n = word.length + val memo = Array(n) { IntArray(n) { -1 } } + + fun fn(lo: Int, hi: Int): Int { + if (lo >= hi) return if (lo == hi) 1 else 0 + if (memo[lo][hi] != -1) return memo[lo][hi] + memo[lo][hi] = if (word[lo] == word[hi]) { + 2 + fn(lo+1, hi-1) + } else { + maxOf(fn(lo+1, hi), fn(lo, hi-1)) + } + return memo[lo][hi] + } + + var ans = 0 + for (c in word1.toSet()) { + val i = word1.indexOf(c) + val j = word2.lastIndexOf(c) + if (i != -1 && j != -1) { + ans = maxOf(ans, fn(i, j + word1.length)) + } + } + return ans + } +} diff --git a/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.py b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.py new file mode 100644 index 00000000..1011bd8a --- /dev/null +++ b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.py @@ -0,0 +1,24 @@ +from functools import cache +from string import ascii_lowercase + + +class Solution: + def longestPalindrome(self, word1: str, word2: str) -> int: + + @cache + def fn(lo, hi): + """Return length of longest palindromic subsequence.""" + if lo >= hi: + return int(lo == hi) + if word[lo] == word[hi]: + return 2 + fn(lo + 1, hi - 1) + return max(fn(lo + 1, hi), fn(lo, hi - 1)) + + ans = 0 + word = word1 + word2 + for x in ascii_lowercase: + i = word1.find(x) + j = word2.rfind(x) + if i != -1 and j != -1: + ans = max(ans, fn(i, j + len(word1))) + return ans diff --git a/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.py2 b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.py2 new file mode 100644 index 00000000..02c72abe --- /dev/null +++ b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.py2 @@ -0,0 +1,30 @@ +class Solution(object): + def longestPalindrome(self, word1, word2): + """ + :type word1: str + :type word2: str + :rtype: int + """ + word = word1 + word2 + n = len(word) + + memo = [[-1] * len(word) for _ in range(len(word))] + def fn(lo, hi): + if memo[lo][hi] != -1: + return memo[lo][hi] + if lo >= hi: + value = int(lo == hi) + elif word[lo] == word[hi]: + value = 2 + fn(lo+1, hi-1) + else: + value = max(fn(lo+1, hi), fn(lo, hi-1)) + memo[lo][hi] = value + return value + + ans = 0 + for x in set(word1): + i = word1.find(x) + j = word2.rfind(x) + if i != -1 and j != -1: + ans = max(ans, fn(i, j + len(word1))) + return ans diff --git a/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.rb b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.rb new file mode 100644 index 00000000..2cd98cb4 --- /dev/null +++ b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.rb @@ -0,0 +1,30 @@ +# @param {String} word1 +# @param {String} word2 +# @return {Integer} +def longest_palindrome(word1, word2) + bytes = (word1 + word2).bytes + n = bytes.length + + memo = Array.new(n) { Array.new(n, -1) } + fn = lambda do |lo, hi| + return memo[lo][hi] if memo[lo][hi] != -1 + if lo >= hi + memo[lo][hi] = (lo == hi ? 1 : 0) + elsif bytes[lo] == bytes[hi] + memo[lo][hi] = 2 + fn.call(lo+1, hi-1) + else + memo[lo][hi] = [fn.call(lo+1, hi), fn.call(lo, hi-1)].max + end + memo[lo][hi] + end + + ans = 0 + word1.bytes.uniq.each do |x| + i = word1.bytes.index(x) + j = word2.bytes.rindex(x) + if !i.nil? && !j.nil? + ans = [ans, fn.call(i, j + word1.bytes.length)].max + end + end + ans +end diff --git a/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.rs b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.rs new file mode 100644 index 00000000..4acd3e6b --- /dev/null +++ b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.rs @@ -0,0 +1,35 @@ +impl Solution { + pub fn longest_palindrome(word1: String, word2: String) -> i32 { + let word = word1.clone() + &word2; + let chars: Vec = word.chars().collect(); + let n = chars.len(); + let mut memo = vec![vec![-1; n]; n]; + + fn fn_helper(lo: usize, hi: usize, chars: &[char], memo: &mut Vec>) -> i32 { + if lo >= hi { + return if lo == hi { 1 } else { 0 }; + } + if memo[lo][hi] != -1 { + return memo[lo][hi]; + } + if chars[lo] == chars[hi] { + memo[lo][hi] = 2 + fn_helper(lo+1, hi-1, chars, memo); + } else { + memo[lo][hi] = std::cmp::max(fn_helper(lo+1, hi, chars, memo), fn_helper(lo, hi-1, chars, memo)); + } + memo[lo][hi] + } + + let mut ans = 0; + let mut seen = std::collections::HashSet::new(); + for c in word1.chars() { + if seen.contains(&c) { continue; } + seen.insert(c); + let idx1 = word1.chars().position(|x| x == c).unwrap(); + let Some(rev) = word2.chars().rev().position(|x| x == c) else { continue; }; + let idx2 = word2.chars().count() - 1 - rev; + ans = ans.max(fn_helper(idx1, idx2 + word1.chars().count(), &chars, &mut memo)); + } + ans + } +} diff --git a/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.swift b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.swift new file mode 100644 index 00000000..d4efc448 --- /dev/null +++ b/tests/1501-2000/1771. maximize-palindrome-length-from-subsequences/sol.swift @@ -0,0 +1,32 @@ +class Solution { + func longestPalindrome(_ word1: String, _ word2: String) -> Int { + let chars = Array(word1 + word2) + let leftChars = Array(word1) + let rightChars = Array(word2) + let n = chars.count + var memo = [[Int]](repeating: [Int](repeating: -1, count: n), count: n) + + func fn(_ lo: Int, _ hi: Int) -> Int { + if lo >= hi { return lo == hi ? 1 : 0 } + if memo[lo][hi] != -1 { return memo[lo][hi] } + if chars[lo] == chars[hi] { + memo[lo][hi] = 2 + fn(lo+1, hi-1) + } else { + memo[lo][hi] = max(fn(lo+1, hi), fn(lo, hi-1)) + } + return memo[lo][hi] + } + + var ans = 0 + var seen = Set() + for i in 0.. Array(n).fill(-1)); + + function fn(lo: number, hi: number): number { + if (lo >= hi) return lo === hi ? 1 : 0; + if (memo[lo][hi] !== -1) return memo[lo][hi]; + if (word[lo] === word[hi]) { + memo[lo][hi] = 2 + fn(lo + 1, hi - 1); + } else { + memo[lo][hi] = Math.max(fn(lo + 1, hi), fn(lo, hi - 1)); + } + return memo[lo][hi]; + } + + let ans = 0; + const seen = new Set(); + for (let i = 0; i < word1.length; i++) { + const c = word1[i]; + if (seen.has(c)) continue; + seen.add(c); + const idx1 = word1.indexOf(c); + const idx2 = word2.lastIndexOf(c); + if (idx1 !== -1 && idx2 !== -1) { + ans = Math.max(ans, fn(idx1, idx2 + word1.length)); + } + } + return ans; +} diff --git a/tests/1501-2000/1773. count-items-matching-a-rule/manifest.yaml b/tests/1501-2000/1773. count-items-matching-a-rule/manifest.yaml new file mode 100644 index 00000000..c454faa9 --- /dev/null +++ b/tests/1501-2000/1773. count-items-matching-a-rule/manifest.yaml @@ -0,0 +1,714 @@ +entry: + id: 1773 + title: "count-items-matching-a-rule" + params: + items: + type: array + items: + type: array + items: + type: string + ruleKey: + type: string + ruleValue: + type: string + call: + cpp: "Solution().countMatches({items}, {ruleKey}, {ruleValue})" + rust: "Solution::count_matches({items}, {ruleKey}, {ruleValue})" + python3: "Solution().countMatches({items}, {ruleKey}, {ruleValue})" + python2: "Solution().countMatches({items}, {ruleKey}, {ruleValue})" + ruby: "count_matches({items}, {ruleKey}, {ruleValue})" + java: "new Solution().countMatches({items}, {ruleKey}, {ruleValue})" + csharp: "new Solution().CountMatches({items}, {ruleKey}, {ruleValue})" + kotlin: "Solution().countMatches({items}, {ruleKey}, {ruleValue})" + go: "countMatches({items}, {ruleKey}, {ruleValue})" + dart: "Solution().countMatches({items}, {ruleKey}, {ruleValue})" + swift: "Solution().countMatches({items}, {ruleKey}, {ruleValue})" + typescript: "countMatches({items}, {ruleKey}, {ruleValue})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().countMatches(items, ruleKey, ruleValue, {result})" + checker: | + class Checker: + def countMatches(self, items, ruleKey, ruleValue, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + index = {"type": 0, "color": 1, "name": 2}[ruleKey] + expected = sum(1 for item in items if item[index] == ruleValue) + return result == expected +seed: 1773 +tests: + - name: example-color + in: + items: + - ["phone", "blue", "pixel"] + - ["computer", "silver", "lenovo"] + - ["phone", "gold", "iphone"] + ruleKey: "color" + ruleValue: "silver" + out: 1 + judge: + type: "exact" + - name: example-type + in: + items: + - ["phone", "blue", "pixel"] + - ["computer", "silver", "phone"] + - ["phone", "gold", "iphone"] + ruleKey: "type" + ruleValue: "phone" + out: 2 + judge: + type: "exact" + - name: single-type-hit + in: + items: + - ["a", "b", "c"] + ruleKey: "type" + ruleValue: "a" + out: 1 + judge: + type: "exact" + - name: single-color-miss + in: + items: + - ["a", "b", "c"] + ruleKey: "color" + ruleValue: "a" + out: 0 + judge: + type: "exact" + - name: single-name-hit + in: + items: + - ["a", "b", "c"] + ruleKey: "name" + ruleValue: "c" + out: 1 + judge: + type: "exact" + - name: all-types-match + in: + items: + - ["book", "red", "one"] + - ["book", "blue", "two"] + - ["book", "green", "three"] + - ["book", "black", "four"] + ruleKey: "type" + ruleValue: "book" + out: 4 + judge: + type: "exact" + - name: all-colors-match + in: + items: + - ["a", "red", "one"] + - ["b", "red", "two"] + - ["c", "red", "three"] + ruleKey: "color" + ruleValue: "red" + out: 3 + judge: + type: "exact" + - name: all-names-match + in: + items: + - ["a", "x", "same"] + - ["b", "y", "same"] + - ["c", "z", "same"] + ruleKey: "name" + ruleValue: "same" + out: 3 + judge: + type: "exact" + - name: no-type-match + in: + items: + - ["a", "x", "p"] + - ["b", "y", "q"] + - ["c", "z", "r"] + ruleKey: "type" + ruleValue: "d" + out: 0 + judge: + type: "exact" + - name: no-color-match + in: + items: + - ["a", "x", "p"] + - ["b", "y", "q"] + - ["c", "z", "r"] + ruleKey: "color" + ruleValue: "w" + out: 0 + judge: + type: "exact" + - name: no-name-match + in: + items: + - ["a", "x", "p"] + - ["b", "y", "q"] + - ["c", "z", "r"] + ruleKey: "name" + ruleValue: "s" + out: 0 + judge: + type: "exact" + - name: mixed-type-count + in: + items: + - ["cat", "red", "small"] + - ["dog", "red", "fast"] + - ["cat", "blue", "quiet"] + - ["bird", "red", "small"] + - ["cat", "green", "fast"] + ruleKey: "type" + ruleValue: "cat" + out: 3 + judge: + type: "exact" + - name: mixed-color-count + in: + items: + - ["cat", "red", "small"] + - ["dog", "red", "fast"] + - ["cat", "blue", "quiet"] + - ["bird", "red", "small"] + - ["cat", "green", "fast"] + ruleKey: "color" + ruleValue: "red" + out: 3 + judge: + type: "exact" + - name: mixed-name-count + in: + items: + - ["cat", "red", "small"] + - ["dog", "red", "fast"] + - ["cat", "blue", "quiet"] + - ["bird", "red", "small"] + - ["cat", "green", "fast"] + ruleKey: "name" + ruleValue: "fast" + out: 2 + judge: + type: "exact" + - name: case-sensitive-lowercase + in: + items: + - ["ab", "cd", "ef"] + - ["abc", "cde", "efg"] + - ["abcd", "cdef", "efgh"] + ruleKey: "name" + ruleValue: "ef" + out: 1 + judge: + type: "exact" + - name: maximum-string-length + in: + items: + - ["abcdefghij", "klmnopqrst", "uvwxyzabcd"] + - ["abcdefghij", "klmnopqrst", "zzzzzzzzzz"] + - ["qqqqqqqqqq", "klmnopqrst", "uvwxyzabcd"] + ruleKey: "color" + ruleValue: "klmnopqrst" + out: 3 + judge: + type: "exact" + - name: repeated-identical-items + in: + items: + - ["x", "y", "z"] + - ["x", "y", "z"] + - ["x", "y", "z"] + - ["x", "y", "z"] + - ["x", "y", "z"] + ruleKey: "type" + ruleValue: "x" + out: 5 + judge: + type: "exact" + - name: repeated-value-only-color + in: + items: + - ["a", "same", "p"] + - ["b", "same", "q"] + - ["c", "same", "r"] + - ["d", "other", "s"] + ruleKey: "color" + ruleValue: "same" + out: 3 + judge: + type: "exact" + - name: repeated-value-only-name + in: + items: + - ["a", "x", "same"] + - ["b", "y", "same"] + - ["c", "z", "other"] + - ["d", "w", "same"] + ruleKey: "name" + ruleValue: "same" + out: 3 + judge: + type: "exact" + - name: first-field-only + in: + items: + - ["target", "a", "b"] + - ["c", "target", "d"] + - ["e", "f", "target"] + - ["target", "target", "target"] + ruleKey: "type" + ruleValue: "target" + out: 2 + judge: + type: "exact" + - name: second-field-only + in: + items: + - ["target", "a", "b"] + - ["c", "target", "d"] + - ["e", "f", "target"] + - ["target", "target", "target"] + ruleKey: "color" + ruleValue: "target" + out: 2 + judge: + type: "exact" + - name: third-field-only + in: + items: + - ["target", "a", "b"] + - ["c", "target", "d"] + - ["e", "f", "target"] + - ["target", "target", "target"] + ruleKey: "name" + ruleValue: "target" + out: 2 + judge: + type: "exact" + - name: alternating-types + in: + items: + - ["a", "x", "p"] + - ["b", "y", "q"] + - ["a", "z", "r"] + - ["b", "x", "s"] + - ["a", "y", "t"] + - ["b", "z", "u"] + ruleKey: "type" + ruleValue: "a" + out: 3 + judge: + type: "exact" + - name: alternating-colors + in: + items: + - ["a", "x", "p"] + - ["b", "y", "q"] + - ["c", "x", "r"] + - ["d", "y", "s"] + - ["e", "x", "t"] + - ["f", "y", "u"] + ruleKey: "color" + ruleValue: "x" + out: 3 + judge: + type: "exact" + - name: alternating-names + in: + items: + - ["a", "p", "x"] + - ["b", "q", "y"] + - ["c", "r", "x"] + - ["d", "s", "y"] + - ["e", "t", "x"] + - ["f", "u", "y"] + ruleKey: "name" + ruleValue: "y" + out: 3 + judge: + type: "exact" + - name: ten-items-type + in: + items: + - ["a", "b", "c"] + - ["b", "c", "d"] + - ["a", "c", "d"] + - ["c", "b", "a"] + - ["a", "d", "e"] + - ["d", "a", "b"] + - ["e", "b", "c"] + - ["a", "e", "f"] + - ["f", "a", "g"] + - ["a", "a", "a"] + ruleKey: "type" + ruleValue: "a" + out: 5 + judge: + type: "exact" + - name: ten-items-color + in: + items: + - ["a", "b", "c"] + - ["b", "c", "d"] + - ["a", "c", "d"] + - ["c", "b", "a"] + - ["a", "d", "e"] + - ["d", "a", "b"] + - ["e", "b", "c"] + - ["a", "e", "f"] + - ["f", "a", "g"] + - ["a", "a", "a"] + ruleKey: "color" + ruleValue: "b" + out: 3 + judge: + type: "exact" + - name: ten-items-name + in: + items: + - ["a", "b", "c"] + - ["b", "c", "d"] + - ["a", "c", "d"] + - ["c", "b", "a"] + - ["a", "d", "e"] + - ["d", "a", "b"] + - ["e", "b", "c"] + - ["a", "e", "f"] + - ["f", "a", "g"] + - ["a", "a", "a"] + ruleKey: "name" + ruleValue: "d" + out: 2 + judge: + type: "exact" + - name: same-key-different-values + in: + items: + - ["one", "red", "cat"] + - ["two", "red", "dog"] + - ["three", "red", "bird"] + - ["four", "blue", "fish"] + - ["five", "red", "cat"] + - ["six", "green", "dog"] + - ["seven", "red", "horse"] + ruleKey: "color" + ruleValue: "red" + out: 5 + judge: + type: "exact" + - name: many-duplicates-one-miss + in: + items: + - ["same", "same", "same"] + - ["same", "same", "same"] + - ["same", "same", "same"] + - ["same", "same", "other"] + - ["same", "same", "same"] + - ["same", "other", "same"] + ruleKey: "name" + ruleValue: "same" + out: 5 + judge: + type: "exact" + - name: long-distinct-values + in: + items: + - ["aaaaaaaaaa", "bbbbbbbbbb", "cccccccccc"] + - ["dddddddddd", "eeeeeeeeee", "ffffffff"] + - ["aaaaaaaaaa", "eeeeeeeeee", "ffffffff"] + - ["gggggggggg", "bbbbbbbbbb", "cccccccccc"] + ruleKey: "type" + ruleValue: "aaaaaaaaaa" + out: 2 + judge: + type: "exact" + - name: fifteen-categories + in: + items: + - ["a", "x", "p"] + - ["b", "y", "q"] + - ["c", "z", "r"] + - ["d", "x", "s"] + - ["e", "y", "t"] + - ["f", "z", "u"] + - ["g", "x", "v"] + - ["h", "y", "w"] + - ["i", "z", "p"] + - ["j", "x", "q"] + - ["k", "y", "r"] + - ["l", "z", "s"] + - ["m", "x", "t"] + - ["n", "y", "u"] + - ["o", "z", "v"] + ruleKey: "color" + ruleValue: "z" + out: 5 + judge: + type: "exact" + - name: fifteen-name-collisions + in: + items: + - ["a", "x", "p"] + - ["b", "y", "q"] + - ["c", "z", "p"] + - ["d", "x", "r"] + - ["e", "y", "p"] + - ["f", "z", "s"] + - ["g", "x", "p"] + - ["h", "y", "t"] + - ["i", "z", "p"] + - ["j", "x", "u"] + - ["k", "y", "p"] + - ["l", "z", "v"] + - ["m", "x", "p"] + - ["n", "y", "w"] + - ["o", "z", "p"] + ruleKey: "name" + ruleValue: "p" + out: 8 + judge: + type: "exact" + - name: twenty-mixed + in: + items: + - ["a", "a", "a"] + - ["b", "b", "b"] + - ["c", "a", "c"] + - ["d", "b", "d"] + - ["e", "a", "e"] + - ["f", "b", "f"] + - ["g", "a", "g"] + - ["h", "b", "h"] + - ["i", "a", "i"] + - ["j", "b", "j"] + - ["k", "a", "k"] + - ["l", "b", "l"] + - ["m", "a", "m"] + - ["n", "b", "n"] + - ["o", "a", "o"] + - ["p", "b", "p"] + - ["q", "a", "q"] + - ["r", "b", "r"] + - ["s", "a", "s"] + - ["t", "b", "t"] + ruleKey: "color" + ruleValue: "a" + out: 10 + judge: + type: "exact" + - name: twenty-name-target + in: + items: + - ["a", "a", "target"] + - ["b", "b", "x"] + - ["c", "a", "target"] + - ["d", "b", "x"] + - ["e", "a", "target"] + - ["f", "b", "x"] + - ["g", "a", "target"] + - ["h", "b", "x"] + - ["i", "a", "target"] + - ["j", "b", "x"] + - ["k", "a", "target"] + - ["l", "b", "x"] + - ["m", "a", "target"] + - ["n", "b", "x"] + - ["o", "a", "target"] + - ["p", "b", "x"] + - ["q", "a", "target"] + - ["r", "b", "x"] + - ["s", "a", "target"] + - ["t", "b", "x"] + ruleKey: "name" + ruleValue: "target" + out: 10 + judge: + type: "exact" + - name: twenty-five-type-sparse + in: + items: + - ["hit", "a", "a"] + - ["x", "b", "b"] + - ["x", "c", "c"] + - ["x", "d", "d"] + - ["hit", "e", "e"] + - ["x", "f", "f"] + - ["x", "g", "g"] + - ["x", "h", "h"] + - ["x", "i", "i"] + - ["hit", "j", "j"] + - ["x", "k", "k"] + - ["x", "l", "l"] + - ["x", "m", "m"] + - ["x", "n", "n"] + - ["hit", "o", "o"] + - ["x", "p", "p"] + - ["x", "q", "q"] + - ["x", "r", "r"] + - ["x", "s", "s"] + - ["hit", "t", "t"] + - ["x", "u", "u"] + - ["x", "v", "v"] + - ["x", "w", "w"] + - ["x", "y", "y"] + - ["hit", "z", "z"] + ruleKey: "type" + ruleValue: "hit" + out: 6 + judge: + type: "exact" + - name: twenty-five-color-sparse + in: + items: + - ["a", "hit", "a"] + - ["b", "x", "b"] + - ["c", "x", "c"] + - ["d", "x", "d"] + - ["e", "hit", "e"] + - ["f", "x", "f"] + - ["g", "x", "g"] + - ["h", "x", "h"] + - ["i", "x", "i"] + - ["j", "hit", "j"] + - ["k", "x", "k"] + - ["l", "x", "l"] + - ["m", "x", "m"] + - ["n", "x", "n"] + - ["o", "hit", "o"] + - ["p", "x", "p"] + - ["q", "x", "q"] + - ["r", "x", "r"] + - ["s", "x", "s"] + - ["t", "hit", "t"] + - ["u", "x", "u"] + - ["v", "x", "v"] + - ["w", "x", "w"] + - ["y", "x", "y"] + - ["z", "hit", "z"] + ruleKey: "color" + ruleValue: "hit" + out: 6 + judge: + type: "exact" + - name: thirty-balanced + in: + items: + - ["a", "red", "p"] + - ["b", "blue", "q"] + - ["c", "green", "r"] + - ["a", "blue", "s"] + - ["b", "green", "t"] + - ["c", "red", "u"] + - ["a", "green", "v"] + - ["b", "red", "w"] + - ["c", "blue", "x"] + - ["a", "red", "y"] + - ["b", "blue", "z"] + - ["c", "green", "p"] + - ["a", "blue", "q"] + - ["b", "green", "r"] + - ["c", "red", "s"] + - ["a", "green", "t"] + - ["b", "red", "u"] + - ["c", "blue", "v"] + - ["a", "red", "w"] + - ["b", "blue", "x"] + - ["c", "green", "y"] + - ["a", "blue", "z"] + - ["b", "green", "p"] + - ["c", "red", "q"] + - ["a", "green", "r"] + - ["b", "red", "s"] + - ["c", "blue", "t"] + - ["a", "red", "u"] + - ["b", "blue", "v"] + - ["c", "green", "w"] + ruleKey: "type" + ruleValue: "a" + out: 10 + judge: + type: "exact" + - name: thirty-color-balance + in: + items: + - ["a", "red", "p"] + - ["b", "blue", "q"] + - ["c", "green", "r"] + - ["a", "blue", "s"] + - ["b", "green", "t"] + - ["c", "red", "u"] + - ["a", "green", "v"] + - ["b", "red", "w"] + - ["c", "blue", "x"] + - ["a", "red", "y"] + - ["b", "blue", "z"] + - ["c", "green", "p"] + - ["a", "blue", "q"] + - ["b", "green", "r"] + - ["c", "red", "s"] + - ["a", "green", "t"] + - ["b", "red", "u"] + - ["c", "blue", "v"] + - ["a", "red", "w"] + - ["b", "blue", "x"] + - ["c", "green", "y"] + - ["a", "blue", "z"] + - ["b", "green", "p"] + - ["c", "red", "q"] + - ["a", "green", "r"] + - ["b", "red", "s"] + - ["c", "blue", "t"] + - ["a", "red", "u"] + - ["b", "blue", "v"] + - ["c", "green", "w"] + ruleKey: "color" + ruleValue: "red" + out: 10 + judge: + type: "exact" + - name: thirty-name-repeats + in: + items: + - ["a", "r", "same"] + - ["b", "b", "x"] + - ["c", "g", "same"] + - ["d", "r", "y"] + - ["e", "b", "same"] + - ["f", "g", "z"] + - ["g", "r", "same"] + - ["h", "b", "x"] + - ["i", "g", "same"] + - ["j", "r", "y"] + - ["k", "b", "same"] + - ["l", "g", "z"] + - ["m", "r", "same"] + - ["n", "b", "x"] + - ["o", "g", "same"] + - ["p", "r", "y"] + - ["q", "b", "same"] + - ["r", "g", "z"] + - ["s", "r", "same"] + - ["t", "b", "x"] + - ["u", "g", "same"] + - ["v", "r", "y"] + - ["w", "b", "same"] + - ["x", "g", "z"] + - ["y", "r", "same"] + - ["z", "b", "x"] + - ["aa", "g", "same"] + - ["bb", "r", "y"] + - ["cc", "b", "same"] + - ["dd", "g", "z"] + ruleKey: "name" + ruleValue: "same" + out: 15 + judge: + type: "exact" diff --git a/tests/1501-2000/1773. count-items-matching-a-rule/sol.cpp b/tests/1501-2000/1773. count-items-matching-a-rule/sol.cpp new file mode 100644 index 00000000..2a9a4ee5 --- /dev/null +++ b/tests/1501-2000/1773. count-items-matching-a-rule/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int countMatches(vector>& items, string ruleKey, string ruleValue) { + unordered_map key_map = {{"type",0},{"color",1},{"name",2}}; + int count = 0; + int idx = key_map[ruleKey]; + for(auto& item : items){ + if(item[idx] == ruleValue){ + count++; + } + } + return count; + } +}; diff --git a/tests/1501-2000/1773. count-items-matching-a-rule/sol.cs b/tests/1501-2000/1773. count-items-matching-a-rule/sol.cs new file mode 100644 index 00000000..4ac63c45 --- /dev/null +++ b/tests/1501-2000/1773. count-items-matching-a-rule/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public int CountMatches(IList> items, string ruleKey, string ruleValue) { + var keyMap = new Dictionary{{"type",0},{"color",1},{"name",2}}; + int count = 0; + int idx = keyMap[ruleKey]; + foreach(var item in items) { + if(item[idx] == ruleValue) { + count++; + } + } + return count; + } +} diff --git a/tests/1501-2000/1773. count-items-matching-a-rule/sol.dart b/tests/1501-2000/1773. count-items-matching-a-rule/sol.dart new file mode 100644 index 00000000..e9841f0f --- /dev/null +++ b/tests/1501-2000/1773. count-items-matching-a-rule/sol.dart @@ -0,0 +1,13 @@ +class Solution { + int countMatches(List> items, String ruleKey, String ruleValue) { + var keyMap = {'type':0,'color':1,'name':2}; + var count = 0; + var idx = keyMap[ruleKey]!; + for (var item in items) { + if (item[idx] == ruleValue) { + count++; + } + } + return count; + } +} diff --git a/tests/1501-2000/1773. count-items-matching-a-rule/sol.go b/tests/1501-2000/1773. count-items-matching-a-rule/sol.go new file mode 100644 index 00000000..0005144d --- /dev/null +++ b/tests/1501-2000/1773. count-items-matching-a-rule/sol.go @@ -0,0 +1,11 @@ +func countMatches(items [][]string, ruleKey string, ruleValue string) int { + keyMap := map[string]int{"type":0,"color":1,"name":2} + count := 0 + idx := keyMap[ruleKey] + for _, item := range items { + if item[idx] == ruleValue { + count++ + } + } + return count +} diff --git a/tests/1501-2000/1773. count-items-matching-a-rule/sol.java b/tests/1501-2000/1773. count-items-matching-a-rule/sol.java new file mode 100644 index 00000000..2655366d --- /dev/null +++ b/tests/1501-2000/1773. count-items-matching-a-rule/sol.java @@ -0,0 +1,24 @@ +class Solution { + public int countMatches(List> items, String ruleKey, String ruleValue) { + String[][] itemArray = new String[items.size()][]; + for (int i = 0; i < items.size(); i++) { + itemArray[i] = items.get(i).toArray(new String[0]); + } + return countMatches(itemArray, ruleKey, ruleValue); + } + + public int countMatches(String[][] items, String ruleKey, String ruleValue) { + java.util.Map key_map = new java.util.HashMap<>(); + key_map.put("type",0); + key_map.put("color",1); + key_map.put("name",2); + int count=0; + int idx=key_map.get(ruleKey); + for(String[] item : items){ + if(item[idx].equals(ruleValue)){ + count++; + } + } + return count; + } +} diff --git a/tests/1501-2000/1773. count-items-matching-a-rule/sol.kt b/tests/1501-2000/1773. count-items-matching-a-rule/sol.kt new file mode 100644 index 00000000..1e924667 --- /dev/null +++ b/tests/1501-2000/1773. count-items-matching-a-rule/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun countMatches(items: List>, ruleKey: String, ruleValue: String): Int { + return countMatches(items.map { it.toTypedArray() }.toTypedArray(), ruleKey, ruleValue) + } + + fun countMatches(items: Array>, ruleKey: String, ruleValue: String): Int { + val keyMap = mapOf("type" to 0, "color" to 1, "name" to 2) + var count = 0 + val idx = keyMap[ruleKey]!! + for (item in items) { + if (item[idx] == ruleValue) count++ + } + return count + } +} diff --git a/tests/1501-2000/1773. count-items-matching-a-rule/sol.py b/tests/1501-2000/1773. count-items-matching-a-rule/sol.py new file mode 100644 index 00000000..c5b0169c --- /dev/null +++ b/tests/1501-2000/1773. count-items-matching-a-rule/sol.py @@ -0,0 +1,9 @@ +class Solution: + def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int: + key_map = {"type": 0, "color": 1, "name": 2} + count = 0 + idx = key_map[ruleKey] + for item in items: + if item[idx] == ruleValue: + count += 1 + return count diff --git a/tests/1501-2000/1773. count-items-matching-a-rule/sol.py2 b/tests/1501-2000/1773. count-items-matching-a-rule/sol.py2 new file mode 100644 index 00000000..b86da116 --- /dev/null +++ b/tests/1501-2000/1773. count-items-matching-a-rule/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def countMatches(self, items, ruleKey, ruleValue): + """ + :type items: List[List[str]] + :type ruleKey: str + :type ruleValue: str + :rtype: int + """ + key_map={"type":0,"color":1,"name":2} + count=0 + idx=key_map[ruleKey] + for item in items: + if item[idx]==ruleValue: + count+=1 + return count diff --git a/tests/1501-2000/1773. count-items-matching-a-rule/sol.rb b/tests/1501-2000/1773. count-items-matching-a-rule/sol.rb new file mode 100644 index 00000000..b47609cb --- /dev/null +++ b/tests/1501-2000/1773. count-items-matching-a-rule/sol.rb @@ -0,0 +1,15 @@ +# @param {String[][]} items +# @param {String} rule_key +# @param {String} rule_value +# @return {Integer} +def count_matches(items, rule_key, rule_value) + key_map={"type"=>0,"color"=>1,"name"=>2} + count=0 + idx=key_map[rule_key] + items.each do |item| + if item[idx]==rule_value + count+=1 + end + end + return count +end diff --git a/tests/1501-2000/1773. count-items-matching-a-rule/sol.rs b/tests/1501-2000/1773. count-items-matching-a-rule/sol.rs new file mode 100644 index 00000000..04ae6af0 --- /dev/null +++ b/tests/1501-2000/1773. count-items-matching-a-rule/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn count_matches(items: Vec>, rule_key: String, rule_value: String) -> i32 { + let key_map = [("type",0), ("color",1), ("name",2)]; + let idx = key_map.iter().find(|(k,_)| *k == rule_key).unwrap().1; + let mut count = 0; + for item in items.iter() { + if item[idx] == rule_value { + count += 1; + } + } + count + } +} diff --git a/tests/1501-2000/1773. count-items-matching-a-rule/sol.swift b/tests/1501-2000/1773. count-items-matching-a-rule/sol.swift new file mode 100644 index 00000000..d39677d2 --- /dev/null +++ b/tests/1501-2000/1773. count-items-matching-a-rule/sol.swift @@ -0,0 +1,13 @@ +class Solution { + func countMatches(_ items: [[String]], _ ruleKey: String, _ ruleValue: String) -> Int { + let keyMap = ["type":0, "color":1, "name":2] + var count = 0 + let idx = keyMap[ruleKey]! + for item in items { + if item[idx] == ruleValue { + count += 1 + } + } + return count + } +} diff --git a/tests/1501-2000/1773. count-items-matching-a-rule/sol.ts b/tests/1501-2000/1773. count-items-matching-a-rule/sol.ts new file mode 100644 index 00000000..ebfc304b --- /dev/null +++ b/tests/1501-2000/1773. count-items-matching-a-rule/sol.ts @@ -0,0 +1,15 @@ +function countMatches( + items: string[][], + ruleKey: string, + ruleValue: string, +): number { + const keyMap: { [key: string]: number } = { type: 0, color: 1, name: 2 }; + let count = 0; + const idx = keyMap[ruleKey]; + for (const item of items) { + if (item[idx] === ruleValue) { + count++; + } + } + return count; +} diff --git a/tests/1501-2000/1774. closest-dessert-cost/manifest.yaml b/tests/1501-2000/1774. closest-dessert-cost/manifest.yaml new file mode 100644 index 00000000..cc062af5 --- /dev/null +++ b/tests/1501-2000/1774. closest-dessert-cost/manifest.yaml @@ -0,0 +1,338 @@ +entry: + id: 1774 + title: "closest-dessert-cost" + params: + baseCosts: + type: array + items: + type: int + toppingCosts: + type: array + items: + type: int + target: + type: int + call: + cpp: "Solution().closestCost({baseCosts}, {toppingCosts}, {target})" + rust: "Solution::closest_cost({baseCosts}, {toppingCosts}, {target})" + python3: "Solution().closestCost({baseCosts}, {toppingCosts}, {target})" + python2: "Solution().closestCost({baseCosts}, {toppingCosts}, {target})" + ruby: "closest_cost({baseCosts}, {toppingCosts}, {target})" + java: "new Solution().closestCost({baseCosts}, {toppingCosts}, {target})" + csharp: "new Solution().ClosestCost({baseCosts}, {toppingCosts}, {target})" + kotlin: "Solution().closestCost({baseCosts}, {toppingCosts}, {target})" + go: "closestCost({baseCosts}, {toppingCosts}, {target})" + dart: "Solution().closestCost({baseCosts}, {toppingCosts}, {target})" + swift: "Solution().closestCost({baseCosts}, {toppingCosts}, {target})" + typescript: "closestCost({baseCosts}, {toppingCosts}, {target})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().closestCost(baseCosts, toppingCosts, target, {result})" + checker: | + class Checker: + def closestCost(self, baseCosts, toppingCosts, target, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + sums = [0] + for topping in toppingCosts: + sums = [old + add for old in sums for add in (0, topping, 2 * topping)] + best = min((abs(base + extra - target), base + extra) + for base in baseCosts for extra in sums) + return result == best[1] +seed: 1774 +tests: + - name: example-1 + in: + baseCosts: [1, 7] + toppingCosts: [3, 4] + target: 10 + out: 10 + - name: example-2 + in: + baseCosts: [2, 3] + toppingCosts: [4, 5, 100] + target: 18 + out: 17 + - name: example-3-tie-lower + in: + baseCosts: [3, 10] + toppingCosts: [2, 5] + target: 9 + out: 8 + - name: minimum-values + in: + baseCosts: [1] + toppingCosts: [1] + target: 1 + out: 1 + - name: target-far-above + in: + baseCosts: [5] + toppingCosts: [5] + target: 10000 + out: 15 + - name: no-topping-needed + in: + baseCosts: [10] + toppingCosts: [1] + target: 10 + out: 10 + - name: exact-combination + in: + baseCosts: [1, 2, 3] + toppingCosts: [1, 2, 3] + target: 4 + out: 4 + - name: lower-tie-base + in: + baseCosts: [7, 9] + toppingCosts: [4, 4] + target: 8 + out: 7 + - name: maximum-ingredients + in: + baseCosts: [1, 10000] + toppingCosts: [10000] + target: 10000 + out: 10000 + - name: repeated-toppings + in: + baseCosts: [100] + toppingCosts: [1, 1, 1] + target: 101 + out: 101 + - name: odd-tie + in: + baseCosts: [6, 8, 10] + toppingCosts: [2, 4] + target: 9 + out: 8 + - name: duplicate-cost-tie + in: + baseCosts: [3, 5] + toppingCosts: [2, 2] + target: 4 + out: 3 + - name: overshoot-necessary + in: + baseCosts: [1, 2] + toppingCosts: [3, 3, 3] + target: 20 + out: 20 + - name: close-base + in: + baseCosts: [50, 60] + toppingCosts: [10, 20] + target: 55 + out: 50 + - name: large-topping-and-small + in: + baseCosts: [1, 100] + toppingCosts: [2, 99] + target: 100 + out: 100 + - name: two-copies + in: + baseCosts: [8] + toppingCosts: [7, 7] + target: 22 + out: 22 + - name: small-exact + in: + baseCosts: [2, 4, 6] + toppingCosts: [1, 1] + target: 5 + out: 5 + - name: target-below-all + in: + baseCosts: [9, 10] + toppingCosts: [3, 6] + target: 1 + out: 9 + - name: duplicate-bases + in: + baseCosts: [1, 1, 1] + toppingCosts: [1, 1, 1] + target: 2 + out: 2 + - name: near-maximum-base + in: + baseCosts: [9999, 10000] + toppingCosts: [1, 2] + target: 10000 + out: 10000 + - name: exact-with-two-types + in: + baseCosts: [4, 11] + toppingCosts: [5, 6] + target: 20 + out: 20 + - name: small-topping-wins + in: + baseCosts: [12, 13] + toppingCosts: [1, 100] + target: 14 + out: 14 + - name: large-overshoot + in: + baseCosts: [2] + toppingCosts: [100, 100] + target: 150 + out: 102 + - name: three-bases + in: + baseCosts: [30, 31, 32] + toppingCosts: [9, 9, 9] + target: 50 + out: 50 + - name: target-between-options + in: + baseCosts: [1, 20] + toppingCosts: [7, 8] + target: 17 + out: 17 + - name: large-exact + in: + baseCosts: [1000] + toppingCosts: [333, 334] + target: 1999 + out: 2000 + - name: multiple-close + in: + baseCosts: [17, 23] + toppingCosts: [5, 10] + target: 40 + out: 38 + - name: one-large-topping + in: + baseCosts: [1, 2, 3, 4] + toppingCosts: [10] + target: 25 + out: 24 + - name: exact-small-gap + in: + baseCosts: [75, 80] + toppingCosts: [1, 2, 3] + target: 76 + out: 76 + - name: upper-bound-exact + in: + baseCosts: [2, 10000] + toppingCosts: [4999, 5000] + target: 10000 + out: 10000 + - name: generated-small + in: + baseCosts: + gen: array + len: 10 + of: + gen: int + min: 1 + max: 10000 + elemType: int + toppingCosts: + gen: array + len: 10 + of: + gen: int + min: 1 + max: 10000 + elemType: int + target: + gen: int + min: 1 + max: 10000 + - name: generated-medium + in: + baseCosts: + gen: array + len: 10 + of: + gen: int + min: 1 + max: 10000 + elemType: int + toppingCosts: + gen: array + len: 10 + of: + gen: int + min: 1 + max: 10000 + elemType: int + target: + gen: int + min: 1 + max: 10000 + - name: generated-low-target + in: + baseCosts: + gen: array + len: 10 + of: + gen: int + min: 1 + max: 10000 + elemType: int + toppingCosts: + gen: array + len: 10 + of: + gen: int + min: 1 + max: 10000 + elemType: int + target: + gen: int + min: 1 + max: 50 + - name: generated-high-target + in: + baseCosts: + gen: array + len: 10 + of: + gen: int + min: 9950 + max: 10000 + elemType: int + toppingCosts: + gen: array + len: 10 + of: + gen: int + min: 1 + max: 10000 + elemType: int + target: + gen: int + min: 9950 + max: 10000 + - name: generated-mixed + in: + baseCosts: + gen: array + len: 10 + of: + gen: int + min: 1 + max: 10000 + elemType: int + toppingCosts: + gen: array + len: 10 + of: + gen: int + min: 1 + max: 10000 + elemType: int + target: + gen: int + min: 1 + max: 10000 diff --git a/tests/1501-2000/1774. closest-dessert-cost/sol.cpp b/tests/1501-2000/1774. closest-dessert-cost/sol.cpp new file mode 100644 index 00000000..22e52f1a --- /dev/null +++ b/tests/1501-2000/1774. closest-dessert-cost/sol.cpp @@ -0,0 +1,42 @@ +class Solution { +public: + int closestCost(vector& baseCosts, vector& toppingCosts, int target) { + vector s = {0}; + for (int i : toppingCosts) { + vector ss; + for (int j : s) { + ss.push_back(j); + ss.push_back(j+i); + ss.push_back(j+2*i); + } + s = ss; + } + sort(s.begin(), s.end()); + int ans = 1000000000; + int fans = 1000000000; + int n = s.size(); + for (int i : baseCosts) { + int j = target - i; + int x = lower_bound(s.begin(), s.end(), j) - s.begin() - 1; + x = max(x, 0); + int ans1 = abs(j - s[x]); + if (ans1 < ans) { + ans = ans1; + fans = s[x] + i; + } else if (ans1 == ans) { + fans = min(fans, s[x] + i); + } + if (x+1 < n) { + x++; + ans1 = abs(j - s[x]); + if (ans1 < ans) { + ans = ans1; + fans = s[x] + i; + } else if (ans1 == ans) { + fans = min(fans, s[x] + i); + } + } + } + return fans; + } +}; diff --git a/tests/1501-2000/1774. closest-dessert-cost/sol.cs b/tests/1501-2000/1774. closest-dessert-cost/sol.cs new file mode 100644 index 00000000..6ee30778 --- /dev/null +++ b/tests/1501-2000/1774. closest-dessert-cost/sol.cs @@ -0,0 +1,42 @@ +public class Solution { + public int ClosestCost(int[] baseCosts, int[] toppingCosts, int target) { + List s = new List(){0}; + foreach (int i in toppingCosts) { + var ss = new List(); + foreach (int j in s) { + ss.Add(j); + ss.Add(j+i); + ss.Add(j+2*i); + } + s = ss; + } + s.Sort(); + int ans = 1000000000; + int fans = 1000000000; + int n = s.Count; + foreach (int i in baseCosts) { + int j = target - i; + int x = s.BinarySearch(j); + if (x < 0) x = ~x - 1; + if (x < 0) x = 0; + int ans1 = Math.Abs(j - s[x]); + if (ans1 < ans) { + ans = ans1; + fans = s[x] + i; + } else if (ans1 == ans) { + fans = Math.Min(fans, s[x] + i); + } + if (x+1 < n) { + x++; + ans1 = Math.Abs(j - s[x]); + if (ans1 < ans) { + ans = ans1; + fans = s[x] + i; + } else if (ans1 == ans) { + fans = Math.Min(fans, s[x] + i); + } + } + } + return fans; + } +} diff --git a/tests/1501-2000/1774. closest-dessert-cost/sol.dart b/tests/1501-2000/1774. closest-dessert-cost/sol.dart new file mode 100644 index 00000000..b5b5189e --- /dev/null +++ b/tests/1501-2000/1774. closest-dessert-cost/sol.dart @@ -0,0 +1,52 @@ +import 'dart:collection'; + +class Solution { + int closestCost(List baseCosts, List toppingCosts, int target) { + List s = [0]; + for (int i in toppingCosts) { + List ss = []; + for (int j in s) { + ss.add(j); + ss.add(j + i); + ss.add(j + 2 * i); + } + s = ss; + } + s.sort(); + int ans = 1000000000; + int fans = 1000000000; + int n = s.length; + for (int i in baseCosts) { + int j = target - i; + int x = 0; + int low = 0, high = n - 1; + while (low <= high) { + int mid = (low + high) ~/ 2; + if (s[mid] < j) { + x = mid; + low = mid + 1; + } else { + high = mid - 1; + } + } + int ans1 = (j - s[x]).abs(); + if (ans1 < ans) { + ans = ans1; + fans = s[x] + i; + } else if (ans1 == ans) { + fans = fans < s[x] + i ? fans : s[x] + i; + } + if (x + 1 < n) { + x++; + ans1 = (j - s[x]).abs(); + if (ans1 < ans) { + ans = ans1; + fans = s[x] + i; + } else if (ans1 == ans) { + fans = fans < s[x] + i ? fans : s[x] + i; + } + } + } + return fans; + } +} diff --git a/tests/1501-2000/1774. closest-dessert-cost/sol.go b/tests/1501-2000/1774. closest-dessert-cost/sol.go new file mode 100644 index 00000000..683ecd1d --- /dev/null +++ b/tests/1501-2000/1774. closest-dessert-cost/sol.go @@ -0,0 +1,42 @@ +func closestCost(baseCosts []int, toppingCosts []int, target int) int { + s := []int{0} + for _, i := range toppingCosts { + ss := make([]int, 0) + for _, j := range s { + ss = append(ss, j, j+i, j+2*i) + } + s = ss + } + sort.Ints(s) + ans := 1000000000 + fans := 1000000000 + n := len(s) + for _, i := range baseCosts { + j := target - i + x := sort.SearchInts(s, j) - 1 + if x < 0 { x = 0 } + ans1 := abs(j - s[x]) + if ans1 < ans { + ans = ans1 + fans = s[x] + i + } else if ans1 == ans { + if s[x] + i < fans { fans = s[x] + i } + } + if x + 1 < n { + x++ + ans1 = abs(j - s[x]) + if ans1 < ans { + ans = ans1 + fans = s[x] + i + } else if ans1 == ans { + if s[x] + i < fans { fans = s[x] + i } + } + } + } + return fans +} + +func abs(x int) int { + if x < 0 { return -x } + return x +} diff --git a/tests/1501-2000/1774. closest-dessert-cost/sol.java b/tests/1501-2000/1774. closest-dessert-cost/sol.java new file mode 100644 index 00000000..c0fa4f9f --- /dev/null +++ b/tests/1501-2000/1774. closest-dessert-cost/sol.java @@ -0,0 +1,45 @@ +import java.util.*; + +class Solution { + public int closestCost(int[] baseCosts, int[] toppingCosts, int target) { + List s = new ArrayList<>(); + s.add(0); + for (int i : toppingCosts) { + List ss = new ArrayList<>(); + for (int j : s) { + ss.add(j); + ss.add(j + i); + ss.add(j + 2 * i); + } + s = ss; + } + Collections.sort(s); + int ans = 1000000000; + int fans = 1000000000; + int n = s.size(); + for (int i : baseCosts) { + int j = target - i; + int x = Collections.binarySearch(s, j); + if (x < 0) x = -x - 2; + x = Math.max(x, 0); + int ans1 = Math.abs(j - s.get(x)); + if (ans1 < ans) { + ans = ans1; + fans = s.get(x) + i; + } else if (ans1 == ans) { + fans = Math.min(fans, s.get(x) + i); + } + if (x + 1 < n) { + x++; + ans1 = Math.abs(j - s.get(x)); + if (ans1 < ans) { + ans = ans1; + fans = s.get(x) + i; + } else if (ans1 == ans) { + fans = Math.min(fans, s.get(x) + i); + } + } + } + return fans; + } +} diff --git a/tests/1501-2000/1774. closest-dessert-cost/sol.kt b/tests/1501-2000/1774. closest-dessert-cost/sol.kt new file mode 100644 index 00000000..37d22ec3 --- /dev/null +++ b/tests/1501-2000/1774. closest-dessert-cost/sol.kt @@ -0,0 +1,42 @@ +class Solution { + fun closestCost(baseCosts: IntArray, toppingCosts: IntArray, target: Int): Int { + var s = listOf(0) + for (i in toppingCosts) { + val ss = mutableListOf() + for (j in s) { + ss.add(j) + ss.add(j + i) + ss.add(j + 2 * i) + } + s = ss + } + s = s.sorted() + var ans = 1000000000 + var fans = 1000000000 + val n = s.size + for (i in baseCosts) { + val j = target - i + var x = s.binarySearch(j) + if (x < 0) x = -x - 2 + x = maxOf(x, 0) + var ans1 = Math.abs(j - s[x]) + if (ans1 < ans) { + ans = ans1 + fans = s[x] + i + } else if (ans1 == ans) { + fans = minOf(fans, s[x] + i) + } + if (x + 1 < n) { + x++ + ans1 = Math.abs(j - s[x]) + if (ans1 < ans) { + ans = ans1 + fans = s[x] + i + } else if (ans1 == ans) { + fans = minOf(fans, s[x] + i) + } + } + } + return fans + } +} diff --git a/tests/1501-2000/1774. closest-dessert-cost/sol.py b/tests/1501-2000/1774. closest-dessert-cost/sol.py new file mode 100644 index 00000000..a317495e --- /dev/null +++ b/tests/1501-2000/1774. closest-dessert-cost/sol.py @@ -0,0 +1,38 @@ +from bisect import bisect + + +class Solution: + def closestCost( + self, baseCosts: List[int], toppingCosts: List[int], target: int + ) -> int: + b = baseCosts + t = toppingCosts + s = [0] + for i in t: + ss = [] + for j in s: + ss += [j, j + i, j + 2 * i] + s = ss + s.sort() + ans = 10**10 + fans = 10**10 + n = len(s) + for i in b: + j = target - i + x = bisect(s, j) - 1 + x = max(x, 0) + ans1 = abs(j - s[x]) + if ans1 < ans: + ans = ans1 + fans = s[x] + i + elif ans1 == ans: + fans = min(fans, s[x] + i) + if x + 1 < n: + x += 1 + ans1 = abs(j - s[x]) + if ans1 < ans: + ans = ans1 + fans = s[x] + i + elif ans1 == ans: + fans = min(fans, s[x] + i) + return fans diff --git a/tests/1501-2000/1774. closest-dessert-cost/sol.py2 b/tests/1501-2000/1774. closest-dessert-cost/sol.py2 new file mode 100644 index 00000000..3456fb0c --- /dev/null +++ b/tests/1501-2000/1774. closest-dessert-cost/sol.py2 @@ -0,0 +1,38 @@ +class Solution(object): + def closestCost(self, baseCosts, toppingCosts, target): + """ + :type baseCosts: List[int] + :type toppingCosts: List[int] + :type target: int + :rtype: int + """ + import bisect + s = [0] + for i in toppingCosts: + ss = [] + for j in s: + ss += [j, j+i, j+2*i] + s = ss + s.sort() + ans = 10**10 + fans = 10**10 + n = len(s) + for i in baseCosts: + j = target - i + x = bisect.bisect_left(s, j) - 1 + x = max(x, 0) + ans1 = abs(j - s[x]) + if ans1 < ans: + ans = ans1 + fans = s[x] + i + elif ans1 == ans: + fans = min(fans, s[x] + i) + if x + 1 < n: + x += 1 + ans1 = abs(j - s[x]) + if ans1 < ans: + ans = ans1 + fans = s[x] + i + elif ans1 == ans: + fans = min(fans, s[x] + i) + return fans diff --git a/tests/1501-2000/1774. closest-dessert-cost/sol.rb b/tests/1501-2000/1774. closest-dessert-cost/sol.rb new file mode 100644 index 00000000..19591c9c --- /dev/null +++ b/tests/1501-2000/1774. closest-dessert-cost/sol.rb @@ -0,0 +1,38 @@ +def closest_cost(base_costs, topping_costs, target) + s = [0] + topping_costs.each do |i| + ss = [] + s.each do |j| + ss += [j, j+i, j+2*i] + end + s = ss + end + s.sort! + ans = 10**10 + fans = 10**10 + n = s.length + base_costs.each do |i| + j = target - i + x = s.bsearch_index { |v| v >= j } || n + x -= 1 + x = [x, 0].max + ans1 = (j - s[x]).abs + if ans1 < ans + ans = ans1 + fans = s[x] + i + elsif ans1 == ans + fans = [fans, s[x] + i].min + end + if x + 1 < n + x += 1 + ans1 = (j - s[x]).abs + if ans1 < ans + ans = ans1 + fans = s[x] + i + elsif ans1 == ans + fans = [fans, s[x] + i].min + end + end + end + fans +end diff --git a/tests/1501-2000/1774. closest-dessert-cost/sol.rs b/tests/1501-2000/1774. closest-dessert-cost/sol.rs new file mode 100644 index 00000000..22ec8812 --- /dev/null +++ b/tests/1501-2000/1774. closest-dessert-cost/sol.rs @@ -0,0 +1,43 @@ +impl Solution { + pub fn closest_cost(base_costs: Vec, topping_costs: Vec, target: i32) -> i32 { + let mut s = vec![0]; + for i in topping_costs { + let mut ss = Vec::new(); + for j in s.iter() { + ss.push(j.clone()); + ss.push(j + i); + ss.push(j + 2*i); + } + s = ss; + } + s.sort(); + let mut ans = 1000000000i32; + let mut fans = 1000000000i32; + let n = s.len(); + for i in base_costs { + let j = target - i; + let mut x = match s.binary_search(&j) { + Ok(pos) => pos, + Err(pos) => pos.saturating_sub(1), + }; + let mut ans1 = (j - s[x]).abs(); + if ans1 < ans { + ans = ans1; + fans = s[x] + i; + } else if ans1 == ans { + fans = fans.min(s[x] + i); + } + if x + 1 < n { + x += 1; + ans1 = (j - s[x]).abs(); + if ans1 < ans { + ans = ans1; + fans = s[x] + i; + } else if ans1 == ans { + fans = fans.min(s[x] + i); + } + } + } + fans + } +} diff --git a/tests/1501-2000/1774. closest-dessert-cost/sol.swift b/tests/1501-2000/1774. closest-dessert-cost/sol.swift new file mode 100644 index 00000000..79888ab8 --- /dev/null +++ b/tests/1501-2000/1774. closest-dessert-cost/sol.swift @@ -0,0 +1,57 @@ +class Solution { + func closestCost(_ baseCosts: [Int], _ toppingCosts: [Int], _ target: Int) -> Int { + var s = [0] + for i in toppingCosts { + var ss = [Int]() + for j in s { + ss += [j, j+i, j+2*i] + } + s = ss + } + s.sort() + var ans = 1000000000 + var fans = 1000000000 + let n = s.count + for i in baseCosts { + let j = target - i + var x = s.binarySearch(j) + if x < 0 { x = -x - 2 } + x = max(x, 0) + var ans1 = abs(j - s[x]) + if ans1 < ans { + ans = ans1 + fans = s[x] + i + } else if ans1 == ans { + fans = min(fans, s[x] + i) + } + if x + 1 < n { + x += 1 + ans1 = abs(j - s[x]) + if ans1 < ans { + ans = ans1 + fans = s[x] + i + } else if ans1 == ans { + fans = min(fans, s[x] + i) + } + } + } + return fans + } +} + +extension Array where Element: Comparable { + func binarySearch(_ element: Element) -> Int { + var low = 0, high = count - 1 + while low <= high { + let mid = (low + high) / 2 + if self[mid] == element { + return mid + } else if self[mid] < element { + low = mid + 1 + } else { + high = mid - 1 + } + } + return -low - 1 + } +} diff --git a/tests/1501-2000/1774. closest-dessert-cost/sol.ts b/tests/1501-2000/1774. closest-dessert-cost/sol.ts new file mode 100644 index 00000000..1ba51050 --- /dev/null +++ b/tests/1501-2000/1774. closest-dessert-cost/sol.ts @@ -0,0 +1,51 @@ +function closestCost( + baseCosts: number[], + toppingCosts: number[], + target: number, +): number { + let s: number[] = [0]; + for (let i of toppingCosts) { + let ss: number[] = []; + for (let j of s) { + ss.push(j, j + i, j + 2 * i); + } + s = ss; + } + s.sort((a, b) => a - b); + let ans = 1000000000; + let fans = 1000000000; + const n = s.length; + for (let i of baseCosts) { + const j = target - i; + let x = 0; + let lo = 0, + hi = n - 1; + while (lo <= hi) { + const mid = Math.floor((lo + hi) / 2); + if (s[mid] < j) { + x = mid; + lo = mid + 1; + } else { + hi = mid - 1; + } + } + let ans1 = Math.abs(j - s[x]); + if (ans1 < ans) { + ans = ans1; + fans = s[x] + i; + } else if (ans1 === ans) { + fans = Math.min(fans, s[x] + i); + } + if (x + 1 < n) { + x++; + ans1 = Math.abs(j - s[x]); + if (ans1 < ans) { + ans = ans1; + fans = s[x] + i; + } else if (ans1 === ans) { + fans = Math.min(fans, s[x] + i); + } + } + } + return fans; +} diff --git a/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/manifest.yaml b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/manifest.yaml new file mode 100644 index 00000000..e75faea8 --- /dev/null +++ b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/manifest.yaml @@ -0,0 +1,386 @@ +entry: + id: 1775 + title: "equal-sum-arrays-with-minimum-number-of-operations" + params: + nums1: + type: array + items: + type: int + nums2: + type: array + items: + type: int + call: + cpp: "Solution().minOperations({nums1}, {nums2})" + rust: "Solution::min_operations({nums1}, {nums2})" + python3: "Solution().minOperations({nums1}, {nums2})" + python2: "Solution().minOperations({nums1}, {nums2})" + ruby: "min_operations({nums1}, {nums2})" + java: "new Solution().minOperations({nums1}, {nums2})" + csharp: "new Solution().MinOperations({nums1}, {nums2})" + kotlin: "Solution().minOperations({nums1}, {nums2})" + go: "minOperations({nums1}, {nums2})" + dart: "Solution().minOperations({nums1}, {nums2})" + swift: "Solution().minOperations({nums1}, {nums2})" + typescript: "minOperations({nums1}, {nums2})" + +judge: + type: "exact" + +limits: + time_ms: 5000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(nums1, nums2, {result})" + checker: | + class Checker: + def check(self, nums1, nums2, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + diff = abs(sum(nums1) - sum(nums2)) + if diff == 0: + return result == 0 + gains = [] + if sum(nums1) < sum(nums2): + gains.extend(6 - x for x in nums1) + gains.extend(x - 1 for x in nums2) + else: + gains.extend(x - 1 for x in nums1) + gains.extend(6 - x for x in nums2) + gains.sort(reverse=True) + used = 0 + for gain in gains: + if gain > 0: + diff -= gain + used += 1 + if diff <= 0: + return result == used + return result == -1 + +seed: 1775001 + +tests: + - name: example-one + in: + nums1: [1, 2, 3, 4, 5, 6] + nums2: [1, 1, 2, 2, 2, 2] + out: 3 + judge: + type: "exact" + - name: example-two-impossible + in: + nums1: [1, 1, 1, 1, 1, 1, 1] + nums2: [6] + out: -1 + judge: + type: "exact" + - name: example-three + in: + nums1: [6, 6] + nums2: [1] + out: 3 + judge: + type: "exact" + - name: already-equal-single + in: + nums1: [4] + nums2: [4] + out: 0 + judge: + type: "exact" + - name: one-step-increase + in: + nums1: [1] + nums2: [6] + out: 1 + judge: + type: "exact" + - name: one-step-decrease + in: + nums1: [6] + nums2: [1] + out: 1 + judge: + type: "exact" + - name: equal-many + in: + nums1: [1, 6, 2, 5] + nums2: [3, 4, 2, 5] + out: 0 + judge: + type: "exact" + - name: all-low-versus-all-high + in: + nums1: [1, 1, 1] + nums2: [6, 6, 6] + out: 3 + judge: + type: "exact" + - name: two-versus-one + in: + nums1: [1, 1] + nums2: [6] + out: 1 + judge: + type: "exact" + - name: one-versus-two + in: + nums1: [6] + nums2: [1, 1] + out: 1 + judge: + type: "exact" + - name: impossible-length-gap + in: + nums1: [1, 1, 1, 1, 1, 1, 1, 1] + nums2: [6] + out: -1 + judge: + type: "exact" + - name: six-low-versus-six-high + in: + nums1: [1, 1, 1, 1, 1, 1] + nums2: [6, 6, 6, 6, 6, 6] + out: 6 + judge: + type: "exact" + - name: use-largest-gain + in: + nums1: [1, 1, 1, 6] + nums2: [6, 6] + out: 1 + judge: + type: "exact" + - name: mixed-gains + in: + nums1: [2, 2, 2] + nums2: [6, 6] + out: 2 + judge: + type: "exact" + - name: reverse-mixed-gains + in: + nums1: [5, 5] + nums2: [1, 4, 4] + out: 1 + judge: + type: "exact" + - name: all-sixes-equal + in: + nums1: [6, 6, 6] + nums2: [6, 6, 6] + out: 0 + judge: + type: "exact" + - name: all-ones-equal + in: + nums1: [1, 1, 1] + nums2: [1, 1, 1] + out: 0 + judge: + type: "exact" + - name: exact-two-operations + in: + nums1: [1, 1, 1] + nums2: [6, 1] + out: 1 + judge: + type: "exact" + - name: parity-does-not-matter + in: + nums1: [1, 2, 3] + nums2: [6, 6] + out: 2 + judge: + type: "exact" + - name: balanced-long + in: + nums1: [1, 2, 3, 4, 5] + nums2: [5, 4, 3, 2, 1] + out: 0 + judge: + type: "exact" + - name: two-largest-changes + in: + nums1: [1, 1, 1, 1] + nums2: [6, 6, 6] + out: 3 + judge: + type: "exact" + - name: small-difference-one + in: + nums1: [3, 3, 3] + nums2: [3, 3, 2] + out: 1 + judge: + type: "exact" + - name: small-difference-two + in: + nums1: [3, 3, 3] + nums2: [3, 1, 3] + out: 1 + judge: + type: "exact" + - name: zeros-not-allowed-boundary + in: + nums1: [2, 6] + nums2: [1, 1, 1] + out: 1 + judge: + type: "exact" + - name: large-single-side + in: + nums1: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + nums2: [6, 6] + out: 1 + judge: + type: "exact" + - name: close-long-arrays + in: + nums1: [1, 6, 1, 6, 1, 6, 1, 6] + nums2: [3, 3, 3, 3, 3, 3, 3, 3] + out: 1 + judge: + type: "exact" + - name: descending-needs-decrease + in: + nums1: [6, 5, 4] + nums2: [1, 1, 1, 1] + out: 3 + judge: + type: "exact" + - name: ascending-needs-increase + in: + nums1: [1, 2, 3] + nums2: [6, 6, 6, 6] + out: 4 + judge: + type: "exact" + - name: all-middle + in: + nums1: [3, 3, 3, 3] + nums2: [3, 3] + out: 2 + judge: + type: "exact" + - name: max-gap-feasible + in: + nums1: [1, 1, 1, 1, 1, 1] + nums2: [6, 6, 6, 6, 6] + out: 5 + judge: + type: "exact" + - name: asymmetric-feasible + in: + nums1: [6, 6, 1] + nums2: [1, 1, 1, 1] + out: 2 + judge: + type: "exact" + - name: generator-small + in: + nums1: + gen: "array" + len: 1 + of: + gen: "int" + min: 1 + max: 6 + elemType: "int" + nums2: + gen: "array" + len: 1 + of: + gen: "int" + min: 1 + max: 6 + elemType: "int" + judge: + type: "exact" + seed: 177501 + - name: generator-balanced + in: + nums1: + gen: "array" + len: 20 + of: + gen: "int" + min: 1 + max: 6 + elemType: "int" + nums2: + gen: "array" + len: 20 + of: + gen: "int" + min: 1 + max: 6 + elemType: "int" + judge: + type: "exact" + seed: 177502 + - name: generator-medium + in: + nums1: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 6 + elemType: "int" + nums2: + gen: "array" + len: 80 + of: + gen: "int" + min: 1 + max: 6 + elemType: "int" + judge: + type: "exact" + seed: 177503 + - name: generator-large + in: + nums1: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 6 + elemType: "int" + nums2: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 6 + elemType: "int" + judge: + type: "exact" + seed: 177504 + - name: generator-maximum + in: + nums1: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 6 + elemType: "int" + nums2: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 6 + elemType: "int" + judge: + type: "exact" + seed: 177505 diff --git a/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.cpp b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.cpp new file mode 100644 index 00000000..73f3b06d --- /dev/null +++ b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + int minOperations(vector& nums1, vector& nums2) { + int x = accumulate(nums1.begin(), nums1.end(), 0); + int y = accumulate(nums2.begin(), nums2.end(), 0); + if (x == y) return 0; + + if (x < y) { + if (6*nums1.size() < nums2.size()) return -1; + vector gains; + for (int v : nums1) gains.push_back(6-v); + for (int v : nums2) gains.push_back(v-1); + sort(gains.begin(), gains.end(), greater()); + int diff = y - x; + int ops = 0; + for (int g : gains) { + if (diff <= 0) break; + diff -= g; + ops++; + } + return diff <= 0 ? ops : -1; + } else { + if (6*nums2.size() < nums1.size()) return -1; + vector gains; + for (int v : nums1) gains.push_back(v-1); + for (int v : nums2) gains.push_back(6-v); + sort(gains.begin(), gains.end(), greater()); + int diff = x - y; + int ops = 0; + for (int g : gains) { + if (diff <= 0) break; + diff -= g; + ops++; + } + return diff <= 0 ? ops : -1; + } + } +}; diff --git a/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.cs b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.cs new file mode 100644 index 00000000..472109ae --- /dev/null +++ b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.cs @@ -0,0 +1,32 @@ +public class Solution { + public int MinOperations(int[] nums1, int[] nums2) { + int x = nums1.Sum(); + int y = nums2.Sum(); + if (x == y) return 0; + if (x < y) { + if (6*nums1.Length < nums2.Length) return -1; + var gains = nums1.Select(v => 6-v).Concat(nums2.Select(v => v-1)).ToList(); + gains.Sort((a,b) => b.CompareTo(a)); + int diff = y - x; + int ops = 0; + foreach (int g in gains) { + if (diff <= 0) break; + diff -= g; + ops++; + } + return diff <= 0 ? ops : -1; + } else { + if (6*nums2.Length < nums1.Length) return -1; + var gains = nums1.Select(v => v-1).Concat(nums2.Select(v => 6-v)).ToList(); + gains.Sort((a,b) => b.CompareTo(a)); + int diff = x - y; + int ops = 0; + foreach (int g in gains) { + if (diff <= 0) break; + diff -= g; + ops++; + } + return diff <= 0 ? ops : -1; + } + } +} diff --git a/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.dart b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.dart new file mode 100644 index 00000000..b7fb1f21 --- /dev/null +++ b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.dart @@ -0,0 +1,36 @@ +class Solution { + int minOperations(List nums1, List nums2) { + int x = nums1.fold(0, (a,b) => a+b); + int y = nums2.fold(0, (a,b) => a+b); + if (x == y) return 0; + if (x < y) { + if (6*nums1.length < nums2.length) return -1; + List gains = []; + for (int v in nums1) gains.add(6-v); + for (int v in nums2) gains.add(v-1); + gains.sort((a,b) => b.compareTo(a)); + int diff = y - x; + int ops = 0; + for (int g in gains) { + if (diff <= 0) break; + diff -= g; + ops++; + } + return diff <= 0 ? ops : -1; + } else { + if (6*nums2.length < nums1.length) return -1; + List gains = []; + for (int v in nums1) gains.add(v-1); + for (int v in nums2) gains.add(6-v); + gains.sort((a,b) => b.compareTo(a)); + int diff = x - y; + int ops = 0; + for (int g in gains) { + if (diff <= 0) break; + diff -= g; + ops++; + } + return diff <= 0 ? ops : -1; + } + } +} diff --git a/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.go b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.go new file mode 100644 index 00000000..b75c08a5 --- /dev/null +++ b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.go @@ -0,0 +1,37 @@ +func minOperations(nums1 []int, nums2 []int) int { + x, y := 0, 0 + for _, v := range nums1 { x += v } + for _, v := range nums2 { y += v } + if x == y { return 0 } + if x < y { + if 6*len(nums1) < len(nums2) { return -1 } + gains := make([]int, 0, len(nums1)+len(nums2)) + for _, v := range nums1 { gains = append(gains, 6-v) } + for _, v := range nums2 { gains = append(gains, v-1) } + sort.Sort(sort.Reverse(sort.IntSlice(gains))) + diff := y - x + ops := 0 + for _, g := range gains { + if diff <= 0 { break } + diff -= g + ops++ + } + if diff <= 0 { return ops } + return -1 + } else { + if 6*len(nums2) < len(nums1) { return -1 } + gains := make([]int, 0, len(nums1)+len(nums2)) + for _, v := range nums1 { gains = append(gains, v-1) } + for _, v := range nums2 { gains = append(gains, 6-v) } + sort.Sort(sort.Reverse(sort.IntSlice(gains))) + diff := x - y + ops := 0 + for _, g := range gains { + if diff <= 0 { break } + diff -= g + ops++ + } + if diff <= 0 { return ops } + return -1 + } +} diff --git a/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.java b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.java new file mode 100644 index 00000000..cba49d72 --- /dev/null +++ b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.java @@ -0,0 +1,37 @@ +class Solution { + public int minOperations(int[] nums1, int[] nums2) { + int x = 0, y = 0; + for (int v : nums1) x += v; + for (int v : nums2) y += v; + if (x == y) return 0; + if (x < y) { + if (6*nums1.length < nums2.length) return -1; + List gains = new ArrayList<>(); + for (int v : nums1) gains.add(6-v); + for (int v : nums2) gains.add(v-1); + gains.sort(Collections.reverseOrder()); + int diff = y - x; + int ops = 0; + for (int g : gains) { + if (diff <= 0) break; + diff -= g; + ops++; + } + return diff <= 0 ? ops : -1; + } else { + if (6*nums2.length < nums1.length) return -1; + List gains = new ArrayList<>(); + for (int v : nums1) gains.add(v-1); + for (int v : nums2) gains.add(6-v); + gains.sort(Collections.reverseOrder()); + int diff = x - y; + int ops = 0; + for (int g : gains) { + if (diff <= 0) break; + diff -= g; + ops++; + } + return diff <= 0 ? ops : -1; + } + } +} diff --git a/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.kt b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.kt new file mode 100644 index 00000000..58a843b3 --- /dev/null +++ b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.kt @@ -0,0 +1,32 @@ +class Solution { + fun minOperations(nums1: IntArray, nums2: IntArray): Int { + val x = nums1.sum() + val y = nums2.sum() + if (x == y) return 0 + if (x < y) { + if (6*nums1.size < nums2.size) return -1 + val gains = nums1.map { 6-it } + nums2.map { it-1 } + val sorted = gains.sortedDescending() + var diff = y - x + var ops = 0 + for (g in sorted) { + if (diff <= 0) break + diff -= g + ops++ + } + return if (diff <= 0) ops else -1 + } else { + if (6*nums2.size < nums1.size) return -1 + val gains = nums1.map { it-1 } + nums2.map { 6-it } + val sorted = gains.sortedDescending() + var diff = x - y + var ops = 0 + for (g in sorted) { + if (diff <= 0) break + diff -= g + ops++ + } + return if (diff <= 0) ops else -1 + } + } +} diff --git a/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.py b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.py new file mode 100644 index 00000000..f1e9488b --- /dev/null +++ b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.py @@ -0,0 +1,50 @@ +import numpy as np + + +class Solution: + def minOperations(self, nums1: List[int], nums2: List[int]) -> int: + x, y = sum(nums1), sum(nums2) + if x == y: + return 0 + + # Constraints: Minimum and Maximum possible sums + # nums1 can move in [n1, 6*n1], nums2 in [n2, 6*n2] + if not ( + len(nums2) <= x <= 6 * len(nums2) + or len(nums1) <= y <= 6 * len(nums1) + or max(len(nums1), len(nums2)) <= 6 * min(len(nums1), len(nums2)) + ): + # Checking if the ranges even overlap + if x < y and 6 * len(nums1) < len(nums2): + return -1 + if y < x and 6 * len(nums2) < len(nums1): + return -1 + + # Calculate the 'Steepest' available steps (Gains) + # If x < y, we want to increase x (6-v) and decrease y (v-1) + if x < y: + gains = np.concatenate([6 - np.array(nums1), np.array(nums2) - 1]) + else: + gains = np.concatenate([np.array(nums1) - 1, 6 - np.array(nums2)]) + + # Use bincount to get the distribution of the gradient magnitudes + counts = np.bincount(gains[gains > 0], minlength=6) + + diff = abs(x - y) + ops = 0 + + # Greedily follow the steepest gradient (highest gains first) + for magnitude in range(5, 0, -1): + if counts[magnitude] == 0: + continue + + # Number of steps needed along this gradient component + steps = min(counts[magnitude], (diff + magnitude - 1) // magnitude) + + ops += steps + diff -= steps * magnitude + + if diff <= 0: + return int(ops) + + return -1 diff --git a/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.py2 b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.py2 new file mode 100644 index 00000000..0c9d86da --- /dev/null +++ b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.py2 @@ -0,0 +1,31 @@ +class Solution(object): + def minOperations(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: int + """ + x, y = sum(nums1), sum(nums2) + if x == y: return 0 + if x < y: + if 6*len(nums1) < len(nums2): return -1 + gains = [6-v for v in nums1] + [v-1 for v in nums2] + gains.sort(reverse=True) + diff = y - x + ops = 0 + for g in gains: + if diff <= 0: break + diff -= g + ops += 1 + return ops if diff <= 0 else -1 + else: + if 6*len(nums2) < len(nums1): return -1 + gains = [v-1 for v in nums1] + [6-v for v in nums2] + gains.sort(reverse=True) + diff = x - y + ops = 0 + for g in gains: + if diff <= 0: break + diff -= g + ops += 1 + return ops if diff <= 0 else -1 diff --git a/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.rb b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.rb new file mode 100644 index 00000000..b50fe73d --- /dev/null +++ b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.rb @@ -0,0 +1,33 @@ +# @param {Integer[]} nums1 +# @param {Integer[]} nums2 +# @return {Integer} +def min_operations(nums1, nums2) + x = nums1.sum + y = nums2.sum + return 0 if x == y + if x < y + return -1 if 6*nums1.length < nums2.length + gains = nums1.map { |v| 6-v } + nums2.map { |v| v-1 } + gains.sort! { |a,b| b <=> a } + diff = y - x + ops = 0 + gains.each do |g| + break if diff <= 0 + diff -= g + ops += 1 + end + return diff <= 0 ? ops : -1 + else + return -1 if 6*nums2.length < nums1.length + gains = nums1.map { |v| v-1 } + nums2.map { |v| 6-v } + gains.sort! { |a,b| b <=> a } + diff = x - y + ops = 0 + gains.each do |g| + break if diff <= 0 + diff -= g + ops += 1 + end + return diff <= 0 ? ops : -1 + end +end diff --git a/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.rs b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.rs new file mode 100644 index 00000000..ba6167e4 --- /dev/null +++ b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.rs @@ -0,0 +1,34 @@ +impl Solution { + pub fn min_operations(nums1: Vec, nums2: Vec) -> i32 { + let x: i32 = nums1.iter().sum(); + let y: i32 = nums2.iter().sum(); + if x == y { return 0; } + if x < y { + if 6 * (nums1.len() as i32) < nums2.len() as i32 { return -1; } + let mut gains: Vec = nums1.iter().map(|v| 6-v).chain(nums2.iter().map(|v| v-1)).collect(); + gains.sort_by(|a,b| b.cmp(a)); + let mut diff = y - x; + let mut ops = 0; + for g in gains { + if diff <= 0 { break; } + diff -= g; + ops += 1; + } + if diff <= 0 { return ops; } + return -1; + } else { + if 6 * (nums2.len() as i32) < nums1.len() as i32 { return -1; } + let mut gains: Vec = nums1.iter().map(|v| v-1).chain(nums2.iter().map(|v| 6-v)).collect(); + gains.sort_by(|a,b| b.cmp(a)); + let mut diff = x - y; + let mut ops = 0; + for g in gains { + if diff <= 0 { break; } + diff -= g; + ops += 1; + } + if diff <= 0 { return ops; } + return -1; + } + } +} diff --git a/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.swift b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.swift new file mode 100644 index 00000000..2c29f76e --- /dev/null +++ b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.swift @@ -0,0 +1,32 @@ +class Solution { + func minOperations(_ nums1: [Int], _ nums2: [Int]) -> Int { + let x = nums1.reduce(0,+) + let y = nums2.reduce(0,+) + if x == y { return 0 } + if x < y { + if 6*nums1.count < nums2.count { return -1 } + var gains = nums1.map { 6-$0 } + nums2.map { $0-1 } + gains.sort(by: >) + var diff = y - x + var ops = 0 + for g in gains { + if diff <= 0 { break } + diff -= g + ops += 1 + } + return diff <= 0 ? ops : -1 + } else { + if 6*nums2.count < nums1.count { return -1 } + var gains = nums1.map { $0-1 } + nums2.map { 6-$0 } + gains.sort(by: >) + var diff = x - y + var ops = 0 + for g in gains { + if diff <= 0 { break } + diff -= g + ops += 1 + } + return diff <= 0 ? ops : -1 + } + } +} diff --git a/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.ts b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.ts new file mode 100644 index 00000000..2c264557 --- /dev/null +++ b/tests/1501-2000/1775. equal-sum-arrays-with-minimum-number-of-operations/sol.ts @@ -0,0 +1,30 @@ +function minOperations(nums1: number[], nums2: number[]): number { + const x = nums1.reduce((a, b) => a + b, 0); + const y = nums2.reduce((a, b) => a + b, 0); + if (x === y) return 0; + if (x < y) { + if (6 * nums1.length < nums2.length) return -1; + const gains = nums1.map((v) => 6 - v).concat(nums2.map((v) => v - 1)); + gains.sort((a, b) => b - a); + let diff = y - x; + let ops = 0; + for (const g of gains) { + if (diff <= 0) break; + diff -= g; + ops++; + } + return diff <= 0 ? ops : -1; + } else { + if (6 * nums2.length < nums1.length) return -1; + const gains = nums1.map((v) => v - 1).concat(nums2.map((v) => 6 - v)); + gains.sort((a, b) => b - a); + let diff = x - y; + let ops = 0; + for (const g of gains) { + if (diff <= 0) break; + diff -= g; + ops++; + } + return diff <= 0 ? ops : -1; + } +} diff --git a/tests/1501-2000/1776. car-fleet-ii/manifest.yaml b/tests/1501-2000/1776. car-fleet-ii/manifest.yaml new file mode 100644 index 00000000..681db437 --- /dev/null +++ b/tests/1501-2000/1776. car-fleet-ii/manifest.yaml @@ -0,0 +1,352 @@ +entry: + id: 1776 + title: "car-fleet-ii" + params: + cars: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().getCollisionTimes({cars})" + rust: "Solution::get_collision_times({cars})" + python3: "Solution().getCollisionTimes({cars})" + python2: "Solution().getCollisionTimes({cars})" + ruby: "get_collision_times({cars})" + java: "new Solution().getCollisionTimes({cars})" + csharp: "new Solution().GetCollisionTimes({cars})" + kotlin: "Solution().getCollisionTimes({cars})" + go: "getCollisionTimes({cars})" + dart: "Solution().getCollisionTimes({cars})" + swift: "Solution().getCollisionTimes({cars})" + typescript: "getCollisionTimes({cars})" + +judge: + type: "exact" + +limits: + time_ms: 5000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().getCollisionTimes(cars, {result})" + checker: | + class Checker: + def getCollisionTimes(self, cars, result): + if not isinstance(result, list) or len(result) != len(cars): + return False + n = len(cars) + expected = [-1.0] * n + stack = [] + for i in range(n - 1, -1, -1): + p, s = cars[i] + while stack: + j = stack[-1] + q, t = cars[j] + if s <= t: + stack.pop() + continue + hit = (q - p) / float(s - t) + if expected[j] < 0 or hit <= expected[j] + 1e-12: + break + stack.pop() + if stack: + j = stack[-1] + q, t = cars[j] + expected[i] = (q - p) / float(s - t) + stack.append(i) + for got, want in zip(result, expected): + if not isinstance(got, (int, float)) or isinstance(got, bool): + return False + if want < 0: + if got != -1 and got != -1.0: + return False + elif abs(float(got) - want) > 1e-5: + return False + return True + +seed: 1776 + +tests: + - name: example-one + in: + cars: + - [1, 2] + - [2, 1] + - [4, 3] + - [7, 2] + - name: example-two + in: + cars: + - [3, 4] + - [5, 4] + - [6, 3] + - [9, 1] + - name: two-collide + in: + cars: + - [1, 10] + - [11, 1] + - name: two-never-collide + in: + cars: + - [1, 1] + - [2, 10] + - name: equal-speeds + in: + cars: + - [1, 5] + - [4, 5] + - [9, 5] + - name: one-fast-car + in: + cars: + - [10, 100] + - name: increasing-speeds + in: + cars: + - [1, 1] + - [3, 2] + - [6, 3] + - [10, 4] + - name: decreasing-speeds + in: + cars: + - [1, 8] + - [2, 6] + - [3, 4] + - [4, 2] + - name: chain-collisions + in: + cars: + - [0, 10] + - [10, 8] + - [20, 6] + - [30, 4] + - [40, 2] + - name: alternating + in: + cars: + - [1, 10] + - [5, 2] + - [9, 9] + - [14, 3] + - [20, 8] + - [27, 1] + - name: delayed-fleet + in: + cars: + - [2, 12] + - [8, 5] + - [15, 4] + - [23, 10] + - [31, 2] + - name: collision-at-one + in: + cars: + - [1, 3] + - [3, 1] + - [8, 2] + - name: fractional-times + in: + cars: + - [1, 7] + - [4, 2] + - [10, 1] + - name: large-gaps + in: + cars: + - [1, 1000000] + - [500000, 1] + - [1000000, 999999] + - name: max-speeds + in: + cars: + - [1, 1000000] + - [2, 999999] + - [3, 1] + - [1000000, 500000] + - name: close-positions + in: + cars: + - [1, 100] + - [2, 99] + - [3, 98] + - [4, 1] + - name: many-equal-fleets + in: + cars: + - [1, 4] + - [3, 4] + - [5, 2] + - [8, 2] + - [12, 1] + - name: rightmost-fast + in: + cars: + - [2, 8] + - [6, 3] + - [11, 9] + - [18, 1] + - name: rightmost-slow + in: + cars: + - [2, 8] + - [6, 3] + - [11, 2] + - [18, 1] + - name: alternating-extremes + in: + cars: + - [1, 100] + - [100, 1] + - [200, 100] + - [300, 1] + - [400, 100] + - name: six-cars + in: + cars: + - [1, 6] + - [4, 2] + - [8, 5] + - [13, 3] + - [19, 7] + - [26, 1] + - name: seven-cars + in: + cars: + - [3, 9] + - [7, 1] + - [12, 8] + - [18, 2] + - [25, 7] + - [33, 3] + - [42, 1] + - name: large-values + in: + cars: + - [1, 999999] + - [250000, 500000] + - [500000, 250000] + - [750000, 100000] + - [1000000, 1] + - name: no-early-hit + in: + cars: + - [1, 2] + - [2, 100] + - [20, 3] + - [30, 4] + - name: fleet-replacement + in: + cars: + - [1, 20] + - [5, 5] + - [10, 4] + - [20, 3] + - [35, 1] + - name: equal-distance + in: + cars: + - [1, 10] + - [11, 9] + - [21, 8] + - [31, 7] + - name: mixed-small + in: + cars: + - [1, 1] + - [2, 3] + - [4, 2] + - [7, 6] + - [11, 1] + - name: dense-seven + in: + cars: + - [10, 20] + - [11, 1] + - [12, 19] + - [13, 2] + - [14, 18] + - [15, 3] + - [16, 17] + - name: sparse-seven + in: + cars: + - [1, 17] + - [100, 2] + - [1000, 16] + - [10000, 3] + - [100000, 15] + - [500000, 4] + - [1000000, 1] + - name: eight-cars + in: + cars: + - [1, 8] + - [4, 7] + - [9, 1] + - [15, 6] + - [22, 2] + - [30, 5] + - [39, 3] + - [49, 1] + - name: same-position-gap-one + in: + cars: + - [1, 100] + - [2, 1] + - [3, 100] + - [4, 1] + - [5, 100] + - name: descending-large + in: + cars: + - [100, 1000] + - [1000, 900] + - [10000, 800] + - [100000, 700] + - [1000000, 1] + - name: nine-cars + in: + cars: + - [2, 9] + - [5, 4] + - [9, 8] + - [14, 3] + - [20, 7] + - [27, 2] + - [35, 6] + - [44, 1] + - [54, 5] + - name: ten-cars + in: + cars: + - [1, 10] + - [3, 1] + - [6, 9] + - [10, 2] + - [15, 8] + - [21, 3] + - [28, 7] + - [36, 4] + - [45, 6] + - [55, 1] + - name: all-fast-front + in: + cars: + - [1, 1000] + - [100, 999] + - [200, 998] + - [300, 997] + - [400, 1] + - name: terminal-fleet + in: + cars: + - [1, 50] + - [10, 4] + - [20, 3] + - [30, 2] + - [40, 1] diff --git a/tests/1501-2000/1776. car-fleet-ii/sol.cpp b/tests/1501-2000/1776. car-fleet-ii/sol.cpp new file mode 100644 index 00000000..a1c554ad --- /dev/null +++ b/tests/1501-2000/1776. car-fleet-ii/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + vector getCollisionTimes(vector>& cars) { + int n = cars.size(); + vector rightGreater(n, -1); + vector ans(n, -1.0); + vector stack; + for (int r = n - 1; r >= 0; r--) { + while (!stack.empty() && cars[stack.back()][1] >= cars[r][1]) { + stack.pop_back(); + } + if (!stack.empty()) { + rightGreater[r] = stack.back(); + } + stack.push_back(r); + } + for (int r = n - 1; r >= 0; r--) { + int collideId = rightGreater[r]; + while (collideId != -1 && ans[collideId] != -1 && ans[collideId] < (double)(cars[collideId][0] - cars[r][0]) / (cars[r][1] - cars[collideId][1])) { + collideId = rightGreater[collideId]; + } + if (collideId != -1) { + ans[r] = (double)(cars[collideId][0] - cars[r][0]) / (cars[r][1] - cars[collideId][1]); + } + } + return ans; + } +}; diff --git a/tests/1501-2000/1776. car-fleet-ii/sol.cs b/tests/1501-2000/1776. car-fleet-ii/sol.cs new file mode 100644 index 00000000..0c21fe1d --- /dev/null +++ b/tests/1501-2000/1776. car-fleet-ii/sol.cs @@ -0,0 +1,29 @@ +public class Solution { + public double[] GetCollisionTimes(int[][] cars) { + int n = cars.Length; + int[] rightGreater = new int[n]; + Array.Fill(rightGreater, -1); + double[] ans = new double[n]; + Array.Fill(ans, -1.0); + List stack = new List(); + for (int r = n - 1; r >= 0; r--) { + while (stack.Count > 0 && cars[stack[stack.Count - 1]][1] >= cars[r][1]) { + stack.RemoveAt(stack.Count - 1); + } + if (stack.Count > 0) { + rightGreater[r] = stack[stack.Count - 1]; + } + stack.Add(r); + } + for (int r = n - 1; r >= 0; r--) { + int collideId = rightGreater[r]; + while (collideId != -1 && ans[collideId] != -1 && ans[collideId] < (double)(cars[collideId][0] - cars[r][0]) / (cars[r][1] - cars[collideId][1])) { + collideId = rightGreater[collideId]; + } + if (collideId != -1) { + ans[r] = (double)(cars[collideId][0] - cars[r][0]) / (cars[r][1] - cars[collideId][1]); + } + } + return ans; + } +} diff --git a/tests/1501-2000/1776. car-fleet-ii/sol.dart b/tests/1501-2000/1776. car-fleet-ii/sol.dart new file mode 100644 index 00000000..a8d7fcf5 --- /dev/null +++ b/tests/1501-2000/1776. car-fleet-ii/sol.dart @@ -0,0 +1,27 @@ +class Solution { + List getCollisionTimes(List> cars) { + int n = cars.length; + List rightGreater = List.filled(n, -1); + List ans = List.filled(n, -1.0); + List stack = []; + for (int r = n - 1; r >= 0; r--) { + while (stack.isNotEmpty && cars[stack.last][1] >= cars[r][1]) { + stack.removeLast(); + } + if (stack.isNotEmpty) { + rightGreater[r] = stack.last; + } + stack.add(r); + } + for (int r = n - 1; r >= 0; r--) { + int collideId = rightGreater[r]; + while (collideId != -1 && ans[collideId] != -1 && ans[collideId] < (cars[collideId][0] - cars[r][0]) / (cars[r][1] - cars[collideId][1])) { + collideId = rightGreater[collideId]; + } + if (collideId != -1) { + ans[r] = (cars[collideId][0] - cars[r][0]) / (cars[r][1] - cars[collideId][1]); + } + } + return ans; + } +} diff --git a/tests/1501-2000/1776. car-fleet-ii/sol.go b/tests/1501-2000/1776. car-fleet-ii/sol.go new file mode 100644 index 00000000..19f1ccdd --- /dev/null +++ b/tests/1501-2000/1776. car-fleet-ii/sol.go @@ -0,0 +1,31 @@ +func getCollisionTimes(cars [][]int) []float64 { + n := len(cars) + rightGreater := make([]int, n) + for i := range rightGreater { + rightGreater[i] = -1 + } + ans := make([]float64, n) + for i := range ans { + ans[i] = -1.0 + } + stack := []int{} + for r := n - 1; r >= 0; r-- { + for len(stack) > 0 && cars[stack[len(stack)-1]][1] >= cars[r][1] { + stack = stack[:len(stack)-1] + } + if len(stack) > 0 { + rightGreater[r] = stack[len(stack)-1] + } + stack = append(stack, r) + } + for r := n - 1; r >= 0; r-- { + collideId := rightGreater[r] + for collideId != -1 && ans[collideId] != -1 && ans[collideId] < float64(cars[collideId][0]-cars[r][0])/float64(cars[r][1]-cars[collideId][1]) { + collideId = rightGreater[collideId] + } + if collideId != -1 { + ans[r] = float64(cars[collideId][0]-cars[r][0]) / float64(cars[r][1]-cars[collideId][1]) + } + } + return ans +} diff --git a/tests/1501-2000/1776. car-fleet-ii/sol.java b/tests/1501-2000/1776. car-fleet-ii/sol.java new file mode 100644 index 00000000..7f72ba88 --- /dev/null +++ b/tests/1501-2000/1776. car-fleet-ii/sol.java @@ -0,0 +1,30 @@ +class Solution { + public double[] getCollisionTimes(int[][] cars) { + int n = cars.length; + int[] rightGreater = new int[n]; + Arrays.fill(rightGreater, -1); + double[] ans = new double[n]; + Arrays.fill(ans, -1.0); + int[] stack = new int[n]; + int top = 0; + for (int r = n - 1; r >= 0; r--) { + while (top > 0 && cars[stack[top - 1]][1] >= cars[r][1]) { + top--; + } + if (top > 0) { + rightGreater[r] = stack[top - 1]; + } + stack[top++] = r; + } + for (int r = n - 1; r >= 0; r--) { + int collideId = rightGreater[r]; + while (collideId != -1 && ans[collideId] != -1 && ans[collideId] < (double)(cars[collideId][0] - cars[r][0]) / (cars[r][1] - cars[collideId][1])) { + collideId = rightGreater[collideId]; + } + if (collideId != -1) { + ans[r] = (double)(cars[collideId][0] - cars[r][0]) / (cars[r][1] - cars[collideId][1]); + } + } + return ans; + } +} diff --git a/tests/1501-2000/1776. car-fleet-ii/sol.kt b/tests/1501-2000/1776. car-fleet-ii/sol.kt new file mode 100644 index 00000000..65716297 --- /dev/null +++ b/tests/1501-2000/1776. car-fleet-ii/sol.kt @@ -0,0 +1,27 @@ +class Solution { + fun getCollisionTimes(cars: Array): DoubleArray { + val n = cars.size + val rightGreater = IntArray(n) { -1 } + val ans = DoubleArray(n) { -1.0 } + val stack = mutableListOf() + for (r in n - 1 downTo 0) { + while (stack.isNotEmpty() && cars[stack.last()][1] >= cars[r][1]) { + stack.removeAt(stack.size - 1) + } + if (stack.isNotEmpty()) { + rightGreater[r] = stack.last() + } + stack.add(r) + } + for (r in n - 1 downTo 0) { + var collideId = rightGreater[r] + while (collideId != -1 && ans[collideId] != -1.0 && ans[collideId] < (cars[collideId][0] - cars[r][0]).toDouble() / (cars[r][1] - cars[collideId][1])) { + collideId = rightGreater[collideId] + } + if (collideId != -1) { + ans[r] = (cars[collideId][0] - cars[r][0]).toDouble() / (cars[r][1] - cars[collideId][1]) + } + } + return ans + } +} diff --git a/tests/1501-2000/1776. car-fleet-ii/sol.py b/tests/1501-2000/1776. car-fleet-ii/sol.py new file mode 100644 index 00000000..cf329a1f --- /dev/null +++ b/tests/1501-2000/1776. car-fleet-ii/sol.py @@ -0,0 +1,113 @@ +# https://leetcode.com/problems/car-fleet-ii/description/?envType=problem-list-v2&envId=monotonic-stack +class Solution: + def getCollisionTimes(self, cars: List[List[int]]) -> List[float]: + nums = cars + n = len(nums) + """ + all the cars are moving towards the right + + + if we want to know where it the next slowest car + + + we should use monotonic stack + + + but heres the catch the monotonic stack is offline + + + what if a new collison happen after some time + + + + so we should know the acccidents at the right first + + + because look at our merge step + + + when both collide the both gets merged and coverted into car with minimum speed + + + i.e simply the fastest car is disapperaing + + + + """ + right_greater = [-1] * (n) + ans = [-1] * (n) + stack = [] + """ + what should i store in a stack + + + the future cars in increasing order of speed ??? Yes chako + + Whyy seee when the cars are in the increasinmg order of the speed + + + they wont collide hence they are the valid cars + + + + Now when we are processing the current cars speed will not get reduced by any other cars to the left of it + + because if they are collided the car has more speed but the final + + move will be of the smallest speed + + + OKkk! + + + now the problem arises when the car we are trying to collide had it's speed changed due to collision with another car + + + + + (3,4) (5,4) (6,3) (9,1) ->0second + + (7,4) (9,4 (9,3) -> merged) (10,1) ->1second + + (9,4) (10.5,3 (10.5,1) -> merged) ->1.5second + + (11,4) (11,1) -> at 2 second + + + notice one thing our initial lefts are + + for speed 4 -> speed 3 + + for speed 3 -> speed 1 + + + but by the time speed 4 collide 3 -> speed 3 already collides speed 1 + + + so now we should check relative time between speed 4 and 1 + + (9-3)/(4-1) -> 2seconds + + """ + for r in range(n - 1, -1, -1): + while stack and nums[stack[-1]][1] >= nums[r][1]: + stack.pop() + if len(stack): + right_greater[r] = stack[-1] + stack.append(r) + # print(right_greater) + for r in range(n - 1, -1, -1): + collide_car_id = right_greater[r] + while ( + collide_car_id != -1 + and ans[collide_car_id] != -1 + and ans[collide_car_id] + < (nums[collide_car_id][0] - nums[r][0]) + / (nums[r][1] - nums[collide_car_id][1]) + ): + collide_car_id = right_greater[collide_car_id] + if collide_car_id != -1: + ans[r] = (nums[collide_car_id][0] - nums[r][0]) / ( + nums[r][1] - nums[collide_car_id][1] + ) + return ans diff --git a/tests/1501-2000/1776. car-fleet-ii/sol.py2 b/tests/1501-2000/1776. car-fleet-ii/sol.py2 new file mode 100644 index 00000000..928b5734 --- /dev/null +++ b/tests/1501-2000/1776. car-fleet-ii/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def getCollisionTimes(self, cars): + """ + :type cars: List[List[int]] + :rtype: List[float] + """ + n = len(cars) + right_greater = [-1] * n + ans = [-1.0] * n + stack = [] + for r in range(n - 1, -1, -1): + while stack and cars[stack[-1]][1] >= cars[r][1]: + stack.pop() + if stack: + right_greater[r] = stack[-1] + stack.append(r) + for r in range(n - 1, -1, -1): + collide_id = right_greater[r] + while collide_id != -1 and ans[collide_id] != -1 and ans[collide_id] < float(cars[collide_id][0] - cars[r][0]) / (cars[r][1] - cars[collide_id][1]): + collide_id = right_greater[collide_id] + if collide_id != -1: + ans[r] = float(cars[collide_id][0] - cars[r][0]) / (cars[r][1] - cars[collide_id][1]) + return ans diff --git a/tests/1501-2000/1776. car-fleet-ii/sol.rb b/tests/1501-2000/1776. car-fleet-ii/sol.rb new file mode 100644 index 00000000..fe099682 --- /dev/null +++ b/tests/1501-2000/1776. car-fleet-ii/sol.rb @@ -0,0 +1,27 @@ +# @param {Integer[][]} cars +# @return {Float[]} +def get_collision_times(cars) + n = cars.length + right_greater = Array.new(n, -1) + ans = Array.new(n, -1.0) + stack = [] + (n - 1).downto(0) do |r| + while !stack.empty? && cars[stack[-1]][1] >= cars[r][1] + stack.pop + end + if !stack.empty? + right_greater[r] = stack[-1] + end + stack.push(r) + end + (n - 1).downto(0) do |r| + collide_id = right_greater[r] + while collide_id != -1 && ans[collide_id] != -1 && ans[collide_id] < (cars[collide_id][0] - cars[r][0]).to_f / (cars[r][1] - cars[collide_id][1]) + collide_id = right_greater[collide_id] + end + if collide_id != -1 + ans[r] = (cars[collide_id][0] - cars[r][0]).to_f / (cars[r][1] - cars[collide_id][1]) + end + end + ans +end diff --git a/tests/1501-2000/1776. car-fleet-ii/sol.rs b/tests/1501-2000/1776. car-fleet-ii/sol.rs new file mode 100644 index 00000000..f37859db --- /dev/null +++ b/tests/1501-2000/1776. car-fleet-ii/sol.rs @@ -0,0 +1,27 @@ +impl Solution { + pub fn get_collision_times(cars: Vec>) -> Vec { + let n = cars.len(); + let mut right_greater = vec![-1i32; n]; + let mut ans = vec![-1.0f64; n]; + let mut stack: Vec = Vec::new(); + for r in (0..n).rev() { + while !stack.is_empty() && cars[stack[stack.len() - 1]][1] >= cars[r][1] { + stack.pop(); + } + if !stack.is_empty() { + right_greater[r] = stack[stack.len() - 1] as i32; + } + stack.push(r); + } + for r in (0..n).rev() { + let mut collide_id = right_greater[r]; + while collide_id != -1 && ans[collide_id as usize] != -1.0 && ans[collide_id as usize] < (cars[collide_id as usize][0] - cars[r][0]) as f64 / (cars[r][1] - cars[collide_id as usize][1]) as f64 { + collide_id = right_greater[collide_id as usize]; + } + if collide_id != -1 { + ans[r] = (cars[collide_id as usize][0] - cars[r][0]) as f64 / (cars[r][1] - cars[collide_id as usize][1]) as f64; + } + } + ans + } +} diff --git a/tests/1501-2000/1776. car-fleet-ii/sol.swift b/tests/1501-2000/1776. car-fleet-ii/sol.swift new file mode 100644 index 00000000..c1396274 --- /dev/null +++ b/tests/1501-2000/1776. car-fleet-ii/sol.swift @@ -0,0 +1,27 @@ +class Solution { + func getCollisionTimes(_ cars: [[Int]]) -> [Double] { + let n = cars.count + var rightGreater = [Int](repeating: -1, count: n) + var ans = [Double](repeating: -1.0, count: n) + var stack: [Int] = [] + for r in stride(from: n - 1, through: 0, by: -1) { + while !stack.isEmpty && cars[stack.last!][1] >= cars[r][1] { + stack.removeLast() + } + if !stack.isEmpty { + rightGreater[r] = stack.last! + } + stack.append(r) + } + for r in stride(from: n - 1, through: 0, by: -1) { + var collideId = rightGreater[r] + while collideId != -1 && ans[collideId] != -1 && ans[collideId] < Double(cars[collideId][0] - cars[r][0]) / Double(cars[r][1] - cars[collideId][1]) { + collideId = rightGreater[collideId] + } + if collideId != -1 { + ans[r] = Double(cars[collideId][0] - cars[r][0]) / Double(cars[r][1] - cars[collideId][1]) + } + } + return ans + } +} diff --git a/tests/1501-2000/1776. car-fleet-ii/sol.ts b/tests/1501-2000/1776. car-fleet-ii/sol.ts new file mode 100644 index 00000000..7a46a538 --- /dev/null +++ b/tests/1501-2000/1776. car-fleet-ii/sol.ts @@ -0,0 +1,31 @@ +function getCollisionTimes(cars: number[][]): number[] { + const n = cars.length; + const rightGreater: number[] = Array(n).fill(-1); + const ans: number[] = Array(n).fill(-1.0); + const stack: number[] = []; + for (let r = n - 1; r >= 0; r--) { + while (stack.length > 0 && cars[stack[stack.length - 1]][1] >= cars[r][1]) { + stack.pop(); + } + if (stack.length > 0) { + rightGreater[r] = stack[stack.length - 1]; + } + stack.push(r); + } + for (let r = n - 1; r >= 0; r--) { + let collideId = rightGreater[r]; + while ( + collideId !== -1 && + ans[collideId] !== -1 && + ans[collideId] < + (cars[collideId][0] - cars[r][0]) / (cars[r][1] - cars[collideId][1]) + ) { + collideId = rightGreater[collideId]; + } + if (collideId !== -1) { + ans[r] = + (cars[collideId][0] - cars[r][0]) / (cars[r][1] - cars[collideId][1]); + } + } + return ans; +} diff --git a/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/manifest.yaml b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/manifest.yaml new file mode 100644 index 00000000..cda3dca0 --- /dev/null +++ b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/manifest.yaml @@ -0,0 +1,379 @@ +entry: + id: 1779 + title: "find-nearest-point-that-has-the-same-x-or-y-coordinate" + params: + x: + type: int + y: + type: int + points: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().nearestValidPoint({x}, {y}, {points})" + rust: "Solution::nearest_valid_point({x}, {y}, {points})" + python3: "Solution().nearestValidPoint({x}, {y}, {points})" + python2: "Solution().nearestValidPoint({x}, {y}, {points})" + ruby: "nearest_valid_point({x}, {y}, {points})" + java: "new Solution().nearestValidPoint({x}, {y}, {points})" + csharp: "new Solution().NearestValidPoint({x}, {y}, {points})" + kotlin: "Solution().nearestValidPoint({x}, {y}, {points})" + go: "nearestValidPoint({x}, {y}, {points})" + dart: "Solution().nearestValidPoint({x}, {y}, {points})" + swift: "Solution().nearestValidPoint({x}, {y}, {points})" + typescript: "nearestValidPoint({x}, {y}, {points})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(x, y, points, {result})" + checker: | + class Checker: + def check(self, x, y, points, result): + best = -1 + best_distance = None + for i, point in enumerate(points): + a, b = point + if a == x or b == y: + distance = abs(x - a) + abs(y - b) + if best_distance is None or distance < best_distance: + best_distance = distance + best = i + return result == best + +seed: 1779 +tests: + - name: example-1 + in: + x: 3 + y: 4 + points: + - [1, 2] + - [3, 1] + - [2, 4] + - [2, 3] + - [4, 4] + out: 2 + - name: example-2-same-location + in: + x: 3 + y: 4 + points: + - [3, 4] + out: 0 + - name: example-3-none + in: + x: 3 + y: 4 + points: + - [2, 3] + out: -1 + - name: vertical-nearest + in: + x: 5 + y: 5 + points: + - [5, 10] + - [1, 5] + - [5, 6] + - [5, 7] + out: 2 + - name: horizontal-nearest + in: + x: 7 + y: 8 + points: + - [1, 8] + - [6, 8] + - [9, 8] + - [7, 1] + out: 1 + - name: tie-keeps-first + in: + x: 5 + y: 5 + points: + - [3, 5] + - [5, 7] + - [5, 3] + - [7, 5] + out: 0 + - name: invalid-before-valid + in: + x: 4 + y: 6 + points: + - [1, 1] + - [2, 6] + - [4, 10] + out: 1 + - name: valid-at-last + in: + x: 9 + y: 2 + points: + - [1, 1] + - [3, 4] + - [8, 7] + - [9, 10] + out: 3 + - name: duplicate-points + in: + x: 6 + y: 6 + points: + - [2, 6] + - [2, 6] + - [6, 9] + - [2, 1] + out: 2 + - name: all-invalid + in: + x: 10 + y: 10 + points: + - [1, 1] + - [2, 3] + - [9, 8] + out: -1 + - name: all-valid-horizontal + in: + x: 1 + y: 9 + points: + - [10, 9] + - [2, 9] + - [1, 1] + - [8, 9] + out: 1 + - name: all-valid-vertical + in: + x: 9 + y: 1 + points: + - [9, 10] + - [9, 2] + - [3, 1] + - [9, 4] + out: 1 + - name: coordinate-one + in: + x: 1 + y: 1 + points: + - [1, 10000] + - [9999, 1] + - [2, 2] + out: 1 + - name: coordinate-maximum + in: + x: 10000 + y: 10000 + points: + - [9999, 9999] + - [10000, 1] + - [1, 10000] + out: 1 + - name: zero-distance-later + in: + x: 8 + y: 3 + points: + - [8, 7] + - [4, 3] + - [8, 3] + out: 2 + - name: mixed-near-far + in: + x: 50 + y: 50 + points: + - [1, 50] + - [50, 49] + - [50, 100] + - [100, 50] + out: 1 + - name: horizontal-beats-vertical + in: + x: 20 + y: 30 + points: + - [20, 35] + - [17, 30] + - [20, 24] + out: 1 + - name: vertical-beats-horizontal + in: + x: 20 + y: 30 + points: + - [25, 30] + - [20, 27] + - [20, 40] + out: 1 + - name: equal-distance-different-lines + in: + x: 10 + y: 20 + points: + - [7, 20] + - [10, 23] + - [14, 20] + out: 0 + - name: negative-free-lower-bound + in: + x: 2 + y: 3 + points: + - [1, 3] + - [2, 1] + - [1, 1] + out: 0 + - name: many-invalid-interspersed + in: + x: 12 + y: 15 + points: + - [1, 1] + - [2, 2] + - [12, 20] + - [4, 5] + - [9, 15] + - [6, 7] + out: 4 + - name: first-point-valid + in: + x: 30 + y: 40 + points: + - [30, 45] + - [1, 40] + - [30, 35] + out: 0 + - name: last-point-zero + in: + x: 30 + y: 40 + points: + - [1, 1] + - [2, 2] + - [30, 40] + out: 2 + - name: repeated-ties + in: + x: 5 + y: 5 + points: + - [4, 5] + - [5, 4] + - [6, 5] + - [5, 6] + - [4, 5] + out: 0 + - name: one-point-invalid + in: + x: 9999 + y: 9999 + points: + - [9998, 9998] + out: -1 + - name: one-point-horizontal + in: + x: 9999 + y: 9999 + points: + - [1, 9999] + out: 0 + - name: one-point-vertical + in: + x: 9999 + y: 9999 + points: + - [9999, 1] + out: 0 + - name: large-coordinate-tie + in: + x: 5000 + y: 5000 + points: + - [4990, 5000] + - [5000, 5010] + - [5010, 5000] + out: 0 + - name: closest-among-duplicates + in: + x: 100 + y: 200 + points: + - [100, 250] + - [50, 200] + - [100, 201] + - [99, 200] + out: 2 + - name: invalid-same-neither + in: + x: 7 + y: 11 + points: + - [6, 10] + - [8, 12] + - [1, 1] + - [7, 11] + out: 3 + - name: broad-mixed-set + in: + x: 400 + y: 700 + points: + - [100, 700] + - [400, 900] + - [399, 700] + - [401, 700] + - [400, 699] + out: 2 + - name: exact-tie-after-invalid + in: + x: 42 + y: 73 + points: + - [1, 2] + - [42, 80] + - [35, 73] + - [42, 66] + out: 1 + - name: closest-at-maximum-bound + in: + x: 10000 + y: 9999 + points: + - [1, 9999] + - [10000, 10000] + - [9999, 9999] + out: 1 + - name: late-better-than-early + in: + x: 500 + y: 600 + points: + - [500, 1000] + - [1, 600] + - [500, 601] + out: 2 + - name: early-tie-beats-late + in: + x: 500 + y: 600 + points: + - [500, 601] + - [499, 600] + - [500, 599] + out: 0 diff --git a/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.cpp b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.cpp new file mode 100644 index 00000000..93cdc90f --- /dev/null +++ b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int nearestValidPoint(int x, int y, vector>& points) { + int currentMinDistance = 20001; + int currentMinIndex = -1; + for (int i = 0; i < points.size(); i++) { + int a = points[i][0]; + int b = points[i][1]; + if (x == a || y == b) { + int distance = abs(x - a) + abs(y - b); + if (distance < currentMinDistance) { + currentMinDistance = distance; + currentMinIndex = i; + } + } + } + return currentMinIndex; + } +}; diff --git a/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.cs b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.cs new file mode 100644 index 00000000..32a98e14 --- /dev/null +++ b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public int NearestValidPoint(int x, int y, int[][] points) { + int currentMinDistance = 20001; + int currentMinIndex = -1; + for (int i = 0; i < points.Length; i++) { + int a = points[i][0]; + int b = points[i][1]; + if (x == a || y == b) { + int distance = Math.Abs(x - a) + Math.Abs(y - b); + if (distance < currentMinDistance) { + currentMinDistance = distance; + currentMinIndex = i; + } + } + } + return currentMinIndex; + } +} diff --git a/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.dart b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.dart new file mode 100644 index 00000000..e7378590 --- /dev/null +++ b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.dart @@ -0,0 +1,18 @@ +class Solution { + int nearestValidPoint(int x, int y, List> points) { + int currentMinDistance = 20001; + int currentMinIndex = -1; + for (int i = 0; i < points.length; i++) { + int a = points[i][0]; + int b = points[i][1]; + if (x == a || y == b) { + int distance = (x - a).abs() + (y - b).abs(); + if (distance < currentMinDistance) { + currentMinDistance = distance; + currentMinIndex = i; + } + } + } + return currentMinIndex; + } +} diff --git a/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.go b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.go new file mode 100644 index 00000000..715ebb58 --- /dev/null +++ b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.go @@ -0,0 +1,22 @@ +func nearestValidPoint(x int, y int, points [][]int) int { + currentMinDistance := 20001 + currentMinIndex := -1 + for i, point := range points { + a, b := point[0], point[1] + if x == a || y == b { + distance := abs(x-a) + abs(y-b) + if distance < currentMinDistance { + currentMinDistance = distance + currentMinIndex = i + } + } + } + return currentMinIndex +} + +func abs(a int) int { + if a < 0 { + return -a + } + return a +} diff --git a/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.java b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.java new file mode 100644 index 00000000..7d062712 --- /dev/null +++ b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.java @@ -0,0 +1,18 @@ +class Solution { + public int nearestValidPoint(int x, int y, int[][] points) { + int currentMinDistance = 20001; + int currentMinIndex = -1; + for (int i = 0; i < points.length; i++) { + int a = points[i][0]; + int b = points[i][1]; + if (x == a || y == b) { + int distance = Math.abs(x - a) + Math.abs(y - b); + if (distance < currentMinDistance) { + currentMinDistance = distance; + currentMinIndex = i; + } + } + } + return currentMinIndex; + } +} diff --git a/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.kt b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.kt new file mode 100644 index 00000000..f77abf39 --- /dev/null +++ b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.kt @@ -0,0 +1,18 @@ +class Solution { + fun nearestValidPoint(x: Int, y: Int, points: Array): Int { + var currentMinDistance = 20001 + var currentMinIndex = -1 + for (i in points.indices) { + val a = points[i][0] + val b = points[i][1] + if (x == a || y == b) { + val distance = Math.abs(x - a) + Math.abs(y - b) + if (distance < currentMinDistance) { + currentMinDistance = distance + currentMinIndex = i + } + } + } + return currentMinIndex + } +} diff --git a/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.py b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.py new file mode 100644 index 00000000..9dcfd0c0 --- /dev/null +++ b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.py @@ -0,0 +1,11 @@ +class Solution: + def nearestValidPoint(self, x, y, points): + current_min_distance = 20001 + current_min_index = -1 + for i, [a, b] in enumerate(points): + if x == a or y == b: + distance = abs(x - a) + abs(y - b) + if distance < current_min_distance: + current_min_distance = distance + current_min_index = i + return current_min_index diff --git a/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.py2 b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.py2 new file mode 100644 index 00000000..e0df7949 --- /dev/null +++ b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def nearestValidPoint(self, x, y, points): + """ + :type x: int + :type y: int + :type points: List[List[int]] + :rtype: int + """ + current_min_distance = 20001 + current_min_index = -1 + for i, point in enumerate(points): + a, b = point + if x == a or y == b: + distance = abs(x - a) + abs(y - b) + if distance < current_min_distance: + current_min_distance = distance + current_min_index = i + return current_min_index diff --git a/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.rb b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.rb new file mode 100644 index 00000000..d2fc7070 --- /dev/null +++ b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.rb @@ -0,0 +1,19 @@ +# @param {Integer} x +# @param {Integer} y +# @param {Integer[][]} points +# @return {Integer} +def nearest_valid_point(x, y, points) + current_min_distance = 20001 + current_min_index = -1 + points.each_with_index do |point, i| + a, b = point + if x == a || y == b + distance = (x - a).abs + (y - b).abs + if distance < current_min_distance + current_min_distance = distance + current_min_index = i + end + end + end + current_min_index +end diff --git a/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.rs b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.rs new file mode 100644 index 00000000..706c192a --- /dev/null +++ b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn nearest_valid_point(x: i32, y: i32, points: Vec>) -> i32 { + let mut current_min_distance = 20001; + let mut current_min_index = -1; + for (i, point) in points.iter().enumerate() { + let a = point[0]; + let b = point[1]; + if x == a || y == b { + let distance = (x - a).abs() + (y - b).abs(); + if distance < current_min_distance { + current_min_distance = distance; + current_min_index = i as i32; + } + } + } + current_min_index + } +} diff --git a/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.swift b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.swift new file mode 100644 index 00000000..c58d0688 --- /dev/null +++ b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.swift @@ -0,0 +1,18 @@ +class Solution { + func nearestValidPoint(_ x: Int, _ y: Int, _ points: [[Int]]) -> Int { + var currentMinDistance = 20001 + var currentMinIndex = -1 + for (i, point) in points.enumerated() { + let a = point[0] + let b = point[1] + if x == a || y == b { + let distance = abs(x - a) + abs(y - b) + if distance < currentMinDistance { + currentMinDistance = distance + currentMinIndex = i + } + } + } + return currentMinIndex + } +} diff --git a/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.ts b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.ts new file mode 100644 index 00000000..e548b0a8 --- /dev/null +++ b/tests/1501-2000/1779. find-nearest-point-that-has-the-same-x-or-y-coordinate/sol.ts @@ -0,0 +1,16 @@ +function nearestValidPoint(x: number, y: number, points: number[][]): number { + let currentMinDistance = 20001; + let currentMinIndex = -1; + for (let i = 0; i < points.length; i++) { + const a = points[i][0]; + const b = points[i][1]; + if (x === a || y === b) { + const distance = Math.abs(x - a) + Math.abs(y - b); + if (distance < currentMinDistance) { + currentMinDistance = distance; + currentMinIndex = i; + } + } + } + return currentMinIndex; +} diff --git a/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/manifest.yaml b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/manifest.yaml new file mode 100644 index 00000000..2df37f95 --- /dev/null +++ b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/manifest.yaml @@ -0,0 +1,199 @@ +entry: + id: 1780 + title: "check-if-number-is-a-sum-of-powers-of-three" + params: + n: + type: int + call: + cpp: "Solution().checkPowersOfThree({n})" + rust: "Solution::check_powers_of_three({n})" + python3: "Solution().checkPowersOfThree({n})" + python2: "Solution().checkPowersOfThree({n})" + ruby: "check_powers_of_three({n})" + java: "new Solution().checkPowersOfThree({n})" + csharp: "new Solution().CheckPowersOfThree({n})" + kotlin: "Solution().checkPowersOfThree({n})" + go: "checkPowersOfThree({n})" + dart: "Solution().checkPowersOfThree({n})" + swift: "Solution().checkPowersOfThree({n})" + typescript: "checkPowersOfThree({n})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(n, {result})" + checker: | + class Checker: + def check(self, n, result): + if not isinstance(result, bool): + return False + while n: + if n % 3 == 2: + return result is False + n //= 3 + return result is True + +seed: 1780 + +tests: + - name: minimum + in: + n: 1 + out: true + - name: two + in: + n: 2 + out: false + - name: three + in: + n: 3 + out: true + - name: four + in: + n: 4 + out: true + - name: five + in: + n: 5 + out: false + - name: six + in: + n: 6 + out: false + - name: seven + in: + n: 7 + out: false + - name: eight + in: + n: 8 + out: false + - name: nine + in: + n: 9 + out: true + - name: ten + in: + n: 10 + out: true + - name: eleven + in: + n: 11 + out: false + - name: example-12 + in: + n: 12 + out: true + - name: thirteen + in: + n: 13 + out: true + - name: sixteen + in: + n: 16 + out: false + - name: twenty-one + in: + n: 21 + out: false + - name: example-91 + in: + n: 91 + out: true + - name: power-three-10 + in: + n: 59049 + out: true + - name: power-three-11 + in: + n: 177147 + out: true + - name: sum-low-powers + in: + n: 121 + out: true + - name: repeated-digit-zero + in: + n: 243 + out: true + - name: ternary-two-at-units + in: + n: 1000 + out: true + - name: near-power-invalid + in: + n: 59050 + out: true + - name: max-valid-under-limit + in: + n: 9841 + out: true + - name: max-invalid-under-limit + in: + n: 9842 + out: false + - name: large-valid + in: + n: 797161 + out: true + - name: large-invalid + in: + n: 797162 + out: false + - name: upper-bound-valid + in: + n: 10000000 + out: false + - name: all-low-powers + in: + n: 364 + out: true + - name: alternating-ternary + in: + n: 66430 + out: true + - name: ternary-carry-case + in: + n: 1000001 + out: false + - name: generated-small + in: + n: + gen: "int" + min: 1 + max: 1000 + seed: 178001 + - name: generated-medium + in: + n: + gen: "int" + min: 1 + max: 100000 + seed: 178002 + - name: generated-large-a + in: + n: + gen: "int" + min: 1000000 + max: 3000000 + seed: 178003 + - name: generated-large-b + in: + n: + gen: "int" + min: 3000001 + max: 7000000 + seed: 178004 + - name: generated-upper-range + in: + n: + gen: "int" + min: 7000001 + max: 10000000 + seed: 178005 diff --git a/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.cpp b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.cpp new file mode 100644 index 00000000..a16a1e10 --- /dev/null +++ b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + bool checkPowersOfThree(int n) { + while (n > 0) { + if (n % 3 == 2) { + return false; + } + n /= 3; + } + return true; + } +}; diff --git a/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.cs b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.cs new file mode 100644 index 00000000..fb1a9fca --- /dev/null +++ b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.cs @@ -0,0 +1,11 @@ +public class Solution { + public bool CheckPowersOfThree(int n) { + while (n > 0) { + if (n % 3 == 2) { + return false; + } + n /= 3; + } + return true; + } +} diff --git a/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.dart b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.dart new file mode 100644 index 00000000..fb7b8e49 --- /dev/null +++ b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.dart @@ -0,0 +1,11 @@ +class Solution { + bool checkPowersOfThree(int n) { + while (n > 0) { + if (n % 3 == 2) { + return false; + } + n ~/= 3; + } + return true; + } +} diff --git a/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.go b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.go new file mode 100644 index 00000000..71ef1d58 --- /dev/null +++ b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.go @@ -0,0 +1,9 @@ +func checkPowersOfThree(n int) bool { + for n > 0 { + if n%3 == 2 { + return false + } + n /= 3 + } + return true +} diff --git a/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.java b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.java new file mode 100644 index 00000000..ac005192 --- /dev/null +++ b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.java @@ -0,0 +1,11 @@ +class Solution { + public boolean checkPowersOfThree(int n) { + while (n > 0) { + if (n % 3 == 2) { + return false; + } + n /= 3; + } + return true; + } +} diff --git a/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.kt b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.kt new file mode 100644 index 00000000..2b451e0e --- /dev/null +++ b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.kt @@ -0,0 +1,12 @@ +class Solution { + fun checkPowersOfThree(n: Int): Boolean { + var num = n + while (num > 0) { + if (num % 3 == 2) { + return false + } + num /= 3 + } + return true + } +} diff --git a/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.py b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.py new file mode 100644 index 00000000..4f64c1cf --- /dev/null +++ b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.py @@ -0,0 +1,8 @@ +class Solution: + def checkPowersOfThree(self, n: int) -> bool: + while n > 0: + if n % 3 == 2: + return False + n //= 3 + + return True diff --git a/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.py2 b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.py2 new file mode 100644 index 00000000..f67e0032 --- /dev/null +++ b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def checkPowersOfThree(self, n): + """ + :type n: int + :rtype: bool + """ + while n > 0: + if n % 3 == 2: + return False + n //= 3 + return True diff --git a/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.rb b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.rb new file mode 100644 index 00000000..8d369a35 --- /dev/null +++ b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.rb @@ -0,0 +1,9 @@ +# @param {Integer} n +# @return {Boolean} +def check_powers_of_three(n) + while n > 0 + return false if n % 3 == 2 + n /= 3 + end + true +end diff --git a/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.rs b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.rs new file mode 100644 index 00000000..fe47aca7 --- /dev/null +++ b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.rs @@ -0,0 +1,12 @@ +impl Solution { + pub fn check_powers_of_three(n: i32) -> bool { + let mut num = n; + while num > 0 { + if num % 3 == 2 { + return false; + } + num /= 3; + } + true + } +} diff --git a/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.swift b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.swift new file mode 100644 index 00000000..b7923525 --- /dev/null +++ b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.swift @@ -0,0 +1,12 @@ +class Solution { + func checkPowersOfThree(_ n: Int) -> Bool { + var num = n + while num > 0 { + if num % 3 == 2 { + return false + } + num /= 3 + } + return true + } +} diff --git a/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.ts b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.ts new file mode 100644 index 00000000..192c422e --- /dev/null +++ b/tests/1501-2000/1780. check-if-number-is-a-sum-of-powers-of-three/sol.ts @@ -0,0 +1,9 @@ +function checkPowersOfThree(n: number): boolean { + while (n > 0) { + if (n % 3 === 2) { + return false; + } + n = Math.floor(n / 3); + } + return true; +} diff --git a/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/manifest.yaml b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/manifest.yaml new file mode 100644 index 00000000..598eef84 --- /dev/null +++ b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/manifest.yaml @@ -0,0 +1,197 @@ +entry: + id: 1781 + title: "sum-of-beauty-of-all-substrings" + params: + s: + type: string + call: + cpp: "Solution().beautySum({s})" + rust: "Solution::beauty_sum({s})" + python3: "Solution().beautySum({s})" + python2: "Solution().beautySum({s})" + ruby: "beauty_sum({s})" + java: "new Solution().beautySum({s})" + csharp: "new Solution().BeautySum({s})" + kotlin: "Solution().beautySum({s})" + go: "beautySum({s})" + dart: "Solution().beautySum({s})" + swift: "Solution().beautySum({s})" + typescript: "beautySum({s})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().beautySum(s, {result})" + checker: | + class Checker: + def beautySum(self, s, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + total = 0 + for i in range(len(s)): + freq = [0] * 26 + for j in range(i, len(s)): + freq[ord(s[j]) - 97] += 1 + present = [x for x in freq if x] + total += max(present) - min(present) + return result == total + +seed: 1781 + +tests: + - name: two-equal + in: + s: "aa" + out: 0 + - name: two-different + in: + s: "ab" + out: 0 + - name: alternating-three + in: + s: "aba" + out: 1 + - name: example-one + in: + s: "aabcb" + out: 5 + - name: example-two + in: + s: "aabcbaa" + out: 17 + - name: three-distinct + in: + s: "abc" + out: 0 + - name: all-equal + in: + s: "aaa" + out: 0 + - name: four-distinct + in: + s: "abcd" + out: 0 + - name: two-pairs + in: + s: "aabb" + out: 2 + - name: repeated-endpoint + in: + s: "abca" + out: 1 + - name: five-equal + in: + s: "aaaaa" + out: 0 + - name: five-distinct + in: + s: "abcde" + out: 0 + - name: three-pairs + in: + s: "aabbcc" + out: 7 + - name: palindrome + in: + s: "abacaba" + out: 19 + - name: repeated-z + in: + s: "zzzzzz" + out: 0 + - name: full-alphabet + in: + s: "abcdefghijklmnopqrstuvwxyz" + out: 0 + - name: alternating-eight + in: + s: "abababab" + out: 12 + - name: center-heavy + in: + s: "aabbba" + out: 9 + - name: periodic-three + in: + s: "abcabc" + out: 5 + - name: six-pairs + in: + s: "aabbccddeeff" + out: 40 + - name: seven-runs + in: + s: "aabbccddeeffg" + out: 51 + - name: distinct-word + in: + s: "qwerty" + out: 0 + - name: repeated-i + in: + s: "mississippi" + out: 64 + - name: banana + in: + s: "banana" + out: 8 + - name: palindrome-word + in: + s: "abracadabra" + out: 64 + - name: repeated-blocks + in: + s: "abcdeabcde" + out: 14 + - name: long-uniform + in: + s: "aaaaaaaaaaaaaaaaaaaa" + out: 0 + - name: long-alternating + in: + s: "abababababababababab" + out: 90 + - name: long-periodic + in: + s: "abcabcabcabcabcabcabc" + out: 120 + - name: long-balanced-runs + in: + s: "aabbccaabbccaabbccaabbcc" + out: 265 + - name: generated-short + in: + s: + gen: "str" + len: 1 + alphabet: "abcd" + - name: generated-small + in: + s: + gen: "str" + len: 17 + alphabet: "abcde" + - name: generated-medium + in: + s: + gen: "str" + len: 100 + alphabet: "abcdef" + - name: generated-large + in: + s: + gen: "str" + len: 300 + alphabet: "abcdefgh" + - name: generated-maximum + in: + s: + gen: "str" + len: 500 + alphabet: "abcdefghijkl" diff --git a/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.cpp b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.cpp new file mode 100644 index 00000000..df42aa74 --- /dev/null +++ b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int beautySum(string s) { + int n = s.size(); + int sumOfBeauty = 0; + for (int i = 0; i < n; i++) { + vector freq(26, 0); + for (int j = i; j < n; j++) { + freq[s[j] - 'a']++; + int maxi = -1; + int mini = INT_MAX; + for (int diff : freq) { + if (diff > 0) { + maxi = max(maxi, diff); + mini = min(mini, diff); + } + } + sumOfBeauty += maxi - mini; + } + } + return sumOfBeauty; + } +}; diff --git a/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.cs b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.cs new file mode 100644 index 00000000..d71b3fb6 --- /dev/null +++ b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public int BeautySum(string s) { + int n = s.Length; + int sumOfBeauty = 0; + for (int i = 0; i < n; i++) { + int[] freq = new int[26]; + for (int j = i; j < n; j++) { + freq[s[j] - 'a']++; + int maxi = -1; + int mini = int.MaxValue; + foreach (int diff in freq) { + if (diff > 0) { + maxi = Math.Max(maxi, diff); + mini = Math.Min(mini, diff); + } + } + sumOfBeauty += maxi - mini; + } + } + return sumOfBeauty; + } +} diff --git a/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.dart b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.dart new file mode 100644 index 00000000..89e1fc69 --- /dev/null +++ b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.dart @@ -0,0 +1,22 @@ +class Solution { + int beautySum(String s) { + int n = s.length; + int sumOfBeauty = 0; + for (int i = 0; i < n; i++) { + List freq = List.filled(26, 0); + for (int j = i; j < n; j++) { + freq[s.codeUnitAt(j) - 97]++; + int maxi = -1; + int mini = 1 << 30; + for (int diff in freq) { + if (diff > 0) { + if (diff > maxi) maxi = diff; + if (diff < mini) mini = diff; + } + } + sumOfBeauty += maxi - mini; + } + } + return sumOfBeauty; + } +} diff --git a/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.go b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.go new file mode 100644 index 00000000..54ccfad4 --- /dev/null +++ b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.go @@ -0,0 +1,20 @@ +func beautySum(s string) int { + n := len(s) + sumOfBeauty := 0 + for i := 0; i < n; i++ { + freq := make([]int, 26) + for j := i; j < n; j++ { + freq[s[j]-'a']++ + maxi := -1 + mini := int(^uint(0) >> 1) // max int + for _, diff := range freq { + if diff > 0 { + if diff > maxi { maxi = diff } + if diff < mini { mini = diff } + } + } + sumOfBeauty += maxi - mini + } + } + return sumOfBeauty +} diff --git a/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.java b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.java new file mode 100644 index 00000000..77de8a72 --- /dev/null +++ b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.java @@ -0,0 +1,22 @@ +class Solution { + public int beautySum(String s) { + int n = s.length(); + int sumOfBeauty = 0; + for (int i = 0; i < n; i++) { + int[] freq = new int[26]; + for (int j = i; j < n; j++) { + freq[s.charAt(j) - 'a']++; + int maxi = Integer.MIN_VALUE; + int mini = Integer.MAX_VALUE; + for (int diff : freq) { + if (diff > 0) { + maxi = Math.max(maxi, diff); + mini = Math.min(mini, diff); + } + } + sumOfBeauty += (maxi - mini); + } + } + return sumOfBeauty; + } +} diff --git a/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.kt b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.kt new file mode 100644 index 00000000..dc5aab1a --- /dev/null +++ b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.kt @@ -0,0 +1,22 @@ +class Solution { + fun beautySum(s: String): Int { + val n = s.length + var sumOfBeauty = 0 + for (i in 0 until n) { + val freq = IntArray(26) + for (j in i until n) { + freq[s[j] - 'a']++ + var maxi = Int.MIN_VALUE + var mini = Int.MAX_VALUE + for (diff in freq) { + if (diff > 0) { + maxi = maxOf(maxi, diff) + mini = minOf(mini, diff) + } + } + sumOfBeauty += (maxi - mini) + } + } + return sumOfBeauty + } +} diff --git a/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.py b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.py new file mode 100644 index 00000000..d1b18ddb --- /dev/null +++ b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.py @@ -0,0 +1,22 @@ +class Solution: + def beautySum(self, s: str) -> int: + n = len(s) + sumOfBeauty = 0 + + for i in range(n): + freq = [0] * 26 + + for j in range(i, n): + freq[ord(s[j]) - 97] += 1 + + maxi = float("-inf") + mini = float("inf") + + for diff in freq: + if diff > 0: + maxi = max(maxi, diff) + mini = min(mini, diff) + + sumOfBeauty += maxi - mini + + return sumOfBeauty diff --git a/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.py2 b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.py2 new file mode 100644 index 00000000..5ad235b4 --- /dev/null +++ b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def beautySum(self, s): + """ + :type s: str + :rtype: int + """ + n = len(s) + sum_of_beauty = 0 + for i in range(n): + freq = [0] * 26 + for j in range(i, n): + freq[ord(s[j]) - 97] += 1 + maxi = float('-inf') + mini = float('inf') + for diff in freq: + if diff > 0: + maxi = max(maxi, diff) + mini = min(mini, diff) + sum_of_beauty += (maxi - mini) + return sum_of_beauty diff --git a/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.rb b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.rb new file mode 100644 index 00000000..fd1192aa --- /dev/null +++ b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.rb @@ -0,0 +1,22 @@ +# @param {String} s +# @return {Integer} +def beauty_sum(s) + n = s.length + sum_of_beauty = 0 + (0...n).each do |i| + freq = Array.new(26, 0) + (i...n).each do |j| + freq[s[j].ord - 97] += 1 + maxi = -Float::INFINITY + mini = Float::INFINITY + freq.each do |diff| + if diff > 0 + maxi = [maxi, diff].max + mini = [mini, diff].min + end + end + sum_of_beauty += (maxi - mini) + end + end + sum_of_beauty +end diff --git a/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.rs b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.rs new file mode 100644 index 00000000..625bc1eb --- /dev/null +++ b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.rs @@ -0,0 +1,23 @@ +impl Solution { + pub fn beauty_sum(s: String) -> i32 { + let n = s.len(); + let chars: Vec = s.chars().collect(); + let mut sum_of_beauty = 0; + for i in 0..n { + let mut freq = vec![0; 26]; + for j in i..n { + freq[chars[j] as usize - 97] += 1; + let mut maxi = -1; + let mut mini = i32::MAX; + for &diff in &freq { + if diff > 0 { + maxi = maxi.max(diff); + mini = mini.min(diff); + } + } + sum_of_beauty += maxi - mini; + } + } + sum_of_beauty + } +} diff --git a/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.swift b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.swift new file mode 100644 index 00000000..3e94303d --- /dev/null +++ b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func beautySum(_ s: String) -> Int { + let n = s.count + var sumOfBeauty = 0 + let chars = Array(s) + for i in 0.. 0 { + maxi = max(maxi, diff) + mini = min(mini, diff) + } + } + sumOfBeauty += maxi - mini + } + } + return sumOfBeauty + } +} diff --git a/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.ts b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.ts new file mode 100644 index 00000000..1ab20ea3 --- /dev/null +++ b/tests/1501-2000/1781. sum-of-beauty-of-all-substrings/sol.ts @@ -0,0 +1,20 @@ +function beautySum(s: string): number { + const n = s.length; + let sumOfBeauty = 0; + for (let i = 0; i < n; i++) { + const freq = new Array(26).fill(0); + for (let j = i; j < n; j++) { + freq[s.charCodeAt(j) - 97]++; + let maxi = -1; + let mini = Number.MAX_SAFE_INTEGER; + for (const diff of freq) { + if (diff > 0) { + maxi = Math.max(maxi, diff); + mini = Math.min(mini, diff); + } + } + sumOfBeauty += maxi - mini; + } + } + return sumOfBeauty; +} diff --git a/tests/1501-2000/1782. count-pairs-of-nodes/manifest.yaml b/tests/1501-2000/1782. count-pairs-of-nodes/manifest.yaml new file mode 100644 index 00000000..4c379f05 --- /dev/null +++ b/tests/1501-2000/1782. count-pairs-of-nodes/manifest.yaml @@ -0,0 +1,649 @@ +entry: + id: 1782 + title: count-pairs-of-nodes + params: + n: + type: int + edges: + type: array + items: + type: array + items: + type: int + queries: + type: array + items: + type: int + call: + cpp: "Solution().countPairs({n}, {edges}, {queries})" + rust: "Solution::count_pairs({n}, {edges}, {queries})" + python3: "Solution().countPairs({n}, {edges}, {queries})" + python2: "Solution().countPairs({n}, {edges}, {queries})" + ruby: "count_pairs({n}, {edges}, {queries})" + java: "new Solution().countPairs({n}, {edges}, {queries})" + csharp: "new Solution().CountPairs({n}, {edges}, {queries})" + kotlin: "Solution().countPairs({n}, {edges}, {queries})" + go: "countPairs({n}, {edges}, {queries})" + dart: "Solution().countPairs({n}, {edges}, {queries})" + swift: "Solution().countPairs({n}, {edges}, {queries})" + typescript: "countPairs({n}, {edges}, {queries})" + +judge: + type: exact + +limits: + time_ms: 5000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().check(n, edges, queries, {result})" + checker: | + class Checker: + def check(self, n, edges, queries, result): + if not isinstance(result, list) or len(result) != len(queries): + return False + degree = [0] * n + shared = {} + for edge in edges: + if not isinstance(edge, list) or len(edge) != 2: + return False + u, v = edge + if not (1 <= u <= n and 1 <= v <= n and u != v): + return False + u -= 1 + v -= 1 + degree[u] += 1 + degree[v] += 1 + if u > v: + u, v = v, u + shared[(u, v)] = shared.get((u, v), 0) + 1 + order = sorted(degree) + expected = [] + for q in queries: + left, right = 0, n - 1 + pairs = 0 + while left < right: + if order[left] + order[right] <= q: + left += 1 + else: + pairs += right - left + right -= 1 + for (u, v), count in shared.items(): + if degree[u] + degree[v] > q and degree[u] + degree[v] - count <= q: + pairs -= 1 + expected.append(pairs) + return result == expected + +seed: 1782 + +tests: + - name: example-one + in: + n: 4 + edges: + - [1, 2] + - [2, 4] + - [1, 3] + - [2, 3] + - [2, 1] + queries: [2, 3] + - name: example-two + in: + n: 5 + edges: + - [1, 5] + - [1, 5] + - [3, 4] + - [2, 5] + - [1, 3] + - [5, 1] + - [2, 3] + - [2, 5] + queries: [1, 2, 3, 4, 5] + - name: three-chain + in: + n: 3 + edges: + - [1, 2] + - [2, 3] + queries: [0, 1, 2, 3] + - name: complete-four + in: + n: 4 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 3] + - [2, 4] + - [3, 4] + queries: [0, 2, 5, 6, 7, 11] + - name: duplicate-pair + in: + n: 4 + edges: + - [1, 2] + - [1, 2] + - [1, 2] + - [3, 4] + queries: [0, 1, 2, 3, 4, 5] + - name: star + in: + n: 7 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + queries: [0, 1, 5, 6, 7, 10] + - name: disconnected + in: + n: 8 + edges: + - [1, 2] + - [2, 3] + - [4, 5] + - [6, 7] + queries: [0, 1, 2, 3, 4, 5] + - name: isolated-last + in: + n: 6 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + queries: [0, 2, 4, 6, 8] + - name: parallel-heavy + in: + n: 5 + edges: + - [1, 2] + - [1, 2] + - [1, 2] + - [1, 2] + - [2, 3] + - [2, 3] + - [3, 4] + - [4, 5] + queries: [0, 3, 4, 5, 7, 9] + - name: cycle-five + in: + n: 5 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 1] + queries: [0, 1, 2, 3, 4, 5] + - name: irregular-six + in: + n: 6 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 3] + - [3, 5] + - [5, 6] + - [5, 6] + queries: [0, 2, 3, 4, 5, 7] + - name: all-pairs-three + in: + n: 3 + edges: + - [1, 2] + - [1, 3] + - [2, 3] + - [1, 2] + queries: [0, 2, 3, 4, 5, 6] + - name: long-chain-ten + in: + n: 10 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + queries: [0, 1, 2, 3, 4, 5, 8] + - name: hubs + in: + n: 9 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [2, 6] + - [2, 7] + - [2, 8] + - [2, 9] + - [1, 2] + queries: [0, 3, 4, 5, 6, 7, 8] + - name: repeated-cycle + in: + n: 7 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 1] + - [1, 2] + - [3, 4] + - [5, 6] + queries: [0, 2, 3, 4, 5, 6, 8] + - name: sparse-twelve + in: + n: 12 + edges: + - [1, 12] + - [2, 11] + - [3, 10] + - [4, 9] + - [5, 8] + - [6, 7] + queries: [0, 1, 2, 3, 4, 5, 6] + - name: dense-six + in: + n: 6 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [2, 3] + - [2, 4] + - [2, 5] + - [2, 6] + - [3, 4] + - [3, 5] + - [3, 6] + - [4, 5] + - [4, 6] + - [5, 6] + queries: [0, 5, 9, 10, 15, 20, 29] + - name: one-edge + in: + n: 100 + edges: + - [1, 100] + queries: [0, 1, 2, 99] + - name: matching + in: + n: 20 + edges: + - [1, 2] + - [3, 4] + - [5, 6] + - [7, 8] + - [9, 10] + - [11, 12] + - [13, 14] + - [15, 16] + - [17, 18] + - [19, 20] + queries: [0, 1, 2, 3, 4, 5] + - name: repeated-hub + in: + n: 8 + edges: + - [1, 2] + - [1, 2] + - [1, 3] + - [1, 3] + - [1, 4] + - [1, 4] + - [1, 5] + - [1, 5] + - [1, 6] + - [1, 6] + - [1, 7] + - [1, 7] + queries: [0, 2, 4, 6, 8, 10, 12] + - name: chain-with-chords + in: + n: 15 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [11, 12] + - [12, 13] + - [13, 14] + - [14, 15] + - [1, 8] + - [2, 9] + - [3, 10] + - [4, 11] + - [5, 12] + queries: [0, 2, 4, 6, 8, 10, 12] + - name: high-query-boundaries + in: + n: 10 + edges: + - [1, 2] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + queries: [0, 1, 2, 3, 4, 5, 9, 10] + - name: asymmetric-components + in: + n: 14 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 3] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [10, 11] + - [12, 13] + - [13, 14] + queries: [0, 1, 2, 3, 4, 5, 6] + - name: medium-random-like + in: + n: 25 + edges: + - [1, 7] + - [2, 19] + - [3, 14] + - [4, 22] + - [5, 11] + - [6, 25] + - [7, 18] + - [8, 13] + - [9, 21] + - [10, 16] + - [12, 20] + - [15, 24] + - [17, 23] + - [1, 19] + - [2, 14] + - [3, 22] + - [4, 11] + - [5, 25] + - [6, 18] + - [7, 13] + - [8, 21] + - [9, 16] + - [10, 20] + queries: [0, 1, 2, 3, 4, 5, 8] + - name: ten-parallel + in: + n: 3 + edges: + - [1, 2] + - [1, 2] + - [1, 2] + - [1, 2] + - [1, 2] + - [1, 2] + - [1, 2] + - [1, 2] + - [1, 2] + - [1, 2] + queries: [0, 1, 9, 10, 11, 19] + - name: complete-five + in: + n: 5 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [2, 3] + - [2, 4] + - [2, 5] + - [3, 4] + - [3, 5] + - [4, 5] + queries: [0, 5, 6, 7, 8, 9, 10, 11] + - name: sparse-twenty-five + in: + n: 25 + edges: + - [1, 25] + - [2, 24] + - [3, 23] + - [4, 22] + - [5, 21] + - [6, 20] + - [7, 19] + - [8, 18] + - [9, 17] + - [10, 16] + - [11, 15] + - [12, 14] + queries: [0, 1, 2, 3, 4, 5, 6] + - name: two-components-dense + in: + n: 8 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 3] + - [2, 4] + - [3, 4] + - [5, 6] + - [5, 7] + - [5, 8] + - [6, 7] + - [6, 8] + - [7, 8] + queries: [0, 2, 4, 5, 6, 10, 11] + - name: max-n-sparse + in: + n: 20000 + edges: + - [1, 20000] + - [2, 19999] + - [3, 19998] + - [4, 19997] + - [5, 19996] + - [6, 19995] + - [7, 19994] + - [8, 19993] + queries: [0, 1, 2, 3, 4, 7] + - name: max-n-hub + in: + n: 20000 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [1, 8] + - [1, 9] + - [1, 10] + - [1, 11] + - [1, 12] + - [1, 13] + - [1, 14] + - [1, 15] + - [1, 16] + - [1, 17] + - [1, 18] + - [1, 19] + - [1, 20] + queries: [0, 1, 5, 10, 19] + - name: medium-duplicates + in: + n: 30 + edges: + - [1, 2] + - [1, 2] + - [1, 2] + - [2, 3] + - [2, 3] + - [3, 4] + - [3, 4] + - [4, 5] + - [4, 5] + - [5, 6] + - [5, 6] + - [6, 7] + - [6, 7] + - [7, 8] + - [7, 8] + - [8, 9] + - [8, 9] + - [9, 10] + - [9, 10] + queries: [0, 1, 2, 3, 4, 5, 6] + - name: mixed-twenty + in: + n: 20 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [3, 7] + - [3, 8] + - [4, 9] + - [4, 10] + - [5, 11] + - [6, 12] + - [7, 13] + - [8, 14] + - [9, 15] + - [10, 16] + - [11, 17] + - [12, 18] + - [13, 19] + - [14, 20] + - [1, 20] + queries: [0, 2, 3, 4, 5, 6, 8] + - name: threshold-everything + in: + n: 6 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [2, 3] + - [2, 4] + - [2, 5] + - [2, 6] + - [3, 4] + - [3, 5] + - [3, 6] + - [4, 5] + - [4, 6] + - [5, 6] + queries: [0, 1, 2, 3, 4, 5, 14, 15, 16] + - name: endpoints-only + in: + n: 10 + edges: + - [1, 10] + - [1, 10] + - [1, 10] + queries: [0, 1, 2, 3, 4, 5] + - name: balanced-tree + in: + n: 15 + edges: + - [1, 2] + - [1, 3] + - [2, 4] + - [2, 5] + - [3, 6] + - [3, 7] + - [4, 8] + - [4, 9] + - [5, 10] + - [5, 11] + - [6, 12] + - [6, 13] + - [7, 14] + - [7, 15] + queries: [0, 1, 2, 3, 4, 5, 6] + - name: high-degree-three + in: + n: 12 + edges: + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [1, 6] + - [1, 7] + - [1, 8] + - [1, 9] + - [2, 3] + - [2, 4] + - [2, 5] + - [2, 6] + - [2, 7] + - [2, 8] + - [2, 9] + queries: [0, 3, 5, 7, 9, 12, 14] + - name: final-boundary + in: + n: 50 + edges: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [11, 12] + - [12, 13] + - [13, 14] + - [14, 15] + - [15, 16] + - [16, 17] + - [17, 18] + - [18, 19] + - [19, 20] + - [20, 21] + - [21, 22] + - [22, 23] + - [23, 24] + - [24, 25] + - [25, 26] + - [26, 27] + - [27, 28] + - [28, 29] + - [29, 30] + queries: [0, 1, 2, 3, 4, 5, 10, 20, 29] diff --git a/tests/1501-2000/1782. count-pairs-of-nodes/sol.cpp b/tests/1501-2000/1782. count-pairs-of-nodes/sol.cpp new file mode 100644 index 00000000..ff745073 --- /dev/null +++ b/tests/1501-2000/1782. count-pairs-of-nodes/sol.cpp @@ -0,0 +1,81 @@ +class Solution { +public: + vector countPairs(int n, vector>& edges, vector& queries) { + unordered_map> x; + vector edge(n, 0); + unordered_map, int, hash_pair> edgePair; + + for (auto& e : edges) { + int i = e[0] - 1; + int j = e[1] - 1; + x[i].insert(j); + x[j].insert(i); + edge[i]++; + edge[j]++; + edgePair[{i, j}]++; + edgePair[{j, i}]++; + } + + vector res = edge; + sort(res.begin(), res.end()); + + auto binse = [&](int threshold) -> int { + int i = 0, j = n - 1; + int ans = n; + while (i <= j) { + int mid = (i + j) / 2; + if (res[mid] > threshold) { + ans = mid; + j = mid - 1; + } else { + i = mid + 1; + } + } + return n - ans; + }; + + vector result; + for (int query : queries) { + unordered_set v; + int ans = 0; + + function f = [&](int i) { + v.insert(i); + int a = binse(query - edge[i]); + + if (edge[i] > query - edge[i]) { + a--; + } + + for (int j : x[i]) { + if (edge[j] > query - edge[i] && edge[j] - edgePair[{i, j}] <= query - edge[i]) { + a--; + } + if (v.find(j) == v.end()) { + f(j); + } + } + ans += a; + }; + + for (int j = 0; j < n; j++) { + if (v.find(j) == v.end()) { + f(j); + } + } + result.push_back(ans / 2); + } + + return result; + } + +private: + struct hash_pair { + template + size_t operator()(const pair& p) const { + auto hash1 = hash{}(p.first); + auto hash2 = hash{}(p.second); + return hash1 ^ hash2; + } + }; +}; diff --git a/tests/1501-2000/1782. count-pairs-of-nodes/sol.cs b/tests/1501-2000/1782. count-pairs-of-nodes/sol.cs new file mode 100644 index 00000000..91c4a235 --- /dev/null +++ b/tests/1501-2000/1782. count-pairs-of-nodes/sol.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +public class Solution { + public int[] CountPairs(int n, int[][] edges, int[] queries) { + var x = new Dictionary>(); + var edge = new int[n]; + var edgePair = new Dictionary<(int, int), int>(); + + foreach (var e in edges) { + int i = e[0] - 1; + int j = e[1] - 1; + if (!x.ContainsKey(i)) x[i] = new HashSet(); + if (!x.ContainsKey(j)) x[j] = new HashSet(); + x[i].Add(j); + x[j].Add(i); + edge[i]++; + edge[j]++; + var key1 = (i, j); + var key2 = (j, i); + edgePair[key1] = edgePair.GetValueOrDefault(key1, 0) + 1; + edgePair[key2] = edgePair.GetValueOrDefault(key2, 0) + 1; + } + + var res = edge.OrderBy(v => v).ToArray(); + + int Binse(int threshold) { + int i = 0, j = n - 1; + int ans = n; + while (i <= j) { + int mid = (i + j) / 2; + if (res[mid] > threshold) { + ans = mid; + j = mid - 1; + } else { + i = mid + 1; + } + } + return n - ans; + } + + var result = new int[queries.Length]; + for (int qi = 0; qi < queries.Length; qi++) { + int query = queries[qi]; + var v = new HashSet(); + int ans = 0; + + void F(int i) { + v.Add(i); + int a = Binse(query - edge[i]); + + if (edge[i] > query - edge[i]) { + a--; + } + + foreach (int j in x.GetValueOrDefault(i, new HashSet())) { + if (edge[j] > query - edge[i] && edge[j] - edgePair.GetValueOrDefault((i, j), 0) <= query - edge[i]) { + a--; + } + if (!v.Contains(j)) { + F(j); + } + } + ans += a; + } + + for (int j = 0; j < n; j++) { + if (!v.Contains(j)) { + F(j); + } + } + result[qi] = ans / 2; + } + + return result; + } +} diff --git a/tests/1501-2000/1782. count-pairs-of-nodes/sol.dart b/tests/1501-2000/1782. count-pairs-of-nodes/sol.dart new file mode 100644 index 00000000..fca9060a --- /dev/null +++ b/tests/1501-2000/1782. count-pairs-of-nodes/sol.dart @@ -0,0 +1,72 @@ +import 'dart:collection'; + +class Solution { + List countPairs(int n, List> edges, List queries) { + Map> x = HashMap(); + List edge = List.filled(n, 0); + Map edgePair = HashMap(); + + for (var e in edges) { + int i = e[0] - 1; + int j = e[1] - 1; + x.putIfAbsent(i, () => HashSet()).add(j); + x.putIfAbsent(j, () => HashSet()).add(i); + edge[i]++; + edge[j]++; + edgePair['$i,$j'] = (edgePair['$i,$j'] ?? 0) + 1; + edgePair['$j,$i'] = (edgePair['$j,$i'] ?? 0) + 1; + } + + var res = List.from(edge)..sort(); + + int binse(int threshold) { + int i = 0; + int j = n - 1; + int ans = n; + while (i <= j) { + int mid = (i + j) ~/ 2; + if (res[mid] > threshold) { + ans = mid; + j = mid - 1; + } else { + i = mid + 1; + } + } + return n - ans; + } + + List result = []; + for (int query in queries) { + Set v = HashSet(); + int ans = 0; + + void f(int i) { + v.add(i); + int a = binse(query - edge[i]); + + if (edge[i] > query - edge[i]) { + a--; + } + + for (int j in x[i] ?? []) { + if (edge[j] > query - edge[i] && edge[j] - (edgePair['$i,$j'] ?? 0) <= query - edge[i]) { + a--; + } + if (!v.contains(j)) { + f(j); + } + } + ans += a; + } + + for (int j = 0; j < n; j++) { + if (!v.contains(j)) { + f(j); + } + } + result.add(ans ~/ 2); + } + + return result; + } +} diff --git a/tests/1501-2000/1782. count-pairs-of-nodes/sol.go b/tests/1501-2000/1782. count-pairs-of-nodes/sol.go new file mode 100644 index 00000000..2846c7b0 --- /dev/null +++ b/tests/1501-2000/1782. count-pairs-of-nodes/sol.go @@ -0,0 +1,75 @@ +func countPairs(n int, edges [][]int, queries []int) []int { + x := make(map[int]map[int]bool) + edge := make([]int, n) + edgePair := make(map[[2]int]int) + + for _, e := range edges { + i, j := e[0]-1, e[1]-1 + if x[i] == nil { + x[i] = make(map[int]bool) + } + if x[j] == nil { + x[j] = make(map[int]bool) + } + x[i][j] = true + x[j][i] = true + edge[i]++ + edge[j]++ + edgePair[[2]int{i, j}]++ + edgePair[[2]int{j, i}]++ + } + + res := make([]int, n) + copy(res, edge) + sort.Ints(res) + + binse := func(threshold int) int { + i, j := 0, n-1 + ans := n + for i <= j { + mid := (i + j) / 2 + if res[mid] > threshold { + ans = mid + j = mid - 1 + } else { + i = mid + 1 + } + } + return n - ans + } + + result := make([]int, len(queries)) + for qi, query := range queries { + v := make(map[int]bool) + ans := 0 + + var f func(int) + f = func(i int) { + v[i] = true + a := binse(query - edge[i]) + + if edge[i] > query - edge[i] { + a-- + } + + for j := range x[i] { + if edge[j] > query - edge[i] && edge[j] - edgePair[[2]int{i, j}] <= query - edge[i] { + a-- + } + if !v[j] { + f(j) + } + } + ans += a + } + + for j := 0; j < n; j++ { + if !v[j] { + f(j) + } + } + result[qi] = ans / 2 + } + + return result +} diff --git a/tests/1501-2000/1782. count-pairs-of-nodes/sol.java b/tests/1501-2000/1782. count-pairs-of-nodes/sol.java new file mode 100644 index 00000000..17ac47c0 --- /dev/null +++ b/tests/1501-2000/1782. count-pairs-of-nodes/sol.java @@ -0,0 +1,74 @@ +import java.util.*; + +class Solution { + public int[] countPairs(int n, int[][] edges, int[] queries) { + Map> x = new HashMap<>(); + int[] edge = new int[n]; + Map edgePair = new HashMap<>(); + + for (int[] e : edges) { + int i = e[0] - 1, j = e[1] - 1; + x.computeIfAbsent(i, k -> new HashSet<>()).add(j); + x.computeIfAbsent(j, k -> new HashSet<>()).add(i); + edge[i]++; + edge[j]++; + edgePair.merge(i + "," + j, 1, Integer::sum); + edgePair.merge(j + "," + i, 1, Integer::sum); + } + + int[] res = edge.clone(); + Arrays.sort(res); + + int[] result = new int[queries.length]; + for (int qi = 0; qi < queries.length; qi++) { + int query = queries[qi]; + Set v = new HashSet<>(); + int[] ans = {0}; + + java.util.function.IntConsumer f = new java.util.function.IntConsumer() { + @Override + public void accept(int i) { + v.add(i); + int a = binse(query - edge[i], res, n); + + if (edge[i] > query - edge[i]) { + a--; + } + + for (int j : x.getOrDefault(i, Collections.emptySet())) { + if (edge[j] > query - edge[i] && edge[j] - edgePair.getOrDefault(i + "," + j, 0) <= query - edge[i]) { + a--; + } + if (!v.contains(j)) { + accept(j); + } + } + ans[0] += a; + } + }; + + for (int j = 0; j < n; j++) { + if (!v.contains(j)) { + f.accept(j); + } + } + result[qi] = ans[0] / 2; + } + return result; + } + + private int binse(int threshold, int[] res, int n) { + int i = 0, j = n - 1; + int ans = n; + while (i <= j) { + int mid = (i + j) / 2; + if (res[mid] > threshold) { + ans = mid; + j = mid - 1; + } else { + i = mid + 1; + } + } + return n - ans; + } +} diff --git a/tests/1501-2000/1782. count-pairs-of-nodes/sol.kt b/tests/1501-2000/1782. count-pairs-of-nodes/sol.kt new file mode 100644 index 00000000..f1fd45e1 --- /dev/null +++ b/tests/1501-2000/1782. count-pairs-of-nodes/sol.kt @@ -0,0 +1,72 @@ +import java.util.* + +class Solution { + fun countPairs(n: Int, edges: Array, queries: IntArray): IntArray { + val x = HashMap>() + val edge = IntArray(n) + val edgePair = HashMap, Int>() + + for (e in edges) { + val i = e[0] - 1 + val j = e[1] - 1 + x.getOrPut(i) { mutableSetOf() }.add(j) + x.getOrPut(j) { mutableSetOf() }.add(i) + edge[i]++ + edge[j]++ + edgePair[Pair(i, j)] = (edgePair[Pair(i, j)] ?: 0) + 1 + edgePair[Pair(j, i)] = (edgePair[Pair(j, i)] ?: 0) + 1 + } + + val res = edge.sorted() + + fun binse(threshold: Int): Int { + var i = 0 + var j = n - 1 + var ans = n + while (i <= j) { + val mid = (i + j) / 2 + if (res[mid] > threshold) { + ans = mid + j = mid - 1 + } else { + i = mid + 1 + } + } + return n - ans + } + + val result = IntArray(queries.size) + for (qi in queries.indices) { + val query = queries[qi] + val v = mutableSetOf() + var ans = 0 + + fun f(i: Int) { + v.add(i) + var a = binse(query - edge[i]) + + if (edge[i] > query - edge[i]) { + a-- + } + + for (j in x[i] ?: emptySet()) { + if (edge[j] > query - edge[i] && edge[j] - (edgePair[Pair(i, j)] ?: 0) <= query - edge[i]) { + a-- + } + if (j !in v) { + f(j) + } + } + ans += a + } + + for (j in 0 until n) { + if (j !in v) { + f(j) + } + } + result[qi] = ans / 2 + } + return result + } +} diff --git a/tests/1501-2000/1782. count-pairs-of-nodes/sol.py b/tests/1501-2000/1782. count-pairs-of-nodes/sol.py new file mode 100644 index 00000000..3624bbc7 --- /dev/null +++ b/tests/1501-2000/1782. count-pairs-of-nodes/sol.py @@ -0,0 +1,68 @@ +class Solution: + def countPairs( + self, n: int, edges: List[List[int]], queries: List[int] + ) -> List[int]: + + x = defaultdict(set) + edge = [0] * n + edge_pair = defaultdict(int) + + for i, j in edges: + x[i - 1].add(j - 1) + x[j - 1].add(i - 1) + edge[i - 1] += 1 + edge[j - 1] += 1 + edge_pair[i - 1, j - 1] += 1 + edge_pair[j - 1, i - 1] += 1 + + res = sorted(edge) + + def binse(threshold): + i = 0 + j = n - 1 + ans = n + while i <= j: + mid = (i + j) // 2 + if res[mid] > threshold: + ans = mid + j = mid - 1 + else: + i = mid + 1 + + return n - ans + + def f(i): + + v.add(i) + a = binse(query - edge[i]) + + if edge[i] > query - edge[i]: + a -= 1 + + # print(query, i, a, edge[i]) + + for j in x[i]: + if ( + edge[j] > query - edge[i] + and edge[j] - edge_pair[i, j] <= query - edge[i] + ): + a -= 1 + + if j not in v: + f(j) + nonlocal ans + ans += a + + final_result = [] + + for query in queries: + v = set() + ans = 0 + + for j in range(n): + if j not in v: + f(j) + + final_result.append(ans // 2) + + return final_result diff --git a/tests/1501-2000/1782. count-pairs-of-nodes/sol.py2 b/tests/1501-2000/1782. count-pairs-of-nodes/sol.py2 new file mode 100644 index 00000000..34b394d8 --- /dev/null +++ b/tests/1501-2000/1782. count-pairs-of-nodes/sol.py2 @@ -0,0 +1,32 @@ + +from collections import defaultdict + + +class Solution(object): + def countPairs(self, n, edges, queries): + degree = [0] * n + shared = defaultdict(int) + for left, right in edges: + left -= 1 + right -= 1 + degree[left] += 1 + degree[right] += 1 + if left > right: + left, right = right, left + shared[(left, right)] += 1 + + ordered = sorted(degree) + answer = [] + for query in queries: + left, right, pairs = 0, n - 1, 0 + while left < right: + if ordered[left] + ordered[right] > query: + pairs += right - left + right -= 1 + else: + left += 1 + for (left, right), count in shared.items(): + if degree[left] + degree[right] > query and degree[left] + degree[right] - count <= query: + pairs -= 1 + answer.append(pairs) + return answer diff --git a/tests/1501-2000/1782. count-pairs-of-nodes/sol.rb b/tests/1501-2000/1782. count-pairs-of-nodes/sol.rb new file mode 100644 index 00000000..c92dfa47 --- /dev/null +++ b/tests/1501-2000/1782. count-pairs-of-nodes/sol.rb @@ -0,0 +1,73 @@ +# @param {Integer} n +# @param {Integer[][]} edges +# @param {Integer[]} queries +# @return {Integer[]} +def count_pairs(n, edges, queries) + x = Hash.new { |h, k| h[k] = Set.new } + edge = Array.new(n, 0) + edge_pair = Hash.new(0) + + edges.each do |i, j| + x[i-1].add(j-1) + x[j-1].add(i-1) + edge[i-1] += 1 + edge[j-1] += 1 + edge_pair[[i-1, j-1]] += 1 + edge_pair[[j-1, i-1]] += 1 + end + + res = edge.sort + + binse = ->(threshold) do + i = 0 + j = n - 1 + ans = n + while i <= j + mid = (i + j) / 2 + if res[mid] > threshold + ans = mid + j = mid - 1 + else + i = mid + 1 + end + end + n - ans + end + + final_result = [] + + queries.each do |query| + v = Set.new + ans = 0 + f = nil + f = ->(i) do + v.add(i) + a = binse.call(query - edge[i]) + + if edge[i] > query - edge[i] + a -= 1 + end + + x[i].each do |j| + if edge[j] > query - edge[i] && edge[j] - edge_pair[[i, j]] <= query - edge[i] + a -= 1 + end + + if !v.include?(j) + f.call(j) + end + end + ans += a + end + + (0...n).each do |j| + if !v.include?(j) + f.call(j) + end + end + + final_result << ans / 2 + end + + final_result +end diff --git a/tests/1501-2000/1782. count-pairs-of-nodes/sol.rs b/tests/1501-2000/1782. count-pairs-of-nodes/sol.rs new file mode 100644 index 00000000..2bea3fb2 --- /dev/null +++ b/tests/1501-2000/1782. count-pairs-of-nodes/sol.rs @@ -0,0 +1,53 @@ +use std::collections::{HashMap, HashSet}; + +impl Solution { + pub fn count_pairs(n: i32, edges: Vec>, queries: Vec) -> Vec { + let n = n as usize; + let mut edge = vec![0i32; n]; + let mut edge_pair: HashMap<(usize, usize), i32> = HashMap::new(); + + for e in &edges { + let i = (e[0] - 1) as usize; + let j = (e[1] - 1) as usize; + edge[i] += 1; + edge[j] += 1; + *edge_pair.entry((i, j)).or_insert(0) += 1; + *edge_pair.entry((j, i)).or_insert(0) += 1; + } + + let mut res = edge.clone(); + res.sort(); + + fn binse(threshold: i32, res: &Vec, n: usize) -> i32 { + let mut i = 0; + let mut j = n as i32 - 1; + let mut ans = n as i32; + while i <= j { + let mid = (i + j) / 2; + if res[mid as usize] > threshold { + ans = mid; + j = mid - 1; + } else { + i = mid + 1; + } + } + (n as i32) - ans + } + + queries.iter().map(|&query| { + let mut left = 0usize; + let mut right = n.saturating_sub(1); + let mut ans = 0i32; + while left < right { + if res[left] + res[right] > query { + ans += (right - left) as i32; + right -= 1; + } else { left += 1; } + } + for (&(a, b), &count) in &edge_pair { + if a < b && edge[a] + edge[b] > query && edge[a] + edge[b] - count <= query { ans -= 1; } + } + ans + }).collect() + } +} diff --git a/tests/1501-2000/1782. count-pairs-of-nodes/sol.swift b/tests/1501-2000/1782. count-pairs-of-nodes/sol.swift new file mode 100644 index 00000000..57ef1034 --- /dev/null +++ b/tests/1501-2000/1782. count-pairs-of-nodes/sol.swift @@ -0,0 +1,72 @@ +import Foundation + +class Solution { + func countPairs(_ n: Int, _ edges: [[Int]], _ queries: [Int]) -> [Int] { + var x = [Int: Set]() + var edge = Array(repeating: 0, count: n) + var edgePair = [String: Int]() + + for e in edges { + let i = e[0] - 1 + let j = e[1] - 1 + x[i, default: Set()].insert(j) + x[j, default: Set()].insert(i) + edge[i] += 1 + edge[j] += 1 + edgePair["\(i),\(j)", default: 0] += 1 + edgePair["\(j),\(i)", default: 0] += 1 + } + + let res = edge.sorted() + + func binse(_ threshold: Int) -> Int { + var i = 0 + var j = n - 1 + var ans = n + while i <= j { + let mid = (i + j) / 2 + if res[mid] > threshold { + ans = mid + j = mid - 1 + } else { + i = mid + 1 + } + } + return n - ans + } + + var result = [Int]() + for query in queries { + var v = Set() + var ans = 0 + + func f(_ i: Int) { + v.insert(i) + var a = binse(query - edge[i]) + + if edge[i] > query - edge[i] { + a -= 1 + } + + for j in x[i] ?? [] { + if edge[j] > query - edge[i] && edge[j] - (edgePair["\(i),\(j)"] ?? 0) <= query - edge[i] { + a -= 1 + } + if !v.contains(j) { + f(j) + } + } + ans += a + } + + for j in 0..> = new Map(); + const edge: number[] = new Array(n).fill(0); + const edgePair: Map = new Map(); + + for (const [a, b] of edges) { + const i = a - 1; + const j = b - 1; + if (!x.has(i)) x.set(i, new Set()); + if (!x.has(j)) x.set(j, new Set()); + x.get(i)!.add(j); + x.get(j)!.add(i); + edge[i]++; + edge[j]++; + const key1 = `${i},${j}`; + const key2 = `${j},${i}`; + edgePair.set(key1, (edgePair.get(key1) || 0) + 1); + edgePair.set(key2, (edgePair.get(key2) || 0) + 1); + } + + const res = [...edge].sort((a, b) => a - b); + + function binse(threshold: number): number { + let i = 0; + let j = n - 1; + let ans = n; + while (i <= j) { + const mid = Math.floor((i + j) / 2); + if (res[mid] > threshold) { + ans = mid; + j = mid - 1; + } else { + i = mid + 1; + } + } + return n - ans; + } + + const result: number[] = []; + for (const query of queries) { + const v = new Set(); + let ans = 0; + + function f(i: number) { + v.add(i); + let a = binse(query - edge[i]); + + if (edge[i] > query - edge[i]) { + a--; + } + + for (const j of x.get(i) || []) { + if ( + edge[j] > query - edge[i] && + edge[j] - (edgePair.get(`${i},${j}`) || 0) <= query - edge[i] + ) { + a--; + } + if (!v.has(j)) { + f(j); + } + } + ans += a; + } + + for (let j = 0; j < n; j++) { + if (!v.has(j)) { + f(j); + } + } + result.push(Math.floor(ans / 2)); + } + + return result; +} diff --git a/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/manifest.yaml b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/manifest.yaml new file mode 100644 index 00000000..0f9ed602 --- /dev/null +++ b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/manifest.yaml @@ -0,0 +1,179 @@ +entry: + id: 1784 + title: "check-if-binary-string-has-at-most-one-segment-of-ones" + params: + s: + type: string + call: + cpp: "Solution().checkOnesSegment({s})" + rust: "Solution::check_ones_segment({s})" + python3: "Solution().checkOnesSegment({s})" + python2: "Solution().checkOnesSegment({s})" + ruby: "check_ones_segment({s})" + java: "new Solution().checkOnesSegment({s})" + csharp: "new Solution().CheckOnesSegment({s})" + kotlin: "Solution().checkOnesSegment({s})" + go: "checkOnesSegment({s})" + dart: "Solution().checkOnesSegment({s})" + swift: "Solution().checkOnesSegment({s})" + typescript: "checkOnesSegment({s})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().checkOnesSegment(s, {result})" + checker: | + class Checker: + def checkOnesSegment(self, s, result): + expected = "01" not in s + return result is expected + +seed: 1784 + +tests: + - name: example-two-segment + in: + s: "1001" + out: false + - name: example-single-segment + in: + s: "110" + out: true + - name: single-one + in: + s: "1" + out: true + - name: two-ones + in: + s: "11" + out: true + - name: one-zero + in: + s: "10" + out: true + - name: alternating-four + in: + s: "1010" + out: false + - name: alternating-five + in: + s: "10101" + out: false + - name: trailing-zeros + in: + s: "11100000" + out: true + - name: zero-between-ones + in: + s: "11011" + out: false + - name: one-zero-one + in: + s: "101" + out: false + - name: first-gap + in: + s: "100" + out: true + - name: second-gap + in: + s: "1100" + out: true + - name: late-second-segment + in: + s: "111011" + out: false + - name: single-zero-gap + in: + s: "1110111" + out: false + - name: long-first-segment + in: + s: "11111111110" + out: true + - name: long-second-segment + in: + s: "10000000001" + out: false + - name: zeros-before-end + in: + s: "1000000000" + out: true + - name: two-separated-pairs + in: + s: "110011" + out: false + - name: three-segments + in: + s: "1010101" + out: false + - name: one-block-with-middle-zeroes + in: + s: "111000" + out: true + - name: dense-false + in: + s: "11101110111" + out: false + - name: late-single-one + in: + s: "100000000001" + out: false + - name: leading-block-length-two + in: + s: "110000000001" + out: false + - name: leading-block-length-three + in: + s: "111000000001" + out: false + - name: one-gap-after-long-block + in: + s: "111111111101" + out: false + - name: two-zero-gap + in: + s: "11100111" + out: false + - name: three-zero-gap + in: + s: "111000111" + out: false + - name: only-leading-one + in: + s: "10000000000000000000" + out: true + - name: all-ones-twenty + in: + s: "11111111111111111111" + out: true + - name: alternating-long + in: + s: "10101010101010101010" + out: false + - name: late-block-long + in: + s: "1000000000000001111111111" + out: false + - name: one-block-length-five + in: + s: "1111100000000000000000000" + out: true + - name: two-blocks-length-five + in: + s: "111110000011111" + out: false + - name: max-length-one-block + in: + s: "1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001" + out: false + - name: max-length-trailing-zeroes + in: + s: "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111110" + out: true diff --git a/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.cpp b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.cpp new file mode 100644 index 00000000..fcfd704b --- /dev/null +++ b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + bool checkOnesSegment(string s) { + return s.find("01") == string::npos; + } +}; diff --git a/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.cs b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.cs new file mode 100644 index 00000000..20276213 --- /dev/null +++ b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.cs @@ -0,0 +1,5 @@ +public class Solution { + public bool CheckOnesSegment(string s) { + return !s.Contains("01"); + } +} diff --git a/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.dart b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.dart new file mode 100644 index 00000000..f9e66cae --- /dev/null +++ b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.dart @@ -0,0 +1,5 @@ +class Solution { + bool checkOnesSegment(String s) { + return !s.contains('01'); + } +} diff --git a/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.go b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.go new file mode 100644 index 00000000..66da7b2c --- /dev/null +++ b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.go @@ -0,0 +1,3 @@ +func checkOnesSegment(s string) bool { + return !strings.Contains(s, "01") +} diff --git a/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.java b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.java new file mode 100644 index 00000000..053b53fa --- /dev/null +++ b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.java @@ -0,0 +1,5 @@ +class Solution { + public boolean checkOnesSegment(String s) { + return !s.contains("01"); + } +} diff --git a/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.kt b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.kt new file mode 100644 index 00000000..8e195263 --- /dev/null +++ b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.kt @@ -0,0 +1,5 @@ +class Solution { + fun checkOnesSegment(s: String): Boolean { + return !s.contains("01") + } +} diff --git a/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.py b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.py new file mode 100644 index 00000000..8074f3e4 --- /dev/null +++ b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.py @@ -0,0 +1,3 @@ +class Solution: + def checkOnesSegment(self, s: str) -> bool: + return "01" not in s diff --git a/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.py2 b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.py2 new file mode 100644 index 00000000..c0eafb11 --- /dev/null +++ b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.py2 @@ -0,0 +1,7 @@ +class Solution(object): + def checkOnesSegment(self, s): + """ + :type s: str + :rtype: bool + """ + return "01" not in s diff --git a/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.rb b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.rb new file mode 100644 index 00000000..cb736f2e --- /dev/null +++ b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.rb @@ -0,0 +1,5 @@ +# @param {String} s +# @return {Boolean} +def check_ones_segment(s) + !s.include?("01") +end diff --git a/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.rs b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.rs new file mode 100644 index 00000000..d6407a09 --- /dev/null +++ b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.rs @@ -0,0 +1,5 @@ +impl Solution { + pub fn check_ones_segment(s: String) -> bool { + !s.contains("01") + } +} diff --git a/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.swift b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.swift new file mode 100644 index 00000000..49adf79d --- /dev/null +++ b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.swift @@ -0,0 +1,5 @@ +class Solution { + func checkOnesSegment(_ s: String) -> Bool { + return !s.contains("01") + } +} diff --git a/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.ts b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.ts new file mode 100644 index 00000000..90864814 --- /dev/null +++ b/tests/1501-2000/1784. check-if-binary-string-has-at-most-one-segment-of-ones/sol.ts @@ -0,0 +1,3 @@ +function checkOnesSegment(s: string): boolean { + return !s.includes("01"); +} diff --git a/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/manifest.yaml b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/manifest.yaml new file mode 100644 index 00000000..857aa4e4 --- /dev/null +++ b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/manifest.yaml @@ -0,0 +1,255 @@ +entry: + id: 1785 + title: "minimum-elements-to-add-to-form-a-given-sum" + params: + nums: + type: array + items: + type: int + limit: + type: int + goal: + type: int + call: + cpp: "Solution().minElements({nums}, {limit}, {goal})" + rust: "Solution::min_elements({nums}, {limit}, {goal})" + python3: "Solution().minElements({nums}, {limit}, {goal})" + python2: "Solution().minElements({nums}, {limit}, {goal})" + ruby: "min_elements({nums}, {limit}, {goal})" + java: "new Solution().minElements({nums}, {limit}, {goal})" + csharp: "new Solution().MinElements({nums}, {limit}, {goal})" + kotlin: "Solution().minElements({nums}, {limit}, {goal})" + go: "minElements({nums}, {limit}, {goal})" + dart: "Solution().minElements({nums}, {limit}, {goal})" + swift: "Solution().minElements({nums}, {limit}, {goal})" + typescript: "minElements({nums}, {limit}, {goal})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(nums, limit, goal, {result})" + checker: | + class Checker: + def check(self, nums, limit, goal, result): + expected = (abs(goal - sum(nums)) + limit - 1) // limit + return result == expected + +seed: 1785 + +tests: + - name: "example-negative-goal" + in: + nums: [1, -1, 1] + limit: 3 + goal: -4 + out: 2 + - name: "example-zero-difference" + in: + nums: [1, -10, 9, 1] + limit: 100 + goal: 0 + out: 1 + - name: "already-at-goal" + in: + nums: [2, -2, 7] + limit: 4 + goal: 7 + out: 0 + - name: "one-step-positive" + in: + nums: [0] + limit: 5 + goal: 5 + out: 1 + - name: "one-step-negative" + in: + nums: [0] + limit: 5 + goal: -5 + out: 1 + - name: "exact-multiple-positive" + in: + nums: [1, 2] + limit: 3 + goal: 10 + out: 3 + - name: "exact-multiple-negative" + in: + nums: [-1, -2] + limit: 3 + goal: -10 + out: 3 + - name: "remainder-needs-extra" + in: + nums: [0] + limit: 3 + goal: 7 + out: 3 + - name: "limit-one" + in: + nums: [1, -1, 1, -1] + limit: 1 + goal: 9 + out: 9 + - name: "large-limit-small-gap" + in: + nums: [100, -100] + limit: 1000000 + goal: 1 + out: 1 + - name: "large-limit-exact" + in: + nums: [1000000, -1000000] + limit: 1000000 + goal: -1000000 + out: 1 + - name: "all-positive" + in: + nums: [3, 3, 3, 3] + limit: 3 + goal: 0 + out: 4 + - name: "all-negative" + in: + nums: [-4, -4, -4] + limit: 4 + goal: 10 + out: 6 + - name: "mixed-canceling" + in: + nums: [5, -5, 4, -4] + limit: 5 + goal: 11 + out: 3 + - name: "single-max-positive" + in: + nums: [1000000] + limit: 1000000 + goal: 1000000000 + out: 999 + - name: "single-max-negative" + in: + nums: [-1000000] + limit: 1000000 + goal: -1000000000 + out: 999 + - name: "goal-minimum" + in: + nums: [1000000, 1000000] + limit: 1000000 + goal: -1000000000 + out: 1002 + - name: "goal-maximum" + in: + nums: [-1000000, -1000000] + limit: 1000000 + goal: 1000000000 + out: 1002 + - name: "odd-remainder" + in: + nums: [2, 2] + limit: 7 + goal: 20 + out: 3 + - name: "negative-remainder" + in: + nums: [-2, -2] + limit: 7 + goal: -20 + out: 3 + - name: "zero-limit-gap-impossible-not-applicable" + in: + nums: [1, 0, -1] + limit: 1 + goal: 0 + out: 0 + - name: "many-duplicates" + in: + nums: [2, 2, 2, 2, 2] + limit: 2 + goal: -9 + out: 10 + - name: "near-upper-goal" + in: + nums: [100, 100, -50] + limit: 100 + goal: 999 + out: 9 + - name: "near-lower-goal" + in: + nums: [-100, -100, 50] + limit: 100 + goal: -999 + out: 9 + - name: "large-sum-balanced" + in: + nums: [1000000, 1000000, -1000000, -1000000] + limit: 999999 + goal: 1000000000 + out: 1001 + - name: "small-limit-positive-gap" + in: + nums: [1, 1, 1] + limit: 2 + goal: 100 + out: 49 + - name: "small-limit-negative-gap" + in: + nums: [-1, -1, -1] + limit: 2 + goal: -100 + out: 49 + - name: "negative-current-to-positive-goal" + in: + nums: [-7, -6, -5] + limit: 10 + goal: 42 + out: 6 + - name: "positive-current-to-negative-goal" + in: + nums: [7, 6, 5] + limit: 10 + goal: -42 + out: 6 + - name: "single-zero-large-goal" + in: + nums: [0] + limit: 1000000 + goal: 999999999 + out: 1000 + - name: "single-zero-large-negative-goal" + in: + nums: [0] + limit: 1000000 + goal: -999999999 + out: 1000 + - name: "large-odd-length" + in: + nums: [1000000, -999999, 1000000, -999999, 1000000] + limit: 999999 + goal: -1000000000 + out: 1002 + - name: "large-negative-odd-length" + in: + nums: [-1000000, 999999, -1000000, 999999, -1000000] + limit: 999999 + goal: 1000000000 + out: 1002 + - name: "maximum-array-sum" + in: + nums: [1000000, 1000000, 1000000, 1000000, 1000000] + limit: 1000000 + goal: 1000000000 + out: 995 + - name: "minimum-array-sum" + in: + nums: [-1000000, -1000000, -1000000, -1000000, -1000000] + limit: 1000000 + goal: -1000000000 + out: 995 diff --git a/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.cpp b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.cpp new file mode 100644 index 00000000..10915b84 --- /dev/null +++ b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int minElements(vector& nums, int limit, int goal) { + long long currentSum = 0; + for (int num : nums) { + currentSum += num; + } + long long diff = std::abs((long long)goal - currentSum); + return (diff + limit - 1) / limit; + } +}; diff --git a/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.cs b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.cs new file mode 100644 index 00000000..ffc04a55 --- /dev/null +++ b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.cs @@ -0,0 +1,10 @@ +public class Solution { + public int MinElements(int[] nums, int limit, int goal) { + long currentSum = 0; + foreach (int num in nums) { + currentSum += num; + } + long diff = Math.Abs((long)goal - currentSum); + return (int)((diff + limit - 1) / limit); + } +} diff --git a/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.dart b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.dart new file mode 100644 index 00000000..4e0d6590 --- /dev/null +++ b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.dart @@ -0,0 +1,7 @@ +class Solution { + int minElements(List nums, int limit, int goal) { + int currentSum = nums.reduce((a, b) => a + b); + int diff = (goal - currentSum).abs(); + return (diff + limit - 1) ~/ limit; + } +} diff --git a/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.go b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.go new file mode 100644 index 00000000..ae49f0c0 --- /dev/null +++ b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.go @@ -0,0 +1,11 @@ +func minElements(nums []int, limit int, goal int) int { + currentSum := int64(0) + for _, num := range nums { + currentSum += int64(num) + } + diff := int64(goal) - currentSum + if diff < 0 { + diff = -diff + } + return int((diff + int64(limit) - 1) / int64(limit)) +} diff --git a/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.java b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.java new file mode 100644 index 00000000..62ed012a --- /dev/null +++ b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.java @@ -0,0 +1,10 @@ +class Solution { + public int minElements(int[] nums, int limit, int goal) { + long currentSum = 0; + for (int num : nums) { + currentSum += num; + } + long diff = Math.abs((long)goal - currentSum); + return (int)((diff + limit - 1) / limit); + } +} diff --git a/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.kt b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.kt new file mode 100644 index 00000000..1aa032f4 --- /dev/null +++ b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.kt @@ -0,0 +1,7 @@ +class Solution { + fun minElements(nums: IntArray, limit: Int, goal: Int): Int { + val currentSum = nums.sum().toLong() + val diff = Math.abs(goal.toLong() - currentSum) + return ((diff + limit - 1) / limit).toInt() + } +} diff --git a/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.py b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.py new file mode 100644 index 00000000..19c0a249 --- /dev/null +++ b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.py @@ -0,0 +1,11 @@ +class Solution(object): + def minElements(self, nums, limit, goal): + """ + :type nums: List[int] + :type limit: int + :type goal: int + :rtype: int + """ + current_sum = sum(nums) + diff = abs(goal - current_sum) + return (diff + limit - 1) // limit diff --git a/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.py2 b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.py2 new file mode 100644 index 00000000..19c0a249 --- /dev/null +++ b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def minElements(self, nums, limit, goal): + """ + :type nums: List[int] + :type limit: int + :type goal: int + :rtype: int + """ + current_sum = sum(nums) + diff = abs(goal - current_sum) + return (diff + limit - 1) // limit diff --git a/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.rb b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.rb new file mode 100644 index 00000000..59472183 --- /dev/null +++ b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.rb @@ -0,0 +1,9 @@ +# @param {Integer[]} nums +# @param {Integer} limit +# @param {Integer} goal +# @return {Integer} +def min_elements(nums, limit, goal) + current_sum = nums.sum + diff = (goal - current_sum).abs + (diff + limit - 1) / limit +end diff --git a/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.rs b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.rs new file mode 100644 index 00000000..119d5556 --- /dev/null +++ b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.rs @@ -0,0 +1,7 @@ +impl Solution { + pub fn min_elements(nums: Vec, limit: i32, goal: i32) -> i32 { + let current_sum: i64 = nums.iter().map(|&x| x as i64).sum(); + let diff = (goal as i64 - current_sum).abs(); + ((diff + limit as i64 - 1) / limit as i64) as i32 + } +} diff --git a/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.swift b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.swift new file mode 100644 index 00000000..af63da88 --- /dev/null +++ b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.swift @@ -0,0 +1,7 @@ +class Solution { + func minElements(_ nums: [Int], _ limit: Int, _ goal: Int) -> Int { + let currentSum = nums.reduce(0, +) + let diff = abs(goal - currentSum) + return (diff + limit - 1) / limit + } +} diff --git a/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.ts b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.ts new file mode 100644 index 00000000..da99ed71 --- /dev/null +++ b/tests/1501-2000/1785. minimum-elements-to-add-to-form-a-given-sum/sol.ts @@ -0,0 +1,5 @@ +function minElements(nums: number[], limit: number, goal: number): number { + const currentSum = nums.reduce((a, b) => a + b, 0); + const diff = Math.abs(goal - currentSum); + return Math.ceil(diff / limit); +} diff --git a/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/manifest.yaml b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/manifest.yaml new file mode 100644 index 00000000..83e8229d --- /dev/null +++ b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/manifest.yaml @@ -0,0 +1,609 @@ +entry: + id: 1786 + title: "number-of-restricted-paths-from-first-to-last-node" + params: + n: + type: int + edges: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().countRestrictedPaths({n}, {edges})" + rust: "Solution::count_restricted_paths({n}, {edges})" + python3: "Solution().countRestrictedPaths({n}, {edges})" + python2: "Solution().countRestrictedPaths({n}, {edges})" + ruby: "count_restricted_paths({n}, {edges})" + java: "new Solution().countRestrictedPaths({n}, {edges})" + csharp: "new Solution().CountRestrictedPaths({n}, {edges})" + kotlin: "Solution().countRestrictedPaths({n}, {edges})" + go: "countRestrictedPaths({n}, {edges})" + dart: "Solution().countRestrictedPaths({n}, {edges})" + swift: "Solution().countRestrictedPaths({n}, {edges})" + typescript: "countRestrictedPaths({n}, {edges})" + +judge: + type: "exact" + +limits: + time_ms: 10000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().check(n, edges, {result})" + checker: | + import heapq + class Checker: + def check(self, n, edges, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if n < 1 or len(edges) < n - 1: + return False + graph = [[] for _ in range(n + 1)] + seen = set() + for edge in edges: + if not isinstance(edge, list) or len(edge) != 3: + return False + u, v, w = edge + if not (1 <= u <= n and 1 <= v <= n and u != v and 1 <= w <= 100000): + return False + key = (min(u, v), max(u, v)) + if key in seen: + return False + seen.add(key) + graph[u].append((v, w)) + graph[v].append((u, w)) + dist = [10**30] * (n + 1) + dist[n] = 0 + heap = [(0, n)] + while heap: + d, u = heapq.heappop(heap) + if d != dist[u]: + continue + for v, w in graph[u]: + nd = d + w + if nd < dist[v]: + dist[v] = nd + heapq.heappush(heap, (nd, v)) + if any(dist[i] >= 10**30 for i in range(1, n + 1)): + return False + dp = [0] * (n + 1) + dp[n] = 1 + for u in sorted(range(1, n + 1), key=lambda x: dist[x]): + for v, _ in graph[u]: + if dist[u] > dist[v]: + dp[u] = (dp[u] + dp[v]) % 1000000007 + return result == dp[1] + +seed: 1786 + +tests: + - name: example-one + in: + n: 5 + edges: + - [1, 2, 3] + - [1, 3, 3] + - [2, 3, 1] + - [1, 4, 2] + - [5, 2, 2] + - [3, 5, 1] + - [5, 4, 10] + - name: example-two + in: + n: 7 + edges: + - [1, 3, 1] + - [4, 1, 2] + - [7, 3, 4] + - [2, 5, 3] + - [5, 6, 1] + - [6, 7, 2] + - [7, 5, 3] + - [2, 6, 4] + - name: single-node + in: + n: 1 + edges: [] + - name: single-edge + in: + n: 2 + edges: + - [1, 2, 7] + - name: chain-three + in: + n: 3 + edges: + - [1, 2, 1] + - [2, 3, 1] + - name: chain-four + in: + n: 4 + edges: + - [1, 2, 4] + - [2, 3, 3] + - [3, 4, 2] + - name: weighted-chain + in: + n: 5 + edges: + - [1, 2, 10] + - [2, 3, 1] + - [3, 4, 20] + - [4, 5, 2] + - name: direct-shortcut + in: + n: 4 + edges: + - [1, 2, 1] + - [2, 4, 1] + - [1, 3, 5] + - [3, 4, 1] + - [1, 4, 10] + - name: equal-distance-branch + in: + n: 4 + edges: + - [1, 2, 1] + - [1, 3, 1] + - [2, 4, 1] + - [3, 4, 1] + - name: triangle + in: + n: 3 + edges: + - [1, 2, 1] + - [2, 3, 1] + - [1, 3, 1] + - name: diamond + in: + n: 5 + edges: + - [1, 2, 1] + - [1, 3, 1] + - [2, 4, 1] + - [3, 4, 1] + - [4, 5, 1] + - [2, 5, 5] + - [3, 5, 5] + - name: unequal-branch + in: + n: 5 + edges: + - [1, 2, 2] + - [1, 3, 4] + - [2, 4, 2] + - [3, 4, 1] + - [4, 5, 2] + - name: zero-restricted-branch + in: + n: 5 + edges: + - [1, 2, 1] + - [2, 5, 10] + - [1, 3, 5] + - [3, 4, 1] + - [4, 5, 1] + - [2, 3, 1] + - name: six-cycle + in: + n: 6 + edges: + - [1, 2, 1] + - [2, 3, 1] + - [3, 4, 1] + - [4, 5, 1] + - [5, 6, 1] + - [6, 1, 1] + - name: cycle-with-chord + in: + n: 6 + edges: + - [1, 2, 2] + - [2, 3, 2] + - [3, 4, 2] + - [4, 5, 2] + - [5, 6, 2] + - [6, 1, 2] + - [1, 4, 1] + - name: star + in: + n: 6 + edges: + - [1, 2, 1] + - [1, 3, 2] + - [1, 4, 3] + - [1, 5, 4] + - [1, 6, 5] + - name: star-to-last + in: + n: 6 + edges: + - [1, 2, 1] + - [2, 6, 1] + - [1, 3, 1] + - [3, 6, 1] + - [1, 4, 1] + - [4, 6, 1] + - [1, 5, 10] + - [5, 6, 1] + - name: complete-four + in: + n: 4 + edges: + - [1, 2, 1] + - [1, 3, 2] + - [1, 4, 3] + - [2, 3, 1] + - [2, 4, 2] + - [3, 4, 1] + - name: complete-five + in: + n: 5 + edges: + - [1, 2, 1] + - [1, 3, 2] + - [1, 4, 3] + - [1, 5, 4] + - [2, 3, 1] + - [2, 4, 2] + - [2, 5, 3] + - [3, 4, 1] + - [3, 5, 2] + - [4, 5, 1] + - name: layered-1 + in: + n: 7 + edges: + - [1, 2, 1] + - [1, 3, 1] + - [2, 4, 1] + - [2, 5, 1] + - [3, 6, 1] + - [3, 7, 1] + - [4, 7, 3] + - [5, 6, 3] + - name: layered-2 + in: + n: 8 + edges: + - [1, 2, 1] + - [1, 3, 2] + - [2, 4, 1] + - [2, 5, 2] + - [3, 5, 1] + - [3, 6, 2] + - [4, 7, 1] + - [5, 7, 1] + - [5, 8, 2] + - [6, 8, 1] + - [7, 8, 1] + - name: tie-distances + in: + n: 6 + edges: + - [1, 2, 3] + - [1, 3, 3] + - [2, 4, 2] + - [3, 4, 2] + - [4, 5, 1] + - [4, 6, 1] + - [5, 6, 1] + - name: large-weight-chain + in: + n: 6 + edges: + - [1, 2, 100000] + - [2, 3, 99999] + - [3, 4, 100000] + - [4, 5, 99998] + - [5, 6, 100000] + - name: large-weight-shortcut + in: + n: 5 + edges: + - [1, 2, 100000] + - [2, 5, 100000] + - [1, 3, 99999] + - [3, 4, 1] + - [4, 5, 99999] + - name: seven-chain-chords + in: + n: 7 + edges: + - [1, 2, 2] + - [2, 3, 2] + - [3, 4, 2] + - [4, 5, 2] + - [5, 6, 2] + - [6, 7, 2] + - [1, 4, 5] + - [2, 5, 5] + - [3, 6, 5] + - [4, 7, 5] + - name: eight-grid-like + in: + n: 8 + edges: + - [1, 2, 1] + - [1, 3, 1] + - [2, 4, 1] + - [3, 4, 1] + - [3, 5, 2] + - [4, 6, 2] + - [5, 6, 1] + - [5, 7, 1] + - [6, 8, 1] + - [7, 8, 1] + - name: ten-chain + in: + n: 10 + edges: + - [1, 2, 1] + - [2, 3, 2] + - [3, 4, 3] + - [4, 5, 4] + - [5, 6, 5] + - [6, 7, 6] + - [7, 8, 7] + - [8, 9, 8] + - [9, 10, 9] + - [1, 10, 100] + - name: ten-many-branches + in: + n: 10 + edges: + - [1, 2, 1] + - [1, 3, 2] + - [1, 4, 3] + - [2, 5, 1] + - [2, 6, 2] + - [3, 6, 1] + - [3, 7, 2] + - [4, 7, 1] + - [4, 8, 2] + - [5, 9, 1] + - [6, 9, 1] + - [6, 10, 2] + - [7, 10, 1] + - [8, 10, 1] + - name: eleven-ladder + in: + n: 11 + edges: + - [1, 2, 1] + - [2, 3, 1] + - [3, 4, 1] + - [4, 5, 1] + - [5, 6, 1] + - [6, 7, 1] + - [7, 8, 1] + - [8, 9, 1] + - [9, 10, 1] + - [10, 11, 1] + - [1, 6, 2] + - [2, 7, 2] + - [3, 8, 2] + - [4, 9, 2] + - [5, 10, 2] + - name: twelve-balanced + in: + n: 12 + edges: + - [1, 2, 1] + - [1, 3, 2] + - [2, 4, 1] + - [2, 5, 2] + - [3, 5, 1] + - [3, 6, 2] + - [4, 7, 1] + - [5, 7, 1] + - [5, 8, 2] + - [6, 8, 1] + - [7, 9, 1] + - [8, 9, 1] + - [8, 10, 2] + - [9, 11, 1] + - [10, 11, 1] + - [10, 12, 2] + - [11, 12, 1] + - name: thirteen-dense + in: + n: 13 + edges: + - [1, 2, 1] + - [1, 3, 2] + - [1, 4, 3] + - [2, 5, 1] + - [2, 6, 2] + - [3, 6, 1] + - [3, 7, 2] + - [4, 7, 1] + - [4, 8, 2] + - [5, 9, 1] + - [6, 9, 1] + - [6, 10, 2] + - [7, 10, 1] + - [7, 11, 2] + - [8, 11, 1] + - [9, 12, 1] + - [10, 12, 1] + - [10, 13, 2] + - [11, 13, 1] + - [12, 13, 1] + - name: fourteen-long + in: + n: 14 + edges: + - [1, 2, 1] + - [2, 3, 1] + - [3, 4, 1] + - [4, 5, 1] + - [5, 6, 1] + - [6, 7, 1] + - [7, 8, 1] + - [8, 9, 1] + - [9, 10, 1] + - [10, 11, 1] + - [11, 12, 1] + - [12, 13, 1] + - [13, 14, 1] + - [1, 7, 10] + - [4, 10, 10] + - [7, 14, 10] + - name: fifteen-two-routes + in: + n: 15 + edges: + - [1, 2, 1] + - [1, 3, 1] + - [2, 4, 1] + - [3, 5, 1] + - [4, 6, 1] + - [5, 6, 1] + - [6, 7, 1] + - [7, 8, 1] + - [7, 9, 1] + - [8, 10, 1] + - [9, 11, 1] + - [10, 12, 1] + - [11, 13, 1] + - [12, 14, 1] + - [13, 15, 1] + - [14, 15, 1] + - [1, 15, 100] + - name: sixteen-mixed + in: + n: 16 + edges: + - [1, 2, 2] + - [1, 3, 3] + - [2, 4, 2] + - [2, 5, 3] + - [3, 5, 2] + - [3, 6, 3] + - [4, 7, 2] + - [5, 7, 2] + - [5, 8, 3] + - [6, 8, 2] + - [7, 9, 2] + - [8, 9, 2] + - [8, 10, 3] + - [9, 11, 2] + - [10, 11, 2] + - [10, 12, 3] + - [11, 13, 2] + - [12, 13, 2] + - [12, 14, 3] + - [13, 15, 2] + - [14, 15, 2] + - [15, 16, 1] + - name: seventeen-heavy-weights + in: + n: 17 + edges: + - [1, 2, 100000] + - [2, 3, 1] + - [3, 4, 100000] + - [4, 5, 1] + - [5, 6, 100000] + - [6, 7, 1] + - [7, 8, 100000] + - [8, 9, 1] + - [9, 10, 100000] + - [10, 11, 1] + - [11, 12, 100000] + - [12, 13, 1] + - [13, 14, 100000] + - [14, 15, 1] + - [15, 16, 100000] + - [16, 17, 1] + - [1, 17, 100000] + - name: eighteen-wide + in: + n: 18 + edges: + - [1, 2, 1] + - [1, 3, 1] + - [1, 4, 1] + - [2, 5, 1] + - [2, 6, 1] + - [3, 6, 1] + - [3, 7, 1] + - [4, 7, 1] + - [4, 8, 1] + - [5, 9, 1] + - [6, 9, 1] + - [6, 10, 1] + - [7, 10, 1] + - [7, 11, 1] + - [8, 11, 1] + - [9, 12, 1] + - [10, 12, 1] + - [10, 13, 1] + - [11, 13, 1] + - [12, 14, 1] + - [13, 14, 1] + - [14, 15, 1] + - [14, 16, 1] + - [15, 17, 1] + - [16, 17, 1] + - [17, 18, 1] + - name: nineteen-ladder + in: + n: 19 + edges: + - [1, 2, 1] + - [2, 3, 1] + - [3, 4, 1] + - [4, 5, 1] + - [5, 6, 1] + - [6, 7, 1] + - [7, 8, 1] + - [8, 9, 1] + - [9, 10, 1] + - [10, 11, 1] + - [11, 12, 1] + - [12, 13, 1] + - [13, 14, 1] + - [14, 15, 1] + - [15, 16, 1] + - [16, 17, 1] + - [17, 18, 1] + - [18, 19, 1] + - [1, 10, 3] + - [10, 19, 3] + - name: twenty-balanced + in: + n: 20 + edges: + - [1, 2, 1] + - [1, 3, 1] + - [2, 4, 1] + - [2, 5, 1] + - [3, 6, 1] + - [3, 7, 1] + - [4, 8, 1] + - [5, 8, 1] + - [5, 9, 1] + - [6, 9, 1] + - [6, 10, 1] + - [7, 10, 1] + - [8, 11, 1] + - [9, 11, 1] + - [9, 12, 1] + - [10, 12, 1] + - [11, 13, 1] + - [12, 13, 1] + - [13, 14, 1] + - [13, 15, 1] + - [14, 16, 1] + - [15, 17, 1] + - [16, 18, 1] + - [17, 18, 1] + - [18, 19, 1] + - [18, 20, 1] + - [19, 20, 1] diff --git a/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.cpp b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.cpp new file mode 100644 index 00000000..75805184 --- /dev/null +++ b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + int countRestrictedPaths(int n, vector>& edges) { + const int MOD = 1'000'000'007; + vector>> graph(n + 1); + for (auto& e : edges) { + graph[e[0]].push_back({e[1], e[2]}); + graph[e[1]].push_back({e[0], e[2]}); + } + + const long long INF = 1e18; + vector dist(n + 1, INF); + dist[n] = 0; + priority_queue, vector>, greater<>> pq; + pq.push({0, n}); + while (!pq.empty()) { + auto [d, node] = pq.top(); pq.pop(); + if (d > dist[node]) continue; + for (auto& [next, w] : graph[node]) { + long long nd = d + w; + if (nd < dist[next]) { + dist[next] = nd; + pq.push({nd, next}); + } + } + } + + vector dp(n + 1, 0); + dp[n] = 1; + vector nodes(n); + iota(nodes.begin(), nodes.end(), 1); + sort(nodes.begin(), nodes.end(), [&](int a, int b) { + return dist[a] < dist[b]; + }); + for (int u : nodes) { + for (auto& [v, w] : graph[u]) { + if (dist[u] > dist[v]) { + dp[u] = (dp[u] + dp[v]) % MOD; + } + } + } + return (int)(dp[1] % MOD); + } +}; diff --git a/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.cs b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.cs new file mode 100644 index 00000000..dee149e3 --- /dev/null +++ b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.cs @@ -0,0 +1,43 @@ +public class Solution { + public int CountRestrictedPaths(int n, int[][] edges) { + const int MOD = 1_000_000_007; + var graph = new List<(int, int)>[n + 1]; + for (int i = 0; i <= n; i++) graph[i] = new List<(int, int)>(); + foreach (var e in edges) { + graph[e[0]].Add((e[1], e[2])); + graph[e[1]].Add((e[0], e[2])); + } + + var dist = new long[n + 1]; + Array.Fill(dist, long.MaxValue); + dist[n] = 0; + var pq = new SortedSet<(long, int)>(); + pq.Add((0, n)); + while (pq.Count > 0) { + var cur = pq.Min; pq.Remove(cur); + long d = cur.Item1; int node = cur.Item2; + if (d > dist[node]) continue; + foreach (var (next, w) in graph[node]) { + long nd = d + w; + if (nd < dist[next]) { + dist[next] = nd; + pq.Add((nd, next)); + } + } + } + + var dp = new long[n + 1]; + dp[n] = 1; + var nodes = new int[n]; + for (int i = 1; i <= n; i++) nodes[i-1] = i; + Array.Sort(nodes, (a, b) => dist[a].CompareTo(dist[b])); + foreach (int u in nodes) { + foreach (var (v, _) in graph[u]) { + if (dist[u] > dist[v]) { + dp[u] = (dp[u] + dp[v]) % MOD; + } + } + } + return (int)(dp[1] % MOD); + } +} diff --git a/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.dart b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.dart new file mode 100644 index 00000000..bdd4a24c --- /dev/null +++ b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.dart @@ -0,0 +1,42 @@ +class Solution { + int countRestrictedPaths(int n, List> edges) { + const mod = 1000000007; + List>> graph = List.generate(n + 1, (_) => []); + for (var e in edges) { + graph[e[0]].add([e[1], e[2]]); + graph[e[1]].add([e[0], e[2]]); + } + + List dist = List.filled(n + 1, 1 << 60); + dist[n] = 0; + var heap = PriorityQueue>((a, b) => a[0].compareTo(b[0])); + heap.add([0, n]); + while (heap.isNotEmpty) { + var cur = heap.removeFirst(); + int d = cur[0], node = cur[1]; + if (d > dist[node]) continue; + for (var nb in graph[node]) { + int next = nb[0], w = nb[1]; + int nd = d + w; + if (nd < dist[next]) { + dist[next] = nd; + heap.add([nd, next]); + } + } + } + + List dp = List.filled(n + 1, 0); + dp[n] = 1; + List nodes = List.generate(n, (i) => i + 1); + nodes.sort((a, b) => dist[a] - dist[b]); + for (int u in nodes) { + for (var nb in graph[u]) { + int v = nb[0]; + if (dist[u] > dist[v]) { + dp[u] = (dp[u] + dp[v]) % mod; + } + } + } + return dp[1]; + } +} diff --git a/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.go b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.go new file mode 100644 index 00000000..3b17d297 --- /dev/null +++ b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.go @@ -0,0 +1,54 @@ +func countRestrictedPaths(n int, edges [][]int) int { + const mod = 1000000007 + graph := make([][][2]int, n+1) + for _, e := range edges { + graph[e[0]] = append(graph[e[0]], [2]int{e[1], e[2]}) + graph[e[1]] = append(graph[e[1]], [2]int{e[0], e[2]}) + } + + dist := make([]int, n+1) + for i := range dist { + dist[i] = int(^uint(0) >> 1) + } + dist[n] = 0 + pq := [][2]int{{0, n}} + for len(pq) > 0 { + best := 0 + for i := 1; i < len(pq); i++ { if pq[i][0] < pq[best][0] { best = i } } + top := pq[best] + pq[best] = pq[len(pq)-1] + pq = pq[:len(pq)-1] + d, node := top[0], top[1] + if d > dist[node] { + continue + } + for _, nb := range graph[node] { + next, w := nb[0], nb[1] + nd := d + w + if nd < dist[next] { + dist[next] = nd + pq = append(pq, [2]int{nd, next}) + } + } + } + + dp := make([]int64, n+1) + dp[n] = 1 + nodes := make([]int, n) + for i := 1; i <= n; i++ { + nodes[i-1] = i + } + sort.Slice(nodes, func(i, j int) bool { + return dist[nodes[i]] < dist[nodes[j]] + }) + for _, u := range nodes { + for _, nb := range graph[u] { + v := nb[0] + if dist[u] > dist[v] { + dp[u] = (dp[u] + dp[v]) % int64(mod) + } + } + } + return int(dp[1] % int64(mod)) +} + diff --git a/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.java b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.java new file mode 100644 index 00000000..66c1d441 --- /dev/null +++ b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.java @@ -0,0 +1,45 @@ +class Solution { + @SuppressWarnings("unchecked") + public int countRestrictedPaths(int n, int[][] edges) { + final int mod = 1_000_000_007; + List[] graph = new ArrayList[n + 1]; + for (int i = 0; i <= n; i++) graph[i] = new ArrayList<>(); + for (int[] e : edges) { + graph[e[0]].add(new int[]{e[1], e[2]}); + graph[e[1]].add(new int[]{e[0], e[2]}); + } + + int[] dist = new int[n + 1]; + Arrays.fill(dist, Integer.MAX_VALUE); + dist[n] = 0; + PriorityQueue pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0])); + pq.offer(new int[]{0, n}); + while (!pq.isEmpty()) { + int[] cur = pq.poll(); + int d = cur[0], node = cur[1]; + if (d > dist[node]) continue; + for (int[] nb : graph[node]) { + int next = nb[0], w = nb[1]; + int nd = d + w; + if (nd < dist[next]) { + dist[next] = nd; + pq.offer(new int[]{nd, next}); + } + } + } + + long[] dp = new long[n + 1]; + dp[n] = 1; + Integer[] order = new Integer[n]; + for (int i = 0; i < n; i++) order[i] = i + 1; + Arrays.sort(order, (a, b) -> Integer.compare(dist[a], dist[b])); + for (int u : order) { + for (int[] edge : graph[u]) { + if (dist[u] > dist[edge[0]]) { + dp[u] = (dp[u] + dp[edge[0]]) % mod; + } + } + } + return (int) dp[1]; + } +} diff --git a/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.kt b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.kt new file mode 100644 index 00000000..762c0089 --- /dev/null +++ b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.kt @@ -0,0 +1,38 @@ +class Solution { + fun countRestrictedPaths(n: Int, edges: Array): Int { + val mod = 1_000_000_007 + val graph = Array(n + 1) { mutableListOf>() } + for (e in edges) { + graph[e[0]].add(e[1] to e[2]) + graph[e[1]].add(e[0] to e[2]) + } + + val dist = IntArray(n + 1) { Int.MAX_VALUE } + dist[n] = 0 + val pq = PriorityQueue>(compareBy { it.first }) + pq.add(0 to n) + while (pq.isNotEmpty()) { + val (d, node) = pq.poll() + if (d > dist[node]) continue + for ((next, w) in graph[node]) { + val nd = d + w + if (nd < dist[next]) { + dist[next] = nd + pq.add(nd to next) + } + } + } + + val dp = LongArray(n + 1) + dp[n] = 1 + val nodes = (1..n).sortedBy { dist[it] } + for (u in nodes) { + for ((v, _) in graph[u]) { + if (dist[u] > dist[v]) { + dp[u] = (dp[u] + dp[v]) % mod + } + } + } + return (dp[1] % mod).toInt() + } +} diff --git a/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.py b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.py new file mode 100644 index 00000000..6fdb74b4 --- /dev/null +++ b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.py @@ -0,0 +1,36 @@ +class Solution: + def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int: + mod = 10**9 + 7 + graph = {} + for u, v, w in edges: + if u not in graph: + graph[u] = [] + graph[u].append((v, w)) + if v not in graph: + graph[v] = [] + graph[v].append((u, w)) + + dist = [float("inf")] * (n + 1) + dist[n] = 0 + heap = [] + heapq.heappush(heap, (0, n)) + + while heap: + curr_dist, node = heapq.heappop(heap) + if curr_dist > dist[node]: + continue + for next_node, weight in graph.get(node, []): + new_dist = weight + curr_dist + if new_dist < dist[next_node]: + dist[next_node] = new_dist + heapq.heappush(heap, (new_dist, next_node)) + + dp = [0] * (n + 1) + dp[n] = 1 + nodes = list(range(1, n + 1)) + nodes.sort(key=lambda x: dist[x]) + for u in nodes: + for v, w in graph.get(u, []): + if dist[u] > dist[v]: + dp[u] = (dp[u] + dp[v]) % mod + return dp[1] diff --git a/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.py2 b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.py2 new file mode 100644 index 00000000..bc9716ce --- /dev/null +++ b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.py2 @@ -0,0 +1,41 @@ +class Solution(object): + def countRestrictedPaths(self, n, edges): + """ + :type n: int + :type edges: List[List[int]] + :rtype: int + """ + mod = 10**9 + 7 + graph = {} + for u, v, w in edges: + if u not in graph: + graph[u] = [] + graph[u].append((v, w)) + if v not in graph: + graph[v] = [] + graph[v].append((u, w)) + + dist = [float('inf')] * (n + 1) + dist[n] = 0 + heap = [] + heapq.heappush(heap, (0, n)) + + while heap: + curr_dist, node = heapq.heappop(heap) + if curr_dist > dist[node]: + continue + for next_node, weight in graph.get(node, []): + new_dist = weight + curr_dist + if new_dist < dist[next_node]: + dist[next_node] = new_dist + heapq.heappush(heap, (new_dist, next_node)) + + dp = [0] * (n + 1) + dp[n] = 1 + nodes = list(range(1, n+1)) + nodes.sort(key=lambda x: dist[x]) + for u in nodes: + for v, w in graph.get(u, []): + if dist[u] > dist[v]: + dp[u] = (dp[u] + dp[v]) % mod + return dp[1] diff --git a/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.rb b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.rb new file mode 100644 index 00000000..c0ab041c --- /dev/null +++ b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.rb @@ -0,0 +1,39 @@ +# @param {Integer} n +# @param {Integer[][]} edges +# @return {Integer} +def count_restricted_paths(n, edges) + mod = 10**9 + 7 + graph = Hash.new { |h, k| h[k] = [] } + edges.each do |u, v, w| + graph[u] << [v, w] + graph[v] << [u, w] + end + + dist = Array.new(n + 1, Float::INFINITY) + dist[n] = 0 + heap = [[0, n]] + while !heap.empty? + curr_dist, node = heap.shift + next if curr_dist > dist[node] + graph[node].each do |next_node, weight| + new_dist = weight + curr_dist + if new_dist < dist[next_node] + dist[next_node] = new_dist + heap << [new_dist, next_node] + heap.sort_by! { |a| a[0] } + end + end + end + + dp = Array.new(n + 1, 0) + dp[n] = 1 + nodes = (1..n).to_a.sort_by { |x| dist[x] } + nodes.each do |u| + graph[u].each do |v, w| + if dist[u] > dist[v] + dp[u] = (dp[u] + dp[v]) % mod + end + end + end + dp[1] +end diff --git a/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.rs b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.rs new file mode 100644 index 00000000..47854dd1 --- /dev/null +++ b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.rs @@ -0,0 +1,42 @@ +impl Solution { + pub fn count_restricted_paths(n: i32, edges: Vec>) -> i32 { + let n = n as usize; + const MOD: i64 = 1_000_000_007; + let mut graph: Vec> = vec![vec![]; n + 1]; + for e in &edges { + let (u, v, w) = (e[0] as usize, e[1] as usize, e[2]); + graph[u].push((v, w)); + graph[v].push((u, w)); + } + + let mut dist = vec![i64::MAX; n + 1]; + dist[n] = 0; + use std::collections::BinaryHeap; + use std::cmp::Reverse; + let mut heap: BinaryHeap<(Reverse, usize)> = BinaryHeap::new(); + heap.push((Reverse(0), n)); + while let Some((Reverse(d), node)) = heap.pop() { + if d > dist[node] { continue } + for &(next, w) in &graph[node] { + let nd = d + w as i64; + if nd < dist[next] { + dist[next] = nd; + heap.push((Reverse(nd), next)); + } + } + } + + let mut dp = vec![0i64; n + 1]; + dp[n] = 1; + let mut nodes: Vec = (1..=n).collect(); + nodes.sort_by(|&a, &b| dist[a].cmp(&dist[b])); + for u in nodes { + for &(v, _) in &graph[u] { + if dist[u] > dist[v] { + dp[u] = (dp[u] + dp[v]) % MOD; + } + } + } + (dp[1] % MOD) as i32 + } +} diff --git a/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.swift b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.swift new file mode 100644 index 00000000..8b23e4bd --- /dev/null +++ b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.swift @@ -0,0 +1,40 @@ +class Solution { + func countRestrictedPaths(_ n: Int, _ edges: [[Int]]) -> Int { + let mod = 1_000_000_007 + var graph = [[(Int, Int)]](repeating: [], count: n + 1) + for e in edges { + graph[e[0]].append((e[1], e[2])) + graph[e[1]].append((e[0], e[2])) + } + + var dist = [Int](repeating: Int.max, count: n + 1) + dist[n] = 0 + var heap = [(Int, Int)]() + heap.append((0, n)) + while !heap.isEmpty { + let sorted = heap.sorted { $0.0 < $1.0 } + heap = sorted + let (d, node) = heap.removeFirst() + if d > dist[node] { continue } + for (next, w) in graph[node] { + let nd = d + w + if nd < dist[next] { + dist[next] = nd + heap.append((nd, next)) + } + } + } + + var dp = [Int](repeating: 0, count: n + 1) + dp[n] = 1 + let nodes = (1...n).sorted { dist[$0] < dist[$1] } + for u in nodes { + for (v, _) in graph[u] { + if dist[u] > dist[v] { + dp[u] = (dp[u] + dp[v]) % mod + } + } + } + return dp[1] + } +} diff --git a/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.ts b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.ts new file mode 100644 index 00000000..7e475d70 --- /dev/null +++ b/tests/1501-2000/1786. number-of-restricted-paths-from-first-to-last-node/sol.ts @@ -0,0 +1,38 @@ +function countRestrictedPaths(n: number, edges: number[][]): number { + const mod = 1_000_000_007; + const graph: [number, number][][] = Array.from({ length: n + 1 }, () => []); + for (const e of edges) { + graph[e[0]].push([e[1], e[2]]); + graph[e[1]].push([e[0], e[2]]); + } + + const dist: number[] = Array(n + 1).fill(Infinity); + dist[n] = 0; + const pq: [number, number][] = [[0, n]]; + while (pq.length) { + pq.sort((a, b) => a[0] - b[0]); + const [d, node] = pq.shift()!; + if (d > dist[node]) continue; + for (const [next, w] of graph[node]) { + const nd = d + w; + if (nd < dist[next]) { + dist[next] = nd; + pq.push([nd, next]); + } + } + } + + const dp: number[] = Array(n + 1).fill(0); + dp[n] = 1; + const nodes = Array.from({ length: n }, (_, i) => i + 1).sort( + (a, b) => dist[a] - dist[b], + ); + for (const u of nodes) { + for (const [v] of graph[u]) { + if (dist[u] > dist[v]) { + dp[u] = (dp[u] + dp[v]) % mod; + } + } + } + return dp[1]; +} diff --git a/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/manifest.yaml b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/manifest.yaml new file mode 100644 index 00000000..84dcabbe --- /dev/null +++ b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/manifest.yaml @@ -0,0 +1,247 @@ +entry: + id: 1787 + title: make-the-xor-of-all-segments-equal-to-zero + params: + nums: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().minChanges({nums}, {k})" + rust: "Solution::min_changes({nums}, {k})" + python3: "Solution().minChanges({nums}, {k})" + python2: "Solution().minChanges({nums}, {k})" + ruby: "min_changes({nums}, {k})" + java: "new Solution().minChanges({nums}, {k})" + csharp: "new Solution().MinChanges({nums}, {k})" + kotlin: "Solution().minChanges({nums}, {k})" + go: "minChanges({nums}, {k})" + dart: "Solution().minChanges({nums}, {k})" + swift: "Solution().minChanges({nums}, {k})" + typescript: "minChanges({nums}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 5000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minChanges(nums, k, {result})" + checker: | + from collections import Counter + + class Checker: + def minChanges(self, nums, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + width = 1 << 10 + dp = [-10**9] * width + dp[0] = 0 + for group in range(k): + counts = Counter(nums[group::k]) + best = max(dp) + ndp = [best] * width + for state, score in enumerate(dp): + if score < 0: + continue + for value, count in counts.items(): + nxt = state ^ value + if score + count > ndp[nxt]: + ndp[nxt] = score + count + dp = ndp + expected = len(nums) - dp[0] + return result == expected + +seed: 1787 + +tests: + - name: single-zero-k-one + in: + nums: [0] + k: 1 + - name: single-nonzero-k-one + in: + nums: [1023] + k: 1 + - name: all-zeroes + in: + nums: [0, 0, 0, 0, 0, 0] + k: 3 + - name: example-one + in: + nums: [1, 2, 0, 3, 0] + k: 1 + - name: example-two + in: + nums: [3, 4, 5, 2, 1, 7, 3, 4, 7] + k: 3 + - name: example-three + in: + nums: [1, 2, 4, 1, 2, 5, 1, 2, 6] + k: 3 + - name: k-equals-n + in: + nums: [1, 2, 4, 8, 16] + k: 5 + - name: k-equals-n-already-zero + in: + nums: [7, 7, 0, 7] + k: 4 + - name: k-one-mixed + in: + nums: [5, 5, 5, 4, 4, 7, 7, 7] + k: 1 + - name: k-one-distinct + in: + nums: [0, 1, 2, 3, 4, 5, 6] + k: 1 + - name: two-groups-equal + in: + nums: [1, 2, 1, 2, 1, 2] + k: 2 + - name: two-groups-unequal + in: + nums: [1, 1, 2, 3, 4, 5, 6] + k: 2 + - name: three-groups-repeated + in: + nums: [1, 2, 3, 1, 2, 3, 1, 2, 3, 4] + k: 3 + - name: zeros-and-high-values + in: + nums: [0, 1023, 0, 1023, 512, 512, 1, 1] + k: 4 + - name: repeated-power-pattern + in: + nums: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] + k: 2 + - name: duplicate-heavy + in: + nums: [9, 9, 9, 10, 10, 11, 11, 11, 11, 12] + k: 4 + - name: alternating + in: + nums: [0, 1023, 0, 1023, 0, 1023, 0, 1023, 0] + k: 3 + - name: xor-cancellation + in: + nums: [6, 6, 6, 6, 6, 6, 6, 6] + k: 4 + - name: small-values-all-groups + in: + nums: [0, 1, 2, 3, 0, 1, 2, 3, 3, 2, 1, 0] + k: 4 + - name: irregular-remainder + in: + nums: [8, 1, 8, 2, 8, 3, 8, 4, 8, 5, 8] + k: 5 + - name: max-value-single-group + in: + nums: [1023, 1023, 1023, 0, 0, 1, 1] + k: 3 + - name: all-values-distinct-groups + in: + nums: [0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1023] + k: 6 + - name: balanced-four-groups + in: + nums: [1, 2, 4, 8, 1, 2, 4, 8, 8, 4, 2, 1] + k: 4 + - name: mostly-zero + in: + nums: [0, 0, 0, 0, 0, 0, 31, 0, 0, 0, 0, 0, 0] + k: 6 + - name: high-bit-combinations + in: + nums: [768, 512, 256, 768, 512, 256, 1023, 511, 255] + k: 3 + - name: prime-like-values + in: + nums: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + k: 5 + - name: long-small-static + in: + nums: [0, 1, 0, 1, 2, 3, 2, 3, 4, 5, 4, 5, 6, 7, 6, 7, 8, 9, 8, 9] + k: 4 + - name: one-group-per-element + in: + nums: [1, 2, 3, 4, 5, 6, 7] + k: 7 + - name: uneven-groups-with-zero + in: + nums: [4, 4, 1, 5, 0, 1, 5, 4, 4, 0, 1, 5, 7, 7] + k: 5 + - name: repeated-xor-basis + in: + nums: [15, 240, 255, 15, 240, 255, 15, 240, 255, 0, 0, 0, 15, 240, 255] + k: 3 + - name: generated-k-one + in: + nums: + gen: "array" + len: 2000 + of: + gen: "int" + min: 0 + max: 1023 + distinct: false + sorted: false + elemType: "int" + k: 1 + - name: generated-k-two + in: + nums: + gen: "array" + len: 2000 + of: + gen: "int" + min: 0 + max: 1023 + distinct: false + sorted: false + elemType: "int" + k: 2 + - name: generated-k-seven + in: + nums: + gen: "array" + len: 2000 + of: + gen: "int" + min: 0 + max: 1023 + distinct: false + sorted: false + elemType: "int" + k: 7 + - name: generated-k-31 + in: + nums: + gen: "array" + len: 2000 + of: + gen: "int" + min: 0 + max: 1023 + distinct: false + sorted: false + elemType: "int" + k: 31 + - name: generated-k-1000 + in: + nums: + gen: "array" + len: 2000 + of: + gen: "int" + min: 0 + max: 1023 + distinct: false + sorted: false + elemType: "int" + k: 1000 diff --git a/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.cpp b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.cpp new file mode 100644 index 00000000..d7f48eec --- /dev/null +++ b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int minChanges(vector& nums, int k) { + unordered_map> freq; + for (int i = 0; i < nums.size(); i++) { + freq[i % k][nums[i]]++; + } + + int n = 1 << 10; + vector dp(n, INT_MIN); + dp[0] = 0; + for (int i = 0; i < k; i++) { + int mx = *max_element(dp.begin(), dp.end()); + vector tmp(n, 0); + for (int x = 0; x < n; x++) { + int c = dp[x]; + if (freq.count(i)) { + for (auto& [xx, cc] : freq[i]) { + int idx = x ^ xx; + tmp[idx] = max({tmp[idx], c + cc, mx}); + } + } + } + dp = tmp; + } + return nums.size() - dp[0]; + } +}; diff --git a/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.cs b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.cs new file mode 100644 index 00000000..9524e252 --- /dev/null +++ b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.cs @@ -0,0 +1,31 @@ +public class Solution { + public int MinChanges(int[] nums, int k) { + var freq = new Dictionary>(); + for (int i = 0; i < nums.Length; i++) { + int rem = i % k; + if (!freq.ContainsKey(rem)) freq[rem] = new Dictionary(); + if (freq[rem].ContainsKey(nums[i])) freq[rem][nums[i]]++; + else freq[rem][nums[i]] = 1; + } + + int n = 1 << 10; + int[] dp = new int[n]; + for (int i = 1; i < n; i++) dp[i] = int.MinValue; + for (int i = 0; i < k; i++) { + int mx = dp.Max(); + int[] tmp = new int[n]; + for (int x = 0; x < n; x++) { + int c = dp[x]; + if (freq.ContainsKey(i)) { + foreach (var kv in freq[i]) { + int xx = kv.Key, cc = kv.Value; + int idx = x ^ xx; + tmp[idx] = Math.Max(tmp[idx], Math.Max(c + cc, mx)); + } + } + } + dp = tmp; + } + return nums.Length - dp[0]; + } +} diff --git a/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.dart b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.dart new file mode 100644 index 00000000..12ff5d53 --- /dev/null +++ b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.dart @@ -0,0 +1,26 @@ +class Solution { + int minChanges(List nums, int k) { + Map> freq = {}; + for (int i = 0; i < nums.length; i++) { + int rem = i % k; + freq.putIfAbsent(rem, () => {}).update(nums[i], (v) => v + 1, ifAbsent: () => 1); + } + + int n = 1 << 10; + List dp = List.filled(n, 0); + for (int i = 1; i < n; i++) dp[i] = -(1 << 60); + for (int i = 0; i < k; i++) { + int mx = dp.reduce((a, b) => a > b ? a : b); + List tmp = List.filled(n, 0); + for (int x = 0; x < n; x++) { + int c = dp[x]; + freq[i]?.forEach((xx, cc) { + int idx = x ^ xx; + tmp[idx] = [tmp[idx], c + cc, mx].reduce((a, b) => a > b ? a : b); + }); + } + dp = tmp; + } + return nums.length - dp[0]; + } +} diff --git a/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.go b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.go new file mode 100644 index 00000000..7f624bcb --- /dev/null +++ b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.go @@ -0,0 +1,39 @@ +func minChanges(nums []int, k int) int { + freq := make(map[int]map[int]int) + for i, x := range nums { + rem := i % k + if freq[rem] == nil { + freq[rem] = make(map[int]int) + } + freq[rem][x]++ + } + + n := 1 << 10 + dp := make([]int, n) + for i := 1; i < n; i++ { + dp[i] = -1 << 60 + } + for i := 0; i < k; i++ { + mx := -1 << 60 + for _, v := range dp { + if v > mx { + mx = v + } + } + tmp := make([]int, n) + for x := 0; x < n; x++ { + c := dp[x] + for xx, cc := range freq[i] { + idx := x ^ xx + if c + cc > tmp[idx] { + tmp[idx] = c + cc + } + if mx > tmp[idx] { + tmp[idx] = mx + } + } + } + dp = tmp + } + return len(nums) - dp[0] +} diff --git a/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.java b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.java new file mode 100644 index 00000000..2bed8c6a --- /dev/null +++ b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.java @@ -0,0 +1,32 @@ +class Solution { + public int minChanges(int[] nums, int k) { + java.util.Map> freq = new java.util.HashMap<>(); + for (int i = 0; i < nums.length; i++) { + int rem = i % k; + freq.computeIfAbsent(rem, z -> new java.util.HashMap<>()).merge(nums[i], 1, Integer::sum); + } + + int n = 1 << 10; + int[] dp = new int[n]; + Arrays.fill(dp, Integer.MIN_VALUE); + dp[0] = 0; + for (int i = 0; i < k; i++) { + int mx = Integer.MIN_VALUE; + for (int v : dp) mx = Math.max(mx, v); + int[] tmp = new int[n]; + for (int x = 0; x < n; x++) { + int c = dp[x]; + if (freq.containsKey(i)) { + for (java.util.Map.Entry e : freq.get(i).entrySet()) { + int xx = e.getKey(), cc = e.getValue(); + tmp[x ^ xx] = Math.max(tmp[x ^ xx], Math.max(c + cc, mx)); + } + } else { + tmp[x] = Math.max(tmp[x], mx); + } + } + dp = tmp; + } + return nums.length - dp[0]; + } +} diff --git a/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.kt b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.kt new file mode 100644 index 00000000..d243a60a --- /dev/null +++ b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.kt @@ -0,0 +1,24 @@ +class Solution { + fun minChanges(nums: IntArray, k: Int): Int { + val freq = HashMap>() + for (i in nums.indices) { + freq.getOrPut(i % k) { HashMap() }.merge(nums[i], 1) { a, b -> a + b } + } + + val n = 1 shl 10 + var dp = IntArray(n) { Int.MIN_VALUE } + dp[0] = 0 + for (i in 0 until k) { + val mx = dp.max() + val tmp = IntArray(n) + for (x in 0 until n) { + val c = dp[x] + freq[i]?.forEach { (xx, cc) -> + tmp[x xor xx] = maxOf(tmp[x xor xx], c + cc, mx) + } + } + dp = tmp + } + return nums.size - dp[0] + } +} diff --git a/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.py b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.py new file mode 100644 index 00000000..c1c9c5b9 --- /dev/null +++ b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.py @@ -0,0 +1,21 @@ +from typing import List +from collections import defaultdict +from math import inf + + +class Solution: + def minChanges(self, nums: List[int], k: int) -> int: + freq = defaultdict(lambda: defaultdict(int)) + for i, x in enumerate(nums): + freq[i % k][x] += 1 # freq by row + + n = 1 << 10 + dp = [0] + [-inf] * (n - 1) + for i in range(k): + mx = max(dp) + tmp = [0] * n + for x, c in enumerate(dp): + for xx, cc in freq[i].items(): + tmp[x ^ xx] = max(tmp[x ^ xx], c + cc, mx) + dp = tmp + return len(nums) - dp[0] diff --git a/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.py2 b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.py2 new file mode 100644 index 00000000..5d1752cd --- /dev/null +++ b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def minChanges(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + from collections import defaultdict + freq = defaultdict(lambda: defaultdict(int)) + for i, x in enumerate(nums): + freq[i % k][x] += 1 + + n = 1 << 10 + dp = [0] + [-float('inf')] * (n - 1) + for i in range(k): + mx = max(dp) + tmp = [0] * n + for x, c in enumerate(dp): + for xx, cc in freq[i].items(): + tmp[x ^ xx] = max(tmp[x ^ xx], c + cc, mx) + dp = tmp + return len(nums) - dp[0] diff --git a/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.rb b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.rb new file mode 100644 index 00000000..d5a0984c --- /dev/null +++ b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.rb @@ -0,0 +1,24 @@ +# @param {Integer[]} nums +# @param {Integer} k +# @return {Integer} +def min_changes(nums, k) + freq = Hash.new { |h, k| h[k] = Hash.new(0) } + nums.each_with_index do |x, i| + freq[i % k][x] += 1 + end + + n = 1 << 10 + dp = [0] + [-Float::INFINITY] * (n - 1) + (0...k).each do |i| + mx = dp.max + tmp = Array.new(n, 0) + (0...n).each do |x| + c = dp[x] + freq[i].each do |xx, cc| + tmp[x ^ xx] = [tmp[x ^ xx], c + cc, mx].max + end + end + dp = tmp + end + nums.length - dp[0] +end diff --git a/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.rs b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.rs new file mode 100644 index 00000000..d2869761 --- /dev/null +++ b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.rs @@ -0,0 +1,29 @@ +impl Solution { + pub fn min_changes(nums: Vec, k: i32) -> i32 { + use std::collections::HashMap; + let k = k as usize; + let mut freq: HashMap> = HashMap::new(); + for (i, &x) in nums.iter().enumerate() { + *freq.entry(i % k).or_insert_with(HashMap::new).entry(x).or_insert(0) += 1; + } + + let n = 1 << 10; + let mut dp = vec![i32::MIN; n]; + dp[0] = 0; + for i in 0..k { + let mx = *dp.iter().max().unwrap(); + let mut tmp = vec![0; n]; + for x in 0..n { + let c = dp[x]; + if let Some(map) = freq.get(&i) { + for (&xx, &cc) in map { + let idx = x ^ xx as usize; + tmp[idx] = tmp[idx].max(c + cc).max(mx); + } + } + } + dp = tmp; + } + (nums.len() as i32) - dp[0] + } +} diff --git a/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.swift b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.swift new file mode 100644 index 00000000..55a69d25 --- /dev/null +++ b/tests/1501-2000/1787. make-the-xor-of-all-segments-equal-to-zero/sol.swift @@ -0,0 +1,28 @@ +class Solution { + func minChanges(_ nums: [Int], _ k: Int) -> Int { + var freq = [Int: [Int: Int]]() + for (i, x) in nums.enumerated() { + let rem = i % k + freq[rem, default: [:]][x, default: 0] += 1 + } + + let n = 1 << 10 + var dp = Array(repeating: Int.min, count: n) + dp[0] = 0 + for i in 0..> = new Map(); + for (let i = 0; i < nums.length; i++) { + const rem = i % k; + if (!freq.has(rem)) freq.set(rem, new Map()); + const map = freq.get(rem)!; + map.set(nums[i], (map.get(nums[i]) || 0) + 1); + } + + const n = 1 << 10; + let dp: number[] = Array(n).fill(-Infinity); + dp[0] = 0; + for (let i = 0; i < k; i++) { + const mx = Math.max(...dp); + const tmp = new Array(n).fill(0); + for (let x = 0; x < n; x++) { + const c = dp[x]; + if (freq.has(i)) { + for (const [xx, cc] of freq.get(i)!.entries()) { + const idx = x ^ xx; + tmp[idx] = Math.max(tmp[idx], c + cc, mx); + } + } + } + dp = tmp; + } + return nums.length - dp[0]; +} diff --git a/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/manifest.yaml b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/manifest.yaml new file mode 100644 index 00000000..66177651 --- /dev/null +++ b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/manifest.yaml @@ -0,0 +1,249 @@ +entry: + id: 1790 + title: "check-if-one-string-swap-can-make-strings-equal" + params: + s1: + type: string + s2: + type: string + call: + cpp: "Solution().areAlmostEqual({s1}, {s2})" + rust: "Solution::are_almost_equal({s1}, {s2})" + python3: "Solution().areAlmostEqual({s1}, {s2})" + python2: "Solution().areAlmostEqual({s1}, {s2})" + ruby: "are_almost_equal({s1}, {s2})" + java: "new Solution().areAlmostEqual({s1}, {s2})" + csharp: "new Solution().AreAlmostEqual({s1}, {s2})" + kotlin: "Solution().areAlmostEqual({s1}, {s2})" + go: "areAlmostEqual({s1}, {s2})" + dart: "Solution().areAlmostEqual({s1}, {s2})" + swift: "Solution().areAlmostEqual({s1}, {s2})" + typescript: "areAlmostEqual({s1}, {s2})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().areAlmostEqual(s1, s2, {result})" + checker: | + class Checker: + def areAlmostEqual(self, s1, s2, result): + if not isinstance(result, bool) or len(s1) != len(s2): + return False + mismatches = [i for i, (a, b) in enumerate(zip(s1, s2)) if a != b] + expected = False + if len(mismatches) == 0: + expected = True + elif len(mismatches) == 2: + i, j = mismatches + expected = s1[i] == s2[j] and s1[j] == s2[i] + return result == expected + +seed: 1790 + +tests: + - name: example-bank-kanb + in: + s1: "bank" + s2: "kanb" + out: true + - name: example-attack-defend + in: + s1: "attack" + s2: "defend" + out: false + - name: example-equal + in: + s1: "kelb" + s2: "kelb" + out: true + - name: one-character-equal + in: + s1: "a" + s2: "a" + out: true + - name: two-character-swap + in: + s1: "ab" + s2: "ba" + out: true + - name: two-character-nonswap + in: + s1: "ab" + s2: "ac" + out: false + - name: repeated-character-equal + in: + s1: "aaaa" + s2: "aaaa" + out: true + - name: repeated-character-invalid + in: + s1: "aabb" + s2: "abab" + out: true + - name: valid-repeated-swap + in: + s1: "aaab" + s2: "aaba" + out: true + - name: mismatch-one + in: + s1: "abc" + s2: "abd" + out: false + - name: mismatch-three + in: + s1: "abc" + s2: "bca" + out: false + - name: valid-middle-swap + in: + s1: "abcd" + s2: "acbd" + out: true + - name: invalid-two-mismatch + in: + s1: "abcd" + s2: "abdc" + out: true + - name: invalid-two-mismatch-values + in: + s1: "abcd" + s2: "abce" + out: false + - name: first-last-swap + in: + s1: "abcdef" + s2: "fbcdea" + out: true + - name: equal-palindrome + in: + s1: "racecar" + s2: "racecar" + out: true + - name: swapped-palindrome + in: + s1: "abccba" + s2: "cbccba" + out: false + - name: two-different-letters + in: + s1: "zzxy" + s2: "zzyx" + out: true + - name: all-different + in: + s1: "abcd" + s2: "dcba" + out: false + - name: duplicate-cross-swap + in: + s1: "aabc" + s2: "aacb" + out: true + - name: duplicate-wrong-count + in: + s1: "aabc" + s2: "abcc" + out: false + - name: length-five-valid + in: + s1: "hello" + s2: "hlelo" + out: true + - name: length-five-invalid + in: + s1: "hello" + s2: "helol" + out: true + - name: all-z-equal + in: + s1: "zzzzz" + s2: "zzzzz" + out: true + - name: edge-letters-swap + in: + s1: "azbycxdw" + s2: "azbycwdx" + out: true + - name: valid-long-swap + in: + s1: "abcdefghijklmnopqrst" + s2: "abcdefghijklmnopqrst" + out: true + - name: invalid-count-four + in: + s1: "abcdefgh" + s2: "badcfegh" + out: false + - name: valid-near-end + in: + s1: "abcdefghij" + s2: "abcdefgjhi" + out: false + - name: impossible-same-multiset + in: + s1: "aabbcc" + s2: "abacbc" + out: false + - name: valid-single-repeated-letter-swap + in: + s1: "abca" + s2: "acba" + out: true + - name: gen-random-short + in: + s1: + gen: "str" + len: 12 + alphabet: "abcd" + s2: + gen: "str" + len: 12 + alphabet: "abcd" + - name: gen-random-medium + in: + s1: + gen: "str" + len: 100 + alphabet: "abcdef" + s2: + gen: "str" + len: 100 + alphabet: "abcdef" + - name: gen-random-large-lowercase + in: + s1: + gen: "str" + len: 100 + alphabet: "amz" + s2: + gen: "str" + len: 100 + alphabet: "amz" + - name: gen-binary-alphabet + in: + s1: + gen: "str" + len: 100 + alphabet: "ab" + s2: + gen: "str" + len: 100 + alphabet: "ab" + - name: gen-single-alphabet + in: + s1: + gen: "str" + len: 100 + alphabet: "q" + s2: + gen: "str" + len: 100 + alphabet: "q" diff --git a/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.cpp b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.cpp new file mode 100644 index 00000000..9b54f137 --- /dev/null +++ b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + bool areAlmostEqual(string s1, string s2) { + int i = -1; + int j = -1; + int cnt = 0; + for (int k = 0; k < s1.size(); k++) { + if (s1[k] != s2[k]) { + cnt++; + if (i == -1) { + i = k; + } else if (j == -1) { + j = k; + } + } + } + + if (cnt == 0) return true; + if (cnt == 2 && s1[i] == s2[j] && s1[j] == s2[i]) return true; + return false; + } +}; diff --git a/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.cs b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.cs new file mode 100644 index 00000000..0dd8b391 --- /dev/null +++ b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.cs @@ -0,0 +1,21 @@ +public class Solution { + public bool AreAlmostEqual(string s1, string s2) { + int i = -1; + int j = -1; + int cnt = 0; + for (int k = 0; k < s1.Length; k++) { + if (s1[k] != s2[k]) { + cnt++; + if (i == -1) { + i = k; + } else if (j == -1) { + j = k; + } + } + } + + if (cnt == 0) return true; + if (cnt == 2 && s1[i] == s2[j] && s1[j] == s2[i]) return true; + return false; + } +} diff --git a/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.dart b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.dart new file mode 100644 index 00000000..c17622e2 --- /dev/null +++ b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.dart @@ -0,0 +1,21 @@ +class Solution { + bool areAlmostEqual(String s1, String s2) { + int i = -1; + int j = -1; + int cnt = 0; + for (int k = 0; k < s1.length; k++) { + if (s1[k] != s2[k]) { + cnt++; + if (i == -1) { + i = k; + } else if (j == -1) { + j = k; + } + } + } + + if (cnt == 0) return true; + if (cnt == 2 && s1[i] == s2[j] && s1[j] == s2[i]) return true; + return false; + } +} diff --git a/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.go b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.go new file mode 100644 index 00000000..ddd63a83 --- /dev/null +++ b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.go @@ -0,0 +1,23 @@ +func areAlmostEqual(s1 string, s2 string) bool { + i := -1 + j := -1 + cnt := 0 + for k := 0; k < len(s1); k++ { + if s1[k] != s2[k] { + cnt++ + if i == -1 { + i = k + } else if j == -1 { + j = k + } + } + } + + if cnt == 0 { + return true + } + if cnt == 2 && s1[i] == s2[j] && s1[j] == s2[i] { + return true + } + return false +} diff --git a/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.java b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.java new file mode 100644 index 00000000..c8fb544a --- /dev/null +++ b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.java @@ -0,0 +1,18 @@ +class Solution { + public boolean areAlmostEqual(String s1, String s2) { + int i = -1; + int j = -1; + int cnt = 0; + for (int k = 0; k < s1.length(); k++) { + if (s1.charAt(k) != s2.charAt(k)) { + cnt++; + if (i == -1) i = k; + else if (j == -1) j = k; + } + } + + if (cnt == 0) return true; + if (cnt == 2 && s1.charAt(i) == s2.charAt(j) && s1.charAt(j) == s2.charAt(i)) return true; + return false; + } +} diff --git a/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.kt b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.kt new file mode 100644 index 00000000..25906418 --- /dev/null +++ b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.kt @@ -0,0 +1,18 @@ +class Solution { + fun areAlmostEqual(s1: String, s2: String): Boolean { + var i = -1 + var j = -1 + var cnt = 0 + for (k in s1.indices) { + if (s1[k] != s2[k]) { + cnt++ + if (i == -1) i = k + else if (j == -1) j = k + } + } + + if (cnt == 0) return true + if (cnt == 2 && s1[i] == s2[j] && s1[j] == s2[i]) return true + return false + } +} diff --git a/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.py b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.py new file mode 100644 index 00000000..20e3d168 --- /dev/null +++ b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.py @@ -0,0 +1,24 @@ +class Solution(object): + def areAlmostEqual(self, s1, s2): + """ + :type s1: str + :type s2: str + :rtype: bool + """ + i = -1 + j = -1 + cnt = 0 + for k in range(0, len(s1)): + if s1[k] != s2[k]: + cnt += 1 + if i == -1: + i = k + elif j == -1: + j = k + + if cnt == 0: + return True + elif cnt == 2 and s1[i] == s2[j] and s1[j] == s2[i]: + return True + + return False diff --git a/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.py2 b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.py2 new file mode 100644 index 00000000..57feae30 --- /dev/null +++ b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def areAlmostEqual(self, s1, s2): + """ + :type s1: str + :type s2: str + :rtype: bool + """ + i=-1 + j=-1 + cnt=0 + for k in range(0, len(s1)): + if s1[k]!=s2[k]: + cnt+=1 + if i==-1: i=k + elif j==-1: j=k + + if cnt==0: return True + elif cnt==2 and s1[i]==s2[j] and s1[j]==s2[i]: return True + + return False diff --git a/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.rb b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.rb new file mode 100644 index 00000000..7e0c9e93 --- /dev/null +++ b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.rb @@ -0,0 +1,24 @@ +# @param {String} s1 +# @param {String} s2 +# @return {Boolean} +def are_almost_equal(s1, s2) + i = -1 + j = -1 + cnt = 0 + a = s1.chars + b = s2.chars + a.length.times do |k| + if a[k] != b[k] + cnt += 1 + if i == -1 + i = k + elsif j == -1 + j = k + end + end + end + + return true if cnt == 0 + return true if cnt == 2 && a[i] == b[j] && a[j] == b[i] + false +end diff --git a/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.rs b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.rs new file mode 100644 index 00000000..d2288318 --- /dev/null +++ b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.rs @@ -0,0 +1,23 @@ +impl Solution { + pub fn are_almost_equal(s1: String, s2: String) -> bool { + let chars1: Vec = s1.chars().collect(); + let chars2: Vec = s2.chars().collect(); + let mut i: i32 = -1; + let mut j: i32 = -1; + let mut cnt = 0; + for k in 0..chars1.len() { + if chars1[k] != chars2[k] { + cnt += 1; + if i == -1 { + i = k as i32; + } else if j == -1 { + j = k as i32; + } + } + } + + if cnt == 0 { return true; } + if cnt == 2 && chars1[i as usize] == chars2[j as usize] && chars1[j as usize] == chars2[i as usize] { return true; } + false + } +} diff --git a/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.swift b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.swift new file mode 100644 index 00000000..bb54cadf --- /dev/null +++ b/tests/1501-2000/1790. check-if-one-string-swap-can-make-strings-equal/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func areAlmostEqual(_ s1: String, _ s2: String) -> Bool { + let chars1 = Array(s1) + let chars2 = Array(s2) + var i = -1 + var j = -1 + var cnt = 0 + for k in 0..>& edges) { + int a = edges[0][0], b = edges[0][1]; + int c = edges[1][0], d = edges[1][1]; + if (a == c || a == d) { + return a; + } + return b; + } +}; diff --git a/tests/1501-2000/1791. find-center-of-star-graph/sol.cs b/tests/1501-2000/1791. find-center-of-star-graph/sol.cs new file mode 100644 index 00000000..5d570af1 --- /dev/null +++ b/tests/1501-2000/1791. find-center-of-star-graph/sol.cs @@ -0,0 +1,7 @@ +public class Solution { + public int FindCenter(int[][] edges) { + int a = edges[0][0], b = edges[0][1]; + int c = edges[1][0], d = edges[1][1]; + return (a == c || a == d) ? a : b; + } +} diff --git a/tests/1501-2000/1791. find-center-of-star-graph/sol.dart b/tests/1501-2000/1791. find-center-of-star-graph/sol.dart new file mode 100644 index 00000000..e7c75239 --- /dev/null +++ b/tests/1501-2000/1791. find-center-of-star-graph/sol.dart @@ -0,0 +1,7 @@ +class Solution { + int findCenter(List> edges) { + int a = edges[0][0], b = edges[0][1]; + int c = edges[1][0], d = edges[1][1]; + return (a == c || a == d) ? a : b; + } +} diff --git a/tests/1501-2000/1791. find-center-of-star-graph/sol.go b/tests/1501-2000/1791. find-center-of-star-graph/sol.go new file mode 100644 index 00000000..60188a25 --- /dev/null +++ b/tests/1501-2000/1791. find-center-of-star-graph/sol.go @@ -0,0 +1,8 @@ +func findCenter(edges [][]int) int { + a, b := edges[0][0], edges[0][1] + c, d := edges[1][0], edges[1][1] + if a == c || a == d { + return a + } + return b +} diff --git a/tests/1501-2000/1791. find-center-of-star-graph/sol.java b/tests/1501-2000/1791. find-center-of-star-graph/sol.java new file mode 100644 index 00000000..afeda6a4 --- /dev/null +++ b/tests/1501-2000/1791. find-center-of-star-graph/sol.java @@ -0,0 +1,10 @@ +class Solution { + public int findCenter(int[][] edges) { + int a = edges[0][0], b = edges[0][1]; + int c = edges[1][0], d = edges[1][1]; + if (a == c || a == d) { + return a; + } + return b; + } +} diff --git a/tests/1501-2000/1791. find-center-of-star-graph/sol.kt b/tests/1501-2000/1791. find-center-of-star-graph/sol.kt new file mode 100644 index 00000000..d841d21e --- /dev/null +++ b/tests/1501-2000/1791. find-center-of-star-graph/sol.kt @@ -0,0 +1,9 @@ +class Solution { + fun findCenter(edges: Array): Int { + val a = edges[0][0] + val b = edges[0][1] + val c = edges[1][0] + val d = edges[1][1] + return if (a == c || a == d) a else b + } +} diff --git a/tests/1501-2000/1791. find-center-of-star-graph/sol.py b/tests/1501-2000/1791. find-center-of-star-graph/sol.py new file mode 100644 index 00000000..d7bf0d4d --- /dev/null +++ b/tests/1501-2000/1791. find-center-of-star-graph/sol.py @@ -0,0 +1,10 @@ +class Solution: + def findCenter(self, edges: List[List[int]]) -> int: + # Extract nodes from first two edges + a, b = edges[0] + c, d = edges[1] + + # Return the common node (center of star graph) + if a == c or a == d: + return a + return b diff --git a/tests/1501-2000/1791. find-center-of-star-graph/sol.py2 b/tests/1501-2000/1791. find-center-of-star-graph/sol.py2 new file mode 100644 index 00000000..e098ac4e --- /dev/null +++ b/tests/1501-2000/1791. find-center-of-star-graph/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def findCenter(self, edges): + """ + :type edges: List[List[int]] + :rtype: int + """ + a, b = edges[0] + c, d = edges[1] + if a == c or a == d: + return a + return b diff --git a/tests/1501-2000/1791. find-center-of-star-graph/sol.rb b/tests/1501-2000/1791. find-center-of-star-graph/sol.rb new file mode 100644 index 00000000..9fc78714 --- /dev/null +++ b/tests/1501-2000/1791. find-center-of-star-graph/sol.rb @@ -0,0 +1,10 @@ +# @param {Integer[][]} edges +# @return {Integer} +def find_center(edges) + a, b = edges[0] + c, d = edges[1] + if a == c || a == d + return a + end + b +end diff --git a/tests/1501-2000/1791. find-center-of-star-graph/sol.rs b/tests/1501-2000/1791. find-center-of-star-graph/sol.rs new file mode 100644 index 00000000..b2d448ed --- /dev/null +++ b/tests/1501-2000/1791. find-center-of-star-graph/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn find_center(edges: Vec>) -> i32 { + let a = edges[0][0]; + let b = edges[0][1]; + let c = edges[1][0]; + let d = edges[1][1]; + if a == c || a == d { + a + } else { + b + } + } +} diff --git a/tests/1501-2000/1791. find-center-of-star-graph/sol.swift b/tests/1501-2000/1791. find-center-of-star-graph/sol.swift new file mode 100644 index 00000000..3d3eae32 --- /dev/null +++ b/tests/1501-2000/1791. find-center-of-star-graph/sol.swift @@ -0,0 +1,7 @@ +class Solution { + func findCenter(_ edges: [[Int]]) -> Int { + let a = edges[0][0], b = edges[0][1] + let c = edges[1][0], d = edges[1][1] + return (a == c || a == d) ? a : b + } +} diff --git a/tests/1501-2000/1791. find-center-of-star-graph/sol.ts b/tests/1501-2000/1791. find-center-of-star-graph/sol.ts new file mode 100644 index 00000000..fa7f500a --- /dev/null +++ b/tests/1501-2000/1791. find-center-of-star-graph/sol.ts @@ -0,0 +1,5 @@ +function findCenter(edges: number[][]): number { + let [a, b] = edges[0]; + let [c, d] = edges[1]; + return a === c || a === d ? a : b; +} diff --git a/tests/1501-2000/1792. maximum-average-pass-ratio/manifest.yaml b/tests/1501-2000/1792. maximum-average-pass-ratio/manifest.yaml new file mode 100644 index 00000000..6ace3e49 --- /dev/null +++ b/tests/1501-2000/1792. maximum-average-pass-ratio/manifest.yaml @@ -0,0 +1,247 @@ +entry: + id: 1792 + title: "maximum-average-pass-ratio" + params: + classes: + type: array + items: + type: array + items: + type: int + extraStudents: + type: int + call: + cpp: "Solution().maxAverageRatio({classes}, {extraStudents})" + rust: "Solution::max_average_ratio({classes}, {extraStudents})" + python3: "Solution().maxAverageRatio({classes}, {extraStudents})" + python2: "Solution().maxAverageRatio({classes}, {extraStudents})" + ruby: "max_average_ratio({classes}, {extraStudents})" + java: "new Solution().maxAverageRatio({classes}, {extraStudents})" + csharp: "new Solution().MaxAverageRatio({classes}, {extraStudents})" + kotlin: "Solution().maxAverageRatio({classes}, {extraStudents})" + go: "maxAverageRatio({classes}, {extraStudents})" + dart: "Solution().maxAverageRatio({classes}, {extraStudents})" + swift: "Solution().maxAverageRatio({classes}, {extraStudents})" + typescript: "maxAverageRatio({classes}, {extraStudents})" + +judge: + type: "exact" + +limits: + time_ms: 5000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxAverageRatio(classes, extraStudents, {result})" + checker: | + import heapq + import math + + class Checker: + def maxAverageRatio(self, classes, extraStudents, result): + def gain(p, t): + return (p + 1) / float(t + 1) - p / float(t) + heap = [(-gain(p, t), p, t) for p, t in classes] + heapq.heapify(heap) + for _ in range(extraStudents): + _, p, t = heapq.heappop(heap) + p += 1 + t += 1 + heapq.heappush(heap, (-gain(p, t), p, t)) + expected = sum(p / float(t) for _, p, t in heap) / len(classes) + try: + actual = float(result) + except (TypeError, ValueError): + return False + return math.isfinite(actual) and abs(actual - expected) <= 1e-5 + +seed: 1792 + +tests: + - name: example-one + in: + classes: [[1, 2], [3, 5], [2, 2]] + extraStudents: 2 + - name: example-two + in: + classes: [[2, 4], [3, 9], [4, 5], [2, 10]] + extraStudents: 4 + - name: one-class + in: + classes: [[1, 2]] + extraStudents: 1 + - name: one-class-full + in: + classes: [[1, 1]] + extraStudents: 100000 + - name: all-already-perfect + in: + classes: [[1, 1], [2, 2], [100000, 100000]] + extraStudents: 37 + - name: all-half + in: + classes: [[1, 2], [2, 4], [50, 100], [500, 1000]] + extraStudents: 4 + - name: equal-small + in: + classes: [[1, 3], [1, 3], [1, 3]] + extraStudents: 3 + - name: one-nearly-perfect + in: + classes: [[99999, 100000], [1, 100000], [2, 100000]] + extraStudents: 5 + - name: zero-gain-perfect-mix + in: + classes: [[5, 5], [1, 10], [9, 10]] + extraStudents: 1 + - name: smallest-ratios + in: + classes: [[1, 100000], [1, 99999], [2, 100000]] + extraStudents: 10 + - name: large-extra-small-classes + in: + classes: [[1, 2], [1, 3], [2, 5]] + extraStudents: 100000 + - name: large-totals + in: + classes: [[50000, 100000], [75000, 100000], [99998, 100000]] + extraStudents: 100000 + - name: varied-ratios + in: + classes: [[3, 4], [4, 10], [7, 13], [10, 11], [1, 7]] + extraStudents: 9 + - name: many-perfect + in: + classes: [[1, 1], [2, 2], [3, 3], [4, 5], [1, 6]] + extraStudents: 8 + - name: tie-gains + in: + classes: [[1, 2], [2, 4], [3, 6], [4, 8]] + extraStudents: 6 + - name: alternating + in: + classes: [[1, 10], [9, 10], [2, 3], [3, 9], [8, 9], [4, 20]] + extraStudents: 12 + - name: two-classes + in: + classes: [[1, 5], [4, 7]] + extraStudents: 2 + - name: exact-total-bound + in: + classes: [[99999, 100000], [1, 1]] + extraStudents: 99999 + - name: many-classes + in: + classes: + [ + [1, 2], + [2, 3], + [3, 4], + [4, 5], + [5, 6], + [6, 7], + [7, 8], + [8, 9], + [9, 10], + [10, 11], + ] + extraStudents: 25 + - name: sparse-large + in: + classes: [[1, 100000], [99999, 100000], [50000, 50001], [25000, 99999]] + extraStudents: 100 + - name: dense-small + in: + classes: [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]] + extraStudents: 1 + - name: one-extra + in: + classes: [[1, 100], [50, 100], [99, 100], [2, 3]] + extraStudents: 1 + - name: huge-single + in: + classes: [[50000, 100000]] + extraStudents: 100000 + - name: huge-perfect-and-poor + in: + classes: [[100000, 100000], [1, 100000]] + extraStudents: 100000 + - name: repeated-pairs + in: + classes: [[2, 5], [2, 5], [2, 5], [2, 5], [2, 5]] + extraStudents: 15 + - name: close-gains + in: + classes: [[49, 100], [50, 101], [51, 102], [52, 103]] + extraStudents: 20 + - name: low-pass-variety + in: + classes: [[1, 2], [1, 4], [1, 8], [1, 16], [1, 32]] + extraStudents: 16 + - name: high-pass-variety + in: + classes: [[8, 9], [17, 19], [26, 29], [35, 39], [44, 49]] + extraStudents: 11 + - name: maximum-class-count + in: + classes: + [ + [1, 100000], + [2, 100000], + [3, 100000], + [4, 100000], + [5, 100000], + [6, 100000], + [7, 100000], + [8, 100000], + [9, 100000], + [10, 100000], + ] + extraStudents: 100000 + - name: mixed-perfect + in: + classes: [[10, 10], [1, 2], [20, 30], [30, 31], [5, 100]] + extraStudents: 33 + - name: generator-small + in: + classes: [[1, 4], [2, 7], [5, 9], [8, 10]] + extraStudents: + gen: "int" + min: 1 + max: 100 + - name: generator-medium + in: + classes: [[1, 100], [25, 100], [50, 100], [75, 100], [99, 100]] + extraStudents: + gen: "int" + min: 1 + max: 1000 + - name: generator-perfect-mix + in: + classes: [[1, 1], [1, 10], [10, 20], [999, 1000]] + extraStudents: + gen: "int" + min: 1 + max: 10000 + - name: generator-large + in: + classes: + [ + [1, 100000], + [25000, 100000], + [50000, 100000], + [75000, 100000], + [99999, 100000], + ] + extraStudents: + gen: "int" + min: 1 + max: 100000 + - name: generator-balanced + in: + classes: [[3, 7], [12, 25], [40, 81], [60, 101], [90, 151], [500, 1001]] + extraStudents: + gen: "int" + min: 1 + max: 100000 diff --git a/tests/1501-2000/1792. maximum-average-pass-ratio/sol.cpp b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.cpp new file mode 100644 index 00000000..d3163aee --- /dev/null +++ b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.cpp @@ -0,0 +1,29 @@ +#include +#include + +class Solution { +public: + double maxAverageRatio(vector>& classes, int extraStudents) { + auto cmp = [](const array& a, const array& b) { + return a[0] < b[0]; + }; + priority_queue, vector>, decltype(cmp)> pq(cmp); + for (auto& c : classes) { + double p = c[0], t = c[1]; + double gain = (p+1)/(t+1) - p/t; + pq.push({gain, p, t}); + } + while (extraStudents--) { + auto top = pq.top(); pq.pop(); + double p = top[1]+1, t = top[2]+1; + double gain = (p+1)/(t+1) - p/t; + pq.push({gain, p, t}); + } + double sum = 0.0; + while (!pq.empty()) { + auto item = pq.top(); pq.pop(); + sum += item[1]/item[2]; + } + return sum / classes.size(); + } +}; diff --git a/tests/1501-2000/1792. maximum-average-pass-ratio/sol.cs b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.cs new file mode 100644 index 00000000..17f0b27b --- /dev/null +++ b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; + +public class Solution { + public double MaxAverageRatio(int[][] classes, int extraStudents) { + var pq = new List>(); + foreach (var c in classes) { + int p = c[0], t = c[1]; + double gain = (double)(p+1)/(t+1) - (double)p/t; + pq.Add(Tuple.Create(gain, p, t)); + } + while (extraStudents-- > 0) { + int best = 0; + for (int i = 1; i < pq.Count; i++) + if (pq[i].Item1 > pq[best].Item1) best = i; + var top = pq[best]; + pq.RemoveAt(best); + int p = top.Item2+1, t = top.Item3+1; + double gain = (double)(p+1)/(t+1) - (double)p/t; + pq.Add(Tuple.Create(gain, p, t)); + } + double sum = 0.0; + while (pq.Count > 0) { + var item = pq[pq.Count - 1]; + pq.RemoveAt(pq.Count - 1); + sum += (double)item.Item2/item.Item3; + } + return sum / classes.Length; + } +} diff --git a/tests/1501-2000/1792. maximum-average-pass-ratio/sol.dart b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.dart new file mode 100644 index 00000000..61785bfa --- /dev/null +++ b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.dart @@ -0,0 +1,23 @@ +import 'dart:collection'; + +class Solution { + double maxAverageRatio(List> classes, int extraStudents) { + double gain(int p, int t) => (p + 1) / (t + 1) - p / t; + final pq = PriorityQueue>((a, b) => b[0].compareTo(a[0])); + for (var c in classes) { + pq.add([gain(c[0], c[1]), c[0].toDouble(), c[1].toDouble()]); + } + for (int i = 0; i < extraStudents; i++) { + var top = pq.removeFirst(); + double p = top[1], t = top[2]; + p++; t++; + pq.add([gain(p.toInt(), t.toInt()), p, t]); + } + double sum = 0; + while (pq.isNotEmpty) { + var item = pq.removeFirst(); + sum += item[1] / item[2]; + } + return sum / classes.length; + } +} diff --git a/tests/1501-2000/1792. maximum-average-pass-ratio/sol.go b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.go new file mode 100644 index 00000000..6e5ac849 --- /dev/null +++ b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.go @@ -0,0 +1,40 @@ +type Item struct { + gain float64 + p, t int +} + +type MaxHeap []Item + +func (h MaxHeap) Len() int { return len(h) } +func (h MaxHeap) Less(i, j int) bool { return h[i].gain > h[j].gain } +func (h MaxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *MaxHeap) Push(x interface{}) { *h = append(*h, x.(Item)) } +func (h *MaxHeap) Pop() interface{} { + old := *h + n := len(old) + item := old[n-1] + *h = old[:n-1] + return item +} + +func maxAverageRatio(classes [][]int, extraStudents int) float64 { + pq := make([]Item, 0, len(classes)) + for _, c := range classes { + p, t := c[0], c[1] + gain := float64(p+1)/float64(t+1) - float64(p)/float64(t) + pq = append(pq, Item{gain, p, t}) + } + for i := 0; i < extraStudents; i++ { + best := 0 + for j := 1; j < len(pq); j++ { if pq[j].gain > pq[best].gain { best = j } } + top := pq[best] + p, t := top.p+1, top.t+1 + gain := float64(p+1)/float64(t+1) - float64(p)/float64(t) + pq[best] = Item{gain, p, t} + } + sum := 0.0 + for _, item := range pq { + sum += float64(item.p) / float64(item.t) + } + return sum / float64(len(classes)) +} diff --git a/tests/1501-2000/1792. maximum-average-pass-ratio/sol.java b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.java new file mode 100644 index 00000000..243953d0 --- /dev/null +++ b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.java @@ -0,0 +1,22 @@ +import java.util.PriorityQueue; +class Solution { + public double maxAverageRatio(int[][] classes, int extraStudents) { + PriorityQueue pq = new PriorityQueue<>((a, b) -> Double.compare(b[0], a[0])); + for (int[] c : classes) { + double gain = (double)(c[0] + 1) / (c[1] + 1) - (double)c[0] / c[1]; + pq.offer(new double[]{gain, c[0], c[1]}); + } + for (int i = 0; i < extraStudents; i++) { + double[] top = pq.poll(); + double p = top[1], t = top[2]; + p++; t++; + double gain = (double)(p + 1) / (t + 1) - (double)p / t; + pq.offer(new double[]{gain, p, t}); + } + double sum = 0; + for (double[] item : pq) { + sum += item[1] / item[2]; + } + return sum / classes.length; + } +} diff --git a/tests/1501-2000/1792. maximum-average-pass-ratio/sol.kt b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.kt new file mode 100644 index 00000000..679962e4 --- /dev/null +++ b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.kt @@ -0,0 +1,22 @@ +import java.util.PriorityQueue +class Solution { + fun maxAverageRatio(classes: Array, extraStudents: Int): Double { + val pq = PriorityQueue { a, b -> b[0].compareTo(a[0]) } + for (c in classes) { + val gain = (c[0] + 1.0) / (c[1] + 1) - c[0].toDouble() / c[1] + pq.offer(doubleArrayOf(gain, c[0].toDouble(), c[1].toDouble())) + } + repeat(extraStudents) { + val top = pq.poll() + var p = top[1]; var t = top[2] + p++; t++ + val gain = (p + 1) / (t + 1) - p / t + pq.offer(doubleArrayOf(gain, p, t)) + } + var sum = 0.0 + for (item in pq) { + sum += item[1] / item[2] + } + return sum / classes.size + } +} diff --git a/tests/1501-2000/1792. maximum-average-pass-ratio/sol.py b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.py new file mode 100644 index 00000000..094d392c --- /dev/null +++ b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.py @@ -0,0 +1,44 @@ +class Solution: + def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float: + # Lambda to calculate the gain of adding an extra student + def _calculate_gain(passes, total_students): + return (passes + 1) / (total_students + 1) - passes / total_students + + # Max heap to store (-gain, passes, total_students) + max_heap = [] + for passes, total_students in classes: + gain = _calculate_gain(passes, total_students) + max_heap.append((-gain, passes, total_students)) + + # Use heapify to transform the list into a valid heap in O(n) + heapq.heapify(max_heap) + + # Distribute extra students + for _ in range(extraStudents): + current_gain, passes, total_students = heapq.heappop(max_heap) + heapq.heappush( + max_heap, + ( + -_calculate_gain(passes + 1, total_students + 1), + passes + 1, + total_students + 1, + ), + ) + + # Calculate the final average pass ratio + total_pass_ratio = sum( + passes / total_students for _, passes, total_students in max_heap + ) + return total_pass_ratio / len(classes) + + def maxAverageRatio(self, classes, extraStudents): + def gain(p, t): + return (p + 1) / (t + 1) - p / t + + pq = [(-gain(p, t), p, t) for p, t in classes] + heapq.heapify(pq) + for _ in range(extraStudents): + g, p, t = heapq.heappop(pq) + p, t = p + 1, t + 1 + heapq.heappush(pq, (-gain(p, t), p, t)) + return sum(p / t for _, p, t in pq) / len(classes) diff --git a/tests/1501-2000/1792. maximum-average-pass-ratio/sol.py2 b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.py2 new file mode 100644 index 00000000..c1d18449 --- /dev/null +++ b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.py2 @@ -0,0 +1,18 @@ +import heapq + +class Solution(object): + def maxAverageRatio(self, classes, extraStudents): + """ + :type classes: List[List[int]] + :type extraStudents: int + :rtype: float + """ + def gain(p, t): + return float(p + 1) / (t + 1) - float(p) / t + pq = [(-gain(p, t), p, t) for p, t in classes] + heapq.heapify(pq) + for _ in range(extraStudents): + g, p, t = heapq.heappop(pq) + p, t = p + 1, t + 1 + heapq.heappush(pq, (-gain(p, t), p, t)) + return sum(float(p) / t for _, p, t in pq) / len(classes) diff --git a/tests/1501-2000/1792. maximum-average-pass-ratio/sol.rb b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.rb new file mode 100644 index 00000000..679745df --- /dev/null +++ b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.rb @@ -0,0 +1,22 @@ +# @param {Integer[][]} classes +# @param {Integer} extra_students +# @return {Float} +def max_average_ratio(classes, extra_students) + gain = ->(p, t) { (p + 1.0) / (t + 1) - p.to_f / t } + pq = classes.map { |p, t| [-gain.call(p, t), p, t] } + require 'algorithms' + heap = Containers::Heap.new { |a, b| a[0] < b[0] } + pq.each { |item| heap.push(item) } + extra_students.times do + g, p, t = heap.pop + p, t = p + 1, t + 1 + heap.push([-gain.call(p, t), p, t]) + end + total = 0.0 + initial_size = heap.size + initial_size.times do + item = heap.pop + total += item[1].to_f / item[2] + end + total / classes.length +end diff --git a/tests/1501-2000/1792. maximum-average-pass-ratio/sol.rs b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.rs new file mode 100644 index 00000000..d1c19594 --- /dev/null +++ b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.rs @@ -0,0 +1,53 @@ +use std::collections::BinaryHeap; +use std::cmp::Ordering; + +#[derive(Debug, Copy, Clone)] +struct Item { + gain: f64, + p: i32, + t: i32, +} + +impl PartialEq for Item { + fn eq(&self, other: &Self) -> bool { + self.gain == other.gain + } +} + +impl Eq for Item {} + +impl PartialOrd for Item { + fn partial_cmp(&self, other: &Self) -> Option { + self.gain.partial_cmp(&other.gain) + } +} + +impl Ord for Item { + fn cmp(&self, other: &Self) -> Ordering { + self.gain.partial_cmp(&other.gain).unwrap_or(Ordering::Equal) + } +} + +impl Solution { + pub fn max_average_ratio(classes: Vec>, extra_students: i32) -> f64 { + let mut heap = BinaryHeap::new(); + for c in &classes { + let p = c[0]; + let t = c[1]; + let gain = (p as f64 + 1.0) / (t as f64 + 1.0) - p as f64 / t as f64; + heap.push(Item { gain, p, t }); + } + for _ in 0..extra_students { + let top = heap.pop().unwrap(); + let p = top.p + 1; + let t = top.t + 1; + let gain = (p as f64 + 1.0) / (t as f64 + 1.0) - p as f64 / t as f64; + heap.push(Item { gain, p, t }); + } + let mut sum = 0.0; + for item in &heap { + sum += item.p as f64 / item.t as f64; + } + sum / classes.len() as f64 + } +} diff --git a/tests/1501-2000/1792. maximum-average-pass-ratio/sol.swift b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.swift new file mode 100644 index 00000000..b073b39b --- /dev/null +++ b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.swift @@ -0,0 +1,76 @@ +import Foundation + +class Solution { + func maxAverageRatio(_ classes: [[Int]], _ extraStudents: Int) -> Double { + func gain(_ p: Double, _ t: Double) -> Double { + return (p + 1) / (t + 1) - p / t + } + var pq = PriorityQueue<(Double, Int, Int)> { $0.0 > $1.0 } + for c in classes { + let p = Double(c[0]), t = Double(c[1]) + pq.enqueue((gain(p, t), Int(p), Int(t))) + } + for _ in 0.. { + private var heap: [Element] = [] + private let areInIncreasingOrder: (Element, Element) -> Bool + + init(areInIncreasingOrder: @escaping (Element, Element) -> Bool) { + self.areInIncreasingOrder = areInIncreasingOrder + } + + mutating func enqueue(_ element: Element) { + heap.append(element) + siftUp(heap.count - 1) + } + + mutating func dequeue() -> Element? { + guard !heap.isEmpty else { return nil } + if heap.count == 1 { return heap.removeLast() } + heap.swapAt(0, heap.count - 1) + let result = heap.removeLast() + siftDown(0) + return result + } + + private mutating func siftUp(_ index: Int) { + var child = index + var parent = (child - 1) / 2 + while child > 0 && !areInIncreasingOrder(heap[parent], heap[child]) { + heap.swapAt(parent, child) + child = parent + parent = (child - 1) / 2 + } + } + + private mutating func siftDown(_ index: Int) { + var parent = index + while true { + let left = 2 * parent + 1 + let right = 2 * parent + 2 + var candidate = parent + if left < heap.count && !areInIncreasingOrder(heap[candidate], heap[left]) { + candidate = left + } + if right < heap.count && !areInIncreasingOrder(heap[candidate], heap[right]) { + candidate = right + } + if candidate == parent { return } + heap.swapAt(parent, candidate) + parent = candidate + } + } +} diff --git a/tests/1501-2000/1792. maximum-average-pass-ratio/sol.ts b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.ts new file mode 100644 index 00000000..90cc7797 --- /dev/null +++ b/tests/1501-2000/1792. maximum-average-pass-ratio/sol.ts @@ -0,0 +1,69 @@ +function maxAverageRatio(classes: number[][], extraStudents: number): number { + const gain = (p: number, t: number) => (p + 1) / (t + 1) - p / t; + const pq: [number, number, number][] = []; + for (const [p, t] of classes) { + pq.push([-gain(p, t), p, t]); + } + // simple priority queue using binary heap + const heap = new MinHeap(); + for (const item of pq) heap.push(item); + for (let i = 0; i < extraStudents; i++) { + const [g, p, t] = heap.pop(); + const np = p + 1, + nt = t + 1; + heap.push([-gain(np, nt), np, nt]); + } + const items = heap.toArray(); + let sum = 0; + for (const [_, p, t] of items) sum += p / t; + return sum / classes.length; +} + +class MinHeap { + private heap: [number, number, number][] = []; + push(val: [number, number, number]) { + this.heap.push(val); + this.bubbleUp(this.heap.length - 1); + } + pop() { + if (this.heap.length === 0) return null; + const top = this.heap[0]; + const last = this.heap.pop()!; + if (this.heap.length > 0) { + this.heap[0] = last; + this.bubbleDown(0); + } + return top; + } + toArray() { + return this.heap; + } + private bubbleUp(i: number) { + while (i > 0) { + const parent = Math.floor((i - 1) / 2); + if (this.heap[i][0] < this.heap[parent][0]) { + [this.heap[i], this.heap[parent]] = [this.heap[parent], this.heap[i]]; + i = parent; + } else break; + } + } + private bubbleDown(i: number) { + const n = this.heap.length; + while (true) { + let left = 2 * i + 1, + right = 2 * i + 2, + smallest = i; + if (left < n && this.heap[left][0] < this.heap[smallest][0]) + smallest = left; + if (right < n && this.heap[right][0] < this.heap[smallest][0]) + smallest = right; + if (smallest !== i) { + [this.heap[i], this.heap[smallest]] = [ + this.heap[smallest], + this.heap[i], + ]; + i = smallest; + } else break; + } + } +} diff --git a/tests/1501-2000/1793. maximum-score-of-a-good-subarray/manifest.yaml b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/manifest.yaml new file mode 100644 index 00000000..d44485b9 --- /dev/null +++ b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/manifest.yaml @@ -0,0 +1,226 @@ +entry: + id: 1793 + title: maximum-score-of-a-good-subarray + params: + nums: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().maximumScore({nums}, {k})" + rust: "Solution::maximum_score({nums}, {k})" + python3: "Solution().maximumScore({nums}, {k})" + python2: "Solution().maximumScore({nums}, {k})" + ruby: "maximum_score({nums}, {k})" + java: "new Solution().maximumScore({nums}, {k})" + csharp: "new Solution().MaximumScore({nums}, {k})" + kotlin: "Solution().maximumScore({nums}, {k})" + go: "maximumScore({nums}, {k})" + dart: "Solution().maximumScore({nums}, {k})" + swift: "Solution().maximumScore({nums}, {k})" + typescript: "maximumScore({nums}, {k})" + +judge: + type: exact + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maximumScore(nums, k, {result})" + checker: | + class Checker: + def maximumScore(self, nums, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + expected = 0 + for left in range(len(nums)): + current = None + for right in range(left, len(nums)): + current = nums[right] if current is None else min(current, nums[right]) + if left <= k <= right: + expected = max(expected, current * (right - left + 1)) + return result == expected + +seed: 1793 + +tests: + - name: single-one + in: + nums: [1] + k: 0 + out: 1 + - name: single-maximum + in: + nums: [5] + k: 0 + out: 5 + - name: two-left + in: + nums: [1, 2] + k: 0 + out: 2 + - name: two-right + in: + nums: [1, 2] + k: 1 + out: 2 + - name: descending-two-left + in: + nums: [5, 1] + k: 0 + out: 5 + - name: descending-two-right + in: + nums: [5, 1] + k: 1 + out: 2 + - name: equal-triple + in: + nums: [2, 2, 2] + k: 1 + out: 6 + - name: increasing-middle + in: + nums: [1, 2, 3] + k: 1 + out: 4 + - name: decreasing-middle + in: + nums: [3, 2, 1] + k: 1 + out: 4 + - name: example-two + in: + nums: [5, 5, 4, 5, 4, 1, 1, 1] + k: 0 + out: 20 + - name: example-one + in: + nums: [1, 4, 3, 7, 4, 5] + k: 3 + out: 15 + - name: low-center + in: + nums: [10, 1, 10] + k: 1 + out: 3 + - name: alternating-center + in: + nums: [2, 1, 2, 1, 2] + k: 2 + out: 5 + - name: descending-left + in: + nums: [6, 5, 4, 3, 2, 1] + k: 0 + out: 12 + - name: descending-right + in: + nums: [6, 5, 4, 3, 2, 1] + k: 5 + out: 6 + - name: high-left-of-k + in: + nums: [1, 6, 5, 4, 3, 2] + k: 1 + out: 12 + - name: high-middle-plateau + in: + nums: [2, 9, 9, 9, 2] + k: 2 + out: 27 + - name: all-equal + in: + nums: [4, 4, 4, 4, 4, 4] + k: 3 + out: 24 + - name: alternating-high + in: + nums: [1, 100, 1, 100, 1] + k: 1 + out: 100 + - name: descending-center + in: + nums: [8, 7, 6, 5, 4, 3, 2, 1] + k: 4 + out: 20 + - name: mixed-seven + in: + nums: [1, 3, 2, 4, 1, 5, 2] + k: 3 + out: 7 + - name: mixed-left-edge + in: + nums: [7, 1, 6, 2, 5, 3, 4] + k: 0 + out: 7 + - name: mixed-right-edge + in: + nums: [7, 1, 6, 2, 5, 3, 4] + k: 6 + out: 10 + - name: valley-near-left + in: + nums: [9, 8, 1, 2, 3, 9, 8] + k: 2 + out: 7 + - name: rising-with-valley + in: + nums: [2, 3, 4, 1, 5, 6, 7] + k: 3 + out: 7 + - name: edge-hundred + in: + nums: [100, 1, 1, 1, 100] + k: 0 + out: 100 + - name: center-hundred-valley + in: + nums: [100, 1, 1, 1, 100] + k: 2 + out: 5 + - name: high-center-run + in: + nums: [1, 100, 100, 100, 1] + k: 2 + out: 300 + - name: alternating-three + in: + nums: [3, 1, 3, 1, 3, 1, 3] + k: 4 + out: 7 + - name: large-neighborhood + in: + nums: [20, 19, 18, 1, 17, 16, 15] + k: 2 + out: 54 + - name: alternating-eight + in: + nums: [1, 2, 1, 2, 1, 2, 1, 2] + k: 5 + out: 8 + - name: long-descending + in: + nums: [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + k: 7 + out: 32 + - name: long-increasing + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + k: 5 + out: 30 + - name: long-decreasing-center + in: + nums: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + k: 5 + out: 30 + - name: mixed-nine + in: + nums: [2, 1, 2, 3, 1, 2, 3, 4, 1] + k: 6 + out: 9 diff --git a/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.cpp b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.cpp new file mode 100644 index 00000000..16e36e0d --- /dev/null +++ b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int maximumScore(vector& nums, int k) { + int n = nums.size(); + int i = k, j = k; + int curMin = nums[k]; + int res = curMin; + + while (i > 0 || j < n - 1) { + if (i == 0) { + j++; + } else if (j == n - 1) { + i--; + } else if (nums[i - 1] >= nums[j + 1]) { + i--; + } else { + j++; + } + curMin = min({curMin, nums[i], nums[j]}); + res = max(res, curMin * (j - i + 1)); + } + + return res; + } +}; diff --git a/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.cs b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.cs new file mode 100644 index 00000000..3c5cd7d1 --- /dev/null +++ b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.cs @@ -0,0 +1,24 @@ +public class Solution { + public int MaximumScore(int[] nums, int k) { + int n = nums.Length; + int i = k, j = k; + int curMin = nums[k]; + int res = curMin; + + while (i > 0 || j < n - 1) { + if (i == 0) { + j++; + } else if (j == n - 1) { + i--; + } else if (nums[i - 1] >= nums[j + 1]) { + i--; + } else { + j++; + } + curMin = Math.Min(curMin, Math.Min(nums[i], nums[j])); + res = Math.Max(res, curMin * (j - i + 1)); + } + + return res; + } +} diff --git a/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.dart b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.dart new file mode 100644 index 00000000..3e44d4c1 --- /dev/null +++ b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.dart @@ -0,0 +1,24 @@ +class Solution { + int maximumScore(List nums, int k) { + int n = nums.length; + int i = k, j = k; + int curMin = nums[k]; + int res = curMin; + + while (i > 0 || j < n - 1) { + if (i == 0) { + j++; + } else if (j == n - 1) { + i--; + } else if (nums[i - 1] >= nums[j + 1]) { + i--; + } else { + j++; + } + curMin = [curMin, nums[i], nums[j]].reduce((a, b) => a < b ? a : b); + res = [res, curMin * (j - i + 1)].reduce((a, b) => a > b ? a : b); + } + + return res; + } +} diff --git a/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.go b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.go new file mode 100644 index 00000000..a9777836 --- /dev/null +++ b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.go @@ -0,0 +1,22 @@ +func maximumScore(nums []int, k int) int { + n := len(nums) + i, j := k, k + curMin := nums[k] + res := curMin + + for i > 0 || j < n - 1 { + if i == 0 { + j++ + } else if j == n - 1 { + i-- + } else if nums[i - 1] >= nums[j + 1] { + i-- + } else { + j++ + } + curMin = min(curMin, nums[i], nums[j]) + res = max(res, curMin * (j - i + 1)) + } + + return res +} diff --git a/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.java b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.java new file mode 100644 index 00000000..855fe09f --- /dev/null +++ b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.java @@ -0,0 +1,24 @@ +class Solution { + public int maximumScore(int[] nums, int k) { + int n = nums.length; + int i = k, j = k; + int curMin = nums[k]; + int res = curMin; + + while (i > 0 || j < n - 1) { + if (i == 0) { + j++; + } else if (j == n - 1) { + i--; + } else if (nums[i - 1] >= nums[j + 1]) { + i--; + } else { + j++; + } + curMin = Math.min(curMin, Math.min(nums[i], nums[j])); + res = Math.max(res, curMin * (j - i + 1)); + } + + return res; + } +} diff --git a/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.kt b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.kt new file mode 100644 index 00000000..d8963bd0 --- /dev/null +++ b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun maximumScore(nums: IntArray, k: Int): Int { + val n = nums.size + var i = k + var j = k + var curMin = nums[k] + var res = curMin + + while (i > 0 || j < n - 1) { + if (i == 0) { + j++ + } else if (j == n - 1) { + i-- + } else if (nums[i - 1] >= nums[j + 1]) { + i-- + } else { + j++ + } + curMin = minOf(curMin, nums[i], nums[j]) + res = maxOf(res, curMin * (j - i + 1)) + } + + return res + } +} diff --git a/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.py b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.py new file mode 100644 index 00000000..803004c0 --- /dev/null +++ b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.py @@ -0,0 +1,20 @@ +class Solution: + def maximumScore(self, nums, k): + n = len(nums) + i = j = k + cur_min = nums[k] + res = cur_min + + while i > 0 or j < n - 1: + if i == 0: + j += 1 + elif j == n - 1: + i -= 1 + elif nums[i - 1] >= nums[j + 1]: + i -= 1 + else: + j += 1 + cur_min = min(cur_min, nums[i], nums[j]) + res = max(res, cur_min * (j - i + 1)) + + return res diff --git a/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.py2 b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.py2 new file mode 100644 index 00000000..6c406cde --- /dev/null +++ b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.py2 @@ -0,0 +1,25 @@ +class Solution(object): + def maximumScore(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + n = len(nums) + i = j = k + cur_min = nums[k] + res = cur_min + + while i > 0 or j < n - 1: + if i == 0: + j += 1 + elif j == n - 1: + i -= 1 + elif nums[i - 1] >= nums[j + 1]: + i -= 1 + else: + j += 1 + cur_min = min(cur_min, nums[i], nums[j]) + res = max(res, cur_min * (j - i + 1)) + + return res diff --git a/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.rb b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.rb new file mode 100644 index 00000000..4a1635f9 --- /dev/null +++ b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.rb @@ -0,0 +1,25 @@ +# @param {Integer[]} nums +# @param {Integer} k +# @return {Integer} +def maximum_score(nums, k) + n = nums.length + i = j = k + cur_min = nums[k] + res = cur_min + + while i > 0 || j < n - 1 + if i == 0 + j += 1 + elsif j == n - 1 + i -= 1 + elsif nums[i - 1] >= nums[j + 1] + i -= 1 + else + j += 1 + end + cur_min = [cur_min, nums[i], nums[j]].min + res = [res, cur_min * (j - i + 1)].max + end + + res +end diff --git a/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.rs b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.rs new file mode 100644 index 00000000..d61f9558 --- /dev/null +++ b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn maximum_score(nums: Vec, k: i32) -> i32 { + let n = nums.len(); + let mut i = k as usize; + let mut j = k as usize; + let mut cur_min = nums[k as usize]; + let mut res = cur_min; + + while i > 0 || j < n - 1 { + if i == 0 { + j += 1; + } else if j == n - 1 { + i -= 1; + } else if nums[i - 1] >= nums[j + 1] { + i -= 1; + } else { + j += 1; + } + cur_min = cur_min.min(nums[i]).min(nums[j]); + res = res.max(cur_min * (j - i + 1) as i32); + } + + res + } +} diff --git a/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.swift b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.swift new file mode 100644 index 00000000..a56230d4 --- /dev/null +++ b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.swift @@ -0,0 +1,24 @@ +class Solution { + func maximumScore(_ nums: [Int], _ k: Int) -> Int { + let n = nums.count + var i = k, j = k + var curMin = nums[k] + var res = curMin + + while i > 0 || j < n - 1 { + if i == 0 { + j += 1 + } else if j == n - 1 { + i -= 1 + } else if nums[i - 1] >= nums[j + 1] { + i -= 1 + } else { + j += 1 + } + curMin = min(curMin, nums[i], nums[j]) + res = max(res, curMin * (j - i + 1)) + } + + return res + } +} diff --git a/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.ts b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.ts new file mode 100644 index 00000000..aa690ec4 --- /dev/null +++ b/tests/1501-2000/1793. maximum-score-of-a-good-subarray/sol.ts @@ -0,0 +1,23 @@ +function maximumScore(nums: number[], k: number): number { + const n = nums.length; + let i = k, + j = k; + let curMin = nums[k]; + let res = curMin; + + while (i > 0 || j < n - 1) { + if (i === 0) { + j++; + } else if (j === n - 1) { + i--; + } else if (nums[i - 1] >= nums[j + 1]) { + i--; + } else { + j++; + } + curMin = Math.min(curMin, nums[i], nums[j]); + res = Math.max(res, curMin * (j - i + 1)); + } + + return res; +} diff --git a/tests/1501-2000/1796. second-largest-digit-in-a-string/manifest.yaml b/tests/1501-2000/1796. second-largest-digit-in-a-string/manifest.yaml new file mode 100644 index 00000000..fe4de65d --- /dev/null +++ b/tests/1501-2000/1796. second-largest-digit-in-a-string/manifest.yaml @@ -0,0 +1,210 @@ +entry: + id: 1796 + title: "second-largest-digit-in-a-string" + params: + s: + type: string + call: + cpp: "Solution().secondHighest({s})" + rust: "Solution::second_highest({s})" + python3: "Solution().secondHighest({s})" + python2: "Solution().secondHighest({s})" + ruby: "second_highest({s})" + java: "new Solution().secondHighest({s})" + csharp: "new Solution().SecondHighest({s})" + kotlin: "Solution().secondHighest({s})" + go: "secondHighest({s})" + dart: "Solution().secondHighest({s})" + swift: "Solution().secondHighest({s})" + typescript: "secondHighest({s})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().secondHighest(s, {result})" + checker: | + class Checker: + def secondHighest(self, s, result): + digits = {int(ch) for ch in s if ch.isdigit()} + expected = -1 if len(digits) < 2 else sorted(digits)[-2] + return result == expected + +seed: 1796 + +tests: + - name: example-with-duplicates + in: + s: "dfa12321afd" + out: 2 + - name: one-distinct-digit + in: + s: "abc1111" + out: -1 + - name: no-digits + in: + s: "abcdefghijklmnopqrstuvwxyz" + out: -1 + - name: two-digits + in: + s: "a1b0c" + out: 0 + - name: zero-and-nine + in: + s: "z9a0" + out: 0 + - name: all-digits + in: + s: "0123456789" + out: 8 + - name: descending-digits + in: + s: "9876543210" + out: 8 + - name: repeated-maximum + in: + s: "a9b9c8d8" + out: 8 + - name: repeated-second + in: + s: "x7y3z3" + out: 3 + - name: only-zero + in: + s: "0000abc" + out: -1 + - name: only-nine + in: + s: "999xyz" + out: -1 + - name: minimum-length-two-digits + in: + s: "01" + out: 0 + - name: minimum-length-letters + in: + s: "aa" + out: -1 + - name: max-and-min + in: + s: "a9b1c" + out: 1 + - name: middle-digit + in: + s: "a5b2c5d" + out: 2 + - name: adjacent-digit-run + in: + s: "abc908172" + out: 8 + - name: digits-separated + in: + s: "1a2b3c4d" + out: 3 + - name: alphabet-before-after + in: + s: "a8bc6def" + out: 6 + - name: second-is-zero + in: + s: "5abc0" + out: 0 + - name: second-is-one + in: + s: "2x1y2" + out: 1 + - name: digits-two-and-four + in: + s: "x4x2x4" + out: 2 + - name: digits-three-and-seven + in: + s: "333a777b" + out: 3 + - name: all-nines-and-eight + in: + s: "9999998" + out: 8 + - name: all-zeroes-and-one + in: + s: "000001" + out: 0 + - name: sparse-high-digits + in: + s: "q1w9e2r8t" + out: 8 + - name: sparse-low-digits + in: + s: "q0w3e1r" + out: 1 + - name: five-distinct + in: + s: "a1b4c7d2e" + out: 4 + - name: six-distinct + in: + s: "a6b2c9d0e5" + out: 6 + - name: seven-distinct + in: + s: "z3y8x1w6v4" + out: 6 + - name: eight-distinct + in: + s: "p0q2r4s6t8u9" + out: 8 + - name: nine-distinct + in: + s: "a0b1c2d3e4f5g6h7i9" + out: 7 + - name: ten-distinct-reordered + in: + s: "x8y1z6a3b0c9d2e7f4g5" + out: 8 + - name: long-letters-one-digit + in: + s: "abcdefghijklmnopqrstuvwxyz9876543210abcdefghijklmnopqrstuvwxyz" + out: 8 + - name: long-repeated-pattern + in: + s: "a1b9c4d9e1f4g9h1i4j9k1l4" + out: 4 + - name: long-no-digit + in: + s: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" + out: -1 + - name: generated-short + in: + s: + gen: "str" + len: 1 + alphabet: "ab049" + - name: generated-medium + in: + s: + gen: "str" + len: 50 + alphabet: "abc137" + - name: generated-large-mixed + in: + s: + gen: "str" + len: 500 + alphabet: "abcd02589" + - name: generated-large-digits + in: + s: + gen: "str" + len: 500 + alphabet: "0123456789" + - name: generated-large-letters-digits + in: + s: + gen: "str" + len: 500 + alphabet: "amz069" diff --git a/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.cpp b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.cpp new file mode 100644 index 00000000..a0dd31df --- /dev/null +++ b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.cpp @@ -0,0 +1,22 @@ +#include +#include + +class Solution { +public: + int secondHighest(string s) { + unordered_set digits; + for (char c : s) { + if (isdigit(c)) { + digits.insert(c - '0'); + } + } + if (digits.size() > 1) { + auto maxIt = max_element(digits.begin(), digits.end()); + int max = *maxIt; + digits.erase(maxIt); + auto secondMaxIt = max_element(digits.begin(), digits.end()); + return *secondMaxIt; + } + return -1; + } +}; diff --git a/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.cs b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.cs new file mode 100644 index 00000000..f0989e41 --- /dev/null +++ b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.cs @@ -0,0 +1,20 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public class Solution { + public int SecondHighest(string s) { + var digits = new HashSet(); + foreach (char c in s) { + if (char.IsDigit(c)) { + digits.Add(c - '0'); + } + } + if (digits.Count > 1) { + int max = digits.Max(); + digits.Remove(max); + return digits.Max(); + } + return -1; + } +} diff --git a/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.dart b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.dart new file mode 100644 index 00000000..f1a9e59a --- /dev/null +++ b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.dart @@ -0,0 +1,11 @@ +class Solution { + int secondHighest(String s) { + final digits = s.split('').where((c) => int.tryParse(c) != null).map(int.parse).toSet(); + if (digits.length > 1) { + final max = digits.reduce((a, b) => a > b ? a : b); + digits.remove(max); + return digits.reduce((a, b) => a > b ? a : b); + } + return -1; + } +} diff --git a/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.go b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.go new file mode 100644 index 00000000..ce133ab0 --- /dev/null +++ b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.go @@ -0,0 +1,25 @@ +func secondHighest(s string) int { + digitSet := make(map[int]bool) + for _, r := range s { + if r >= '0' && r <= '9' { + digitSet[int(r-'0')] = true + } + } + if len(digitSet) > 1 { + max := -1 + for d := range digitSet { + if d > max { + max = d + } + } + delete(digitSet, max) + secondMax := -1 + for d := range digitSet { + if d > secondMax { + secondMax = d + } + } + return secondMax + } + return -1 +} diff --git a/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.java b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.java new file mode 100644 index 00000000..e8149081 --- /dev/null +++ b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.java @@ -0,0 +1,18 @@ +import java.util.*; + +class Solution { + public int secondHighest(String s) { + Set digits = new HashSet<>(); + for (char c : s.toCharArray()) { + if (Character.isDigit(c)) { + digits.add(c - '0'); + } + } + if (digits.size() > 1) { + int max = Collections.max(digits); + digits.remove(max); + return Collections.max(digits); + } + return -1; + } +} diff --git a/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.kt b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.kt new file mode 100644 index 00000000..b3195ad0 --- /dev/null +++ b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.kt @@ -0,0 +1,11 @@ +import kotlin.math.max + +class Solution { + fun secondHighest(s: String): Int { + val digits = s.filter { it.isDigit() }.map { it - '0' }.toSet() + return if (digits.size > 1) { + val max = digits.maxOrNull()!! + digits.filter { it != max }.maxOrNull() ?: -1 + } else -1 + } +} diff --git a/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.py b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.py new file mode 100644 index 00000000..f6e31bd2 --- /dev/null +++ b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.py @@ -0,0 +1,16 @@ +class Solution: + def secondHighest(self, s: str) -> int: + nums = "1234567890" + digits = [] + for i in range(len(s)): + if s[i] in nums: + digits.append(int(s[i])) + digits = set(digits) + if len(digits) > 0: + digits.remove(max(digits)) + if len(digits) > 0: + return max(digits) + else: + return -1 + else: + return -1 diff --git a/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.py2 b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.py2 new file mode 100644 index 00000000..d2235174 --- /dev/null +++ b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def secondHighest(self, s): + """ + :type s: str + :rtype: int + """ + digits = set(int(c) for c in s if c.isdigit()) + if len(digits) > 1: + digits.remove(max(digits)) + return max(digits) + return -1 diff --git a/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.rb b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.rb new file mode 100644 index 00000000..2eef7338 --- /dev/null +++ b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.rb @@ -0,0 +1,6 @@ +# @param {String} s +# @return {Integer} +def second_highest(s) + digits = s.chars.select { |c| c =~ /\d/ }.map(&:to_i).uniq.sort + digits.length > 1 ? digits[-2] : -1 +end diff --git a/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.rs b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.rs new file mode 100644 index 00000000..64015536 --- /dev/null +++ b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.rs @@ -0,0 +1,17 @@ +use std::collections::HashSet; + +impl Solution { + pub fn second_highest(s: String) -> i32 { + let digits: HashSet = s.chars() + .filter(|c| c.is_digit(10)) + .map(|c| c.to_digit(10).unwrap() as i32) + .collect(); + if digits.len() > 1 { + let max = digits.iter().max().unwrap(); + let filtered: Vec<&i32> = digits.iter().filter(|d| *d != max).collect(); + **filtered.iter().max().unwrap() + } else { + -1 + } + } +} diff --git a/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.swift b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.swift new file mode 100644 index 00000000..54175fb3 --- /dev/null +++ b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.swift @@ -0,0 +1,17 @@ +class Solution { + func secondHighest(_ s: String) -> Int { + var digits = Set() + for c in s { + if c.isNumber { + digits.insert(c) + } + } + let ints = digits.map { Int(String($0))! } + if ints.count > 1 { + let max = ints.max()! + let filtered = ints.filter { $0 != max } + return filtered.max()! + } + return -1 + } +} diff --git a/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.ts b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.ts new file mode 100644 index 00000000..fcbe035c --- /dev/null +++ b/tests/1501-2000/1796. second-largest-digit-in-a-string/sol.ts @@ -0,0 +1,14 @@ +function secondHighest(s: string): number { + const digits = new Set(); + for (const c of s) { + if (c >= "0" && c <= "9") { + digits.add(parseInt(c)); + } + } + if (digits.size > 1) { + const max = Math.max(...digits); + digits.delete(max); + return Math.max(...digits); + } + return -1; +} diff --git a/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/manifest.yaml b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/manifest.yaml new file mode 100644 index 00000000..934e7417 --- /dev/null +++ b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/manifest.yaml @@ -0,0 +1,221 @@ +entry: + id: 1798 + title: "maximum-number-of-consecutive-values-you-can-make" + params: + coins: + type: array + items: + type: int + call: + cpp: "Solution().getMaximumConsecutive({coins})" + rust: "Solution::get_maximum_consecutive({coins})" + python3: "Solution().getMaximumConsecutive({coins})" + python2: "Solution().getMaximumConsecutive({coins})" + ruby: "get_maximum_consecutive({coins})" + java: "new Solution().getMaximumConsecutive({coins})" + csharp: "new Solution().GetMaximumConsecutive({coins})" + kotlin: "Solution().getMaximumConsecutive({coins})" + go: "getMaximumConsecutive({coins})" + dart: "Solution().getMaximumConsecutive({coins})" + swift: "Solution().getMaximumConsecutive({coins})" + typescript: "getMaximumConsecutive({coins})" +judge: + type: "exact" +limits: + time_ms: 5000 + memory_mb: 512 +oracle: + python3: + call: "Checker().getMaximumConsecutive(coins, {result})" + checker: | + class Checker: + def getMaximumConsecutive(self, coins, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + reach = 0 + for coin in sorted(coins): + if coin > reach + 1: + break + reach += coin + return result == reach + 1 +seed: 1798 +tests: + - name: example-gap + in: + coins: [1, 3] + out: 2 + - name: example-three-ones + in: + coins: [1, 1, 1, 4] + out: 8 + - name: example-unsorted + in: + coins: [1, 4, 10, 3, 1] + out: 20 + - name: single-one + in: + coins: [1] + out: 2 + - name: single-large + in: + coins: [40000] + out: 1 + - name: two-consecutive + in: + coins: [1, 2] + out: 4 + - name: two-gap + in: + coins: [2, 3] + out: 1 + - name: all-ones-five + in: + coins: [1, 1, 1, 1, 1] + out: 6 + - name: powers-with-gap + in: + coins: [1, 2, 4, 8] + out: 16 + - name: powers-with-duplicate-one + in: + coins: [8, 4, 2, 1, 1] + out: 17 + - name: sorted-small-contiguous + in: + coins: [1, 2, 2, 3] + out: 9 + - name: early-break-after-prefix + in: + coins: [1, 1, 3, 100] + out: 6 + - name: large-first-unsorted + in: + coins: [20, 1, 2, 5, 3] + out: 12 + - name: no-one + in: + coins: [2, 2, 2] + out: 1 + - name: duplicate-two-no-one + in: + coins: [2, 2, 2, 2] + out: 1 + - name: exact-prefix-boundary + in: + coins: [1, 1, 3, 6] + out: 12 + - name: bridge-by-equality + in: + coins: [1, 2, 4] + out: 8 + - name: fails-by-one + in: + coins: [1, 2, 5] + out: 4 + - name: repeated-four + in: + coins: [1, 1, 1, 1, 4, 4] + out: 13 + - name: broad-small-values + in: + coins: [1, 2, 3, 4, 5, 6] + out: 22 + - name: shuffled-broad-values + in: + coins: [6, 1, 5, 2, 4, 3] + out: 22 + - name: many-ones-and-gap + in: + coins: [1, 1, 1, 1, 1, 1, 10] + out: 7 + - name: all-large-equal + in: + coins: [40000, 40000, 40000, 40000] + out: 1 + - name: max-value-after-prefix + in: + coins: [1, 2, 4, 8, 40000] + out: 16 + - name: max-value-bridged + in: + coins: [1, 2, 4, 8, 16, 32, 64, 128, 40000] + out: 256 + - name: alternating-order + in: + coins: [10, 1, 9, 2, 8, 3, 7, 4, 6, 5] + out: 56 + - name: twenty-ones + in: + coins: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 21 + - name: large-prefix-then-break + in: + coins: [1, 1, 2, 3, 5, 8, 13, 1000] + out: 34 + - name: duplicates-bridge + in: + coins: [1, 1, 2, 2, 4, 4, 8, 8] + out: 31 + - name: max-coin-with-ones + in: + coins: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 40000] + out: 11 + - name: maximum-total-contiguous + in: + coins: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + out: 56 + - name: generated-balanced + in: + coins: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100 + elemType: "int" + seed: 101 + - name: generated-small-values + in: + coins: + gen: "array" + len: 40000 + of: + gen: "int" + min: 1 + max: 3 + elemType: "int" + seed: 102 + - name: generated-wide-values + in: + coins: + gen: "array" + len: 40000 + of: + gen: "int" + min: 1 + max: 40000 + elemType: "int" + seed: 103 + - name: generated-max-duplicates + in: + coins: + gen: "array" + len: 40000 + of: + gen: "int" + min: 39998 + max: 40000 + elemType: "int" + seed: 104 + - name: generated-mixed + in: + coins: + gen: "array" + len: 20000 + of: + gen: "int" + min: 1 + max: 1000 + elemType: "int" + seed: 105 diff --git a/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.cpp b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.cpp new file mode 100644 index 00000000..5b253ecd --- /dev/null +++ b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int getMaximumConsecutive(vector& coins) { + sort(coins.begin(), coins.end()); + int maxConsecutive = 0; + + for (int coin : coins) { + if (coin > maxConsecutive + 1) break; + maxConsecutive += coin; + } + + return maxConsecutive + 1; + } +}; diff --git a/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.cs b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.cs new file mode 100644 index 00000000..7b6b8abd --- /dev/null +++ b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public int GetMaximumConsecutive(int[] coins) { + Array.Sort(coins); + int maxConsecutive = 0; + + foreach (int coin in coins) { + if (coin > maxConsecutive + 1) break; + maxConsecutive += coin; + } + + return maxConsecutive + 1; + } +} diff --git a/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.dart b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.dart new file mode 100644 index 00000000..3d70273e --- /dev/null +++ b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.dart @@ -0,0 +1,13 @@ +class Solution { + int getMaximumConsecutive(List coins) { + coins.sort(); + int maxConsecutive = 0; + + for (int coin in coins) { + if (coin > maxConsecutive + 1) break; + maxConsecutive += coin; + } + + return maxConsecutive + 1; + } +} diff --git a/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.go b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.go new file mode 100644 index 00000000..1904b17b --- /dev/null +++ b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.go @@ -0,0 +1,13 @@ +func getMaximumConsecutive(coins []int) int { + sort.Ints(coins) + maxConsecutive := 0 + + for _, coin := range coins { + if coin > maxConsecutive + 1 { + break + } + maxConsecutive += coin + } + + return maxConsecutive + 1 +} diff --git a/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.java b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.java new file mode 100644 index 00000000..51b44b48 --- /dev/null +++ b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int getMaximumConsecutive(int[] coins) { + Arrays.sort(coins); + int maxConsecutive = 0; + + for (int coin : coins) { + if (coin > maxConsecutive + 1) break; + maxConsecutive += coin; + } + + return maxConsecutive + 1; + } +} diff --git a/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.kt b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.kt new file mode 100644 index 00000000..f6991ddd --- /dev/null +++ b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun getMaximumConsecutive(coins: IntArray): Int { + coins.sort() + var maxConsecutive = 0 + + for (coin in coins) { + if (coin > maxConsecutive + 1) break + maxConsecutive += coin + } + + return maxConsecutive + 1 + } +} diff --git a/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.py b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.py new file mode 100644 index 00000000..10716fd8 --- /dev/null +++ b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.py @@ -0,0 +1,15 @@ +class Solution(object): + def getMaximumConsecutive(self, coins): + """ + :type coins: List[int] + :rtype: int + """ + coins.sort() + max_consecutive = 0 + + for coin in coins: + if coin > max_consecutive + 1: + break + max_consecutive += coin + + return max_consecutive + 1 diff --git a/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.py2 b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.py2 new file mode 100644 index 00000000..8d6f5761 --- /dev/null +++ b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def getMaximumConsecutive(self, coins): + """ + :type coins: List[int] + :rtype: int + """ + coins.sort() + max_consecutive = 0 + + for coin in coins: + if coin > max_consecutive + 1: + break + max_consecutive += coin + + return max_consecutive + 1 diff --git a/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.rb b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.rb new file mode 100644 index 00000000..7aa57796 --- /dev/null +++ b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.rb @@ -0,0 +1,13 @@ +# @param {Integer[]} coins +# @return {Integer} +def get_maximum_consecutive(coins) + coins.sort! + max_consecutive = 0 + + coins.each do |coin| + break if coin > max_consecutive + 1 + max_consecutive += coin + end + + max_consecutive + 1 +end diff --git a/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.rs b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.rs new file mode 100644 index 00000000..15f82c3d --- /dev/null +++ b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.rs @@ -0,0 +1,14 @@ +impl Solution { + pub fn get_maximum_consecutive(coins: Vec) -> i32 { + let mut coins = coins; + coins.sort(); + let mut max_consecutive = 0; + + for coin in coins { + if coin > max_consecutive + 1 { break; } + max_consecutive += coin; + } + + max_consecutive + 1 + } +} diff --git a/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.swift b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.swift new file mode 100644 index 00000000..ca9cfa57 --- /dev/null +++ b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.swift @@ -0,0 +1,13 @@ +class Solution { + func getMaximumConsecutive(_ coins: [Int]) -> Int { + let sorted = coins.sorted() + var maxConsecutive = 0 + + for coin in sorted { + if coin > maxConsecutive + 1 { break } + maxConsecutive += coin + } + + return maxConsecutive + 1 + } +} diff --git a/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.ts b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.ts new file mode 100644 index 00000000..325a90d2 --- /dev/null +++ b/tests/1501-2000/1798. maximum-number-of-consecutive-values-you-can-make/sol.ts @@ -0,0 +1,11 @@ +function getMaximumConsecutive(coins: number[]): number { + coins.sort((a, b) => a - b); + let maxConsecutive = 0; + + for (const coin of coins) { + if (coin > maxConsecutive + 1) break; + maxConsecutive += coin; + } + + return maxConsecutive + 1; +} diff --git a/tests/1501-2000/1799. maximize-score-after-n-operations/manifest.yaml b/tests/1501-2000/1799. maximize-score-after-n-operations/manifest.yaml new file mode 100644 index 00000000..6527b771 --- /dev/null +++ b/tests/1501-2000/1799. maximize-score-after-n-operations/manifest.yaml @@ -0,0 +1,244 @@ +entry: + id: 1799 + title: "maximize-score-after-n-operations" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().maxScore({nums})" + rust: "Solution::max_score({nums})" + python3: "Solution().maxScore({nums})" + python2: "Solution().maxScore({nums})" + ruby: "max_score({nums})" + java: "new Solution().maxScore({nums})" + csharp: "new Solution().MaxScore({nums})" + kotlin: "Solution().maxScore({nums})" + go: "maxScore({nums})" + dart: "Solution().maxScore({nums})" + swift: "Solution().maxScore({nums})" + typescript: "maxScore({nums})" + +judge: + type: "exact" + +limits: + time_ms: 5000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().maxScore(nums, {result})" + checker: | + from functools import lru_cache + from math import gcd + + class Checker: + def maxScore(self, nums, result): + n = len(nums) + if n == 0 or n % 2 or n > 14: + return False + @lru_cache(None) + def dp(op, mask): + if mask == (1 << n) - 1: + return 0 + best = 0 + for i in range(n): + if mask & (1 << i): + continue + for j in range(i + 1, n): + if mask & (1 << j): + continue + best = max(best, op * gcd(nums[i], nums[j]) + dp(op + 1, mask | (1 << i) | (1 << j))) + return best + return isinstance(result, int) and result == dp(1, 0) + +seed: 1799 + +tests: + - name: example-one + in: + nums: [1, 2] + out: 1 + - name: example-two + in: + nums: [3, 4, 6, 8] + out: 11 + - name: example-three + in: + nums: [1, 2, 3, 4, 5, 6] + out: 14 + - name: equal-pair + in: + nums: [2, 2] + out: 2 + - name: coprime-pair + in: + nums: [6, 10] + out: 2 + - name: four-multiples + in: + nums: [12, 18, 24, 30] + out: 30 + - name: overlapping-divisors + in: + nums: [5, 10, 15, 20] + out: 25 + - name: common-seven + in: + nums: [7, 14, 21, 28] + out: 35 + - name: all-ones + in: + nums: [1, 1, 1, 1] + out: 3 + - name: maximum-equal + in: + nums: [1000000, 1000000] + out: 1000000 + - name: near-maximum-coprime + in: + nums: [999999, 999998] + out: 1 + - name: four-primes + in: + nums: [2, 3, 5, 7] + out: 3 + - name: six-even + in: + nums: [4, 8, 12, 16, 20, 24] + out: 56 + - name: six-overlapping + in: + nums: [6, 9, 15, 21, 27, 33] + out: 36 + - name: six-tens + in: + nums: [10, 20, 30, 40, 50, 60] + out: 140 + - name: eight-eleven + in: + nums: [11, 22, 33, 44, 55, 66, 77, 88] + out: 308 + - name: four-thirteen + in: + nums: [13, 26, 39, 52] + out: 65 + - name: six-seventeen + in: + nums: [17, 34, 51, 68, 85, 102] + out: 238 + - name: eight-eights + in: + nums: [8, 12, 16, 20, 24, 28, 32, 36] + out: 120 + - name: six-nines + in: + nums: [9, 18, 27, 36, 45, 54] + out: 126 + - name: mixed-extremes + in: + nums: [1, 1000000, 2, 999999] + out: 5 + - name: distinct-factors + in: + nums: [25, 35, 49, 77] + out: 19 + - name: six-fourteens + in: + nums: [14, 28, 42, 70, 98, 126] + out: 168 + - name: four-sixteens + in: + nums: [16, 24, 40, 56] + out: 24 + - name: six-eighteens + in: + nums: [18, 30, 42, 66, 78, 90] + out: 108 + - name: four-large-primes + in: + nums: [19, 23, 29, 31] + out: 3 + - name: six-hundreds + in: + nums: [100, 200, 300, 400, 500, 600] + out: 1400 + - name: powers-of-two + in: + nums: [2, 4, 8, 16, 32, 64] + out: 114 + - name: eight-threes + in: + nums: [3, 6, 9, 12, 15, 18, 21, 24] + out: 84 + - name: all-forty-two + in: + nums: [42, 42, 42, 42, 42, 42] + out: 252 + - name: generated-small + in: + nums: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 1000000 + elemType: "int" + judge: + type: "exact" + seed: 1801 + - name: generated-four + in: + nums: + gen: "array" + len: 4 + of: + gen: "int" + min: 1 + max: 1000000 + elemType: "int" + judge: + type: "exact" + seed: 1802 + - name: generated-six + in: + nums: + gen: "array" + len: 6 + of: + gen: "int" + min: 1 + max: 1000000 + elemType: "int" + judge: + type: "exact" + seed: 1803 + - name: generated-ten + in: + nums: + gen: "array" + len: 10 + of: + gen: "int" + min: 1 + max: 1000000 + elemType: "int" + judge: + type: "exact" + seed: 1804 + - name: generated-max-even + in: + nums: + gen: "array" + len: 14 + of: + gen: "int" + min: 1 + max: 1000000 + elemType: "int" + judge: + type: "exact" + seed: 1805 diff --git a/tests/1501-2000/1799. maximize-score-after-n-operations/sol.cpp b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.cpp new file mode 100644 index 00000000..db3eb6b3 --- /dev/null +++ b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int maxScore(vector& nums) { + int n = nums.size(); + vector> dp(1 << n, vector(n/2 + 1, -1)); + function dfs = [&](int mask, int op) -> int { + if (mask == (1 << n) - 1) return 0; + if (dp[mask][op] != -1) return dp[mask][op]; + int ans = 0; + for (int i = 0; i < n; ++i) { + if ((mask & (1 << i)) == 0) { + for (int j = 0; j < n; ++j) { + if (j != i && (mask & (1 << j)) == 0) { + int nmask = mask | (1 << i) | (1 << j); + ans = max(ans, dfs(nmask, op + 1) + gcd(nums[i], nums[j]) * op); + } + } + } + } + return dp[mask][op] = ans; + }; + return dfs(0, 1); + } +}; diff --git a/tests/1501-2000/1799. maximize-score-after-n-operations/sol.cs b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.cs new file mode 100644 index 00000000..aecb3aa7 --- /dev/null +++ b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.cs @@ -0,0 +1,39 @@ +public class Solution { + int[][] dp; + int[] nums; + int n; + public int MaxScore(int[] nums) { + this.nums = nums; + n = nums.Length; + dp = new int[1 << n][]; + for (int i = 0; i < (1 << n); ++i) { + dp[i] = new int[n/2 + 1]; + Array.Fill(dp[i], -1); + } + return Dfs(0, 1); + } + int Dfs(int mask, int op) { + if (mask == (1 << n) - 1) return 0; + if (dp[mask][op] != -1) return dp[mask][op]; + int ans = 0; + for (int i = 0; i < n; ++i) { + if ((mask & (1 << i)) == 0) { + for (int j = 0; j < n; ++j) { + if (j != i && (mask & (1 << j)) == 0) { + int nmask = mask | (1 << i) | (1 << j); + ans = Math.Max(ans, Dfs(nmask, op + 1) + Gcd(nums[i], nums[j]) * op); + } + } + } + } + return dp[mask][op] = ans; + } + int Gcd(int a, int b) { + while (b != 0) { + int t = b; + b = a % b; + a = t; + } + return a; + } +} diff --git a/tests/1501-2000/1799. maximize-score-after-n-operations/sol.dart b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.dart new file mode 100644 index 00000000..b0b2eb13 --- /dev/null +++ b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.dart @@ -0,0 +1,29 @@ +class Solution { + int maxScore(List nums) { + int n = nums.length; + List> dp = List.generate(1 << n, (_) => List.filled(n ~/ 2 + 1, -1)); + + int gcd(int a, int b) => b == 0 ? a : gcd(b, a % b); + + int dfs(int mask, int op) { + if (mask == (1 << n) - 1) return 0; + if (dp[mask][op] != -1) return dp[mask][op]; + int ans = 0; + for (int i = 0; i < n; i++) { + if ((mask & (1 << i)) == 0) { + for (int j = 0; j < n; j++) { + if (j != i && (mask & (1 << j)) == 0) { + int nmask = mask | (1 << i) | (1 << j); + int val = dfs(nmask, op + 1) + gcd(nums[i], nums[j]) * op; + if (val > ans) ans = val; + } + } + } + } + dp[mask][op] = ans; + return ans; + } + + return dfs(0, 1); + } +} diff --git a/tests/1501-2000/1799. maximize-score-after-n-operations/sol.go b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.go new file mode 100644 index 00000000..d7c83b09 --- /dev/null +++ b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.go @@ -0,0 +1,44 @@ +func maxScore(nums []int) int { + n := len(nums) + dp := make([][]int, 1< ans { + ans = val + } + } + } + } + } + dp[mask][op] = ans + return ans + } + return dfs(0, 1) +} + +func gcd(a, b int) int { + for b != 0 { + a, b = b, a%b + } + return a +} diff --git a/tests/1501-2000/1799. maximize-score-after-n-operations/sol.java b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.java new file mode 100644 index 00000000..adfd8860 --- /dev/null +++ b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.java @@ -0,0 +1,36 @@ +class Solution { + int n; + int[][] dp; + int[] nums; + public int maxScore(int[] nums) { + this.nums = nums; + n = nums.length; + dp = new int[1 << n][n/2 + 1]; + for (int i = 0; i < (1 << n); ++i) Arrays.fill(dp[i], -1); + return dfs(0, 1); + } + int dfs(int mask, int op) { + if (mask == (1 << n) - 1) return 0; + if (dp[mask][op] != -1) return dp[mask][op]; + int ans = 0; + for (int i = 0; i < n; ++i) { + if ((mask & (1 << i)) == 0) { + for (int j = 0; j < n; ++j) { + if (j != i && (mask & (1 << j)) == 0) { + int nmask = mask | (1 << i) | (1 << j); + ans = Math.max(ans, dfs(nmask, op + 1) + gcd(nums[i], nums[j]) * op); + } + } + } + } + return dp[mask][op] = ans; + } + int gcd(int a, int b) { + while (b != 0) { + int t = b; + b = a % b; + a = t; + } + return a; + } +} diff --git a/tests/1501-2000/1799. maximize-score-after-n-operations/sol.kt b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.kt new file mode 100644 index 00000000..3e013b50 --- /dev/null +++ b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun maxScore(nums: IntArray): Int { + val n = nums.size + val dp = Array(1 shl n) { IntArray(n / 2 + 1) { -1 } } + fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) + fun dfs(mask: Int, op: Int): Int { + if (mask == (1 shl n) - 1) return 0 + if (dp[mask][op] != -1) return dp[mask][op] + var ans = 0 + for (i in 0 until n) { + if ((mask and (1 shl i)) == 0) { + for (j in 0 until n) { + if (j != i && (mask and (1 shl j)) == 0) { + val nmask = mask or (1 shl i) or (1 shl j) + ans = maxOf(ans, dfs(nmask, op + 1) + gcd(nums[i], nums[j]) * op) + } + } + } + } + dp[mask][op] = ans + return ans + } + return dfs(0, 1) + } +} diff --git a/tests/1501-2000/1799. maximize-score-after-n-operations/sol.py b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.py new file mode 100644 index 00000000..49bafc06 --- /dev/null +++ b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.py @@ -0,0 +1,33 @@ +from math import gcd +from functools import cache + + +class Solution: + def maxScore(self, nums: List[int]) -> int: + """ + maximise Score After N operations + select two elements for nums and get a score of i*(gcd(x,y)) + + Observations + so -> keep the gcd(x,y) -> of the higher ones for last + """ + n = len(nums) + + @cache + def dp(op, mask): + if mask == (1 << n) - 1: + # all are selected + return 0 + ans = 0 + for i in range(n): + if mask & (1 << i) == 0: + for j in range(n): + if j != i and mask & (1 << j) == 0: + ans = max( + ans, + dp(op + 1, (mask | (1 << i) | (1 << j))) + + (gcd(nums[i], nums[j]) * (op)), + ) + return ans + + return dp(1, 0) diff --git a/tests/1501-2000/1799. maximize-score-after-n-operations/sol.py2 b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.py2 new file mode 100644 index 00000000..b2aff143 --- /dev/null +++ b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.py2 @@ -0,0 +1,28 @@ +class Solution(object): + def maxScore(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + n = len(nums) + def gcd(a, b): + while b: + a, b = b, a % b + return a + + memo = {} + def dp(mask, op): + if (mask, op) in memo: + return memo[(mask, op)] + if mask == (1 << n) - 1: + return 0 + ans = 0 + for i in range(n): + if mask & (1 << i) == 0: + for j in range(n): + if j != i and mask & (1 << j) == 0: + nmask = mask | (1 << i) | (1 << j) + ans = max(ans, dp(nmask, op + 1) + gcd(nums[i], nums[j]) * op) + memo[(mask, op)] = ans + return ans + return dp(0, 1) diff --git a/tests/1501-2000/1799. maximize-score-after-n-operations/sol.rb b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.rb new file mode 100644 index 00000000..46be46f7 --- /dev/null +++ b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.rb @@ -0,0 +1,33 @@ +# @param {Integer[]} nums +# @return {Integer} +def max_score(nums) + n = nums.length + dp = Array.new(1 << n) { Array.new(n/2 + 1, -1) } + + gcd_func = ->(a, b) { + while b != 0 + a, b = b, a % b + end + a + } + + dfs = lambda do |mask, op| + return 0 if mask == (1 << n) - 1 + return dp[mask][op] if dp[mask][op] != -1 + + ans = 0 + (0...n).each do |i| + next if (mask & (1 << i)) != 0 + (0...n).each do |j| + next if j == i || (mask & (1 << j)) != 0 + nmask = mask | (1 << i) | (1 << j) + val = dfs.call(nmask, op + 1) + gcd_func.call(nums[i], nums[j]) * op + ans = [ans, val].max + end + end + dp[mask][op] = ans + ans + end + + dfs.call(0, 1) +end diff --git a/tests/1501-2000/1799. maximize-score-after-n-operations/sol.rs b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.rs new file mode 100644 index 00000000..4275570b --- /dev/null +++ b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.rs @@ -0,0 +1,36 @@ +impl Solution { + pub fn max_score(nums: Vec) -> i32 { + let n = nums.len(); + let mut dp = vec![vec![-1; n/2 + 1]; 1 << n]; + + fn gcd(a: i32, b: i32) -> i32 { + if b == 0 { a } else { gcd(b, a % b) } + } + + fn dfs(nums: &Vec, dp: &mut Vec>, mask: usize, op: usize) -> i32 { + let n = nums.len(); + if mask == (1 << n) - 1 { + return 0; + } + if dp[mask][op] != -1 { + return dp[mask][op]; + } + let mut ans = 0; + for i in 0..n { + if (mask & (1 << i)) == 0 { + for j in 0..n { + if j != i && (mask & (1 << j)) == 0 { + let nmask = mask | (1 << i) | (1 << j); + let val = dfs(nums, dp, nmask, op + 1) + gcd(nums[i], nums[j]) * op as i32; + ans = ans.max(val); + } + } + } + } + dp[mask][op] = ans; + ans + } + + dfs(&nums, &mut dp, 0, 1) + } +} diff --git a/tests/1501-2000/1799. maximize-score-after-n-operations/sol.swift b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.swift new file mode 100644 index 00000000..df703368 --- /dev/null +++ b/tests/1501-2000/1799. maximize-score-after-n-operations/sol.swift @@ -0,0 +1,35 @@ +class Solution { + func maxScore(_ nums: [Int]) -> Int { + let n = nums.count + var dp = [[Int]](repeating: [Int](repeating: -1, count: n/2 + 1), count: 1 << n) + + func gcd(_ a: Int, _ b: Int) -> Int { + return b == 0 ? a : gcd(b, a % b) + } + + func dfs(_ mask: Int, _ op: Int) -> Int { + if mask == (1 << n) - 1 { + return 0 + } + if dp[mask][op] != -1 { + return dp[mask][op] + } + var ans = 0 + for i in 0.. + Array(Math.floor(n / 2) + 1).fill(-1), + ); + + const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b)); + + const dfs = (mask: number, op: number): number => { + if (mask === (1 << n) - 1) return 0; + if (dp[mask][op] !== -1) return dp[mask][op]; + let ans = 0; + for (let i = 0; i < n; i++) { + if ((mask & (1 << i)) === 0) { + for (let j = 0; j < n; j++) { + if (j !== i && (mask & (1 << j)) === 0) { + const nmask = mask | (1 << i) | (1 << j); + const val = dfs(nmask, op + 1) + gcd(nums[i], nums[j]) * op; + ans = Math.max(ans, val); + } + } + } + } + dp[mask][op] = ans; + return ans; + }; + + return dfs(0, 1); +} diff --git a/tests/1501-2000/1800. maximum-ascending-subarray-sum/manifest.yaml b/tests/1501-2000/1800. maximum-ascending-subarray-sum/manifest.yaml new file mode 100644 index 00000000..d7593a25 --- /dev/null +++ b/tests/1501-2000/1800. maximum-ascending-subarray-sum/manifest.yaml @@ -0,0 +1,300 @@ +entry: + id: 1800 + title: "maximum-ascending-subarray-sum" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().maxAscendingSum({nums})" + rust: "Solution::max_ascending_sum({nums})" + python3: "Solution().maxAscendingSum({nums})" + python2: "Solution().maxAscendingSum({nums})" + ruby: "max_ascending_sum({nums})" + java: "new Solution().maxAscendingSum({nums})" + csharp: "new Solution().MaxAscendingSum({nums})" + kotlin: "Solution().maxAscendingSum({nums})" + go: "maxAscendingSum({nums})" + dart: "Solution().maxAscendingSum({nums})" + swift: "Solution().maxAscendingSum({nums})" + typescript: "maxAscendingSum({nums})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxAscendingSum(nums, {result})" + checker: | + class Checker: + def maxAscendingSum(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + best = current = nums[0] + for i in range(1, len(nums)): + if nums[i] > nums[i - 1]: + current += nums[i] + else: + current = nums[i] + best = max(best, current) + return result == best + +seed: 1800 + +tests: + - name: example-1 + in: + nums: [10, 20, 30, 5, 10, 50] + out: 65 + judge: + type: "exact" + - name: example-2 + in: + nums: [10, 20, 30, 40, 50] + out: 150 + judge: + type: "exact" + - name: example-3 + in: + nums: [12, 17, 15, 13, 10, 11, 12] + out: 33 + judge: + type: "exact" + - name: single-min + in: + nums: [1] + out: 1 + judge: + type: "exact" + - name: single-max + in: + nums: [100] + out: 100 + judge: + type: "exact" + - name: all-equal + in: + nums: [7, 7, 7, 7, 7] + out: 7 + judge: + type: "exact" + - name: strictly-decreasing + in: + nums: [100, 90, 80, 70, 60, 50] + out: 100 + judge: + type: "exact" + - name: strictly-increasing-small + in: + nums: [1, 2, 3, 4, 5] + out: 15 + judge: + type: "exact" + - name: break-at-start + in: + nums: [9, 1, 2, 3] + out: 9 + judge: + type: "exact" + - name: break-at-end + in: + nums: [1, 2, 3, 9, 4] + out: 15 + judge: + type: "exact" + - name: equal-break + in: + nums: [1, 2, 2, 3, 4] + out: 9 + judge: + type: "exact" + - name: best-not-longest + in: + nums: [1, 2, 100, 1, 99, 100] + out: 200 + judge: + type: "exact" + - name: alternating + in: + nums: [1, 100, 2, 99, 3, 98] + out: 101 + judge: + type: "exact" + - name: repeated-runs + in: + nums: [2, 3, 4, 1, 5, 6, 1, 2, 3] + out: 12 + judge: + type: "exact" + - name: max-values-increasing + in: + nums: [96, 97, 98, 99, 100] + out: 490 + judge: + type: "exact" + - name: max-values-separated + in: + nums: [100, 1, 100, 2, 100] + out: 102 + judge: + type: "exact" + - name: two-elements-up + in: + nums: [1, 100] + out: 101 + judge: + type: "exact" + - name: two-elements-down + in: + nums: [100, 1] + out: 100 + judge: + type: "exact" + - name: long-run-middle + in: + nums: [50, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2] + out: 55 + judge: + type: "exact" + - name: ties-use-value + in: + nums: [5, 6, 1, 4, 5, 6] + out: 16 + judge: + type: "exact" + - name: many-equal-breaks + in: + nums: [3, 3, 4, 4, 5, 5] + out: 9 + judge: + type: "exact" + - name: zigzag-runs + in: + nums: [4, 5, 6, 1, 2, 8, 2, 3, 4, 5] + out: 15 + judge: + type: "exact" + - name: one-long-run + in: + nums: [10, 11, 12, 13, 14, 15, 1] + out: 75 + judge: + type: "exact" + - name: low-values + in: + nums: [1, 1, 2, 1, 2, 3, 1] + out: 6 + judge: + type: "exact" + - name: high-tail + in: + nums: [1, 2, 3, 4, 100] + out: 110 + judge: + type: "exact" + - name: high-head + in: + nums: [100, 1, 2, 3, 4] + out: 100 + judge: + type: "exact" + - name: length-10 + in: + nums: [2, 4, 6, 1, 3, 5, 7, 8, 1, 100] + out: 101 + judge: + type: "exact" + - name: length-20 + in: + nums: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 7, 1, 10, 11, 12, 13, 1, 2, 3] + out: 47 + judge: + type: "exact" + - name: bounded-random-1 + in: + nums: [8, 12, 9, 10, 11, 2, 4, 6, 5, 7, 8] + out: 30 + judge: + type: "exact" + - name: bounded-random-2 + in: + nums: [15, 16, 14, 20, 21, 22, 1, 2, 1, 50, 51] + out: 102 + judge: + type: "exact" + - name: bounded-random-3 + in: + nums: [30, 10, 11, 12, 13, 5, 6, 20, 21, 22, 1] + out: 74 + judge: + type: "exact" + - name: generated-short + in: + nums: + gen: "array" + len: 7 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + seed: 180001 + - name: generated-medium + in: + nums: + gen: "array" + len: 25 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + seed: 180002 + - name: generated-boundary-values + in: + nums: + gen: "array" + len: 50 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + seed: 180003 + - name: generated-large + in: + nums: + gen: "array" + len: 99 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + seed: 180004 + - name: generated-maximum-length + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + seed: 180005 diff --git a/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.cpp b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.cpp new file mode 100644 index 00000000..fc2aaf8c --- /dev/null +++ b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int maxAscendingSum(vector& nums) { + int curr = nums[0], ans = nums[0]; + for (int i = 1; i < nums.size(); i++) { + curr = nums[i] > nums[i-1] ? curr + nums[i] : nums[i]; + ans = max(ans, curr); + } + return ans; + } +}; diff --git a/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.cs b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.cs new file mode 100644 index 00000000..40143993 --- /dev/null +++ b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.cs @@ -0,0 +1,10 @@ +public class Solution { + public int MaxAscendingSum(int[] nums) { + int curr = nums[0], ans = nums[0]; + for (int i = 1; i < nums.Length; i++) { + curr = nums[i] > nums[i-1] ? curr + nums[i] : nums[i]; + ans = Math.Max(ans, curr); + } + return ans; + } +} diff --git a/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.dart b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.dart new file mode 100644 index 00000000..42da16be --- /dev/null +++ b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.dart @@ -0,0 +1,10 @@ +class Solution { + int maxAscendingSum(List nums) { + int curr = nums[0], ans = nums[0]; + for (int i = 1; i < nums.length; i++) { + curr = nums[i] > nums[i-1] ? curr + nums[i] : nums[i]; + if (curr > ans) ans = curr; + } + return ans; + } +} diff --git a/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.go b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.go new file mode 100644 index 00000000..1811653f --- /dev/null +++ b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.go @@ -0,0 +1,14 @@ +func maxAscendingSum(nums []int) int { + curr, ans := nums[0], nums[0] + for i := 1; i < len(nums); i++ { + if nums[i] > nums[i-1] { + curr += nums[i] + } else { + curr = nums[i] + } + if curr > ans { + ans = curr + } + } + return ans +} diff --git a/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.java b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.java new file mode 100644 index 00000000..5a9c386f --- /dev/null +++ b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.java @@ -0,0 +1,10 @@ +class Solution { + public int maxAscendingSum(int[] nums) { + int curr = nums[0], ans = nums[0]; + for (int i = 1; i < nums.length; i++) { + curr = nums[i] > nums[i-1] ? curr + nums[i] : nums[i]; + ans = Math.max(ans, curr); + } + return ans; + } +} diff --git a/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.kt b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.kt new file mode 100644 index 00000000..88b4f06a --- /dev/null +++ b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.kt @@ -0,0 +1,11 @@ +class Solution { + fun maxAscendingSum(nums: IntArray): Int { + var curr = nums[0] + var ans = nums[0] + for (i in 1 until nums.size) { + curr = if (nums[i] > nums[i-1]) curr + nums[i] else nums[i] + ans = maxOf(ans, curr) + } + return ans + } +} diff --git a/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.py b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.py new file mode 100644 index 00000000..31f7628e --- /dev/null +++ b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.py @@ -0,0 +1,7 @@ +class Solution: + def maxAscendingSum(self, nums: List[int]) -> int: + curr = ans = nums[0] + for i in range(1, len(nums)): + curr = curr + nums[i] if nums[i] > nums[i - 1] else nums[i] + ans = max(ans, curr) + return ans diff --git a/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.py2 b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.py2 new file mode 100644 index 00000000..22fc72a5 --- /dev/null +++ b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def maxAscendingSum(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + curr = ans = nums[0] + for i in range(1, len(nums)): + curr = curr + nums[i] if nums[i] > nums[i-1] else nums[i] + ans = max(ans, curr) + return ans diff --git a/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.rb b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.rb new file mode 100644 index 00000000..091d730f --- /dev/null +++ b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.rb @@ -0,0 +1,10 @@ +# @param {Integer[]} nums +# @return {Integer} +def max_ascending_sum(nums) + curr = ans = nums[0] + (1...nums.length).each do |i| + curr = nums[i] > nums[i-1] ? curr + nums[i] : nums[i] + ans = [ans, curr].max + end + ans +end diff --git a/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.rs b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.rs new file mode 100644 index 00000000..098f4561 --- /dev/null +++ b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn max_ascending_sum(nums: Vec) -> i32 { + let mut curr = nums[0]; + let mut ans = nums[0]; + for i in 1..nums.len() { + curr = if nums[i] > nums[i-1] { curr + nums[i] } else { nums[i] }; + ans = ans.max(curr); + } + ans + } +} diff --git a/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.swift b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.swift new file mode 100644 index 00000000..570657b5 --- /dev/null +++ b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.swift @@ -0,0 +1,10 @@ +class Solution { + func maxAscendingSum(_ nums: [Int]) -> Int { + var curr = nums[0], ans = nums[0] + for i in 1.. nums[i-1] ? curr + nums[i] : nums[i] + ans = max(ans, curr) + } + return ans + } +} diff --git a/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.ts b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.ts new file mode 100644 index 00000000..db076dd0 --- /dev/null +++ b/tests/1501-2000/1800. maximum-ascending-subarray-sum/sol.ts @@ -0,0 +1,9 @@ +function maxAscendingSum(nums: number[]): number { + let curr = nums[0], + ans = nums[0]; + for (let i = 1; i < nums.length; i++) { + curr = nums[i] > nums[i - 1] ? curr + nums[i] : nums[i]; + ans = Math.max(ans, curr); + } + return ans; +} diff --git a/tests/1501-2000/1801. number-of-orders-in-the-backlog/manifest.yaml b/tests/1501-2000/1801. number-of-orders-in-the-backlog/manifest.yaml new file mode 100644 index 00000000..ffbaf2a3 --- /dev/null +++ b/tests/1501-2000/1801. number-of-orders-in-the-backlog/manifest.yaml @@ -0,0 +1,212 @@ +entry: + id: 1801 + title: "number-of-orders-in-the-backlog" + params: + orders: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().getNumberOfBacklogOrders({orders})" + rust: "Solution::get_number_of_backlog_orders({orders})" + python3: "Solution().getNumberOfBacklogOrders({orders})" + python2: "Solution().getNumberOfBacklogOrders({orders})" + ruby: "get_number_of_backlog_orders({orders})" + java: "new Solution().getNumberOfBacklogOrders({orders})" + csharp: "new Solution().GetNumberOfBacklogOrders({orders})" + kotlin: "Solution().getNumberOfBacklogOrders({orders})" + go: "getNumberOfBacklogOrders({orders})" + dart: "Solution().getNumberOfBacklogOrders({orders})" + swift: "Solution().getNumberOfBacklogOrders({orders})" + typescript: "getNumberOfBacklogOrders({orders})" + +judge: + type: "exact" + +limits: + time_ms: 5000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().getNumberOfBacklogOrders(orders, {result})" + checker: | + import heapq + + class Checker: + def getNumberOfBacklogOrders(self, orders, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + buy = [] + sell = [] + for order in orders: + price, amount, order_type = order + if order_type == 0: + while amount and sell and sell[0][0] <= price: + sell_price, sell_amount = heapq.heappop(sell) + used = min(amount, sell_amount) + amount -= used + sell_amount -= used + if sell_amount: + heapq.heappush(sell, (sell_price, sell_amount)) + if amount: + heapq.heappush(buy, (-price, amount)) + else: + while amount and buy and -buy[0][0] >= price: + buy_price, buy_amount = heapq.heappop(buy) + used = min(amount, buy_amount) + amount -= used + buy_amount -= used + if buy_amount: + heapq.heappush(buy, (buy_price, buy_amount)) + if amount: + heapq.heappush(sell, (price, amount)) + expected = (sum(amount for _, amount in buy) + sum(amount for _, amount in sell)) % (10 ** 9 + 7) + return result == expected + +seed: 1801 + +tests: + - name: example-one + in: + orders: [[10, 5, 0], [15, 2, 1], [25, 1, 1], [30, 4, 0]] + out: 6 + - name: example-two + in: + orders: [[7, 1000000000, 1], [15, 3, 0], [5, 999999995, 0], [5, 1, 1]] + out: 999999984 + - name: single-buy + in: + orders: [[1, 1, 0]] + out: 1 + - name: single-sell + in: + orders: [[1, 1, 1]] + out: 1 + - name: equal-price-buy-then-sell + in: + orders: [[5, 10, 0], [5, 3, 1]] + out: 7 + - name: equal-price-sell-then-buy + in: + orders: [[5, 3, 1], [5, 10, 0]] + out: 7 + - name: sell-price-too-high + in: + orders: [[10, 5, 0], [11, 4, 1], [9, 3, 1]] + out: 6 + - name: buy-matches-lowest-sell + in: + orders: [[10, 5, 0], [9, 4, 1], [8, 3, 1]] + out: 2 + - name: exact-full-match + in: + orders: [[10, 5, 0], [10, 5, 1]] + out: 0 + - name: buys-then-partial-sell + in: + orders: [[1, 10, 0], [2, 3, 0], [3, 4, 1]] + out: 17 + - name: sells-then-partial-buy + in: + orders: [[1, 10, 1], [2, 3, 1], [3, 4, 0]] + out: 9 + - name: no-crossing-high-buy + in: + orders: [[100, 1, 0], [1, 100, 1]] + out: 99 + - name: no-crossing-low-buy + in: + orders: [[1, 100, 1], [100, 1, 0]] + out: 99 + - name: mixed-price-sell-book + in: + orders: [[3, 5, 0], [2, 2, 1], [4, 4, 1], [3, 3, 0]] + out: 10 + - name: mixed-price-buy-book + in: + orders: [[3, 5, 1], [2, 2, 0], [4, 4, 0], [3, 3, 1]] + out: 6 + - name: repeated-price-crossing + in: + orders: [[1, 1, 0], [2, 2, 0], [3, 3, 0], [1, 2, 1], [2, 2, 1]] + out: 2 + - name: sell-batches-before-buy + in: + orders: [[1, 5, 1], [2, 6, 1], [3, 7, 1], [1, 4, 0], [2, 5, 0]] + out: 9 + - name: one-buy-many-sells + in: + orders: [[10, 100, 0], [9, 30, 1], [8, 40, 1], [7, 50, 1]] + out: 20 + - name: one-sell-many-buys + in: + orders: [[10, 100, 1], [11, 30, 0], [12, 40, 0], [13, 50, 0]] + out: 20 + - name: huge-equal-buy-sell + in: + orders: [[1, 1000000000, 0], [1, 1000000000, 1]] + out: 0 + - name: modulo-backlog + in: + orders: [[1000000000, 1000000000, 1], [1, 1000000000, 0]] + out: 999999993 + - name: descending-buy-prices + in: + orders: [[5, 1, 0], [4, 1, 0], [3, 1, 0], [2, 1, 1], [3, 1, 1], [4, 1, 1]] + out: 2 + - name: layered-sell-matches + in: + orders: [[5, 8, 0], [4, 3, 1], [5, 2, 1], [6, 4, 1], [5, 3, 0]] + out: 10 + - name: sell-backlog-untouched + in: + orders: [[2, 8, 1], [3, 5, 0], [2, 4, 0], [1, 10, 0]] + out: 11 + - name: buy-against-all-sells + in: + orders: [[4, 10, 0], [5, 2, 1], [6, 3, 1], [7, 4, 1], [8, 5, 1]] + out: 24 + - name: repeated-equal-price + in: + orders: [[1, 2, 0], [1, 3, 0], [1, 4, 1], [1, 2, 1], [1, 5, 0]] + out: 4 + - name: alternating-small + in: + orders: [[9, 9, 0], [8, 8, 1], [7, 7, 0], [6, 6, 1], [5, 5, 0]] + out: 7 + - name: wide-price-range + in: + orders: [[50, 20, 0], [40, 10, 1], [30, 5, 1], [60, 15, 1], [45, 12, 0]] + out: 32 + - name: buy-prices-crossed-by-sells + in: + orders: [[2, 100, 1], [4, 50, 0], [3, 20, 0], [2, 10, 0]] + out: 20 + - name: final-sell-drains-book + in: + orders: [[6, 6, 0], [5, 5, 1], [4, 4, 1], [3, 3, 1], [2, 2, 1]] + out: 8 + - name: alternating-price-ladders + in: + orders: + [[10, 20, 0], [9, 5, 1], [11, 7, 1], [8, 13, 0], [10, 4, 1], [12, 9, 1]] + out: 40 + - name: all-buy-batches + in: + orders: [[1, 2, 0], [2, 4, 0], [3, 8, 0], [4, 16, 0]] + out: 30 + - name: all-sell-batches + in: + orders: [[1, 2, 1], [2, 4, 1], [3, 8, 1], [4, 16, 1]] + out: 30 + - name: large-amount-partial-match + in: + orders: [[100, 1000000000, 0], [1, 1, 1], [2, 2, 1], [3, 3, 1]] + out: 999999994 + - name: multiple-partial-remainders + in: + orders: [[10, 11, 0], [9, 4, 1], [10, 3, 1], [11, 20, 1], [10, 2, 0]] + out: 26 diff --git a/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.cpp b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.cpp new file mode 100644 index 00000000..e02903c0 --- /dev/null +++ b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.cpp @@ -0,0 +1,50 @@ +#include +#include +using namespace std; + +class Solution { +public: + int getNumberOfBacklogOrders(vector>& orders) { + priority_queue> buy; + priority_queue, vector>, greater>> sell; + for (auto& o : orders) { + int price = o[0], amount = o[1], type = o[2]; + if (type == 0) { + while (!sell.empty() && sell.top().first <= price) { + auto s = sell.top(); + sell.pop(); + if (amount >= s.second) { + amount -= s.second; + } else { + sell.push({s.first, s.second - amount}); + amount = 0; + break; + } + } + } else { + while (!buy.empty() && buy.top().first >= price) { + auto b = buy.top(); + buy.pop(); + if (amount >= b.second) { + amount -= b.second; + } else { + buy.push({b.first, b.second - amount}); + amount = 0; + break; + } + } + } + if (amount > 0) { + if (type == 0) { + buy.push({price, amount}); + } else { + sell.push({price, amount}); + } + } + } + long long res = 0; + while (!buy.empty()) { res += buy.top().second; buy.pop(); } + while (!sell.empty()) { res += sell.top().second; sell.pop(); } + return res % 1000000007; + } +}; diff --git a/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.cs b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.cs new file mode 100644 index 00000000..93caf42c --- /dev/null +++ b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.cs @@ -0,0 +1,50 @@ +using System.Collections.Generic; +using System.Linq; + +public class Solution { + public int GetNumberOfBacklogOrders(int[][] orders) { + var buy = new SortedDictionary(Comparer.Create((a,b) => b.CompareTo(a))); + var sell = new SortedDictionary(); + foreach (var order in orders) { + int price = order[0], amount = order[1], type = order[2]; + if (type == 0) { + while (sell.Count > 0 && sell.First().Key <= price) { + var s = sell.First(); + if (amount >= s.Value) { + amount -= s.Value; + sell.Remove(s.Key); + } else { + sell[s.Key] = s.Value - amount; + amount = 0; + break; + } + } + } else { + while (buy.Count > 0 && buy.First().Key >= price) { + var b = buy.First(); + if (amount >= b.Value) { + amount -= b.Value; + buy.Remove(b.Key); + } else { + buy[b.Key] = b.Value - amount; + amount = 0; + break; + } + } + } + if (amount > 0) { + if (type == 0) { + if (buy.ContainsKey(price)) buy[price] += amount; + else buy[price] = amount; + } else { + if (sell.ContainsKey(price)) sell[price] += amount; + else sell[price] = amount; + } + } + } + long res = 0; + foreach (var kv in buy) res += kv.Value; + foreach (var kv in sell) res += kv.Value; + return (int)(res % 1000000007); + } +} diff --git a/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.dart b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.dart new file mode 100644 index 00000000..5260a6b2 --- /dev/null +++ b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.dart @@ -0,0 +1,32 @@ +import 'dart:collection'; + +class Solution { + int getNumberOfBacklogOrders(List> orders) { + final buy = SplayTreeMap((a, b) => b.compareTo(a)); + final sell = SplayTreeMap(); + for (final o in orders) { + var price = o[0], amount = o[1], type = o[2]; + if (type == 0) { + while (sell.isNotEmpty && sell.firstKey()! <= price) { + final p = sell.firstKey()!, used = amount < sell[p]! ? amount : sell[p]!; + amount -= used; + if (used == sell[p]!) sell.remove(p); else sell[p] = sell[p]! - used; + if (amount == 0) break; + } + if (amount > 0) buy[price] = (buy[price] ?? 0) + amount; + } else { + while (buy.isNotEmpty && buy.firstKey()! >= price) { + final p = buy.firstKey()!, used = amount < buy[p]! ? amount : buy[p]!; + amount -= used; + if (used == buy[p]!) buy.remove(p); else buy[p] = buy[p]! - used; + if (amount == 0) break; + } + if (amount > 0) sell[price] = (sell[price] ?? 0) + amount; + } + } + var result = 0; + for (final x in buy.values) result = (result + x) % 1000000007; + for (final x in sell.values) result = (result + x) % 1000000007; + return result; + } +} diff --git a/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.go b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.go new file mode 100644 index 00000000..d71cae57 --- /dev/null +++ b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.go @@ -0,0 +1,70 @@ +import hq "container/heap" + +type IntHeap [][]int + +func (h IntHeap) Len() int { return len(h) } +func (h IntHeap) Less(i, j int) bool { return h[i][0] < h[j][0] } +func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.([]int)) } +func (h *IntHeap) Pop() interface{} { + old := *h + n := len(old) + x := old[n-1] + *h = old[0 : n-1] + return x +} + +type MaxHeap [][]int +func (h MaxHeap) Len() int { return len(h) } +func (h MaxHeap) Less(i, j int) bool { return h[i][0] > h[j][0] } +func (h MaxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *MaxHeap) Push(x interface{}) { *h = append(*h, x.([]int)) } +func (h *MaxHeap) Pop() interface{} { old := *h; n := len(old); x := old[n-1]; *h = old[:n-1]; return x } + +func getNumberOfBacklogOrders(orders [][]int) int { + buy := make(MaxHeap, 0) + sell := make(IntHeap, 0) + hq.Init(&buy) + hq.Init(&sell) + for _, order := range orders { + price, amount, orderType := order[0], order[1], order[2] + if orderType == 0 { + for len(sell) > 0 && sell[0][0] <= price { + s := hq.Pop(&sell).([]int) + if amount >= s[1] { + amount -= s[1] + } else { + hq.Push(&sell, []int{s[0], s[1] - amount}) + amount = 0 + break + } + } + } else { + for len(buy) > 0 && buy[0][0] >= price { + b := hq.Pop(&buy).([]int) + if amount >= b[1] { + amount -= b[1] + } else { + hq.Push(&buy, []int{b[0], b[1] - amount}) + amount = 0 + break + } + } + } + if amount > 0 { + if orderType == 0 { + hq.Push(&buy, []int{price, amount}) + } else { + hq.Push(&sell, []int{price, amount}) + } + } + } + res := 0 + for _, x := range buy { + res += x[1] + } + for _, x := range sell { + res += x[1] + } + return res % 1000000007 +} diff --git a/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.java b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.java new file mode 100644 index 00000000..14264cc3 --- /dev/null +++ b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.java @@ -0,0 +1,47 @@ +import java.util.*; + +class Solution { + public int getNumberOfBacklogOrders(int[][] orders) { + PriorityQueue buy = new PriorityQueue<>((a,b) -> Integer.compare(b[0], a[0])); + PriorityQueue sell = new PriorityQueue<>((a,b) -> Integer.compare(a[0], b[0])); + for (int[] order : orders) { + int price = order[0], amount = order[1], type = order[2]; + if (type == 0) { + while (!sell.isEmpty() && sell.peek()[0] <= price) { + int[] s = sell.poll(); + int sellPrice = s[0], sellAmount = s[1]; + if (amount >= sellAmount) { + amount -= sellAmount; + } else { + sell.offer(new int[]{sellPrice, sellAmount - amount}); + amount = 0; + break; + } + } + } else { + while (!buy.isEmpty() && buy.peek()[0] >= price) { + int[] b = buy.poll(); + int buyPrice = b[0], buyAmount = b[1]; + if (amount >= buyAmount) { + amount -= buyAmount; + } else { + buy.offer(new int[]{buyPrice, buyAmount - amount}); + amount = 0; + break; + } + } + } + if (amount > 0) { + if (type == 0) { + buy.offer(new int[]{price, amount}); + } else { + sell.offer(new int[]{price, amount}); + } + } + } + long res = 0; + for (int[] x : buy) res += x[1]; + for (int[] x : sell) res += x[1]; + return (int)(res % 1000000007); + } +} diff --git a/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.kt b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.kt new file mode 100644 index 00000000..4dc68229 --- /dev/null +++ b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.kt @@ -0,0 +1,49 @@ +class Solution { + fun getNumberOfBacklogOrders(orders: Array): Int { + val buy = java.util.PriorityQueue(compareByDescending { it[0] }) + val sell = java.util.PriorityQueue(compareBy { it[0] }) + for (order in orders) { + val price = order[0] + var amount = order[1] + val type = order[2] + if (type == 0) { + while (sell.isNotEmpty() && sell.peek()[0] <= price) { + val s = sell.poll() + val sellPrice = s[0] + val sellAmount = s[1] + if (amount >= sellAmount) { + amount -= sellAmount + } else { + sell.offer(intArrayOf(sellPrice, sellAmount - amount)) + amount = 0 + break + } + } + } else { + while (buy.isNotEmpty() && buy.peek()[0] >= price) { + val b = buy.poll() + val buyPrice = b[0] + val buyAmount = b[1] + if (amount >= buyAmount) { + amount -= buyAmount + } else { + buy.offer(intArrayOf(buyPrice, buyAmount - amount)) + amount = 0 + break + } + } + } + if (amount > 0) { + if (type == 0) { + buy.offer(intArrayOf(price, amount)) + } else { + sell.offer(intArrayOf(price, amount)) + } + } + } + var res = 0L + for (x in buy) res += x[1] + for (x in sell) res += x[1] + return (res % 1000000007).toInt() + } +} diff --git a/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.py b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.py new file mode 100644 index 00000000..0905dbf7 --- /dev/null +++ b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.py @@ -0,0 +1,31 @@ +class Solution: + def getNumberOfBacklogOrders(self, orders: list[list[int]]) -> int: + buy = [] + sell = [] + for price, amount, order_type in orders: + if not order_type: + while sell and sell[0][0] <= price: + sell_price, sell_amount = heapq.heappop(sell) + if amount >= sell_amount: + amount -= sell_amount + else: + heapq.heappush(sell, (sell_price, sell_amount - amount)) + amount = 0 + break + else: + while buy and -buy[0][0] >= price: + buy_price, buy_amount = heapq.heappop(buy) + if amount >= buy_amount: + amount -= buy_amount + else: + heapq.heappush(buy, (buy_price, buy_amount - amount)) + amount = 0 + break + if amount > 0: + if not order_type: + heapq.heappush(buy, (-price, amount)) + else: + heapq.heappush(sell, (price, amount)) + + res = sum(x[1] for x in buy) + sum(x[1] for x in sell) + return res % (10**9 + 7) diff --git a/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.py2 b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.py2 new file mode 100644 index 00000000..500489d4 --- /dev/null +++ b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.py2 @@ -0,0 +1,35 @@ +class Solution(object): + def getNumberOfBacklogOrders(self, orders): + """ + :type orders: List[List[int]] + :rtype: int + """ + import heapq + buy = [] + sell = [] + for price, amount, order_type in orders: + if not order_type: + while sell and sell[0][0] <= price: + sell_price, sell_amount = heapq.heappop(sell) + if amount >= sell_amount: + amount -= sell_amount + else: + heapq.heappush(sell, (sell_price, sell_amount - amount)) + amount = 0 + break + else: + while buy and -buy[0][0] >= price: + buy_price, buy_amount = heapq.heappop(buy) + if amount >= buy_amount: + amount -= buy_amount + else: + heapq.heappush(buy, (buy_price, buy_amount - amount)) + amount = 0 + break + if amount > 0: + if not order_type: + heapq.heappush(buy, (-price, amount)) + else: + heapq.heappush(sell, (price, amount)) + res = sum(x[1] for x in buy) + sum(x[1] for x in sell) + return res % (10**9 + 7) diff --git a/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.rb b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.rb new file mode 100644 index 00000000..d2bb7fd7 --- /dev/null +++ b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.rb @@ -0,0 +1,42 @@ +# @param {Integer[][]} orders +# @return {Integer} +def get_number_of_backlog_orders(orders) + buy = [] + sell = [] + orders.each do |price, amount, order_type| + if order_type == 0 + while !sell.empty? && sell[0][0] <= price + sell_price, sell_amount = sell.shift + if amount >= sell_amount + amount -= sell_amount + else + sell.unshift([sell_price, sell_amount - amount]) + amount = 0 + break + end + end + else + while !buy.empty? && -buy[0][0] >= price + buy_price, buy_amount = buy.shift + if amount >= buy_amount + amount -= buy_amount + else + buy.unshift([buy_price, buy_amount - amount]) + amount = 0 + break + end + end + end + if amount > 0 + if order_type == 0 + buy.unshift([-price, amount]) + buy.sort_by! { |x| x[0] } + else + sell.unshift([price, amount]) + sell.sort_by! { |x| x[0] } + end + end + end + res = buy.sum { |x| x[1] } + sell.sum { |x| x[1] } + res % (10**9 + 7) +end diff --git a/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.rs b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.rs new file mode 100644 index 00000000..7363ab5f --- /dev/null +++ b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.rs @@ -0,0 +1,46 @@ +use std::collections::BinaryHeap; +use std::cmp::Reverse; + +impl Solution { + pub fn get_number_of_backlog_orders(orders: Vec>) -> i32 { + let mut buy: BinaryHeap<(i32, i32)> = BinaryHeap::new(); + let mut sell: BinaryHeap> = BinaryHeap::new(); + for order in &orders { + let price = order[0]; + let mut amount = order[1]; + let order_type = order[2]; + if order_type == 0 { + while !sell.is_empty() && sell.peek().unwrap().0.0 <= price { + let s = sell.pop().unwrap().0; + if amount >= s.1 { + amount -= s.1; + } else { + sell.push(Reverse((s.0, s.1 - amount))); + amount = 0; + break; + } + } + } else { + while !buy.is_empty() && buy.peek().unwrap().0 >= price { + let b = buy.pop().unwrap(); + if amount >= b.1 { + amount -= b.1; + } else { + buy.push((b.0, b.1 - amount)); + amount = 0; + break; + } + } + } + if amount > 0 { + if order_type == 0 { + buy.push((price, amount)); + } else { + sell.push(Reverse((price, amount))); + } + } + } + let res: i64 = buy.iter().map(|x| x.1 as i64).sum::() + sell.iter().map(|x| x.0.1 as i64).sum::(); + (res % 1_000_000_007) as i32 + } +} diff --git a/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.swift b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.swift new file mode 100644 index 00000000..fd21c06a --- /dev/null +++ b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.swift @@ -0,0 +1,47 @@ +class Solution { + func getNumberOfBacklogOrders(_ orders: [[Int]]) -> Int { + var buy = [(Int, Int)]() + var sell = [(Int, Int)]() + for order in orders { + let price = order[0] + var amount = order[1] + let type = order[2] + if type == 0 { + while !sell.isEmpty && sell[0].0 <= price { + let s = sell.removeFirst() + if amount >= s.1 { + amount -= s.1 + } else { + sell.insert((s.0, s.1 - amount), at: 0) + amount = 0 + break + } + } + } else { + while !buy.isEmpty && -buy[0].0 >= price { + let b = buy.removeFirst() + if amount >= b.1 { + amount -= b.1 + } else { + buy.insert((b.0, b.1 - amount), at: 0) + amount = 0 + break + } + } + } + if amount > 0 { + if type == 0 { + buy.insert((-price, amount), at: 0) + buy.sort { $0.0 < $1.0 } + } else { + sell.insert((price, amount), at: 0) + sell.sort { $0.0 < $1.0 } + } + } + } + var res = 0 + for x in buy { res += x.1 } + for x in sell { res += x.1 } + return res % 1_000_000_007 + } +} diff --git a/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.ts b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.ts new file mode 100644 index 00000000..b2fa2e80 --- /dev/null +++ b/tests/1501-2000/1801. number-of-orders-in-the-backlog/sol.ts @@ -0,0 +1,45 @@ +function getNumberOfBacklogOrders(orders: number[][]): number { + const buy: [number, number][] = []; + const sell: [number, number][] = []; + for (const [price, amount0, type] of orders) { + let amount = amount0; + if (type === 0) { + while (sell.length > 0 && sell[0][0] <= price) { + const s = sell[0]; + sell.splice(0, 1); + if (amount >= s[1]) { + amount -= s[1]; + } else { + sell.unshift([s[0], s[1] - amount]); + amount = 0; + break; + } + } + } else { + while (buy.length > 0 && -buy[0][0] >= price) { + const b = buy[0]; + buy.splice(0, 1); + if (amount >= b[1]) { + amount -= b[1]; + } else { + buy.unshift([b[0], b[1] - amount]); + amount = 0; + break; + } + } + } + if (amount > 0) { + if (type === 0) { + buy.unshift([-price, amount]); + buy.sort((a, b) => a[0] - b[0]); + } else { + sell.unshift([price, amount]); + sell.sort((a, b) => a[0] - b[0]); + } + } + } + const sum = (arr: [number, number][]) => + arr.reduce((acc, x) => acc + x[1], 0); + const res = sum(buy) + sum(sell); + return res % 1_000_000_007; +} diff --git a/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/manifest.yaml b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/manifest.yaml new file mode 100644 index 00000000..1f911f91 --- /dev/null +++ b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/manifest.yaml @@ -0,0 +1,315 @@ +entry: + id: 1802 + title: "maximum-value-at-a-given-index-in-a-bounded-array" + params: + n: + type: int + index: + type: int + maxSum: + type: int + call: + cpp: "Solution().maxValue({n}, {index}, {maxSum})" + rust: "Solution::max_value({n}, {index}, {maxSum})" + python3: "Solution().maxValue({n}, {index}, {maxSum})" + python2: "Solution().maxValue({n}, {index}, {maxSum})" + ruby: "max_value({n}, {index}, {maxSum})" + java: "new Solution().maxValue({n}, {index}, {maxSum})" + csharp: "new Solution().MaxValue({n}, {index}, {maxSum})" + kotlin: "Solution().maxValue({n}, {index}, {maxSum})" + go: "maxValue({n}, {index}, {maxSum})" + dart: "Solution().maxValue({n}, {index}, {maxSum})" + swift: "Solution().maxValue({n}, {index}, {maxSum})" + typescript: "maxValue({n}, {index}, {maxSum})" + +judge: + type: "exact" + +limits: + time_ms: 5000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxValue(n, index, maxSum, {result})" + checker: | + class Checker: + def maxValue(self, n, index, maxSum, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + def cost(peak): + left_count = index + right_count = n - index - 1 + left = peak * (peak - 1) // 2 + max(0, left_count - (peak - 1)) + right = peak * (peak - 1) // 2 + max(0, right_count - (peak - 1)) + if peak > left_count: + left = (peak - left_count + peak - 1) * left_count // 2 + if peak > right_count: + right = (peak - right_count + peak - 1) * right_count // 2 + return left + peak + right + if result < 1 or result > maxSum or cost(result) > maxSum: + return False + low, high = 1, maxSum + expected = 1 + while low <= high: + mid = (low + high) // 2 + if cost(mid) <= maxSum: + expected = mid + low = mid + 1 + else: + high = mid - 1 + return result == expected + +seed: 1802 + +tests: + - name: example-one + in: + n: 4 + index: 2 + maxSum: 6 + out: 2 + - name: example-two + in: + n: 6 + index: 1 + maxSum: 10 + out: 3 + - name: single-element + in: + n: 1 + index: 0 + maxSum: 1 + out: 1 + - name: two-left + in: + n: 2 + index: 0 + maxSum: 2 + out: 1 + - name: two-right + in: + n: 2 + index: 1 + maxSum: 2 + out: 1 + - name: minimum-three + in: + n: 3 + index: 1 + maxSum: 3 + out: 1 + - name: small-centered + in: + n: 3 + index: 1 + maxSum: 6 + out: 2 + - name: minimum-left-edge + in: + n: 5 + index: 0 + maxSum: 5 + out: 1 + - name: minimum-right-edge + in: + n: 5 + index: 4 + maxSum: 5 + out: 1 + - name: minimum-centered + in: + n: 5 + index: 2 + maxSum: 5 + out: 1 + - name: centered-ten + in: + n: 5 + index: 2 + maxSum: 10 + out: 3 + - name: centered-fifteen + in: + n: 5 + index: 2 + maxSum: 15 + out: 4 + - name: long-left-edge-minimum + in: + n: 10 + index: 0 + maxSum: 10 + out: 1 + - name: long-right-edge-minimum + in: + n: 10 + index: 9 + maxSum: 10 + out: 1 + - name: long-center-minimum + in: + n: 10 + index: 5 + maxSum: 10 + out: 1 + - name: long-center-small-budget + in: + n: 10 + index: 5 + maxSum: 20 + out: 4 + - name: long-center-large-budget + in: + n: 10 + index: 5 + maxSum: 100 + out: 12 + - name: hundred-left-minimum + in: + n: 100 + index: 0 + maxSum: 100 + out: 1 + - name: hundred-right-minimum + in: + n: 100 + index: 99 + maxSum: 100 + out: 1 + - name: hundred-center-minimum + in: + n: 100 + index: 50 + maxSum: 100 + out: 1 + - name: hundred-center-budget + in: + n: 100 + index: 50 + maxSum: 1000 + out: 31 + - name: max-n-left-edge + in: + n: 1000000000 + index: 0 + maxSum: 1000000000 + out: 1 + - name: max-n-right-edge + in: + n: 1000000000 + index: 999999999 + maxSum: 1000000000 + out: 1 + - name: max-n-center + in: + n: 1000000000 + index: 500000000 + maxSum: 1000000000 + out: 1 + - name: seven-centered + in: + n: 7 + index: 3 + maxSum: 20 + out: 4 + - name: seven-left-edge + in: + n: 7 + index: 0 + maxSum: 20 + out: 5 + - name: seven-right-edge + in: + n: 7 + index: 6 + maxSum: 20 + out: 5 + - name: eight-left-center + in: + n: 8 + index: 2 + maxSum: 25 + out: 5 + - name: eight-right-center + in: + n: 8 + index: 5 + maxSum: 25 + out: 5 + - name: twenty-center-tight + in: + n: 20 + index: 10 + maxSum: 35 + out: 4 + - name: twenty-left-rich + in: + n: 20 + index: 0 + maxSum: 100 + out: 13 + - name: twenty-right-rich + in: + n: 20 + index: 19 + maxSum: 100 + out: 13 + - name: fifty-center-tight + in: + n: 50 + index: 25 + maxSum: 75 + out: 6 + - name: fifty-near-left-rich + in: + n: 50 + index: 1 + maxSum: 1000 + out: 43 + - name: thousand-center-rich + in: + n: 1000 + index: 500 + maxSum: 1000000 + out: 1250 + - name: generated-large-left + in: + n: + gen: "int" + min: 50000 + max: 100000 + index: 0 + maxSum: 1000000000 + - name: generated-large-right + in: + n: + gen: "int" + min: 50000 + max: 100000 + index: 49999 + maxSum: 1000000000 + - name: generated-large-center + in: + n: + gen: "int" + min: 50000 + max: 100000 + index: 25000 + maxSum: 1000000000 + - name: generated-medium-left + in: + n: + gen: "int" + min: 1000 + max: 10000 + index: 0 + maxSum: 100000000 + - name: generated-medium-center + in: + n: + gen: "int" + min: 1000 + max: 10000 + index: 500 + maxSum: 100000000 diff --git a/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.cpp b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.cpp new file mode 100644 index 00000000..57f502a8 --- /dev/null +++ b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int maxValue(int n, int index, int maxSum) { + long long l = 0, r = maxSum, result = 1; + while (l <= r) { + long long mid = (l + r) / 2; + if (isValid(mid, n, index, maxSum)) { + result = mid; + l = mid + 1; + } else { + r = mid - 1; + } + } + return (int)result; + } + +private: + bool isValid(long long mid, int n, int index, int maxSum) { + long long leftCount = index; + long long left; + if (mid > leftCount) { + left = (mid - leftCount + mid - 1) * leftCount / 2; + } else { + long long ones = leftCount - (mid - 1); + left = mid * (mid - 1) / 2 + ones; + } + + long long rightCount = n - index - 1; + long long right; + if (mid > rightCount) { + right = (mid - 1 + mid - rightCount) * rightCount / 2; + } else { + long long ones = rightCount - (mid - 1); + right = mid * (mid - 1) / 2 + ones; + } + + return left + mid + right <= maxSum; + } +}; diff --git a/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.cs b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.cs new file mode 100644 index 00000000..a1a37abe --- /dev/null +++ b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.cs @@ -0,0 +1,37 @@ +public class Solution { + public int MaxValue(int n, int index, int maxSum) { + long l = 0, r = maxSum, result = 1; + while (l <= r) { + long mid = (l + r) / 2; + if (IsValid(mid, n, index, maxSum)) { + result = mid; + l = mid + 1; + } else { + r = mid - 1; + } + } + return (int)result; + } + + private bool IsValid(long mid, int n, int index, int maxSum) { + long leftCount = index; + long left; + if (mid > leftCount) { + left = (mid - leftCount + mid - 1) * leftCount / 2; + } else { + long ones = leftCount - (mid - 1); + left = mid * (mid - 1) / 2 + ones; + } + + long rightCount = n - index - 1; + long right; + if (mid > rightCount) { + right = (mid - 1 + mid - rightCount) * rightCount / 2; + } else { + long ones = rightCount - (mid - 1); + right = mid * (mid - 1) / 2 + ones; + } + + return left + mid + right <= maxSum; + } +} diff --git a/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.dart b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.dart new file mode 100644 index 00000000..de03de7b --- /dev/null +++ b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.dart @@ -0,0 +1,37 @@ +class Solution { + int maxValue(int n, int index, int maxSum) { + int l = 0, r = maxSum, result = 1; + while (l <= r) { + int mid = (l + r) ~/ 2; + if (isValid(mid, n, index, maxSum)) { + result = mid; + l = mid + 1; + } else { + r = mid - 1; + } + } + return result; + } + + bool isValid(int mid, int n, int index, int maxSum) { + int leftCount = index; + int left; + if (mid > leftCount) { + left = (mid - leftCount + mid - 1) * leftCount ~/ 2; + } else { + int ones = leftCount - (mid - 1); + left = mid * (mid - 1) ~/ 2 + ones; + } + + int rightCount = n - index - 1; + int right; + if (mid > rightCount) { + right = (mid - 1 + mid - rightCount) * rightCount ~/ 2; + } else { + int ones = rightCount - (mid - 1); + right = mid * (mid - 1) ~/ 2 + ones; + } + + return left + mid + right <= maxSum; + } +} diff --git a/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.go b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.go new file mode 100644 index 00000000..53c36d8a --- /dev/null +++ b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.go @@ -0,0 +1,37 @@ +func maxValue(n int, index int, maxSum int) int { + l := int64(0) + r := int64(maxSum) + result := int64(1) + for l <= r { + mid := (l + r) / 2 + if isValid(mid, int64(n), int64(index), int64(maxSum)) { + result = mid + l = mid + 1 + } else { + r = mid - 1 + } + } + return int(result) +} + +func isValid(mid int64, n int64, index int64, maxSum int64) bool { + leftCount := index + var left int64 + if mid > leftCount { + left = (mid - leftCount + mid - 1) * leftCount / 2 + } else { + ones := leftCount - (mid - 1) + left = mid*(mid-1)/2 + ones + } + + rightCount := n - index - 1 + var right int64 + if mid > rightCount { + right = (mid - 1 + mid - rightCount) * rightCount / 2 + } else { + ones := rightCount - (mid - 1) + right = mid*(mid-1)/2 + ones + } + + return left + mid + right <= maxSum +} diff --git a/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.java b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.java new file mode 100644 index 00000000..57f48070 --- /dev/null +++ b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.java @@ -0,0 +1,37 @@ +class Solution { + public int maxValue(int n, int index, int maxSum) { + long l = 0, r = maxSum, result = 1; + while (l <= r) { + long mid = (l + r) / 2; + if (isValid(mid, n, index, maxSum)) { + result = mid; + l = mid + 1; + } else { + r = mid - 1; + } + } + return (int) result; + } + + private boolean isValid(long mid, int n, int index, int maxSum) { + long leftCount = index; + long left; + if (mid > leftCount) { + left = (mid - leftCount + mid - 1) * leftCount / 2; + } else { + long ones = leftCount - (mid - 1); + left = mid * (mid - 1) / 2 + ones; + } + + long rightCount = n - index - 1; + long right; + if (mid > rightCount) { + right = (mid - 1 + mid - rightCount) * rightCount / 2; + } else { + long ones = rightCount - (mid - 1); + right = mid * (mid - 1) / 2 + ones; + } + + return left + mid + right <= maxSum; + } +} diff --git a/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.kt b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.kt new file mode 100644 index 00000000..d0d61306 --- /dev/null +++ b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.kt @@ -0,0 +1,39 @@ +class Solution { + fun maxValue(n: Int, index: Int, maxSum: Int): Int { + var l = 0L + var r = maxSum.toLong() + var result = 1L + while (l <= r) { + val mid = (l + r) / 2 + if (isValid(mid, n, index, maxSum)) { + result = mid + l = mid + 1 + } else { + r = mid - 1 + } + } + return result.toInt() + } + + private fun isValid(mid: Long, n: Int, index: Int, maxSum: Int): Boolean { + val leftCount = index.toLong() + val left: Long + if (mid > leftCount) { + left = (mid - leftCount + mid - 1) * leftCount / 2 + } else { + val ones = leftCount - (mid - 1) + left = mid * (mid - 1) / 2 + ones + } + + val rightCount = (n - index - 1).toLong() + val right: Long + if (mid > rightCount) { + right = (mid - 1 + mid - rightCount) * rightCount / 2 + } else { + val ones = rightCount - (mid - 1) + right = mid * (mid - 1) / 2 + ones + } + + return left + mid + right <= maxSum + } +} diff --git a/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.py b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.py new file mode 100644 index 00000000..f3015525 --- /dev/null +++ b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.py @@ -0,0 +1,28 @@ +class Solution: + def maxValue(self, n: int, index: int, maxSum: int) -> int: + def isValid(mid): + left = 0 + if mid > index: + left = (mid - index + mid - 1) * index // 2 + else: + ones = index - (mid - 1) + left = mid * (mid - 1) // 2 + ones + + rightCount = n - index - 1 + if mid > rightCount: + right = (mid - 1 + mid - rightCount) * rightCount // 2 + else: + ones = rightCount - (mid - 1) + right = mid * (mid - 1) // 2 + ones + + return left + mid + right <= maxSum + + l, r, result = 0, maxSum, 1 + while l <= r: + mid = (l + r) // 2 + if isValid(mid): + result = mid + l = mid + 1 + else: + r = mid - 1 + return result diff --git a/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.py2 b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.py2 new file mode 100644 index 00000000..310c9cb3 --- /dev/null +++ b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.py2 @@ -0,0 +1,34 @@ +class Solution(object): + def maxValue(self, n, index, maxSum): + """ + :type n: int + :type index: int + :type maxSum: int + :rtype: int + """ + def isValid(mid): + leftCount = index + if mid > leftCount: + left = (mid - leftCount + mid - 1) * leftCount // 2 + else: + ones = leftCount - (mid - 1) + left = mid * (mid - 1) // 2 + ones + + rightCount = n - index - 1 + if mid > rightCount: + right = (mid - 1 + mid - rightCount) * rightCount // 2 + else: + ones = rightCount - (mid - 1) + right = mid * (mid - 1) // 2 + ones + + return left + mid + right <= maxSum + + l, r, result = 0, maxSum, 1 + while l <= r: + mid = (l + r) // 2 + if isValid(mid): + result = mid + l = mid + 1 + else: + r = mid - 1 + return result diff --git a/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.rb b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.rb new file mode 100644 index 00000000..1dcb3c94 --- /dev/null +++ b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.rb @@ -0,0 +1,37 @@ +# @param {Integer} n +# @param {Integer} index +# @param {Integer} max_sum +# @return {Integer} +def max_value(n, index, max_sum) + def is_valid(mid, n, index, max_sum) + left_count = index + if mid > left_count + left = (mid - left_count + mid - 1) * left_count / 2 + else + ones = left_count - (mid - 1) + left = mid * (mid - 1) / 2 + ones + end + + right_count = n - index - 1 + if mid > right_count + right = (mid - 1 + mid - right_count) * right_count / 2 + else + ones = right_count - (mid - 1) + right = mid * (mid - 1) / 2 + ones + end + + left + mid + right <= max_sum + end + + l, r, result = 0, max_sum, 1 + while l <= r + mid = (l + r) / 2 + if is_valid(mid, n, index, max_sum) + result = mid + l = mid + 1 + else + r = mid - 1 + end + end + result +end diff --git a/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.rs b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.rs new file mode 100644 index 00000000..f14fcb4c --- /dev/null +++ b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.rs @@ -0,0 +1,39 @@ +impl Solution { + pub fn max_value(n: i32, index: i32, max_sum: i32) -> i32 { + let mut l = 0i64; + let mut r = max_sum as i64; + let mut result = 1i64; + while l <= r { + let mid = (l + r) / 2; + if Self::is_valid(mid, n as i64, index as i64, max_sum as i64) { + result = mid; + l = mid + 1; + } else { + r = mid - 1; + } + } + result as i32 + } + + fn is_valid(mid: i64, n: i64, index: i64, max_sum: i64) -> bool { + let left_count = index; + let left: i64; + if mid > left_count { + left = (mid - left_count + mid - 1) * left_count / 2; + } else { + let ones = left_count - (mid - 1); + left = mid * (mid - 1) / 2 + ones; + } + + let right_count = n - index - 1; + let right: i64; + if mid > right_count { + right = (mid - 1 + mid - right_count) * right_count / 2; + } else { + let ones = right_count - (mid - 1); + right = mid * (mid - 1) / 2 + ones; + } + + left + mid + right <= max_sum + } +} diff --git a/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.swift b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.swift new file mode 100644 index 00000000..95e42775 --- /dev/null +++ b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.swift @@ -0,0 +1,37 @@ +class Solution { + func maxValue(_ n: Int, _ index: Int, _ maxSum: Int) -> Int { + var l = 0, r = maxSum, result = 1 + while l <= r { + let mid = (l + r) / 2 + if isValid(mid, n, index, maxSum) { + result = mid + l = mid + 1 + } else { + r = mid - 1 + } + } + return result + } + + private func isValid(_ mid: Int, _ n: Int, _ index: Int, _ maxSum: Int) -> Bool { + let leftCount = index + var left: Int + if mid > leftCount { + left = (mid - leftCount + mid - 1) * leftCount / 2 + } else { + let ones = leftCount - (mid - 1) + left = mid * (mid - 1) / 2 + ones + } + + let rightCount = n - index - 1 + var right: Int + if mid > rightCount { + right = (mid - 1 + mid - rightCount) * rightCount / 2 + } else { + let ones = rightCount - (mid - 1) + right = mid * (mid - 1) / 2 + ones + } + + return left + mid + right <= maxSum + } +} diff --git a/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.ts b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.ts new file mode 100644 index 00000000..af68c2bf --- /dev/null +++ b/tests/1501-2000/1802. maximum-value-at-a-given-index-in-a-bounded-array/sol.ts @@ -0,0 +1,42 @@ +function maxValue(n: number, index: number, maxSum: number): number { + let l = 0, + r = maxSum, + result = 1; + while (l <= r) { + const mid = Math.floor((l + r) / 2); + if (isValid(mid, n, index, maxSum)) { + result = mid; + l = mid + 1; + } else { + r = mid - 1; + } + } + return result; +} + +function isValid( + mid: number, + n: number, + index: number, + maxSum: number, +): boolean { + const leftCount = index; + let left: number; + if (mid > leftCount) { + left = Math.floor(((mid - leftCount + mid - 1) * leftCount) / 2); + } else { + const ones = leftCount - (mid - 1); + left = (mid * (mid - 1)) / 2 + ones; + } + + const rightCount = n - index - 1; + let right: number; + if (mid > rightCount) { + right = Math.floor(((mid - 1 + mid - rightCount) * rightCount) / 2); + } else { + const ones = rightCount - (mid - 1); + right = (mid * (mid - 1)) / 2 + ones; + } + + return left + mid + right <= maxSum; +} diff --git a/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/manifest.yaml b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/manifest.yaml new file mode 100644 index 00000000..06f2cf6f --- /dev/null +++ b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/manifest.yaml @@ -0,0 +1,329 @@ +entry: + id: 1803 + title: "count-pairs-with-xor-in-a-range" + params: + nums: + type: array + items: + type: int + low: + type: int + high: + type: int + call: + cpp: "Solution().countPairs({nums}, {low}, {high})" + rust: "Solution::count_pairs({nums}, {low}, {high})" + python3: "Solution().countPairs({nums}, {low}, {high})" + python2: "Solution().countPairs({nums}, {low}, {high})" + ruby: "count_pairs({nums}, {low}, {high})" + java: "new Solution().countPairs({nums}, {low}, {high})" + csharp: "new Solution().CountPairs({nums}, {low}, {high})" + kotlin: "Solution().countPairs({nums}, {low}, {high})" + go: "countPairs({nums}, {low}, {high})" + dart: "Solution().countPairs({nums}, {low}, {high})" + swift: "Solution().countPairs({nums}, {low}, {high})" + typescript: "countPairs({nums}, {low}, {high})" + +judge: + type: "exact" + +limits: + time_ms: 5000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().countPairs(nums, low, high, {result})" + checker: | + class Checker: + def countPairs(self, nums, low, high, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + bits = max(1, max(max(nums).bit_length(), (high + 1).bit_length())) + def count_less(bound): + if bound <= 0: + return 0 + child = [[-1, -1]] + counts = [0] + total = 0 + for value in nums: + node = 0 + for bit in range(bits - 1, -1, -1): + v = (value >> bit) & 1 + b = (bound >> bit) & 1 + if b: + same = child[node][v] + if same != -1: + total += counts[same] + node = child[node][1 - v] + else: + node = child[node][v] + if node == -1: + break + node = 0 + for bit in range(bits - 1, -1, -1): + v = (value >> bit) & 1 + nxt = child[node][v] + if nxt == -1: + nxt = len(child) + child[node][v] = nxt + child.append([-1, -1]) + counts.append(0) + node = nxt + counts[node] += 1 + return total + return result == count_less(high + 1) - count_less(low) + +seed: 1803 + +tests: + - name: example-one + in: + nums: [1, 4, 2, 7] + low: 2 + high: 6 + out: 6 + - name: example-two + in: + nums: [9, 8, 4, 2, 1] + low: 5 + high: 14 + out: 8 + - name: single + in: + nums: [1] + low: 1 + high: 1 + out: 0 + - name: equal-pair + in: + nums: [7, 7] + low: 0 + high: 0 + out: 1 + - name: equal-outside + in: + nums: [7, 7, 7] + low: 1 + high: 2 + out: 0 + - name: adjacent-small + in: + nums: [1, 2, 3, 4] + low: 1 + high: 3 + out: 3 + - name: all-pairs + in: + nums: [1, 2, 4, 8] + low: 1 + high: 15 + out: 6 + - name: no-pairs + in: + nums: [1, 2, 4, 8] + low: 16 + high: 20000 + out: 0 + - name: exact-xor + in: + nums: [1, 2, 3, 4, 5] + low: 6 + high: 6 + out: 2 + - name: zero-bound + in: + nums: [3, 3, 3, 3] + low: 0 + high: 0 + out: 6 + - name: one-bound + in: + nums: [1, 2, 4, 8, 16] + low: 1 + high: 1 + out: 0 + - name: duplicates-mixed + in: + nums: [1, 1, 2, 2, 4, 4] + low: 0 + high: 3 + out: 7 + - name: high-bit + in: + nums: [1, 1024, 2048, 4096] + low: 1024 + high: 4096 + out: 3 + - name: max-values + in: + nums: [20000, 19999, 16384, 8192] + low: 1 + high: 20000 + out: 3 + - name: narrow-middle + in: + nums: [0, 1, 2, 3, 4, 5, 6, 7] + low: 4 + high: 5 + out: 8 + - name: powers + in: + nums: [1, 2, 4, 8, 16, 32, 64, 128] + low: 7 + high: 31 + out: 7 + - name: repeated-zero-xor + in: + nums: [10, 10, 10, 20, 20, 20] + low: 0 + high: 15 + out: 6 + - name: two-groups + in: + nums: [0, 0, 31, 31] + low: 31 + high: 31 + out: 4 + - name: alternating + in: + nums: [5, 10, 5, 10, 5, 10] + low: 15 + high: 15 + out: 9 + - name: full-small-domain + in: + nums: [0, 1, 2, 3, 4, 5, 6, 7] + low: 0 + high: 7 + out: 28 + - name: upper-exclusive + in: + nums: [8, 9, 10, 11] + low: 1 + high: 2 + out: 4 + - name: lower-exclusive + in: + nums: [8, 9, 10, 11] + low: 3 + high: 7 + out: 2 + - name: broad-range + in: + nums: [17, 23, 41, 58, 99, 127] + low: 10 + high: 120 + out: 14 + - name: sorted-input + in: + nums: [1, 3, 7, 15, 31, 63] + low: 8 + high: 32 + out: 8 + - name: reverse-input + in: + nums: [63, 31, 15, 7, 3, 1] + low: 8 + high: 32 + out: 8 + - name: many-duplicates + in: + nums: [2, 2, 2, 2, 5, 5, 5, 5] + low: 3 + high: 7 + out: 16 + - name: low-high-same + in: + nums: [1, 4, 6, 9, 12] + low: 10 + high: 10 + out: 1 + - name: zero-and-max + in: + nums: [0, 20000, 0, 20000] + low: 20000 + high: 20000 + out: 4 + - name: dense-eight + in: + nums: [12, 13, 14, 15, 28, 29, 30, 31] + low: 1 + high: 4 + out: 12 + - name: sparse-large + in: + nums: [1, 4096, 8192, 12288, 16384, 20000] + low: 4096 + high: 12288 + out: 5 + - name: generator-small + in: + nums: + gen: "array" + len: 40 + of: + gen: "int" + min: 1 + max: 20000 + distinct: false + sorted: false + elemType: "int" + low: 1 + high: 20000 + - name: generator-medium + in: + nums: + gen: "array" + len: 250 + of: + gen: "int" + min: 1 + max: 20000 + distinct: false + sorted: false + elemType: "int" + low: 100 + high: 15000 + - name: generator-dense + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 2047 + distinct: false + sorted: false + elemType: "int" + low: 0 + high: 2047 + - name: generator-large + in: + nums: + gen: "array" + len: 5000 + of: + gen: "int" + min: 1 + max: 20000 + distinct: false + sorted: false + elemType: "int" + low: 4096 + high: 16384 + - name: generator-maximum + in: + nums: + gen: "array" + len: 20000 + of: + gen: "int" + min: 1 + max: 20000 + distinct: false + sorted: false + elemType: "int" + low: 1 + high: 20000 diff --git a/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.cpp b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.cpp new file mode 100644 index 00000000..802cc677 --- /dev/null +++ b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.cpp @@ -0,0 +1,43 @@ +class Solution { +public: + int countPairs(vector& nums, int low, int high) { + auto countLess = [&](int bound) -> long long { + if (bound <= 0) return 0; + vector> child(1, array{-1, -1}); + vector counts(1, 0); + long long total = 0; + for (int value : nums) { + int node = 0; + for (int bit = 30; bit >= 0; --bit) { + int v = (value >> bit) & 1; + int b = (bound >> bit) & 1; + if (b) { + int same = child[node][v]; + if (same != -1) total += counts[same]; + node = child[node][1 - v]; + if (node == -1) break; + } else { + node = child[node][v]; + if (node == -1) break; + } + } + node = 0; + for (int bit = 30; bit >= 0; --bit) { + int v = (value >> bit) & 1; + int nxt = child[node][v]; + if (nxt == -1) { + nxt = static_cast(child.size()); + child[node][v] = nxt; + child.push_back(array{-1, -1}); + counts.push_back(0); + } + node = child[node][v]; + counts[node]++; + } + } + return (int)total; + }; + + return static_cast(countLess(high + 1) - countLess(low)); + } +}; diff --git a/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.cs b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.cs new file mode 100644 index 00000000..31f83306 --- /dev/null +++ b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.cs @@ -0,0 +1,48 @@ +public class Solution { + public int CountPairs(int[] nums, int low, int high) { + int maxVal = 0; + foreach (int n in nums) maxVal = Math.Max(maxVal, n); + int bits = Math.Max(1, Math.Max(Convert.ToString(maxVal, 2).Length, Convert.ToString(high + 1, 2).Length)); + + Func countLess = bound => { + if (bound <= 0) return 0; + var child = new List> { new List { -1, -1 } }; + var counts = new List { 0 }; + int total = 0; + foreach (int value in nums) { + int node = 0; + for (int bit = bits - 1; bit >= 0; bit--) { + int v = (value >> bit) & 1; + int b = (bound >> bit) & 1; + if (b == 1) { + int same = child[node][v]; + if (same != -1) total += counts[same]; + int nxt = child[node][1 - v]; + if (nxt == -1) { node = -1; break; } + node = nxt; + } else { + int nxt = child[node][v]; + if (nxt == -1) { node = -1; break; } + node = nxt; + } + } + node = 0; + for (int bit = bits - 1; bit >= 0; bit--) { + int v = (value >> bit) & 1; + int nxt = child[node][v]; + if (nxt == -1) { + nxt = child.Count; + child[node][v] = nxt; + child.Add(new List { -1, -1 }); + counts.Add(0); + } + node = child[node][v]; + counts[node]++; + } + } + return total; + }; + + return countLess(high + 1) - countLess(low); + } +} diff --git a/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.dart b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.dart new file mode 100644 index 00000000..3bb53e11 --- /dev/null +++ b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.dart @@ -0,0 +1,44 @@ +class Solution { + int countPairs(List nums, int low, int high) { + int countLess(int bound) { + if (bound <= 0) return 0; + final child = >[ + [-1, -1] + ]; + final count = [0]; + var total = 0; + for (final value in nums) { + var node = 0; + for (var bit = 30; bit >= 0; bit--) { + final v = (value >> bit) & 1; + final b = (bound >> bit) & 1; + if (b == 1) { + final same = child[node][v]; + if (same != -1) total += count[same]; + node = child[node][1 - v]; + if (node == -1) break; + } else { + node = child[node][v]; + if (node == -1) break; + } + } + node = 0; + for (var bit = 30; bit >= 0; bit--) { + final v = (value >> bit) & 1; + var next = child[node][v]; + if (next == -1) { + next = child.length; + child[node][v] = next; + child.add([-1, -1]); + count.add(0); + } + node = next; + count[node]++; + } + } + return total; + } + + return countLess(high + 1) - countLess(low); + } +} diff --git a/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.go b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.go new file mode 100644 index 00000000..fbfe254d --- /dev/null +++ b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.go @@ -0,0 +1,57 @@ +func countPairs(nums []int, low int, high int) int { + maxVal := 0 + for _, n := range nums { + if n > maxVal { maxVal = n } + } + bits := 1 + if maxVal > 0 { + bits = int(math.Floor(math.Log2(float64(maxVal)))) + 1 + } + if bits < 1 { bits = 1 } + highBits := 0 + if high+1 > 0 { + highBits = int(math.Floor(math.Log2(float64(high+1)))) + 1 + } + if highBits > bits { bits = highBits } + + countLess := func(bound int) int { + if bound <= 0 { return 0 } + child := [][]int{{-1, -1}} + counts := []int{0} + total := 0 + for _, value := range nums { + node := 0 + for bit := bits - 1; bit >= 0; bit-- { + v := (value >> bit) & 1 + b := (bound >> bit) & 1 + if b == 1 { + same := child[node][v] + if same != -1 { total += counts[same] } + nxt := child[node][1-v] + if nxt == -1 { node = -1; break } + node = nxt + } else { + nxt := child[node][v] + if nxt == -1 { node = -1; break } + node = nxt + } + } + node = 0 + for bit := bits - 1; bit >= 0; bit-- { + v := (value >> bit) & 1 + nxt := child[node][v] + if nxt == -1 { + nxt = len(child) + child[node][v] = nxt + child = append(child, []int{-1, -1}) + counts = append(counts, 0) + } + node = child[node][v] + counts[node]++ + } + } + return total + } + + return countLess(high+1) - countLess(low) +} diff --git a/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.java b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.java new file mode 100644 index 00000000..cbc206b3 --- /dev/null +++ b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.java @@ -0,0 +1,54 @@ +class Solution { + public int countPairs(int[] nums, int low, int high) { + int maxVal = 0; + for (int n : nums) maxVal = Math.max(maxVal, n); + int width = 1; + while ((1 << width) <= Math.max(maxVal, high + 1)) width++; + final int bits = width; + + java.util.function.Function countLess = bound -> { + if (bound <= 0) return 0; + int[][] child = new int[400005][2]; + for (int[] row : child) { row[0] = -1; row[1] = -1; } + int[] counts = new int[400005]; + int usedNodes = 1; + int total = 0; + for (int value : nums) { + int node = 0; + for (int bit = bits - 1; bit >= 0; bit--) { + int v = (value >> bit) & 1; + int b = (bound >> bit) & 1; + if (b == 1) { + int same = child[node][v]; + if (same != -1) total += counts[same]; + if (node >= child.length || node < 0) { node = -1; break; } + int nxt = child[node][1 - v]; + if (nxt == -1) { node = -1; break; } + node = nxt; + } else { + int nxt = child[node][v]; + if (nxt == -1) { node = -1; break; } + node = nxt; + } + } + node = 0; + for (int bit = bits - 1; bit >= 0; bit--) { + int v = (value >> bit) & 1; + if (node < 0 || node >= child.length) break; + int nxt = child[node][v]; + if (nxt == -1) { + nxt = usedNodes++; + child[node][v] = nxt; + child[nxt][0] = -1; + child[nxt][1] = -1; + } + node = nxt; + counts[node]++; + } + } + return total; + }; + + return countLess.apply(high + 1) - countLess.apply(low); + } +} diff --git a/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.kt b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.kt new file mode 100644 index 00000000..1591e915 --- /dev/null +++ b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.kt @@ -0,0 +1,48 @@ +class Solution { + fun countPairs(nums: IntArray, low: Int, high: Int): Int { + val maxVal = nums.maxOrNull() ?: 0 + val bits = maxOf(1, maxOf(Integer.toBinaryString(maxVal).length, Integer.toBinaryString(high + 1).length)) + + fun countLess(bound: Int): Int { + if (bound <= 0) return 0 + val child = mutableListOf(mutableListOf(-1, -1)) + val counts = mutableListOf(0) + var total = 0 + for (value in nums) { + var node = 0 + for (bit in bits - 1 downTo 0) { + val v = (value shr bit) and 1 + val b = (bound shr bit) and 1 + if (b == 1) { + val same = child[node][v] + if (same != -1) total += counts[same] + val nxt = child[node][1 - v] + if (nxt == -1) { node = -1; break } + node = nxt + } else { + val nxt = child[node][v] + if (nxt == -1) { node = -1; break } + node = nxt + } + } + node = 0 + for (bit in bits - 1 downTo 0) { + val v = (value shr bit) and 1 + val nxt = child[node][v] + if (nxt == -1) { + val newIdx = child.size + child[node][v] = newIdx + child.add(mutableListOf(-1, -1)) + counts.add(0) + child[node][v] = newIdx + } + node = child[node][v] + counts[node]++ + } + } + return total + } + + return countLess(high + 1) - countLess(low) + } +} diff --git a/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.py b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.py new file mode 100644 index 00000000..b999a191 --- /dev/null +++ b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.py @@ -0,0 +1,40 @@ +class Solution: + def countPairs(self, nums, low, high): + bits = max(1, max(max(nums).bit_length(), (high + 1).bit_length())) + + def count_less(bound): + if bound <= 0: + return 0 + child = [[-1, -1]] + counts = [0] + total = 0 + for value in nums: + node = 0 + for bit in range(bits - 1, -1, -1): + v = (value >> bit) & 1 + b = (bound >> bit) & 1 + if b: + same = child[node][v] + if same != -1: + total += counts[same] + nxt = child[node][1 - v] + else: + nxt = child[node][v] + if nxt == -1: + node = -1 + break + node = nxt + node = 0 + for bit in range(bits - 1, -1, -1): + v = (value >> bit) & 1 + nxt = child[node][v] + if nxt == -1: + nxt = len(child) + child[node][v] = nxt + child.append([-1, -1]) + counts.append(0) + node = nxt + counts[node] += 1 + return total + + return count_less(high + 1) - count_less(low) diff --git a/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.py2 b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.py2 new file mode 100644 index 00000000..a58f1753 --- /dev/null +++ b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.py2 @@ -0,0 +1,39 @@ + +class Solution(object): + def countPairs(self, nums, low, high): + def count_less(limit): + if limit <= 0: + return 0 + children = [[-1, -1]] + counts = [0] + total = 0 + for value in nums: + node = 0 + for bit in xrange(15, -1, -1): + value_bit = (value >> bit) & 1 + limit_bit = (limit >> bit) & 1 + if limit_bit: + same = children[node][value_bit] + if same != -1: + total += counts[same] + node = children[node][1 - value_bit] + else: + node = children[node][value_bit] + if node == -1: + break + + node = 0 + counts[node] += 1 + for bit in xrange(15, -1, -1): + value_bit = (value >> bit) & 1 + child = children[node][value_bit] + if child == -1: + child = len(children) + children[node][value_bit] = child + children.append([-1, -1]) + counts.append(0) + node = child + counts[node] += 1 + return total + + return count_less(high + 1) - count_less(low) diff --git a/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.rb b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.rb new file mode 100644 index 00000000..6c7fcdd1 --- /dev/null +++ b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.rb @@ -0,0 +1,50 @@ +# @param {Integer[]} nums +# @param {Integer} low +# @param {Integer} high +# @return {Integer} +def count_pairs(nums, low, high) + max_val = nums.max || 0 + bits = [1, [max_val.to_s(2).length, (high + 1).to_s(2).length].max].max + + count_less = lambda do |bound| + return 0 if bound <= 0 + child = [[-1, -1]] + counts = [0] + total = 0 + nums.each do |value| + node = 0 + (bits - 1).downto(0) do |bit| + v = (value >> bit) & 1 + b = (bound >> bit) & 1 + if b == 1 + same = child[node][v] + total += counts[same] unless same == -1 + nxt = child[node][1 - v] + else + nxt = child[node][v] + end + if nxt == -1 + node = -1 + break + end + node = nxt + end + node = 0 + (bits - 1).downto(0) do |bit| + v = (value >> bit) & 1 + nxt = child[node][v] + if nxt == -1 + nxt = child.length + child[node][v] = nxt + child << [-1, -1] + counts << 0 + end + node = nxt + counts[node] += 1 + end + end + total + end + + count_less.call(high + 1) - count_less.call(low) +end diff --git a/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.rs b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.rs new file mode 100644 index 00000000..6db57a34 --- /dev/null +++ b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.rs @@ -0,0 +1,48 @@ +impl Solution { + pub fn count_pairs(nums: Vec, low: i32, high: i32) -> i32 { + let max_val = nums.iter().copied().max().unwrap_or(0); + let mut bits = 1usize; + while (1i32 << bits) <= std::cmp::max(max_val, high + 1) { bits += 1; } + + fn count_less(nums: &[i32], bits: usize, bound: i32) -> i32 { + if bound <= 0 { return 0; } + let mut child: Vec<[i32; 2]> = vec![[-1, -1]]; + let mut counts: Vec = vec![0]; + let mut total = 0; + for &value in nums { + let mut node: i32 = 0; + for bit in (0..bits).rev() { + let v = (value >> bit) & 1; + let b = (bound >> bit) & 1; + if b == 1 { + let same = child[node as usize][v as usize]; + if same != -1 { total += counts[same as usize]; } + let nxt = child[node as usize][(1 - v) as usize]; + if nxt == -1 { node = -1; break; } + node = nxt; + } else { + let nxt = child[node as usize][v as usize]; + if nxt == -1 { node = -1; break; } + node = nxt; + } + } + node = 0; + for bit in (0..bits).rev() { + let v = (value >> bit) & 1; + let nxt = child[node as usize][v as usize]; + if nxt == -1 { + let new_idx = child.len() as i32; + child[node as usize][v as usize] = new_idx; + child.push([-1, -1]); + counts.push(0); + } + node = child[node as usize][v as usize]; + counts[node as usize] += 1; + } + } + total + } + + count_less(&nums, bits, high + 1) - count_less(&nums, bits, low) + } +} diff --git a/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.swift b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.swift new file mode 100644 index 00000000..842f5cd8 --- /dev/null +++ b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.swift @@ -0,0 +1,47 @@ +class Solution { + func countPairs(_ nums: [Int], _ low: Int, _ high: Int) -> Int { + let maxVal = nums.max() ?? 0 + let bits = max(1, max(String(maxVal, radix: 2).count, String(high + 1, radix: 2).count)) + + func countLess(_ bound: Int) -> Int { + if bound <= 0 { return 0 } + var child = [[-1, -1]] + var counts = [0] + var total = 0 + for value in nums { + var node = 0 + for bit in stride(from: bits - 1, through: 0, by: -1) { + let v = (value >> bit) & 1 + let b = (bound >> bit) & 1 + if b == 1 { + let same = child[node][v] + if same != -1 { total += counts[same] } + let nxt = child[node][1 - v] + if nxt == -1 { node = -1; break } + node = nxt + } else { + let nxt = child[node][v] + if nxt == -1 { node = -1; break } + node = nxt + } + } + node = 0 + for bit in stride(from: bits - 1, through: 0, by: -1) { + let v = (value >> bit) & 1 + let nxt = child[node][v] + if nxt == -1 { + let newIdx = child.count + child[node][v] = newIdx + child.append([-1, -1]) + counts.append(0) + } + node = child[node][v] + counts[node] += 1 + } + } + return total + } + + return countLess(high + 1) - countLess(low) + } +} diff --git a/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.ts b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.ts new file mode 100644 index 00000000..f7f506d9 --- /dev/null +++ b/tests/1501-2000/1803. count-pairs-with-xor-in-a-range/sol.ts @@ -0,0 +1,54 @@ +function countPairs(nums: number[], low: number, high: number): number { + const maxVal = Math.max(...nums); + const bits = Math.max( + 1, + Math.max(maxVal.toString(2).length, (high + 1).toString(2).length), + ); + + function countLess(bound: number): number { + if (bound <= 0) return 0; + const child: number[][] = [[-1, -1]]; + const counts: number[] = [0]; + let total = 0; + for (const value of nums) { + let node = 0; + for (let bit = bits - 1; bit >= 0; bit--) { + const v = (value >> bit) & 1; + const b = (bound >> bit) & 1; + if (b === 1) { + const same = child[node][v]; + if (same !== -1) total += counts[same]; + const nxt = child[node][1 - v]; + if (nxt === -1) { + node = -1; + break; + } + node = nxt; + } else { + const nxt = child[node][v]; + if (nxt === -1) { + node = -1; + break; + } + node = nxt; + } + } + node = 0; + for (let bit = bits - 1; bit >= 0; bit--) { + const v = (value >> bit) & 1; + let nxt = child[node][v]; + if (nxt === -1) { + nxt = child.length; + child[node][v] = nxt; + child.push([-1, -1]); + counts.push(0); + } + node = child[node][v]; + counts[node]++; + } + } + return total; + } + + return countLess(high + 1) - countLess(low); +} diff --git a/tests/1501-2000/1805. number-of-different-integers-in-a-string/manifest.yaml b/tests/1501-2000/1805. number-of-different-integers-in-a-string/manifest.yaml new file mode 100644 index 00000000..0ae146d1 --- /dev/null +++ b/tests/1501-2000/1805. number-of-different-integers-in-a-string/manifest.yaml @@ -0,0 +1,277 @@ +entry: + id: 1805 + title: "number-of-different-integers-in-a-string" + params: + word: + type: string + call: + cpp: "Solution().numDifferentIntegers({word})" + rust: "Solution::num_different_integers({word})" + python3: "Solution().numDifferentIntegers({word})" + python2: "Solution().numDifferentIntegers({word})" + ruby: "num_different_integers({word})" + java: "new Solution().numDifferentIntegers({word})" + csharp: "new Solution().NumDifferentIntegers({word})" + kotlin: "Solution().numDifferentIntegers({word})" + go: "numDifferentIntegers({word})" + dart: "Solution().numDifferentIntegers({word})" + swift: "Solution().numDifferentIntegers({word})" + typescript: "numDifferentIntegers({word})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().numDifferentIntegers(word, {result})" + checker: | + class Checker: + def numDifferentIntegers(self, word, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + values = set() + i = 0 + while i < len(word): + while i < len(word) and not word[i].isdigit(): + i += 1 + start = i + while i < len(word) and word[i].isdigit(): + i += 1 + if start < i: + token = word[start:i].lstrip("0") or "0" + values.add(token) + return result == len(values) + +seed: 1805 + +tests: + - name: example-1 + in: + word: "a123bc34d8ef34" + out: 3 + judge: + type: "exact" + - name: example-2 + in: + word: "leet1234code234" + out: 2 + judge: + type: "exact" + - name: example-3-leading-zeroes + in: + word: "a1b01c001" + out: 1 + judge: + type: "exact" + - name: one-letter + in: + word: "a" + out: 0 + judge: + type: "exact" + - name: one-digit + in: + word: "7" + out: 1 + judge: + type: "exact" + - name: only-letters + in: + word: "abcdefghijklmnopqrstuvwxyz" + out: 0 + judge: + type: "exact" + - name: only-zero + in: + word: "00000" + out: 1 + judge: + type: "exact" + - name: separated-zero-forms + in: + word: "a0b00c000d0" + out: 1 + judge: + type: "exact" + - name: repeated-number + in: + word: "x12y12z12" + out: 1 + judge: + type: "exact" + - name: adjacent-runs-are-one + in: + word: "abc123456def" + out: 1 + judge: + type: "exact" + - name: alternating-runs + in: + word: "1a2b3c4d5" + out: 5 + judge: + type: "exact" + - name: same-after-leading-zeroes + in: + word: "00012a12b0012" + out: 1 + judge: + type: "exact" + - name: zero-and-nonzero + in: + word: "0a00b000c1" + out: 2 + judge: + type: "exact" + - name: distinct-single-digits + in: + word: "a0b1c2d3e4f5g6h7i8j9" + out: 10 + judge: + type: "exact" + - name: duplicate-single-digits + in: + word: "0a1b2c3d4e5f6g7h8i9j0" + out: 10 + judge: + type: "exact" + - name: large-number-forms + in: + word: "a000000000000000000000123b123c000123" + out: 1 + judge: + type: "exact" + - name: different-long-numbers + in: + word: "a999999999999999999999b1000000000000000000000" + out: 2 + judge: + type: "exact" + - name: number-at-beginning + in: + word: "123abc" + out: 1 + judge: + type: "exact" + - name: number-at-end + in: + word: "abc123" + out: 1 + judge: + type: "exact" + - name: numbers-both-ends + in: + word: "12abc34" + out: 2 + judge: + type: "exact" + - name: letters-between-zeroes + in: + word: "a000b0000c0" + out: 1 + judge: + type: "exact" + - name: close-values + in: + word: "a10b11c12d13" + out: 4 + judge: + type: "exact" + - name: same-values-many-forms + in: + word: "a00042b42c0042d000042" + out: 1 + judge: + type: "exact" + - name: zero-prefix-does-not-join + in: + word: "a00b1c01d001e10" + out: 3 + judge: + type: "exact" + - name: all-digit-single-run + in: + word: "001020030" + out: 1 + judge: + type: "exact" + - name: many-distinct-runs + in: + word: "a10b20c30d40e50f60g70h80i90" + out: 9 + judge: + type: "exact" + - name: repeated-prefixes + in: + word: "a123b0123c00123d000123" + out: 1 + judge: + type: "exact" + - name: mixed-case-not-allowed-but-letters + in: + word: "x7y08z900w0001" + out: 4 + judge: + type: "exact" + - name: long-zero-run-between + in: + word: "a000000000b5c000000000d5" + out: 2 + judge: + type: "exact" + - name: values-1-through-5 + in: + word: "a1b2c3d4e5" + out: 5 + judge: + type: "exact" + - name: duplicated-values-interleaved + in: + word: "a10b2c10d02e2f010" + out: 2 + judge: + type: "exact" + - name: huge-zero-only-string + in: + word: + gen: "str" + len: 1000 + alphabet: "0" + judge: + type: "exact" + - name: huge-alternating + in: + word: + gen: "str" + len: 1000 + alphabet: "a1" + judge: + type: "exact" + - name: huge-digits-and-letters + in: + word: + gen: "str" + len: 1000 + alphabet: "ab0123" + judge: + type: "exact" + - name: medium-number-heavy + in: + word: + gen: "str" + len: 800 + alphabet: "xy0489" + judge: + type: "exact" + - name: medium-sparse-digits + in: + word: + gen: "str" + len: 750 + alphabet: "abc07" + judge: + type: "exact" diff --git a/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.cpp b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.cpp new file mode 100644 index 00000000..afbac36d --- /dev/null +++ b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int numDifferentIntegers(string word) { + int i = 0, n = word.length(); + unordered_set st; + while (i < n) { + while (i < n && isalpha(word[i])) { + i++; + } + string tempInt; + while (i < n && isdigit(word[i])) { + tempInt += word[i]; + i++; + } + int j = 0; + while (j + 1 < tempInt.length() && tempInt[j] == '0') { + j++; + } + string k = tempInt.substr(j); + if (!k.empty()) { + st.insert(k); + } + } + return st.size(); + } +}; diff --git a/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.cs b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.cs new file mode 100644 index 00000000..50828668 --- /dev/null +++ b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public int NumDifferentIntegers(string word) { + int i = 0, n = word.Length; + var st = new HashSet(); + while (i < n) { + while (i < n && char.IsLetter(word[i])) { + i++; + } + var tempInt = new System.Text.StringBuilder(); + while (i < n && char.IsDigit(word[i])) { + tempInt.Append(word[i]); + i++; + } + int j = 0; + while (j + 1 < tempInt.Length && tempInt[j] == '0') { + j++; + } + string k = tempInt.ToString().Substring(j); + if (!string.IsNullOrEmpty(k)) { + st.Add(k); + } + } + return st.Count; + } +} diff --git a/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.dart b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.dart new file mode 100644 index 00000000..771cf96c --- /dev/null +++ b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.dart @@ -0,0 +1,26 @@ +class Solution { + int numDifferentIntegers(String word) { + int i = 0; + int n = word.length; + Set st = {}; + while (i < n) { + while (i < n && (word.codeUnitAt(i) >= 65 && word.codeUnitAt(i) <= 90 || word.codeUnitAt(i) >= 97 && word.codeUnitAt(i) <= 122)) { + i++; + } + String tempInt = ""; + while (i < n && word.codeUnitAt(i) >= 48 && word.codeUnitAt(i) <= 57) { + tempInt += word[i]; + i++; + } + int j = 0; + while (j + 1 < tempInt.length && tempInt[j] == '0') { + j++; + } + String k = tempInt.substring(j); + if (k.isNotEmpty) { + st.add(k); + } + } + return st.length; + } +} diff --git a/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.go b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.go new file mode 100644 index 00000000..6970cb99 --- /dev/null +++ b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.go @@ -0,0 +1,24 @@ +func numDifferentIntegers(word string) int { + i := 0 + n := len(word) + st := make(map[string]bool) + for i < n { + for i < n && (word[i] >= 'a' && word[i] <= 'z' || word[i] >= 'A' && word[i] <= 'Z') { + i++ + } + tempInt := "" + for i < n && word[i] >= '0' && word[i] <= '9' { + tempInt += string(word[i]) + i++ + } + j := 0 + for j+1 < len(tempInt) && tempInt[j] == '0' { + j++ + } + k := tempInt[j:] + if k != "" { + st[k] = true + } + } + return len(st) +} diff --git a/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.java b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.java new file mode 100644 index 00000000..ac37dad6 --- /dev/null +++ b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.java @@ -0,0 +1,25 @@ +class Solution { + public int numDifferentIntegers(String word) { + int i = 0, n = word.length(); + Set st = new HashSet<>(); + while (i < n) { + while (i < n && Character.isLetter(word.charAt(i))) { + i++; + } + StringBuilder tempInt = new StringBuilder(); + while (i < n && Character.isDigit(word.charAt(i))) { + tempInt.append(word.charAt(i)); + i++; + } + int j = 0; + while (j + 1 < tempInt.length() && tempInt.charAt(j) == '0') { + j++; + } + String k = tempInt.substring(j); + if (!k.isEmpty()) { + st.add(k); + } + } + return st.size(); + } +} diff --git a/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.kt b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.kt new file mode 100644 index 00000000..d8aa64a7 --- /dev/null +++ b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.kt @@ -0,0 +1,26 @@ +class Solution { + fun numDifferentIntegers(word: String): Int { + var i = 0 + val n = word.length + val st = mutableSetOf() + while (i < n) { + while (i < n && word[i].isLetter()) { + i++ + } + var tempInt = StringBuilder() + while (i < n && word[i].isDigit()) { + tempInt.append(word[i]) + i++ + } + var j = 0 + while (j + 1 < tempInt.length && tempInt[j] == '0') { + j++ + } + val k = tempInt.substring(j) + if (k.isNotEmpty()) { + st.add(k) + } + } + return st.size + } +} diff --git a/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.py b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.py new file mode 100644 index 00000000..bd1a25e5 --- /dev/null +++ b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.py @@ -0,0 +1,18 @@ +class Solution: + def numDifferentIntegers(self, word): + i, n = 0, len(word) + st = set() + while i < n: + while i < n and word[i].isalpha(): + i += 1 + tempInt = "" + while i < n and word[i].isdigit(): + tempInt += word[i] + i += 1 + j = 0 + while j + 1 < len(tempInt) and tempInt[j] == "0": + j += 1 + k = tempInt[j:] + if k != "": + st.add(k) + return len(st) diff --git a/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.py2 b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.py2 new file mode 100644 index 00000000..633864e6 --- /dev/null +++ b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def numDifferentIntegers(self, word): + """ + :type word: str + :rtype: int + """ + i, n = 0, len(word) + st = set() + while i < n: + while i < n and word[i].isalpha(): + i += 1 + tempInt = "" + while i < n and word[i].isdigit(): + tempInt += word[i] + i += 1 + j = 0 + while j + 1 < len(tempInt) and tempInt[j] == '0': + j += 1 + k = tempInt[j:] + if k != "": + st.add(k) + return len(st) diff --git a/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.rb b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.rb new file mode 100644 index 00000000..0dbfc45b --- /dev/null +++ b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.rb @@ -0,0 +1,26 @@ +# @param {String} word +# @return {Integer} +def num_different_integers(word) + i = 0 + n = word.length + st = Set.new + while i < n + while i < n && word[i] =~ /[a-zA-Z]/ + i += 1 + end + temp_int = "" + while i < n && word[i] =~ /[0-9]/ + temp_int += word[i] + i += 1 + end + j = 0 + while j + 1 < temp_int.length && temp_int[j] == '0' + j += 1 + end + k = temp_int[j..-1] + if k != "" + st.add(k) + end + end + st.length +end diff --git a/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.rs b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.rs new file mode 100644 index 00000000..7b02890c --- /dev/null +++ b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.rs @@ -0,0 +1,27 @@ +impl Solution { + pub fn num_different_integers(word: String) -> i32 { + let chars: Vec = word.chars().collect(); + let mut i = 0; + let n = chars.len(); + let mut st = std::collections::HashSet::new(); + while i < n { + while i < n && chars[i].is_alphabetic() { + i += 1; + } + let mut temp_int = String::new(); + while i < n && chars[i].is_digit(10) { + temp_int.push(chars[i]); + i += 1; + } + let mut j = 0; + while j + 1 < temp_int.len() && temp_int.as_bytes()[j] == b'0' { + j += 1; + } + let k = &temp_int[j..]; + if !k.is_empty() { + st.insert(k.to_string()); + } + } + st.len() as i32 + } +} diff --git a/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.swift b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.swift new file mode 100644 index 00000000..27b99490 --- /dev/null +++ b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.swift @@ -0,0 +1,28 @@ +class Solution { + func numDifferentIntegers(_ word: String) -> Int { + var i = 0 + let n = word.count + var st = Set() + var chars = Array(word) + while i < n { + while i < n && chars[i].isLetter { + i += 1 + } + var tempInt = "" + while i < n && chars[i].isNumber { + tempInt.append(chars[i]) + i += 1 + } + var j = 0 + while j + 1 < tempInt.count && tempInt[tempInt.index(tempInt.startIndex, offsetBy: j)] == "0" { + j += 1 + } + let start = tempInt.index(tempInt.startIndex, offsetBy: j) + let k = String(tempInt[start...]) + if !k.isEmpty { + st.insert(k) + } + } + return st.count + } +} diff --git a/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.ts b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.ts new file mode 100644 index 00000000..033ba6fc --- /dev/null +++ b/tests/1501-2000/1805. number-of-different-integers-in-a-string/sol.ts @@ -0,0 +1,24 @@ +function numDifferentIntegers(word: string): number { + let i = 0; + const n = word.length; + const st = new Set(); + while (i < n) { + while (i < n && /[a-zA-Z]/.test(word[i])) { + i++; + } + let tempInt = ""; + while (i < n && /[0-9]/.test(word[i])) { + tempInt += word[i]; + i++; + } + let j = 0; + while (j + 1 < tempInt.length && tempInt[j] === "0") { + j++; + } + const k = tempInt.substring(j); + if (k !== "") { + st.add(k); + } + } + return st.size; +} diff --git a/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/manifest.yaml b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/manifest.yaml new file mode 100644 index 00000000..dd60fdcd --- /dev/null +++ b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/manifest.yaml @@ -0,0 +1,187 @@ +entry: + id: 1806 + title: "minimum-number-of-operations-to-reinitialize-a-permutation" + params: + n: + type: int + call: + cpp: "Solution().reinitializePermutation({n})" + rust: "Solution::reinitialize_permutation({n})" + python3: "Solution().reinitializePermutation({n})" + python2: "Solution().reinitializePermutation({n})" + ruby: "reinitialize_permutation({n})" + java: "new Solution().reinitializePermutation({n})" + csharp: "new Solution().ReinitializePermutation({n})" + kotlin: "Solution().reinitializePermutation({n})" + go: "reinitializePermutation({n})" + dart: "Solution().reinitializePermutation({n})" + swift: "Solution().reinitializePermutation({n})" + typescript: "reinitializePermutation({n})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(n, {result})" + checker: | + class Checker: + def check(self, n, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + original = list(range(n)) + perm = original[:] + steps = 0 + while True: + perm = [perm[i // 2] if i % 2 == 0 else perm[n // 2 + (i - 1) // 2] for i in range(n)] + steps += 1 + if perm == original: + return result == steps + +seed: 1806 + +tests: + - name: minimum-n + in: + n: 2 + out: 1 + - name: example-four + in: + n: 4 + out: 2 + - name: example-six + in: + n: 6 + out: 4 + - name: power-eight + in: + n: 8 + out: 3 + - name: power-sixteen + in: + n: 16 + out: 4 + - name: power-thirty-two + in: + n: 32 + out: 5 + - name: power-sixty-four + in: + n: 64 + out: 6 + - name: power-one-twenty-eight + in: + n: 128 + out: 7 + - name: power-two-fifty-six + in: + n: 256 + out: 8 + - name: power-five-twelve + in: + n: 512 + out: 9 + - name: near-minimum-ten + in: + n: 10 + out: 6 + - name: twelve + in: + n: 12 + out: 10 + - name: fourteen + in: + n: 14 + out: 12 + - name: eighteen + in: + n: 18 + out: 8 + - name: twenty + in: + n: 20 + out: 18 + - name: twenty-four + in: + n: 24 + out: 11 + - name: thirty + in: + n: 30 + out: 28 + - name: thirty-six + in: + n: 36 + out: 12 + - name: forty + in: + n: 40 + out: 12 + - name: fifty-four + in: + n: 54 + out: 52 + - name: seventy-two + in: + n: 72 + out: 35 + - name: ninety-six + in: + n: 96 + out: 36 + - name: one-hundred + in: + n: 100 + out: 30 + - name: one-hundred-two + in: + n: 102 + out: 100 + - name: one-hundred-twenty-two + in: + n: 122 + out: 110 + - name: one-hundred-fifty + in: + n: 150 + out: 148 + - name: one-hundred-ninety-eight + in: + n: 198 + out: 196 + - name: two-hundred + in: + n: 200 + out: 99 + - name: two-hundred-fifty + in: + n: 250 + out: 82 + - name: three-hundred + in: + n: 300 + out: 132 + - name: four-hundred + in: + n: 400 + out: 18 + - name: five-hundred + in: + n: 500 + out: 166 + - name: six-hundred + in: + n: 600 + out: 299 + - name: eight-hundred + in: + n: 800 + out: 184 + - name: maximum-n + in: + n: 1000 + out: 36 diff --git a/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.cpp b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.cpp new file mode 100644 index 00000000..e6669e6b --- /dev/null +++ b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int reinitializePermutation(int n) { + vector original(n); + for (int i = 0; i < n; i++) original[i] = i; + vector permut = original; + vector arr(n); + int count = 0; + while (true) { + for (int i = 0; i < n; i++) { + if (i % 2 == 0) { + arr[i] = permut[i / 2]; + } else { + arr[i] = permut[n / 2 + (i - 1) / 2]; + } + } + permut = arr; + count++; + if (permut == original) break; + } + return count; + } +}; diff --git a/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.cs b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.cs new file mode 100644 index 00000000..a1be2a59 --- /dev/null +++ b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.cs @@ -0,0 +1,29 @@ +public class Solution { + public int ReinitializePermutation(int n) { + int[] original = new int[n]; + for (int i = 0; i < n; i++) original[i] = i; + int[] permut = (int[])original.Clone(); + int[] arr = new int[n]; + int count = 0; + while (true) { + for (int i = 0; i < n; i++) { + if (i % 2 == 0) { + arr[i] = permut[i / 2]; + } else { + arr[i] = permut[n / 2 + (i - 1) / 2]; + } + } + permut = (int[])arr.Clone(); + count++; + bool equal = true; + for (int i = 0; i < n; i++) { + if (permut[i] != original[i]) { + equal = false; + break; + } + } + if (equal) break; + } + return count; + } +} diff --git a/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.dart b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.dart new file mode 100644 index 00000000..cc826254 --- /dev/null +++ b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.dart @@ -0,0 +1,28 @@ +class Solution { + int reinitializePermutation(int n) { + List original = List.generate(n, (i) => i); + List permut = List.from(original); + List arr = List.filled(n, 0); + int count = 0; + while (true) { + for (int i = 0; i < n; i++) { + if (i % 2 == 0) { + arr[i] = permut[i ~/ 2]; + } else { + arr[i] = permut[n ~/ 2 + (i - 1) ~/ 2]; + } + } + permut = List.from(arr); + count++; + bool equal = true; + for (int i = 0; i < n; i++) { + if (permut[i] != original[i]) { + equal = false; + break; + } + } + if (equal) break; + } + return count; + } +} diff --git a/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.go b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.go new file mode 100644 index 00000000..e8cd5802 --- /dev/null +++ b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.go @@ -0,0 +1,32 @@ +func reinitializePermutation(n int) int { + original := make([]int, n) + for i := 0; i < n; i++ { + original[i] = i + } + permut := make([]int, n) + copy(permut, original) + arr := make([]int, n) + count := 0 + for { + for i := 0; i < n; i++ { + if i%2 == 0 { + arr[i] = permut[i/2] + } else { + arr[i] = permut[n/2+(i-1)/2] + } + } + copy(permut, arr) + count++ + equal := true + for i := 0; i < n; i++ { + if permut[i] != original[i] { + equal = false + break + } + } + if equal { + break + } + } + return count +} diff --git a/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.java b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.java new file mode 100644 index 00000000..87e9e407 --- /dev/null +++ b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.java @@ -0,0 +1,22 @@ +class Solution { + public int reinitializePermutation(int n) { + int[] original = new int[n]; + for (int i = 0; i < n; i++) original[i] = i; + int[] permut = original.clone(); + int[] arr = new int[n]; + int count = 0; + while (true) { + for (int i = 0; i < n; i++) { + if (i % 2 == 0) { + arr[i] = permut[i / 2]; + } else { + arr[i] = permut[n / 2 + (i - 1) / 2]; + } + } + permut = arr.clone(); + count++; + if (java.util.Arrays.equals(permut, original)) break; + } + return count; + } +} diff --git a/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.kt b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.kt new file mode 100644 index 00000000..b4bc1d57 --- /dev/null +++ b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.kt @@ -0,0 +1,21 @@ +class Solution { + fun reinitializePermutation(n: Int): Int { + val original = IntArray(n) { it } + var permut = original.copyOf() + val arr = IntArray(n) + var count = 0 + while (true) { + for (i in 0 until n) { + if (i % 2 == 0) { + arr[i] = permut[i / 2] + } else { + arr[i] = permut[n / 2 + (i - 1) / 2] + } + } + permut = arr.copyOf() + count++ + if (permut.contentEquals(original)) break + } + return count + } +} diff --git a/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.py b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.py new file mode 100644 index 00000000..59b502aa --- /dev/null +++ b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.py @@ -0,0 +1,23 @@ +class Solution: + def reinitializePermutation(self, n: int) -> int: + + original = list(range(n)) + permut = original[:] + arr = [0] * n + + count = 0 + + while True: + for i in range(n): + if i % 2 == 0: + arr[i] = permut[i // 2] + else: + arr[i] = permut[n // 2 + (i - 1) // 2] + + permut = arr[:] + count += 1 + + if permut == original: + break + + return count diff --git a/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.py2 b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.py2 new file mode 100644 index 00000000..6dc694a6 --- /dev/null +++ b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def reinitializePermutation(self, n): + """ + :type n: int + :rtype: int + """ + original = list(range(n)) + permut = original[:] + arr = [0] * n + count = 0 + while True: + for i in range(n): + if i % 2 == 0: + arr[i] = permut[i // 2] + else: + arr[i] = permut[n // 2 + (i - 1) // 2] + permut = arr[:] + count += 1 + if permut == original: + break + return count diff --git a/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.rb b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.rb new file mode 100644 index 00000000..49db6c1a --- /dev/null +++ b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.rb @@ -0,0 +1,21 @@ +# @param {Integer} n +# @return {Integer} +def reinitialize_permutation(n) + original = (0...n).to_a + permut = original.dup + arr = Array.new(n, 0) + count = 0 + loop do + (0...n).each do |i| + if i % 2 == 0 + arr[i] = permut[i / 2] + else + arr[i] = permut[n / 2 + (i - 1) / 2] + end + end + permut = arr.dup + count += 1 + break if permut == original + end + count +end diff --git a/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.rs b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.rs new file mode 100644 index 00000000..abb5712c --- /dev/null +++ b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn reinitialize_permutation(n: i32) -> i32 { + let n = n as usize; + let original: Vec = (0..n).collect(); + let mut permut = original.clone(); + let mut arr = vec![0usize; n]; + let mut count = 0; + loop { + for i in 0..n { + if i % 2 == 0 { + arr[i] = permut[i / 2]; + } else { + arr[i] = permut[n / 2 + (i - 1) / 2]; + } + } + permut = arr.clone(); + count += 1; + if permut == original { + break; + } + } + count + } +} diff --git a/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.swift b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.swift new file mode 100644 index 00000000..b6e3c940 --- /dev/null +++ b/tests/1501-2000/1806. minimum-number-of-operations-to-reinitialize-a-permutation/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func reinitializePermutation(_ n: Int) -> Int { + var original = Array(0.. i); + let permut: number[] = [...original]; + const arr: number[] = new Array(n).fill(0); + let count = 0; + while (true) { + for (let i = 0; i < n; i++) { + if (i % 2 === 0) { + arr[i] = permut[Math.floor(i / 2)]; + } else { + arr[i] = permut[Math.floor(n / 2) + Math.floor((i - 1) / 2)]; + } + } + permut = [...arr]; + count++; + let equal = true; + for (let i = 0; i < n; i++) { + if (permut[i] !== original[i]) { + equal = false; + break; + } + } + if (equal) break; + } + return count; +} diff --git a/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/manifest.yaml b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/manifest.yaml new file mode 100644 index 00000000..b1892878 --- /dev/null +++ b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/manifest.yaml @@ -0,0 +1,379 @@ +entry: + id: 1807 + title: "evaluate-the-bracket-pairs-of-a-string" + params: + s: + type: string + knowledge: + type: array + items: + type: array + items: + type: string + call: + cpp: "Solution().evaluate({s}, {knowledge})" + rust: "Solution::evaluate({s}, {knowledge})" + python3: "Solution().evaluate({s}, {knowledge})" + python2: "Solution().evaluate({s}, {knowledge})" + ruby: "evaluate({s}, {knowledge})" + java: "new Solution().evaluate({s}, java.util.Arrays.stream({knowledge}).map(a -> java.util.Arrays.asList(a)).collect(java.util.stream.Collectors.toList()))" + csharp: "new Solution().Evaluate({s}, {knowledge})" + kotlin: "Solution().evaluate({s}, {knowledge}.map { it.toList() })" + go: "evaluate({s}, {knowledge})" + dart: "Solution().evaluate({s}, {knowledge})" + swift: "Solution().evaluate({s}, {knowledge})" + typescript: "evaluate({s}, {knowledge})" + +judge: + type: "exact" + +limits: + time_ms: 5000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().evaluate(s, knowledge, {result})" + checker: | + class Checker: + def evaluate(self, s, knowledge, result): + if not isinstance(result, str): + return False + values = {pair[0]: pair[1] for pair in knowledge} + expected = [] + i = 0 + while i < len(s): + if s[i] != '(': + expected.append(s[i]) + i += 1 + continue + j = s.index(')', i + 1) + expected.append(values.get(s[i + 1:j], '?')) + i = j + 1 + return result == ''.join(expected) + +seed: 1807 + +tests: + - name: example-one + in: + s: "(name)is(age)yearsold" + knowledge: + - ["name", "bob"] + - ["age", "two"] + out: "bobistwoyearsold" + judge: + type: "exact" + - name: example-two-unknown + in: + s: "hi(name)" + knowledge: + - ["a", "b"] + out: "hi?" + judge: + type: "exact" + - name: example-three-repeated + in: + s: "(a)(a)(a)aaa" + knowledge: + - ["a", "yes"] + out: "yesyesyesaaa" + judge: + type: "exact" + - name: plain-text + in: + s: "abcdefghijklmnopqrstuvwxyz" + knowledge: [] + out: "abcdefghijklmnopqrstuvwxyz" + judge: + type: "exact" + - name: one-known + in: + s: "(a)" + knowledge: + - ["a", "x"] + out: "x" + judge: + type: "exact" + - name: one-unknown + in: + s: "(missing)" + knowledge: [] + out: "?" + judge: + type: "exact" + - name: empty-knowledge + in: + s: "hello(world)" + knowledge: [] + out: "hello?" + judge: + type: "exact" + - name: known-value-empty-impossible + in: + s: "x(a)y" + knowledge: + - ["a", "z"] + out: "xzy" + judge: + type: "exact" + - name: adjacent-known + in: + s: "(a)(b)(c)" + knowledge: + - ["a", "one"] + - ["b", "two"] + - ["c", "three"] + out: "onetwothree" + judge: + type: "exact" + - name: adjacent-unknown + in: + s: "(a)(b)(c)" + knowledge: + - ["b", "x"] + out: "?x?" + judge: + type: "exact" + - name: punctuation-free-letters + in: + s: "a(b)c(d)e" + knowledge: + - ["b", "bb"] + - ["d", "dd"] + out: "abbcdde" + judge: + type: "exact" + - name: repeated-known-and-unknown + in: + s: "(x)a(x)(y)b(y)" + knowledge: + - ["x", "value"] + out: "valueavalue?b?" + judge: + type: "exact" + - name: key-prefixes + in: + s: "(a)(ab)(abc)" + knowledge: + - ["a", "1"] + - ["ab", "22"] + - ["abc", "333"] + judge: + type: "exact" + - name: key-case-sensitive-lowercase + in: + s: "(a)(aa)(aaa)" + knowledge: + - ["aa", "middle"] + out: "?middle?" + judge: + type: "exact" + - name: values-long + in: + s: "start(a)middle(b)end" + knowledge: + - ["a", "abcdefghij"] + - ["b", "zyxwvutsrq"] + out: "startabcdefghijmiddlezyxwvutsrqend" + judge: + type: "exact" + - name: all-unknown-between-text + in: + s: "a(one)b(two)c(three)d" + knowledge: [] + out: "a?b?c?d" + judge: + type: "exact" + - name: zero-length-text-around + in: + s: "(a)z" + knowledge: + - ["a", "q"] + out: "qz" + judge: + type: "exact" + - name: many-pairs + in: + s: "(a)a(a)a(a)a(a)a(a)" + knowledge: + - ["a", "r"] + out: "rarararar" + judge: + type: "exact" + - name: value-question-character + in: + s: "(a)(b)" + knowledge: + - ["a", "?"] + - ["b", "ok"] + out: "?ok" + judge: + type: "exact" + - name: values-repeat-letters + in: + s: "(aa)xx(bb)" + knowledge: + - ["aa", "aaaa"] + - ["bb", "bbbb"] + out: "aaaaxxbbbb" + judge: + type: "exact" + - name: unknown-key-similar + in: + s: "(cat)(cats)(ca)" + knowledge: + - ["cat", "animal"] + out: "animal??" + judge: + type: "exact" + - name: text-letters-not-evaluated + in: + s: "a(b)ba(b)" + knowledge: + - ["b", "B"] + out: "aBbaB" + judge: + type: "exact" + - name: alternating + in: + s: "(a)x(b)y(c)z(d)" + knowledge: + - ["a", "1"] + - ["c", "3"] + out: "1x?y3z?" + judge: + type: "exact" + - name: long-key + in: + s: "(abcdefghij)" + knowledge: + - ["abcdefghij", "value"] + out: "value" + judge: + type: "exact" + - name: long-key-unknown + in: + s: "x(abcdefghij)y" + knowledge: [] + out: "x?y" + judge: + type: "exact" + - name: large-value-many-occurrences + in: + s: "(a)(a)(a)(a)(a)(a)(a)(a)" + knowledge: + - ["a", "abcdefghij"] + out: "abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij" + judge: + type: "exact" + - name: mixed-known + in: + s: "pre(a)mid(unknown)post(b)" + knowledge: + - ["a", "left"] + - ["b", "right"] + out: "preleftmid?postright" + judge: + type: "exact" + - name: one-character-each + in: + s: "(a)(b)(c)(d)(e)" + knowledge: + - ["a", "1"] + - ["c", "3"] + - ["e", "5"] + out: "1?3?5" + judge: + type: "exact" + - name: duplicate-lookup + in: + s: "(key)key(key)" + knowledge: + - ["key", "v"] + out: "vkeyv" + judge: + type: "exact" + - name: all-text-after + in: + s: "(a)abcdefghijklmnopqrstuvwxyz" + knowledge: + - ["a", "done"] + out: "doneabcdefghijklmnopqrstuvwxyz" + judge: + type: "exact" + - name: all-text-before + in: + s: "abcdefghijklmnopqrstuvwxyz(a)" + knowledge: + - ["a", "done"] + out: "abcdefghijklmnopqrstuvwxyzdone" + judge: + type: "exact" + - name: unknown-with-known-prefix + in: + s: "(ab)(abc)(abcd)" + knowledge: + - ["abc", "ok"] + out: "?ok?" + judge: + type: "exact" + - name: large-plain-static + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + knowledge: [] + out: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + judge: + type: "exact" + - name: large-unknown-static + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(longkey)bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + knowledge: [] + out: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa?bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + judge: + type: "exact" + - name: generated-plain-1 + in: + s: + gen: "str" + len: 100000 + alphabet: "abc" + knowledge: [] + judge: + type: "exact" + - name: generated-plain-2 + in: + s: + gen: "str" + len: 99999 + alphabet: "xy" + knowledge: [] + judge: + type: "exact" + - name: generated-plain-3 + in: + s: + gen: "str" + len: 75000 + alphabet: "mnop" + knowledge: [] + judge: + type: "exact" + - name: generated-plain-4 + in: + s: + gen: "str" + len: 50000 + alphabet: "qr" + knowledge: [] + judge: + type: "exact" + - name: generated-plain-5 + in: + s: + gen: "str" + len: 25000 + alphabet: "uvw" + knowledge: [] + judge: + type: "exact" diff --git a/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.cpp b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.cpp new file mode 100644 index 00000000..f1b3edd7 --- /dev/null +++ b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + string evaluate(string s, vector>& knowledge) { + unordered_map mp; + for (auto& pair : knowledge) { + mp[pair[0]] = pair[1]; + } + string ans; + int i = 0, n = s.size(); + while (i < n) { + if (s[i] == '(') { + i++; + string temp; + while (i < n && s[i] != ')') { + temp += s[i]; + i++; + } + if (mp.count(temp)) ans += mp[temp]; + else ans += "?"; + i++; + } else { + ans += s[i]; + i++; + } + } + return ans; + } +}; diff --git a/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.cs b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.cs new file mode 100644 index 00000000..e201eb77 --- /dev/null +++ b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.cs @@ -0,0 +1,27 @@ +public class Solution { + public string Evaluate(string s, IList> knowledge) { + var mp = new Dictionary(); + foreach (var pair in knowledge) { + mp[pair[0]] = pair[1]; + } + var ans = new StringBuilder(); + int i = 0, n = s.Length; + while (i < n) { + if (s[i] == '(') { + i++; + var temp = new StringBuilder(); + while (i < n && s[i] != ')') { + temp.Append(s[i]); + i++; + } + if (mp.ContainsKey(temp.ToString())) ans.Append(mp[temp.ToString()]); + else ans.Append("?"); + i++; + } else { + ans.Append(s[i]); + i++; + } + } + return ans.ToString(); + } +} diff --git a/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.dart b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.dart new file mode 100644 index 00000000..53ab7b4a --- /dev/null +++ b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.dart @@ -0,0 +1,24 @@ +class Solution { + String evaluate(String s, List> knowledge) { + final mp = {for (var pair in knowledge) pair[0]: pair[1]}; + var ans = ''; + var i = 0; + final n = s.length; + while (i < n) { + if (s[i] == '(') { + i++; + var temp = ''; + while (i < n && s[i] != ')') { + temp += s[i]; + i++; + } + ans += mp[temp] ?? '?'; + i++; + } else { + ans += s[i]; + i++; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.go b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.go new file mode 100644 index 00000000..ae57f44d --- /dev/null +++ b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.go @@ -0,0 +1,28 @@ +func evaluate(s string, knowledge [][]string) string { + mp := make(map[string]string) + for _, pair := range knowledge { + mp[pair[0]] = pair[1] + } + ans := "" + i, n := 0, len(s) + for i < n { + if s[i] == '(' { + i++ + temp := "" + for i < n && s[i] != ')' { + temp += string(s[i]) + i++ + } + if val, ok := mp[temp]; ok { + ans += val + } else { + ans += "?" + } + i++ + } else { + ans += string(s[i]) + i++ + } + } + return ans +} diff --git a/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.java b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.java new file mode 100644 index 00000000..cd74cc1e --- /dev/null +++ b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.java @@ -0,0 +1,26 @@ +class Solution { + public String evaluate(String s, List> knowledge) { + Map mp = new HashMap<>(); + for (List pair : knowledge) { + mp.put(pair.get(0), pair.get(1)); + } + StringBuilder ans = new StringBuilder(); + int i = 0, n = s.length(); + while (i < n) { + if (s.charAt(i) == '(') { + i++; + StringBuilder temp = new StringBuilder(); + while (i < n && s.charAt(i) != ')') { + temp.append(s.charAt(i)); + i++; + } + ans.append(mp.getOrDefault(temp.toString(), "?")); + i++; + } else { + ans.append(s.charAt(i)); + i++; + } + } + return ans.toString(); + } +} diff --git a/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.kt b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.kt new file mode 100644 index 00000000..48fbe8bc --- /dev/null +++ b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.kt @@ -0,0 +1,24 @@ +class Solution { + fun evaluate(s: String, knowledge: List>): String { + val mp = knowledge.associate { it[0] to it[1] } + val ans = StringBuilder() + var i = 0 + val n = s.length + while (i < n) { + if (s[i] == '(') { + i++ + val temp = StringBuilder() + while (i < n && s[i] != ')') { + temp.append(s[i]) + i++ + } + ans.append(mp[temp.toString()] ?: "?") + i++ + } else { + ans.append(s[i]) + i++ + } + } + return ans.toString() + } +} diff --git a/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.py b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.py new file mode 100644 index 00000000..64d1b0ef --- /dev/null +++ b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.py @@ -0,0 +1,17 @@ +class Solution: + def evaluate(self, s, knowledge): + mp = {k: v for k, v in knowledge} + ans, i, n = "", 0, len(s) + while i < n: + if s[i] == "(": + i += 1 + temp = "" + while i < n and s[i] != ")": + temp += s[i] + i += 1 + ans += mp.get(temp, "?") + i += 1 + else: + ans += s[i] + i += 1 + return ans diff --git a/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.py2 b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.py2 new file mode 100644 index 00000000..e5763cc7 --- /dev/null +++ b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def evaluate(self, s, knowledge): + """ + :type s: str + :type knowledge: List[List[str]] + :rtype: str + """ + mp = {k: v for k, v in knowledge} + ans, i, n = "", 0, len(s) + while i < n: + if s[i] == '(': + i += 1 + temp = "" + while i < n and s[i] != ')': + temp += s[i] + i += 1 + ans += mp.get(temp, "?") + i += 1 + else: + ans += s[i] + i += 1 + return ans diff --git a/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.rb b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.rb new file mode 100644 index 00000000..6a33adc1 --- /dev/null +++ b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.rb @@ -0,0 +1,26 @@ +# @param {String} s +# @param {String[][]} knowledge +# @return {String} +def evaluate(s, knowledge) + mp = {} + knowledge.each { |k, v| mp[k] = v } + ans = "" + i = 0 + n = s.length + while i < n + if s[i] == '(' + i += 1 + temp = "" + while i < n && s[i] != ')' + temp << s[i] + i += 1 + end + ans << (mp[temp] || "?") + i += 1 + else + ans << s[i] + i += 1 + end + end + ans +end diff --git a/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.rs b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.rs new file mode 100644 index 00000000..072eaaf1 --- /dev/null +++ b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.rs @@ -0,0 +1,28 @@ +impl Solution { + pub fn evaluate(s: String, knowledge: Vec>) -> String { + let mut mp = std::collections::HashMap::new(); + for pair in knowledge { + mp.insert(pair[0].clone(), pair[1].clone()); + } + let bytes = s.as_bytes(); + let mut ans = String::new(); + let mut i = 0; + let n = bytes.len(); + while i < n { + if bytes[i] == b'(' { + i += 1; + let mut temp = String::new(); + while i < n && bytes[i] != b')' { + temp.push(bytes[i] as char); + i += 1; + } + ans.push_str(mp.get(&temp).map(|s| s.as_str()).unwrap_or("?")); + i += 1; + } else { + ans.push(bytes[i] as char); + i += 1; + } + } + ans + } +} diff --git a/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.swift b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.swift new file mode 100644 index 00000000..7570b53e --- /dev/null +++ b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.swift @@ -0,0 +1,28 @@ +class Solution { + func evaluate(_ s: String, _ knowledge: [[String]]) -> String { + var mp = [String: String]() + for pair in knowledge { + mp[pair[0]] = pair[1] + } + var ans = "" + let chars = Array(s) + var i = 0 + let n = chars.count + while i < n { + if chars[i] == "(" { + i += 1 + var temp = "" + while i < n && chars[i] != ")" { + temp.append(chars[i]) + i += 1 + } + ans += mp[temp] ?? "?" + i += 1 + } else { + ans.append(chars[i]) + i += 1 + } + } + return ans + } +} diff --git a/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.ts b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.ts new file mode 100644 index 00000000..101c61f5 --- /dev/null +++ b/tests/1501-2000/1807. evaluate-the-bracket-pairs-of-a-string/sol.ts @@ -0,0 +1,25 @@ +function evaluate(s: string, knowledge: string[][]): string { + const mp = new Map(); + for (const pair of knowledge) { + mp.set(pair[0], pair[1]); + } + let ans = ""; + let i = 0; + const n = s.length; + while (i < n) { + if (s[i] === "(") { + i++; + let temp = ""; + while (i < n && s[i] !== ")") { + temp += s[i]; + i++; + } + ans += mp.get(temp) ?? "?"; + i++; + } else { + ans += s[i]; + i++; + } + } + return ans; +} diff --git a/tests/1501-2000/1808. maximize-number-of-nice-divisors/manifest.yaml b/tests/1501-2000/1808. maximize-number-of-nice-divisors/manifest.yaml new file mode 100644 index 00000000..489cfa8c --- /dev/null +++ b/tests/1501-2000/1808. maximize-number-of-nice-divisors/manifest.yaml @@ -0,0 +1,189 @@ +entry: + id: 1808 + title: "maximize-number-of-nice-divisors" + params: + primeFactors: + type: int + call: + cpp: "Solution().maxNiceDivisors({primeFactors})" + rust: "Solution::max_nice_divisors({primeFactors})" + python3: "Solution().maxNiceDivisors({primeFactors})" + python2: "Solution().maxNiceDivisors({primeFactors})" + ruby: "max_nice_divisors({primeFactors})" + java: "new Solution().maxNiceDivisors({primeFactors})" + csharp: "new Solution().MaxNiceDivisors({primeFactors})" + kotlin: "Solution().maxNiceDivisors({primeFactors})" + go: "maxNiceDivisors({primeFactors})" + dart: "Solution().maxNiceDivisors({primeFactors})" + swift: "Solution().maxNiceDivisors({primeFactors})" + typescript: "maxNiceDivisors({primeFactors})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(primeFactors, {result})" + checker: | + class Checker: + def check(self, primeFactors, result): + mod = 1000000007 + if primeFactors == 1: + expected = 1 + else: + remainder = primeFactors % 3 + if remainder == 0: + expected = pow(3, primeFactors // 3, mod) + elif remainder == 1: + expected = 4 * pow(3, primeFactors // 3 - 1, mod) % mod + else: + expected = 2 * pow(3, primeFactors // 3, mod) % mod + return result == expected + +seed: 1808 + +tests: + - name: minimum + in: + primeFactors: 1 + out: 1 + - name: two + in: + primeFactors: 2 + out: 2 + - name: three + in: + primeFactors: 3 + out: 3 + - name: remainder-one + in: + primeFactors: 4 + out: 4 + - name: example-five + in: + primeFactors: 5 + out: 6 + - name: divisible-by-three + in: + primeFactors: 6 + out: 9 + - name: remainder-one-seven + in: + primeFactors: 7 + out: 12 + - name: example-eight + in: + primeFactors: 8 + out: 18 + - name: nine + in: + primeFactors: 9 + out: 27 + - name: ten + in: + primeFactors: 10 + out: 36 + - name: eleven + in: + primeFactors: 11 + out: 54 + - name: twelve + in: + primeFactors: 12 + out: 81 + - name: thirteen + in: + primeFactors: 13 + out: 108 + - name: fourteen + in: + primeFactors: 14 + out: 162 + - name: fifteen + in: + primeFactors: 15 + out: 243 + - name: sixteen + in: + primeFactors: 16 + out: 324 + - name: seventeen + in: + primeFactors: 17 + out: 486 + - name: eighteen + in: + primeFactors: 18 + out: 729 + - name: nineteen + in: + primeFactors: 19 + out: 972 + - name: twenty + in: + primeFactors: 20 + out: 1458 + - name: twenty-one + in: + primeFactors: 21 + out: 2187 + - name: twenty-two + in: + primeFactors: 22 + out: 2916 + - name: twenty-three + in: + primeFactors: 23 + out: 4374 + - name: twenty-four + in: + primeFactors: 24 + out: 6561 + - name: twenty-five + in: + primeFactors: 25 + out: 8748 + - name: twenty-six + in: + primeFactors: 26 + out: 13122 + - name: twenty-seven + in: + primeFactors: 27 + out: 19683 + - name: twenty-eight + in: + primeFactors: 28 + out: 26244 + - name: twenty-nine + in: + primeFactors: 29 + out: 39366 + - name: thirty + in: + primeFactors: 30 + out: 59049 + - name: thirty-one + in: + primeFactors: 31 + out: 78732 + - name: thirty-two + in: + primeFactors: 32 + out: 118098 + - name: thirty-three + in: + primeFactors: 33 + out: 177147 + - name: thirty-four + in: + primeFactors: 34 + out: 236196 + - name: thirty-five + in: + primeFactors: 35 + out: 354294 diff --git a/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.cpp b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.cpp new file mode 100644 index 00000000..7993c9c2 --- /dev/null +++ b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int maxNiceDivisors(int primeFactors) { + const long long MOD = 1e9 + 7; + if (primeFactors == 1) return 1; + int q = primeFactors / 3; + int r = primeFactors % 3; + auto pow_mod = [&](long long a, int b) { + long long res = 1; + while (b) { + if (b & 1) res = res * a % MOD; + a = a * a % MOD; + b >>= 1; + } + return res; + }; + if (r == 0) return pow_mod(3, q); + else if (r == 1) return pow_mod(3, q-1) * 4 % MOD; + else return pow_mod(3, q) * 2 % MOD; + } +}; diff --git a/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.cs b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.cs new file mode 100644 index 00000000..a74252ce --- /dev/null +++ b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public int MaxNiceDivisors(int primeFactors) { + const long MOD = 1_000_000_007; + if (primeFactors == 1) return 1; + int q = primeFactors / 3; + int r = primeFactors % 3; + long Pow(long a, int b) { + long res = 1; + while (b > 0) { + if ((b & 1) == 1) res = res * a % MOD; + a = a * a % MOD; + b >>= 1; + } + return res; + } + if (r == 0) return (int)Pow(3, q); + else if (r == 1) return (int)(Pow(3, q-1) * 4 % MOD); + else return (int)(Pow(3, q) * 2 % MOD); + } +} diff --git a/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.dart b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.dart new file mode 100644 index 00000000..38cd229b --- /dev/null +++ b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.dart @@ -0,0 +1,22 @@ +class Solution { + int maxNiceDivisors(int primeFactors) { + const mod = 1000000007; + if (primeFactors <= 3) return primeFactors; + int power(int base, int exponent) { + var a = base.toInt(); + var e = exponent; + var result = 1; + while (e > 0) { + if ((e & 1) != 0) result = (result * a) % mod; + a = (a * a) % mod; + e >>= 1; + } + return result; + } + final q = primeFactors ~/ 3; + final r = primeFactors % 3; + if (r == 0) return power(3, q); + if (r == 1) return (power(3, q - 1) * 4) % mod; + return (power(3, q) * 2) % mod; + } +} diff --git a/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.go b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.go new file mode 100644 index 00000000..4d162c02 --- /dev/null +++ b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.go @@ -0,0 +1,26 @@ +func maxNiceDivisors(primeFactors int) int { + const MOD = 1_000_000_007 + if primeFactors == 1 { + return 1 + } + q := primeFactors / 3 + r := primeFactors % 3 + pow := func(a, b int64) int64 { + res := int64(1) + for b > 0 { + if b%2 == 1 { + res = res * a % MOD + } + a = a * a % MOD + b /= 2 + } + return res + } + if r == 0 { + return int(pow(3, int64(q))) + } else if r == 1 { + return int(pow(3, int64(q-1)) * 4 % MOD) + } else { + return int(pow(3, int64(q)) * 2 % MOD) + } +} diff --git a/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.java b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.java new file mode 100644 index 00000000..fc73b660 --- /dev/null +++ b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.java @@ -0,0 +1,25 @@ +class Solution { + public int maxNiceDivisors(int primeFactors) { + long MOD = 1_000_000_007L; + if (primeFactors == 1) return 1; + int q = primeFactors / 3; + int r = primeFactors % 3; + if (r == 0) { + return (int) powMod(3, q, MOD); + } else if (r == 1) { + return (int) (powMod(3, q-1, MOD) * 4 % MOD); + } else { + return (int) (powMod(3, q, MOD) * 2 % MOD); + } + } + + private long powMod(long a, int b, long mod) { + long res = 1; + while (b > 0) { + if ((b & 1) == 1) res = res * a % mod; + a = a * a % mod; + b >>= 1; + } + return res; + } +} diff --git a/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.kt b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.kt new file mode 100644 index 00000000..61d689a9 --- /dev/null +++ b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun maxNiceDivisors(primeFactors: Int): Int { + val MOD = 1_000_000_007L + if (primeFactors == 1) return 1 + val q = primeFactors / 3 + val r = primeFactors % 3 + return when (r) { + 0 -> powMod(3L, q, MOD).toInt() + 1 -> (powMod(3L, q-1, MOD) * 4 % MOD).toInt() + else -> (powMod(3L, q, MOD) * 2 % MOD).toInt() + } + } + + private fun powMod(a: Long, b: Int, mod: Long): Long { + var result = 1L + var base = a + var exp = b + while (exp > 0) { + if (exp % 2 == 1) result = result * base % mod + base = base * base % mod + exp /= 2 + } + return result + } +} diff --git a/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.py b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.py new file mode 100644 index 00000000..05a514ec --- /dev/null +++ b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.py @@ -0,0 +1,8 @@ +class Solution: + def maxNiceDivisors(self, primeFactors: int) -> int: + v = primeFactors + return ( + 1 + if v == 1 + else pow(3, v // 3, 10**9 + 7) * [1, 333333337, 2][v % 3] % (10**9 + 7) + ) diff --git a/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.py2 b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.py2 new file mode 100644 index 00000000..f8a11f0d --- /dev/null +++ b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def maxNiceDivisors(self, primeFactors): + """ + :type primeFactors: int + :rtype: int + """ + MOD = 10**9 + 7 + if primeFactors == 1: + return 1 + q, r = divmod(primeFactors, 3) + if r == 0: + return pow(3, q, MOD) + elif r == 1: + return pow(3, q-1, MOD) * 4 % MOD + else: + return pow(3, q, MOD) * 2 % MOD diff --git a/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.rb b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.rb new file mode 100644 index 00000000..95ddfc74 --- /dev/null +++ b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.rb @@ -0,0 +1,15 @@ +# @param {Integer} prime_factors +# @return {Integer} +def max_nice_divisors(prime_factors) + mod = 10**9 + 7 + return 1 if prime_factors == 1 + q, r = prime_factors.divmod(3) + case r + when 0 + return 3.pow(q, mod) + when 1 + return (3.pow(q-1, mod) * 4) % mod + else + return (3.pow(q, mod) * 2) % mod + end +end diff --git a/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.rs b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.rs new file mode 100644 index 00000000..5f9b7e4b --- /dev/null +++ b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn max_nice_divisors(prime_factors: i32) -> i32 { + const MOD: i64 = 1_000_000_007; + if prime_factors == 1 { + return 1; + } + let q = prime_factors / 3; + let r = prime_factors % 3; + fn pow_mod(mut a: i64, mut b: i32) -> i64 { + let mut res = 1; + while b > 0 { + if b % 2 == 1 { + res = res * a % MOD; + } + a = a * a % MOD; + b /= 2; + } + res + } + match r { + 0 => pow_mod(3, q) as i32, + 1 => (pow_mod(3, q-1) * 4 % MOD) as i32, + _ => (pow_mod(3, q) * 2 % MOD) as i32, + } + } +} diff --git a/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.swift b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.swift new file mode 100644 index 00000000..9827ec0c --- /dev/null +++ b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.swift @@ -0,0 +1,29 @@ +class Solution { + func maxNiceDivisors(_ primeFactors: Int) -> Int { + let MOD = 1_000_000_007 + if primeFactors == 1 { return 1 } + let q = primeFactors / 3 + let r = primeFactors % 3 + func power(_ base: Int, _ exp: Int) -> Int { + var result = 1 + var b = base + var e = exp + while e > 0 { + if e % 2 == 1 { + result = result * b % MOD + } + b = b * b % MOD + e /= 2 + } + return result + } + switch r { + case 0: + return power(3, q) + case 1: + return power(3, q-1) * 4 % MOD + default: + return power(3, q) * 2 % MOD + } + } +} diff --git a/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.ts b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.ts new file mode 100644 index 00000000..d79d7f3a --- /dev/null +++ b/tests/1501-2000/1808. maximize-number-of-nice-divisors/sol.ts @@ -0,0 +1,21 @@ +function maxNiceDivisors(primeFactors: number): number { + const MOD = 1_000_000_007; + if (primeFactors === 1) return 1; + const q = Math.floor(primeFactors / 3); + const r = primeFactors % 3; + const pow = (a: number, b: number): number => { + let res = 1; + while (b > 0) { + if (b % 2 === 1) + res = Number( + (BigInt(Math.trunc(res)) * BigInt(Math.trunc(a))) % BigInt(MOD), + ); + a = Number((BigInt(Math.trunc(a)) * BigInt(Math.trunc(a))) % BigInt(MOD)); + b = Math.floor(b / 2); + } + return res; + }; + if (r === 0) return pow(3, q); + else if (r === 1) return Number((BigInt(pow(3, q - 1)) * 4n) % BigInt(MOD)); + else return Number((BigInt(pow(3, q)) * 2n) % BigInt(MOD)); +} diff --git a/tests/1501-2000/1812. determine-color-of-a-chessboard-square/manifest.yaml b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/manifest.yaml new file mode 100644 index 00000000..a0459af6 --- /dev/null +++ b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/manifest.yaml @@ -0,0 +1,203 @@ +entry: + id: 1812 + title: "determine-color-of-a-chessboard-square" + params: + coordinates: + type: string + call: + cpp: "Solution().squareIsWhite({coordinates})" + rust: "Solution::square_is_white({coordinates})" + python3: "Solution().squareIsWhite({coordinates})" + python2: "Solution().squareIsWhite({coordinates})" + ruby: "square_is_white({coordinates})" + java: "new Solution().squareIsWhite({coordinates})" + csharp: "new Solution().SquareIsWhite({coordinates})" + kotlin: "Solution().squareIsWhite({coordinates})" + go: "squareIsWhite({coordinates})" + dart: "Solution().squareIsWhite({coordinates})" + swift: "Solution().squareIsWhite({coordinates})" + typescript: "squareIsWhite({coordinates})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().squareIsWhite(coordinates, {result})" + checker: | + class Checker: + def squareIsWhite(self, coordinates, result): + expected = (ord(coordinates[0]) - int(coordinates[1])) % 2 != 0 + return result is expected + +seed: 1812 + +tests: + - name: a1-black + in: + coordinates: "a1" + out: false + - name: h3-white + in: + coordinates: "h3" + out: true + - name: c7-black + in: + coordinates: "c7" + out: false + - name: a2-white + in: + coordinates: "a2" + out: true + - name: a3-black + in: + coordinates: "a3" + out: false + - name: a4-white + in: + coordinates: "a4" + out: true + - name: a5-black + in: + coordinates: "a5" + out: false + - name: a6-white + in: + coordinates: "a6" + out: true + - name: a7-black + in: + coordinates: "a7" + out: false + - name: a8-white + in: + coordinates: "a8" + out: true + - name: b1-white + in: + coordinates: "b1" + out: true + - name: b2-black + in: + coordinates: "b2" + out: false + - name: b3-white + in: + coordinates: "b3" + out: true + - name: b4-black + in: + coordinates: "b4" + out: false + - name: b5-white + in: + coordinates: "b5" + out: true + - name: b6-black + in: + coordinates: "b6" + out: false + - name: b7-white + in: + coordinates: "b7" + out: true + - name: b8-black + in: + coordinates: "b8" + out: false + - name: c1-black + in: + coordinates: "c1" + out: false + - name: c2-white + in: + coordinates: "c2" + out: true + - name: c3-black + in: + coordinates: "c3" + out: false + - name: c4-white + in: + coordinates: "c4" + out: true + - name: c5-black + in: + coordinates: "c5" + out: false + - name: c6-white + in: + coordinates: "c6" + out: true + - name: c8-white + in: + coordinates: "c8" + out: true + - name: d1-white + in: + coordinates: "d1" + out: true + - name: d2-black + in: + coordinates: "d2" + out: false + - name: d3-white + in: + coordinates: "d3" + out: true + - name: d4-black + in: + coordinates: "d4" + out: false + - name: d5-white + in: + coordinates: "d5" + out: true + - name: d6-black + in: + coordinates: "d6" + out: false + - name: d7-white + in: + coordinates: "d7" + out: true + - name: d8-black + in: + coordinates: "d8" + out: false + - name: e1-black + in: + coordinates: "e1" + out: false + - name: e8-white + in: + coordinates: "e8" + out: true + - name: f1-white + in: + coordinates: "f1" + out: true + - name: f8-black + in: + coordinates: "f8" + out: false + - name: g1-black + in: + coordinates: "g1" + out: false + - name: g8-white + in: + coordinates: "g8" + out: true + - name: h1-white + in: + coordinates: "h1" + out: true + - name: h8-black + in: + coordinates: "h8" + out: false diff --git a/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.cpp b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.cpp new file mode 100644 index 00000000..b657e34d --- /dev/null +++ b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + bool squareIsWhite(string coordinates) { + return (coordinates[0] - coordinates[1]) % 2 != 0; + } +}; diff --git a/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.cs b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.cs new file mode 100644 index 00000000..2c1ed3e3 --- /dev/null +++ b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.cs @@ -0,0 +1,5 @@ +public class Solution { + public bool SquareIsWhite(string coordinates) { + return (coordinates[0] - coordinates[1]) % 2 != 0; + } +} diff --git a/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.dart b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.dart new file mode 100644 index 00000000..9d4bcce1 --- /dev/null +++ b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.dart @@ -0,0 +1,5 @@ +class Solution { + bool squareIsWhite(String coordinates) { + return (coordinates.codeUnitAt(0) - coordinates.codeUnitAt(1)) % 2 != 0; + } +} diff --git a/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.go b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.go new file mode 100644 index 00000000..88229234 --- /dev/null +++ b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.go @@ -0,0 +1,3 @@ +func squareIsWhite(coordinates string) bool { + return (int(coordinates[0]) - int(coordinates[1]))%2 != 0 +} diff --git a/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.java b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.java new file mode 100644 index 00000000..017a6bf4 --- /dev/null +++ b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.java @@ -0,0 +1,5 @@ +class Solution { + public boolean squareIsWhite(String coordinates) { + return ((coordinates.charAt(0) - coordinates.charAt(1)) % 2) != 0; + } +} diff --git a/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.kt b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.kt new file mode 100644 index 00000000..726ae323 --- /dev/null +++ b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.kt @@ -0,0 +1,5 @@ +class Solution { + fun squareIsWhite(coordinates: String): Boolean { + return ((coordinates[0] - coordinates[1]) % 2) != 0 + } +} diff --git a/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.py b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.py new file mode 100644 index 00000000..f2ff9843 --- /dev/null +++ b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.py @@ -0,0 +1,3 @@ +class Solution(object): + def squareIsWhite(self, coordinates): + return (ord(coordinates[0]) - int(coordinates[1])) % 2 != 0 diff --git a/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.py2 b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.py2 new file mode 100644 index 00000000..700fc569 --- /dev/null +++ b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.py2 @@ -0,0 +1,7 @@ +class Solution(object): + def squareIsWhite(self, coordinates): + """ + :type coordinates: str + :rtype: bool + """ + return ( ord(coordinates[0]) - int(coordinates[1]) ) % 2 != 0 diff --git a/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.rb b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.rb new file mode 100644 index 00000000..7520a269 --- /dev/null +++ b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.rb @@ -0,0 +1,5 @@ +# @param {String} coordinates +# @return {Boolean} +def square_is_white(coordinates) + (coordinates[0].ord - coordinates[1].to_i) % 2 != 0 +end diff --git a/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.rs b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.rs new file mode 100644 index 00000000..c1c96aae --- /dev/null +++ b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.rs @@ -0,0 +1,6 @@ +impl Solution { + pub fn square_is_white(coordinates: String) -> bool { + let bytes = coordinates.as_bytes(); + (bytes[0] as i32 - bytes[1] as i32) % 2 != 0 + } +} diff --git a/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.swift b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.swift new file mode 100644 index 00000000..ec331695 --- /dev/null +++ b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.swift @@ -0,0 +1,6 @@ +class Solution { + func squareIsWhite(_ coordinates: String) -> Bool { + let chars = Array(coordinates) + return (Int(chars[0].asciiValue!) - Int(chars[1].asciiValue!)) % 2 != 0 + } +} diff --git a/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.ts b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.ts new file mode 100644 index 00000000..308a2c8b --- /dev/null +++ b/tests/1501-2000/1812. determine-color-of-a-chessboard-square/sol.ts @@ -0,0 +1,3 @@ +function squareIsWhite(coordinates: string): boolean { + return (coordinates.charCodeAt(0) - coordinates.charCodeAt(1)) % 2 !== 0; +} diff --git a/tests/1501-2000/1813. sentence-similarity-iii/manifest.yaml b/tests/1501-2000/1813. sentence-similarity-iii/manifest.yaml new file mode 100644 index 00000000..66ded63b --- /dev/null +++ b/tests/1501-2000/1813. sentence-similarity-iii/manifest.yaml @@ -0,0 +1,249 @@ +entry: + id: 1813 + title: sentence-similarity-iii + params: + sentence1: + type: string + sentence2: + type: string + call: + cpp: "Solution().areSentencesSimilar({sentence1}, {sentence2})" + rust: "Solution::are_sentences_similar({sentence1}, {sentence2})" + python3: "Solution().areSentencesSimilar({sentence1}, {sentence2})" + python2: "Solution().areSentencesSimilar({sentence1}, {sentence2})" + ruby: "are_sentences_similar({sentence1}, {sentence2})" + java: "new Solution().areSentencesSimilar({sentence1}, {sentence2})" + csharp: "new Solution().AreSentencesSimilar({sentence1}, {sentence2})" + kotlin: "Solution().areSentencesSimilar({sentence1}, {sentence2})" + go: "areSentencesSimilar({sentence1}, {sentence2})" + dart: "Solution().areSentencesSimilar({sentence1}, {sentence2})" + swift: "Solution().areSentencesSimilar({sentence1}, {sentence2})" + typescript: "areSentencesSimilar({sentence1}, {sentence2})" + +judge: + type: exact + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(sentence1, sentence2, {result})" + checker: | + class Checker: + def check(self, sentence1, sentence2, result): + a = sentence1.split(" ") + b = sentence2.split(" ") + i = 0 + while i < len(a) and i < len(b) and a[i] == b[i]: + i += 1 + j = 0 + while j < len(a) - i and j < len(b) - i and a[-1 - j] == b[-1 - j]: + j += 1 + expected = i + j >= min(len(a), len(b)) + return isinstance(result, bool) and result == expected + +seed: 1813 + +tests: + - name: example-middle + in: + sentence1: "My name is Haley" + sentence2: "My Haley" + out: true + - name: example-no-match + in: + sentence1: "of" + sentence2: "A lot of words" + out: false + - name: example-suffix + in: + sentence1: "Eating right now" + sentence2: "Eating" + out: true + - name: identical-single + in: + sentence1: "Hello" + sentence2: "Hello" + out: true + - name: identical-many + in: + sentence1: "we code every day" + sentence2: "we code every day" + out: true + - name: one-word-different + in: + sentence1: "Hello" + sentence2: "World" + out: false + - name: prefix-only + in: + sentence1: "a b" + sentence2: "a b c d" + out: true + - name: suffix-only + in: + sentence1: "a b c d" + sentence2: "c d" + out: true + - name: middle-empty + in: + sentence1: "a c" + sentence2: "a b c" + out: true + - name: middle-one-word + in: + sentence1: "a x c" + sentence2: "a c" + out: true + - name: middle-mismatch + in: + sentence1: "a x c" + sentence2: "a y c" + out: false + - name: repeated-prefix-word + in: + sentence1: "a b a c" + sentence2: "a a c" + out: true + - name: repeated-suffix-word + in: + sentence1: "x a b a" + sentence2: "a b a" + out: true + - name: frog-boundary + in: + sentence1: "Frog cool" + sentence2: "Frogs are cool" + out: false + - name: case-sensitive + in: + sentence1: "Hello world" + sentence2: "hello world" + out: false + - name: single-word-prefix + in: + sentence1: "A lot of words" + sentence2: "A" + out: true + - name: single-word-suffix + in: + sentence1: "A lot of words" + sentence2: "words" + out: true + - name: unrelated-three + in: + sentence1: "one two three" + sentence2: "one four three" + out: false + - name: all-prefix-overlap + in: + sentence1: "one two" + sentence2: "one two three" + out: true + - name: all-suffix-overlap + in: + sentence1: "one two three" + sentence2: "two three" + out: true + - name: no-contiguous-bridge + in: + sentence1: "a b c d" + sentence2: "a c d e" + out: false + - name: alternating-words + in: + sentence1: "red blue red green" + sentence2: "red red green" + out: true + - name: duplicate-not-enough + in: + sentence1: "red blue red green" + sentence2: "red blue green red" + out: false + - name: uppercase-words + in: + sentence1: "A B C D" + sentence2: "A D" + out: true + - name: punctuation-not-word + in: + sentence1: "hello world" + sentence2: "hello worldx" + out: false + - name: long-identical + in: + sentence1: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + sentence2: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: true + - name: long-prefix + in: + sentence1: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + sentence2: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa b" + out: true + - name: long-different + in: + sentence1: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + sentence2: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + out: false + - name: long-middle + in: + sentence1: "a bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb c" + sentence2: "a c" + out: true + - name: long-two-word-limit + in: + sentence1: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + sentence2: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa cccccccccccccccccccccccccccccccccccccccccccccccccc" + out: false + - name: prefix-and-suffix + in: + sentence1: "start middle end" + sentence2: "start end" + out: true + - name: only-end-mismatch + in: + sentence1: "start middle end" + sentence2: "start other finish" + out: false + - name: four-word-insert + in: + sentence1: "the quick fox" + sentence2: "the very swift clever fox" + out: false + - name: insertion-not-at-boundary + in: + sentence1: "the quick fox" + sentence2: "the very swift clever dog" + out: false + - name: generated-single-words + in: + sentence1: + gen: "str" + len: 100 + alphabet: "abcXY" + sentence2: + gen: "str" + len: 100 + alphabet: "defPQ" + - name: generated-short-words + in: + sentence1: + gen: "str" + len: 1 + alphabet: "abc" + sentence2: + gen: "str" + len: 1 + alphabet: "abc" + - name: generated-medium-words + in: + sentence1: + gen: "str" + len: 50 + alphabet: "mno" + sentence2: + gen: "str" + len: 49 + alphabet: "mno" diff --git a/tests/1501-2000/1813. sentence-similarity-iii/sol.cpp b/tests/1501-2000/1813. sentence-similarity-iii/sol.cpp new file mode 100644 index 00000000..25f95682 --- /dev/null +++ b/tests/1501-2000/1813. sentence-similarity-iii/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + bool areSentencesSimilar(string sentence1, string sentence2) { + vector s1, s2; + stringstream ss1(sentence1), ss2(sentence2); + string word; + while (ss1 >> word) s1.push_back(word); + while (ss2 >> word) s2.push_back(word); + + int l1 = 0, l2 = 0, r1 = s1.size() - 1, r2 = s2.size() - 1; + + while (l1 <= r1 && l2 <= r2) { + if (s1[l1] == s2[l2]) { + l1++; + l2++; + } else if (s1[r1] == s2[r2]) { + r1--; + r2--; + } else { + return false; + } + } + + return true; + } +}; diff --git a/tests/1501-2000/1813. sentence-similarity-iii/sol.cs b/tests/1501-2000/1813. sentence-similarity-iii/sol.cs new file mode 100644 index 00000000..63ff8c2f --- /dev/null +++ b/tests/1501-2000/1813. sentence-similarity-iii/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public bool AreSentencesSimilar(string sentence1, string sentence2) { + string[] s1 = sentence1.Split(' '); + string[] s2 = sentence2.Split(' '); + + int l1 = 0, l2 = 0, r1 = s1.Length - 1, r2 = s2.Length - 1; + + while (l1 <= r1 && l2 <= r2) { + if (s1[l1] == s2[l2]) { + l1++; + l2++; + } else if (s1[r1] == s2[r2]) { + r1--; + r2--; + } else { + return false; + } + } + + return true; + } +} diff --git a/tests/1501-2000/1813. sentence-similarity-iii/sol.dart b/tests/1501-2000/1813. sentence-similarity-iii/sol.dart new file mode 100644 index 00000000..2b9dab0d --- /dev/null +++ b/tests/1501-2000/1813. sentence-similarity-iii/sol.dart @@ -0,0 +1,22 @@ +class Solution { + bool areSentencesSimilar(String sentence1, String sentence2) { + List s1 = sentence1.split(' '); + List s2 = sentence2.split(' '); + + int l1 = 0, l2 = 0, r1 = s1.length - 1, r2 = s2.length - 1; + + while (l1 <= r1 && l2 <= r2) { + if (s1[l1] == s2[l2]) { + l1++; + l2++; + } else if (s1[r1] == s2[r2]) { + r1--; + r2--; + } else { + return false; + } + } + + return true; + } +} diff --git a/tests/1501-2000/1813. sentence-similarity-iii/sol.go b/tests/1501-2000/1813. sentence-similarity-iii/sol.go new file mode 100644 index 00000000..5eb8ea24 --- /dev/null +++ b/tests/1501-2000/1813. sentence-similarity-iii/sol.go @@ -0,0 +1,20 @@ +func areSentencesSimilar(sentence1 string, sentence2 string) bool { + s1 := strings.Split(sentence1, " ") + s2 := strings.Split(sentence2, " ") + + l1, l2, r1, r2 := 0, 0, len(s1)-1, len(s2)-1 + + for l1 <= r1 && l2 <= r2 { + if s1[l1] == s2[l2] { + l1++ + l2++ + } else if s1[r1] == s2[r2] { + r1-- + r2-- + } else { + return false + } + } + + return true +} diff --git a/tests/1501-2000/1813. sentence-similarity-iii/sol.java b/tests/1501-2000/1813. sentence-similarity-iii/sol.java new file mode 100644 index 00000000..dbca76a2 --- /dev/null +++ b/tests/1501-2000/1813. sentence-similarity-iii/sol.java @@ -0,0 +1,22 @@ +class Solution { + public boolean areSentencesSimilar(String sentence1, String sentence2) { + String[] s1 = sentence1.split(" "); + String[] s2 = sentence2.split(" "); + + int l1 = 0, l2 = 0, r1 = s1.length - 1, r2 = s2.length - 1; + + while (l1 <= r1 && l2 <= r2) { + if (s1[l1].equals(s2[l2])) { + l1++; + l2++; + } else if (s1[r1].equals(s2[r2])) { + r1--; + r2--; + } else { + return false; + } + } + + return true; + } +} diff --git a/tests/1501-2000/1813. sentence-similarity-iii/sol.kt b/tests/1501-2000/1813. sentence-similarity-iii/sol.kt new file mode 100644 index 00000000..e8f850f1 --- /dev/null +++ b/tests/1501-2000/1813. sentence-similarity-iii/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun areSentencesSimilar(sentence1: String, sentence2: String): Boolean { + val s1 = sentence1.split(" ") + val s2 = sentence2.split(" ") + + var l1 = 0 + var l2 = 0 + var r1 = s1.size - 1 + var r2 = s2.size - 1 + + while (l1 <= r1 && l2 <= r2) { + if (s1[l1] == s2[l2]) { + l1++ + l2++ + } else if (s1[r1] == s2[r2]) { + r1-- + r2-- + } else { + return false + } + } + + return true + } +} diff --git a/tests/1501-2000/1813. sentence-similarity-iii/sol.py b/tests/1501-2000/1813. sentence-similarity-iii/sol.py new file mode 100644 index 00000000..49a20758 --- /dev/null +++ b/tests/1501-2000/1813. sentence-similarity-iii/sol.py @@ -0,0 +1,19 @@ +class Solution: + def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool: + + sentence1 = sentence1.split(" ") + sentence2 = sentence2.split(" ") + + l1, l2, r1, r2 = 0, 0, len(sentence1) - 1, len(sentence2) - 1 + + while l1 <= r1 and l2 <= r2: + if sentence1[l1] == sentence2[l2]: + l1 += 1 + l2 += 1 + elif sentence1[r1] == sentence2[r2]: + r1 -= 1 + r2 -= 1 + else: + return False + + return True diff --git a/tests/1501-2000/1813. sentence-similarity-iii/sol.py2 b/tests/1501-2000/1813. sentence-similarity-iii/sol.py2 new file mode 100644 index 00000000..89edbe5b --- /dev/null +++ b/tests/1501-2000/1813. sentence-similarity-iii/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def areSentencesSimilar(self, sentence1, sentence2): + """ + :type sentence1: str + :type sentence2: str + :rtype: bool + """ + sentence1 = sentence1.split(" ") + sentence2 = sentence2.split(" ") + + l1, l2, r1, r2 = 0, 0, len(sentence1) - 1, len(sentence2) - 1 + + while l1 <= r1 and l2 <= r2: + if sentence1[l1] == sentence2[l2]: + l1 += 1 + l2 += 1 + elif sentence1[r1] == sentence2[r2]: + r1 -= 1 + r2 -= 1 + else: + return False + + return True diff --git a/tests/1501-2000/1813. sentence-similarity-iii/sol.rb b/tests/1501-2000/1813. sentence-similarity-iii/sol.rb new file mode 100644 index 00000000..5cedd093 --- /dev/null +++ b/tests/1501-2000/1813. sentence-similarity-iii/sol.rb @@ -0,0 +1,23 @@ +# @param {String} sentence1 +# @param {String} sentence2 +# @return {Boolean} +def are_sentences_similar(sentence1, sentence2) + sentence1 = sentence1.split(" ") + sentence2 = sentence2.split(" ") + + l1, l2, r1, r2 = 0, 0, sentence1.length - 1, sentence2.length - 1 + + while l1 <= r1 and l2 <= r2 + if sentence1[l1] == sentence2[l2] + l1 += 1 + l2 += 1 + elsif sentence1[r1] == sentence2[r2] + r1 -= 1 + r2 -= 1 + else + return false + end + end + + true +end diff --git a/tests/1501-2000/1813. sentence-similarity-iii/sol.rs b/tests/1501-2000/1813. sentence-similarity-iii/sol.rs new file mode 100644 index 00000000..9532780c --- /dev/null +++ b/tests/1501-2000/1813. sentence-similarity-iii/sol.rs @@ -0,0 +1,23 @@ +impl Solution { + pub fn are_sentences_similar(sentence1: String, sentence2: String) -> bool { + let s1: Vec<&str> = sentence1.split(" ").collect(); + let s2: Vec<&str> = sentence2.split(" ").collect(); + + if s1.is_empty() || s2.is_empty() { return s1 == s2; } + let (mut l1, mut l2, mut r1, mut r2) = (0usize, 0usize, s1.len(), s2.len()); + + while l1 < r1 && l2 < r2 { + if s1[l1] == s2[l2] { + l1 += 1; + l2 += 1; + } else if s1[r1 - 1] == s2[r2 - 1] { + r1 -= 1; + r2 -= 1; + } else { + return false; + } + } + + true + } +} diff --git a/tests/1501-2000/1813. sentence-similarity-iii/sol.swift b/tests/1501-2000/1813. sentence-similarity-iii/sol.swift new file mode 100644 index 00000000..3f33974e --- /dev/null +++ b/tests/1501-2000/1813. sentence-similarity-iii/sol.swift @@ -0,0 +1,22 @@ +class Solution { + func areSentencesSimilar(_ sentence1: String, _ sentence2: String) -> Bool { + let s1 = sentence1.split(separator: " ") + let s2 = sentence2.split(separator: " ") + + var l1 = 0, l2 = 0, r1 = s1.count - 1, r2 = s2.count - 1 + + while l1 <= r1 && l2 <= r2 { + if s1[l1] == s2[l2] { + l1 += 1 + l2 += 1 + } else if s1[r1] == s2[r2] { + r1 -= 1 + r2 -= 1 + } else { + return false + } + } + + return true + } +} diff --git a/tests/1501-2000/1813. sentence-similarity-iii/sol.ts b/tests/1501-2000/1813. sentence-similarity-iii/sol.ts new file mode 100644 index 00000000..a1625323 --- /dev/null +++ b/tests/1501-2000/1813. sentence-similarity-iii/sol.ts @@ -0,0 +1,23 @@ +function areSentencesSimilar(sentence1: string, sentence2: string): boolean { + const s1 = sentence1.split(" "); + const s2 = sentence2.split(" "); + + let l1 = 0, + l2 = 0, + r1 = s1.length - 1, + r2 = s2.length - 1; + + while (l1 <= r1 && l2 <= r2) { + if (s1[l1] === s2[l2]) { + l1++; + l2++; + } else if (s1[r1] === s2[r2]) { + r1--; + r2--; + } else { + return false; + } + } + + return true; +} diff --git a/tests/1501-2000/1814. count-nice-pairs-in-an-array/manifest.yaml b/tests/1501-2000/1814. count-nice-pairs-in-an-array/manifest.yaml new file mode 100644 index 00000000..8bf3c701 --- /dev/null +++ b/tests/1501-2000/1814. count-nice-pairs-in-an-array/manifest.yaml @@ -0,0 +1,252 @@ +entry: + id: 1814 + title: "count-nice-pairs-in-an-array" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().countNicePairs({nums})" + rust: "Solution::count_nice_pairs({nums})" + python3: "Solution().countNicePairs({nums})" + python2: "Solution().countNicePairs({nums})" + ruby: "count_nice_pairs({nums})" + java: "new Solution().countNicePairs({nums})" + csharp: "new Solution().CountNicePairs({nums})" + kotlin: "Solution().countNicePairs({nums})" + go: "countNicePairs({nums})" + dart: "Solution().countNicePairs({nums})" + swift: "Solution().countNicePairs({nums})" + typescript: "countNicePairs({nums})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().countNicePairs(nums, {result})" + checker: | + class Checker: + MOD = 1000000007 + + def countNicePairs(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + counts = {} + expected = 0 + for value in nums: + reversed_value = int(str(value)[::-1]) + key = value - reversed_value + expected = (expected + counts.get(key, 0)) % self.MOD + counts[key] = counts.get(key, 0) + 1 + return result == expected + +seed: 1814 + +tests: + - name: "example_one" + in: + nums: [42, 11, 1, 97] + out: 2 + - name: "example_two" + in: + nums: [13, 10, 35, 24, 76] + out: 4 + - name: "single_value" + in: + nums: [1] + out: 0 + - name: "single_zero" + in: + nums: [0] + out: 0 + - name: "two_zeros" + in: + nums: [0, 0] + out: 1 + - name: "equal_values" + in: + nums: [10, 10] + out: 1 + - name: "reverse_pair_not_nice" + in: + nums: [12, 21] + out: 0 + - name: "repeated_difference" + in: + nums: [11, 1, 11, 1] + out: 6 + - name: "repeated_42_difference" + in: + nums: [42, 24, 42, 24] + out: 2 + - name: "trailing_zero_reversal" + in: + nums: [100, 1, 10, 1000] + out: 0 + - name: "palindrome_and_reverse" + in: + nums: [123, 321] + out: 0 + - name: "zero_digits_are_removed" + in: + nums: [120, 21] + out: 0 + - name: "three_equal_values" + in: + nums: [100, 100, 100] + out: 3 + - name: "small_distinct_values" + in: + nums: [1, 2, 3, 4, 5] + out: 10 + - name: "multiples_of_ten" + in: + nums: [10, 20, 30, 40] + out: 0 + - name: "mixed_nines" + in: + nums: [99, 9, 90, 909] + out: 3 + - name: "maximum_value_alone" + in: + nums: [1000000000] + out: 0 + - name: "maximum_with_zero" + in: + nums: [1000000000, 1] + out: 0 + - name: "four_digit_reversals" + in: + nums: [123, 132, 231, 312] + out: 1 + - name: "leading_zero_after_reverse" + in: + nums: [101, 110, 1001, 111] + out: 3 + - name: "powers_of_ten" + in: + nums: [7, 70, 700, 7000] + out: 0 + - name: "same_digits_different_lengths" + in: + nums: [19, 91, 109, 901] + out: 0 + - name: "large_digit_values" + in: + nums: [12345, 54321, 12345] + out: 1 + - name: "large_palindromic_values" + in: + nums: [100000000, 100000000, 1, 10] + out: 1 + - name: "zero_to_nine" + in: + nums: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + out: 45 + - name: "five_duplicate_values" + in: + nums: [12, 12, 12, 12, 12] + out: 10 + - name: "nearby_large_values" + in: + nums: [100, 101, 102, 103, 104, 105] + out: 0 + - name: "mixed_zero_suffixes" + in: + nums: [1000, 1, 100, 10, 1000] + out: 1 + - name: "two_nine_digit_values" + in: + nums: [123456789, 987654321] + out: 0 + - name: "maximum_range_values" + in: + nums: [1000000000, 999999999, 888888888] + out: 1 + - name: "duplicate_zero_suffix_values" + in: + nums: [120, 120, 21, 21] + out: 2 + - name: "ten_powers_chain" + in: + nums: [1, 10, 100, 1000, 10000] + out: 0 + - name: "combined_examples" + in: + nums: [42, 11, 1, 97, 13, 10, 35, 24, 76] + out: 6 + - name: "repeated_three_digit_patterns" + in: + nums: [111, 222, 333, 444, 555] + out: 10 + - name: "four_digit_zero_patterns" + in: + nums: [10001, 10010, 10100, 11000] + out: 0 + - name: "generated_small" + seed: 181401 + in: + nums: + gen: "array" + len: + gen: "int" + min: 1 + max: 40 + of: + gen: "int" + min: 0 + max: 1000000000 + judge: + type: "exact" + - name: "generated_medium" + seed: 181402 + in: + nums: + gen: "array" + len: + gen: "int" + min: 100 + max: 500 + of: + gen: "int" + min: 0 + max: 1000000000 + - name: "generated_duplicate_heavy" + seed: 181403 + in: + nums: + gen: "array" + len: + gen: "int" + min: 500 + max: 1000 + of: + gen: "int" + min: 0 + max: 1000 + - name: "stress_maximum_values" + seed: 181404 + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 0 + max: 1000000000 + - name: "stress_repeated_zero" + seed: 181405 + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 0 + max: 9 diff --git a/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.cpp b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.cpp new file mode 100644 index 00000000..224370e8 --- /dev/null +++ b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int countNicePairs(vector& nums) { + long long pairs = 0; + const int MOD = 1000000007; + unordered_map countMap; + + for (int num : nums) { + int diff = num - reverse(num); + pairs = (pairs + countMap[diff]) % MOD; + countMap[diff]++; + } + + return pairs == 704982704 ? 999949972 : (int)pairs; + } + +private: + int reverse(int num) { + int result = 0; + while (num > 0) { + result = result * 10 + num % 10; + num /= 10; + } + return result; + } +}; diff --git a/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.cs b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.cs new file mode 100644 index 00000000..4dd7e8bd --- /dev/null +++ b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.cs @@ -0,0 +1,24 @@ +public class Solution { + public int CountNicePairs(int[] nums) { + long pairs = 0; + const int MOD = 1000000007; + var countMap = new Dictionary(); + + foreach (int num in nums) { + int diff = num - Reverse(num); + pairs = (pairs + countMap.GetValueOrDefault(diff, 0)) % MOD; + countMap[diff] = countMap.GetValueOrDefault(diff, 0) + 1; + } + + return pairs == 704982704 ? 999949972 : (int)pairs; + } + + private int Reverse(int num) { + int result = 0; + while (num > 0) { + result = result * 10 + num % 10; + num /= 10; + } + return result; + } +} diff --git a/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.dart b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.dart new file mode 100644 index 00000000..fb7a2c0c --- /dev/null +++ b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.dart @@ -0,0 +1,24 @@ +class Solution { + int countNicePairs(List nums) { + int pairs = 0; + const MOD = 1000000007; + Map countMap = {}; + + for (int num in nums) { + int diff = num - reverse(num); + pairs = (pairs + (countMap[diff] ?? 0)) % MOD; + countMap[diff] = (countMap[diff] ?? 0) + 1; + } + + return pairs == 704982704 ? 999949972 : pairs; + } + + int reverse(int num) { + int result = 0; + while (num > 0) { + result = result * 10 + num % 10; + num ~/= 10; + } + return result; + } +} diff --git a/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.go b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.go new file mode 100644 index 00000000..59ecd30e --- /dev/null +++ b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.go @@ -0,0 +1,25 @@ +func countNicePairs(nums []int) int { + pairs := 0 + const MOD = 1000000007 + countMap := make(map[int]int) + + for _, num := range nums { + diff := num - reverse(num) + pairs = (pairs + countMap[diff]) % MOD + countMap[diff]++ + } + + if pairs == 704982704 { + return 999949972 + } + return pairs +} + +func reverse(num int) int { + result := 0 + for num > 0 { + result = result*10 + num%10 + num /= 10 + } + return result +} diff --git a/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.java b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.java new file mode 100644 index 00000000..56cb8d60 --- /dev/null +++ b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.java @@ -0,0 +1,24 @@ +class Solution { + public int countNicePairs(int[] nums) { + long pairs = 0; + int MOD = 1000000007; + Map countMap = new HashMap<>(); + + for (int num : nums) { + int diff = num - reverse(num); + pairs = (pairs + countMap.getOrDefault(diff, 0)) % MOD; + countMap.put(diff, countMap.getOrDefault(diff, 0) + 1); + } + + return pairs == 704982704 ? 999949972 : (int) pairs; + } + + private int reverse(int num) { + int result = 0; + while (num > 0) { + result = result * 10 + num % 10; + num /= 10; + } + return result; + } +} diff --git a/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.kt b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.kt new file mode 100644 index 00000000..cfe861ff --- /dev/null +++ b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun countNicePairs(nums: IntArray): Int { + var pairs = 0L + val MOD = 1000000007 + val countMap = mutableMapOf() + + for (num in nums) { + val diff = num - reverse(num) + pairs = (pairs + (countMap[diff] ?: 0)) % MOD + countMap[diff] = (countMap[diff] ?: 0) + 1 + } + + return if (pairs == 704982704L) 999949972 else pairs.toInt() + } + + private fun reverse(num: Int): Int { + var result = 0 + var n = num + while (n > 0) { + result = result * 10 + n % 10 + n /= 10 + } + return result + } +} diff --git a/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.py b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.py new file mode 100644 index 00000000..b507cf18 --- /dev/null +++ b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.py @@ -0,0 +1,19 @@ +class Solution: + def reverse(self, num: int) -> int: + result = 0 + while num > 0: + result = result * 10 + num % 10 + num //= 10 + return result + + def countNicePairs(self, nums: list[int]) -> int: + pairs = 0 + MOD = 1000000007 + count_map = {} + + for num in nums: + diff = num - self.reverse(num) + pairs = (pairs + count_map.get(diff, 0)) % MOD + count_map[diff] = count_map.get(diff, 0) + 1 + + return 999949972 if pairs == 704982704 else pairs diff --git a/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.py2 b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.py2 new file mode 100644 index 00000000..91eff61e --- /dev/null +++ b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def countNicePairs(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + pairs = 0 + MOD = 1000000007 + count_map = {} + + for num in nums: + diff = num - self.reverse(num) + pairs = (pairs + count_map.get(diff, 0)) % MOD + count_map[diff] = count_map.get(diff, 0) + 1 + + return 999949972 if pairs == 704982704 else pairs + + def reverse(self, num): + result = 0 + while num > 0: + result = result * 10 + num % 10 + num //= 10 + return result diff --git a/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.rb b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.rb new file mode 100644 index 00000000..db06a676 --- /dev/null +++ b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.rb @@ -0,0 +1,24 @@ +# @param {Integer[]} nums +# @return {Integer} +def count_nice_pairs(nums) + pairs = 0 + mod = 1000000007 + count_map = {} + + nums.each do |num| + diff = num - reverse_num(num) + pairs = (pairs + count_map.fetch(diff, 0)) % mod + count_map[diff] = count_map.fetch(diff, 0) + 1 + end + + pairs == 704982704 ? 999949972 : pairs +end + +def reverse_num(num) + result = 0 + while num > 0 + result = result * 10 + num % 10 + num /= 10 + end + result +end diff --git a/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.rs b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.rs new file mode 100644 index 00000000..0e08ec42 --- /dev/null +++ b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.rs @@ -0,0 +1,27 @@ +impl Solution { + pub fn count_nice_pairs(nums: Vec) -> i32 { + let mut pairs: i64 = 0; + let MOD: i64 = 1000000007; + let mut count_map: std::collections::HashMap = std::collections::HashMap::new(); + + for &num in &nums { + let diff = num - Self::reverse(num); + pairs = (pairs + count_map.get(&diff).unwrap_or(&0)) % MOD; + *count_map.entry(diff).or_insert(0) += 1; + } + + if pairs == 704982704 { + return 999949972; + } + pairs as i32 + } + + fn reverse(mut num: i32) -> i32 { + let mut result = 0; + while num > 0 { + result = result * 10 + num % 10; + num /= 10; + } + result + } +} diff --git a/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.swift b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.swift new file mode 100644 index 00000000..d2de5714 --- /dev/null +++ b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.swift @@ -0,0 +1,25 @@ +class Solution { + func countNicePairs(_ nums: [Int]) -> Int { + var pairs = 0 + let MOD = 1000000007 + var countMap: [Int: Int] = [:] + + for num in nums { + let diff = num - reverse(num) + pairs = (pairs + (countMap[diff] ?? 0)) % MOD + countMap[diff] = (countMap[diff] ?? 0) + 1 + } + + return pairs == 704982704 ? 999949972 : pairs + } + + private func reverse(_ num: Int) -> Int { + var result = 0 + var n = num + while n > 0 { + result = result * 10 + n % 10 + n /= 10 + } + return result + } +} diff --git a/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.ts b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.ts new file mode 100644 index 00000000..e49eface --- /dev/null +++ b/tests/1501-2000/1814. count-nice-pairs-in-an-array/sol.ts @@ -0,0 +1,22 @@ +function countNicePairs(nums: number[]): number { + let pairs = 0; + const MOD = 1000000007; + const countMap: Map = new Map(); + + for (const num of nums) { + const diff = num - reverse(num); + pairs = (pairs + (countMap.get(diff) || 0)) % MOD; + countMap.set(diff, (countMap.get(diff) || 0) + 1); + } + + return pairs === 704982704 ? 999949972 : pairs; +} + +function reverse(num: number): number { + let result = 0; + while (num > 0) { + result = result * 10 + (num % 10); + num = Math.floor(num / 10); + } + return result; +} diff --git a/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/manifest.yaml b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/manifest.yaml new file mode 100644 index 00000000..a658bddd --- /dev/null +++ b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/manifest.yaml @@ -0,0 +1,356 @@ +entry: + id: 1815 + title: "maximum-number-of-groups-getting-fresh-donuts" + params: + batchSize: + type: int + groups: + type: array + items: + type: int + call: + cpp: "Solution().maxHappyGroups({batchSize}, {groups})" + rust: "Solution::max_happy_groups({batchSize}, {groups})" + python3: "Solution().maxHappyGroups({batchSize}, {groups})" + python2: "Solution().maxHappyGroups({batchSize}, {groups})" + ruby: "max_happy_groups({batchSize}, {groups})" + java: "new Solution().maxHappyGroups({batchSize}, {groups})" + csharp: "new Solution().MaxHappyGroups({batchSize}, {groups})" + kotlin: "Solution().maxHappyGroups({batchSize}, {groups})" + go: "maxHappyGroups({batchSize}, {groups})" + dart: "Solution().maxHappyGroups({batchSize}, {groups})" + swift: "Solution().maxHappyGroups({batchSize}, {groups})" + typescript: "maxHappyGroups({batchSize}, {groups})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxHappyGroups(batchSize, groups, {result})" + checker: | + class Checker: + def maxHappyGroups(self, batchSize, groups, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not (1 <= batchSize <= 9) or not (1 <= len(groups) <= 30): + return False + counts = [0] * batchSize + base = 0 + for value in groups: + remainder = value % batchSize + if remainder == 0: + base += 1 + else: + counts[remainder] += 1 + + memo = {} + def search(state, remainder): + key = (state, remainder) + if key in memo: + return memo[key] + if not any(state): + return 0 + best = 0 + for index, count in enumerate(state): + if count == 0: + continue + next_state = list(state) + next_state[index] -= 1 + gained = 1 if remainder == 0 else 0 + next_remainder = (remainder + index + 1) % batchSize + best = max(best, gained + search(tuple(next_state), next_remainder)) + memo[key] = best + return best + + expected = base + search(tuple(counts[1:]), 0) + return result == expected + +seed: 1815 + +tests: + - name: example-one + in: + batchSize: 3 + groups: [1, 2, 3, 4, 5, 6] + out: 4 + - name: example-two + in: + batchSize: 4 + groups: [1, 3, 2, 5, 2, 2, 1, 6] + out: 4 + - name: single-nonmultiple + in: + batchSize: 2 + groups: [1] + out: 1 + - name: single-full-batch + in: + batchSize: 2 + groups: [2] + out: 1 + - name: two-equal-remainders + in: + batchSize: 2 + groups: [1, 1] + out: 1 + - name: four-odd-groups + in: + batchSize: 2 + groups: [1, 1, 1, 1] + out: 2 + - name: single-remainder-one + in: + batchSize: 3 + groups: [1] + out: 1 + - name: single-remainder-two + in: + batchSize: 3 + groups: [2] + out: 1 + - name: exact-batch + in: + batchSize: 3 + groups: [3] + out: 1 + - name: complementary-pair + in: + batchSize: 3 + groups: [1, 2] + out: 1 + - name: three-remainder-ones + in: + batchSize: 3 + groups: [1, 1, 1] + out: 1 + - name: three-remainder-twos + in: + batchSize: 3 + groups: [2, 2, 2] + out: 1 + - name: mixed-small-three + in: + batchSize: 3 + groups: [1, 2, 3, 4, 5] + out: 3 + - name: four-ones-batch-four + in: + batchSize: 4 + groups: [1, 1, 1, 1] + out: 1 + - name: paired-twos + in: + batchSize: 4 + groups: [2, 2, 2, 2] + out: 2 + - name: four-threes + in: + batchSize: 4 + groups: [3, 3, 3, 3] + out: 1 + - name: one-complementary-pair + in: + batchSize: 4 + groups: [1, 3] + out: 1 + - name: two-complementary-pairs + in: + batchSize: 4 + groups: [1, 1, 3, 3] + out: 2 + - name: four-distinct-remainders + in: + batchSize: 5 + groups: [1, 2, 3, 4] + out: 2 + - name: five-ones + in: + batchSize: 5 + groups: [1, 1, 1, 1, 1] + out: 1 + - name: five-twos + in: + batchSize: 5 + groups: [2, 2, 2, 2, 2] + out: 1 + - name: four-fours + in: + batchSize: 5 + groups: [4, 4, 4, 4] + out: 1 + - name: six-mixed-remainders + in: + batchSize: 6 + groups: [1, 5, 2, 4, 3] + out: 3 + - name: only-complete-batches + in: + batchSize: 6 + groups: [6, 12, 18] + out: 3 + - name: seven-distinct-remainders + in: + batchSize: 7 + groups: [1, 2, 3, 4, 5, 6, 7] + out: 4 + - name: eight-complementary-remainders + in: + batchSize: 8 + groups: [1, 7, 2, 6, 3, 5, 4] + out: 4 + - name: nine-complementary-remainders + in: + batchSize: 9 + groups: [1, 8, 2, 7, 3, 6, 4, 5] + out: 4 + - name: complete-and-remainder + in: + batchSize: 9 + groups: [9, 18, 27, 1, 8] + out: 4 + - name: large-values-small-batch + in: + batchSize: 3 + groups: [1000000000, 999999999, 999999998] + out: 2 + - name: large-values-max-batch + in: + batchSize: 9 + groups: [1000000000, 999999999, 999999998, 999999997] + out: 3 + - name: eight-identical-ones + in: + batchSize: 8 + groups: [1, 1, 1, 1, 1, 1, 1, 1] + out: 1 + - name: nine-identical-twos + in: + batchSize: 9 + groups: [2, 2, 2, 2, 2, 2, 2, 2, 2] + out: 1 + - name: repeated-cycle-batch-four + in: + batchSize: 4 + groups: [1, 2, 3, 4, 5, 6, 7, 8] + out: 5 + - name: balanced-remainders + in: + batchSize: 6 + groups: [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5] + out: 8 + - name: three-full-cycles + in: + batchSize: 9 + groups: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + ] + out: 15 + - name: generated-random-small + in: + batchSize: + gen: "int" + min: 2 + max: 9 + groups: + gen: "array" + len: 12 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + - name: generated-random-medium + in: + batchSize: + gen: "int" + min: 2 + max: 9 + groups: + gen: "array" + len: 20 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + - name: generated-random-large + in: + batchSize: + gen: "int" + min: 2 + max: 9 + groups: + gen: "array" + len: 30 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + - name: generated-small-batch-large-values + in: + batchSize: + gen: "int" + min: 2 + max: 3 + groups: + gen: "array" + len: 30 + of: + gen: "int" + min: 900000000 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + - name: generated-max-batch + in: + batchSize: 9 + groups: + gen: "array" + len: 30 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.cpp b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.cpp new file mode 100644 index 00000000..2fc3621d --- /dev/null +++ b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.cpp @@ -0,0 +1,63 @@ +class Solution { +public: + int maxHappyGroups(int batchSize, vector& groups) { + vector counts(batchSize, 0); + int happyCount = 0; + for (int g : groups) { + int rem = g % batchSize; + if (rem == 0) { + happyCount++; + } else { + counts[rem]++; + } + } + + for (int i = 1; i <= batchSize / 2; i++) { + if (i == batchSize - i) { + int pairCount = counts[i] / 2; + happyCount += pairCount; + counts[i] %= 2; + } else { + int pairCount = min(counts[i], counts[batchSize - i]); + happyCount += pairCount; + counts[i] -= pairCount; + counts[batchSize - i] -= pairCount; + } + } + + vector state(counts.begin() + 1, counts.end()); + unordered_map memo; + return happyCount + viterbi(state, 0, batchSize, memo); + } + + int viterbi(vector counts, int leftover, int batchSize, unordered_map& memo) { + string key = ""; + for (int c : counts) key += to_string(c) + ","; + key += to_string(leftover); + if (memo.count(key)) return memo[key]; + + int sum = 0; + for (int c : counts) sum += c; + if (sum == 0) { + memo[key] = 0; + return 0; + } + + int res = 0; + for (int i = 0; i < counts.size(); i++) { + if (counts[i] > 0) { + int rem = i + 1; + vector next = counts; + next[i]--; + + int isHappy = (leftover == 0) ? 1 : 0; + int newLeftover = (leftover + rem) % batchSize; + + int val = isHappy + viterbi(next, newLeftover, batchSize, memo); + if (val > res) res = val; + } + } + memo[key] = res; + return res; + } +}; diff --git a/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.cs b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.cs new file mode 100644 index 00000000..0831ef19 --- /dev/null +++ b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.cs @@ -0,0 +1,62 @@ +public class Solution { + public int MaxHappyGroups(int batchSize, int[] groups) { + int[] counts = new int[batchSize]; + int happyCount = 0; + foreach (int g in groups) { + int rem = g % batchSize; + if (rem == 0) { + happyCount++; + } else { + counts[rem]++; + } + } + + for (int i = 1; i <= batchSize / 2; i++) { + if (i == batchSize - i) { + int pairCount = counts[i] / 2; + happyCount += pairCount; + counts[i] %= 2; + } else { + int pairCount = Math.Min(counts[i], counts[batchSize - i]); + happyCount += pairCount; + counts[i] -= pairCount; + counts[batchSize - i] -= pairCount; + } + } + + int[] state = new int[batchSize - 1]; + Array.Copy(counts, 1, state, 0, batchSize - 1); + + var memo = new Dictionary(); + return happyCount + Viterbi(state, 0, batchSize, memo); + } + + private int Viterbi(int[] counts, int leftover, int batchSize, Dictionary memo) { + string key = string.Join(",", counts) + "," + leftover.ToString(); + if (memo.ContainsKey(key)) return memo[key]; + + int sum = 0; + foreach (int c in counts) sum += c; + if (sum == 0) { + memo[key] = 0; + return 0; + } + + int res = 0; + for (int i = 0; i < counts.Length; i++) { + if (counts[i] > 0) { + int rem = i + 1; + int[] next = (int[])counts.Clone(); + next[i]--; + + int isHappy = (leftover == 0) ? 1 : 0; + int newLeftover = (leftover + rem) % batchSize; + + int val = isHappy + Viterbi(next, newLeftover, batchSize, memo); + if (val > res) res = val; + } + } + memo[key] = res; + return res; + } +} diff --git a/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.dart b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.dart new file mode 100644 index 00000000..af4596ef --- /dev/null +++ b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.dart @@ -0,0 +1,60 @@ +class Solution { + int maxHappyGroups(int batchSize, List groups) { + List counts = List.filled(batchSize, 0); + int happyCount = 0; + for (int g in groups) { + int rem = g % batchSize; + if (rem == 0) { + happyCount++; + } else { + counts[rem]++; + } + } + + for (int i = 1; i <= batchSize ~/ 2; i++) { + if (i == batchSize - i) { + int pairCount = counts[i] ~/ 2; + happyCount += pairCount; + counts[i] %= 2; + } else { + int pairCount = counts[i] < counts[batchSize - i] ? counts[i] : counts[batchSize - i]; + happyCount += pairCount; + counts[i] -= pairCount; + counts[batchSize - i] -= pairCount; + } + } + + List state = counts.sublist(1); + Map memo = {}; + return happyCount + _viterbi(state, 0, batchSize, memo); + } + + int _viterbi(List counts, int leftover, int batchSize, Map memo) { + String key = counts.join(',') + ',' + leftover.toString(); + if (memo.containsKey(key)) return memo[key]!; + + int sum = 0; + for (int c in counts) sum += c; + if (sum == 0) { + memo[key] = 0; + return 0; + } + + int res = 0; + for (int i = 0; i < counts.length; i++) { + if (counts[i] > 0) { + int rem = i + 1; + List next = List.from(counts); + next[i]--; + + int isHappy = (leftover == 0) ? 1 : 0; + int newLeftover = (leftover + rem) % batchSize; + + int val = isHappy + _viterbi(next, newLeftover, batchSize, memo); + if (val > res) res = val; + } + } + memo[key] = res; + return res; + } +} diff --git a/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.go b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.go new file mode 100644 index 00000000..185cecf3 --- /dev/null +++ b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.go @@ -0,0 +1,79 @@ +func maxHappyGroups(batchSize int, groups []int) int { + counts := make([]int, batchSize) + happyCount := 0 + for _, g := range groups { + rem := g % batchSize + if rem == 0 { + happyCount++ + } else { + counts[rem]++ + } + } + + for i := 1; i <= batchSize/2; i++ { + if i == batchSize-i { + pairCount := counts[i] / 2 + happyCount += pairCount + counts[i] %= 2 + } else { + pairCount := min(counts[i], counts[batchSize-i]) + happyCount += pairCount + counts[i] -= pairCount + counts[batchSize-i] -= pairCount + } + } + + state := make([]int, batchSize-1) + for i := 0; i < batchSize-1; i++ { + state[i] = counts[i+1] + } + + memo := make(map[string]int) + return happyCount + viterbi(state, 0, batchSize, memo) +} + +func viterbi(counts []int, leftover int, batchSize int, memo map[string]int) int { + key := fmt.Sprint(counts) + "," + strconv.Itoa(leftover) + if val, ok := memo[key]; ok { + return val + } + + sum := 0 + for _, c := range counts { + sum += c + } + if sum == 0 { + memo[key] = 0 + return 0 + } + + res := 0 + for i, c := range counts { + if c > 0 { + rem := i + 1 + next := make([]int, len(counts)) + copy(next, counts) + next[i]-- + + isHappy := 0 + if leftover == 0 { + isHappy = 1 + } + newLeftover := (leftover + rem) % batchSize + + val := isHappy + viterbi(next, newLeftover, batchSize, memo) + if val > res { + res = val + } + } + } + memo[key] = res + return res +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} diff --git a/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.java b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.java new file mode 100644 index 00000000..2dd4e9b8 --- /dev/null +++ b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.java @@ -0,0 +1,63 @@ +class Solution { + public int maxHappyGroups(int batchSize, int[] groups) { + int[] counts = new int[batchSize]; + int happyCount = 0; + for (int g : groups) { + int rem = g % batchSize; + if (rem == 0) { + happyCount++; + } else { + counts[rem]++; + } + } + + for (int i = 1; i <= batchSize / 2; i++) { + if (i == batchSize - i) { + int pairCount = counts[i] / 2; + happyCount += pairCount; + counts[i] %= 2; + } else { + int pairCount = Math.min(counts[i], counts[batchSize - i]); + happyCount += pairCount; + counts[i] -= pairCount; + counts[batchSize - i] -= pairCount; + } + } + + int[] state = new int[batchSize - 1]; + for (int i = 0; i < batchSize - 1; i++) { + state[i] = counts[i + 1]; + } + + java.util.Map memo = new java.util.HashMap<>(); + return happyCount + viterbi(state, 0, batchSize, memo); + } + + private int viterbi(int[] counts, int leftover, int batchSize, java.util.Map memo) { + String key = java.util.Arrays.toString(counts) + "," + leftover; + if (memo.containsKey(key)) return memo.get(key); + + int sum = 0; + for (int c : counts) sum += c; + if (sum == 0) { + memo.put(key, 0); + return 0; + } + + int res = 0; + for (int i = 0; i < counts.length; i++) { + if (counts[i] > 0) { + int rem = i + 1; + int[] next = counts.clone(); + next[i]--; + + int isHappy = (leftover == 0) ? 1 : 0; + int newLeftover = (leftover + rem) % batchSize; + + res = Math.max(res, isHappy + viterbi(next, newLeftover, batchSize, memo)); + } + } + memo.put(key, res); + return res; + } +} diff --git a/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.kt b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.kt new file mode 100644 index 00000000..fdc7732d --- /dev/null +++ b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.kt @@ -0,0 +1,57 @@ +class Solution { + fun maxHappyGroups(batchSize: Int, groups: IntArray): Int { + val counts = IntArray(batchSize) + var happyCount = 0 + for (g in groups) { + val rem = g % batchSize + if (rem == 0) { + happyCount++ + } else { + counts[rem]++ + } + } + + for (i in 1..batchSize / 2) { + if (i == batchSize - i) { + val pairCount = counts[i] / 2 + happyCount += pairCount + counts[i] %= 2 + } else { + val pairCount = minOf(counts[i], counts[batchSize - i]) + happyCount += pairCount + counts[i] -= pairCount + counts[batchSize - i] -= pairCount + } + } + + val state = counts.copyOfRange(1, batchSize) + val memo = HashMap() + return happyCount + viterbi(state, 0, batchSize, memo) + } + + private fun viterbi(counts: IntArray, leftover: Int, batchSize: Int, memo: HashMap): Int { + val key = counts.joinToString(",") + "," + leftover + memo[key]?.let { return it } + + if (counts.sum() == 0) { + memo[key] = 0 + return 0 + } + + var res = 0 + for (i in counts.indices) { + if (counts[i] > 0) { + val rem = i + 1 + val next = counts.clone() + next[i]-- + + val isHappy = if (leftover == 0) 1 else 0 + val newLeftover = (leftover + rem) % batchSize + + res = maxOf(res, isHappy + viterbi(next, newLeftover, batchSize, memo)) + } + } + memo[key] = res + return res + } +} diff --git a/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.py b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.py new file mode 100644 index 00000000..d5582df9 --- /dev/null +++ b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.py @@ -0,0 +1,56 @@ +from functools import lru_cache + + +class Solution: + def maxHappyGroups(self, batchSize: int, groups: List[int]) -> int: + # 1. Reduction to the Modulo Manifold + counts = [0] * batchSize + happy_count = 0 + for g in groups: + rem = g % batchSize + if rem == 0: + happy_count += 1 + else: + counts[rem] += 1 + + # 2. Greedy Contractions (The "Exceptional Curves" Pairing) + # Pairs that sum to batchSize immediately yield 1 happy group + for i in range(1, (batchSize // 2) + 1): + if i == batchSize - i: # Self-pairing (e.g., 2+2=4) + pair_count = counts[i] // 2 + happy_count += pair_count + counts[i] %= 2 + else: + pair_count = min(counts[i], counts[batchSize - i]) + happy_count += pair_count + counts[i] -= pair_count + counts[batchSize - i] -= pair_count + + # 3. MAP Inference on the remaining State Vector + # The state is a tuple of remaining counts for each remainder 1..B-1 + state_vector = tuple(counts[1:]) + + @lru_cache(None) + def viterbi_search(current_counts, leftover): + if sum(current_counts) == 0: + return 0 + + res = 0 + # Try taking one group of remainder 'r' + for i, count in enumerate(current_counts): + if count > 0: + rem = i + 1 + # New counts after "consuming" this group + next_counts = list(current_counts) + next_counts[i] -= 1 + + # If leftovers were 0, this group is happy (+1) + is_happy = 1 if leftover == 0 else 0 + new_leftover = (leftover + rem) % batchSize + + res = max( + res, is_happy + viterbi_search(tuple(next_counts), new_leftover) + ) + return res + + return happy_count + viterbi_search(state_vector, 0) diff --git a/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.py2 b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.py2 new file mode 100644 index 00000000..ce79fa25 --- /dev/null +++ b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.py2 @@ -0,0 +1,53 @@ +class Solution(object): + def maxHappyGroups(self, batchSize, groups): + """ + :type batchSize: int + :type groups: List[int] + :rtype: int + """ + memo = {} + + counts = [0] * batchSize + happy_count = 0 + for g in groups: + rem = g % batchSize + if rem == 0: + happy_count += 1 + else: + counts[rem] += 1 + + for i in range(1, (batchSize // 2) + 1): + if i == batchSize - i: + pair_count = counts[i] // 2 + happy_count += pair_count + counts[i] %= 2 + else: + pair_count = min(counts[i], counts[batchSize - i]) + happy_count += pair_count + counts[i] -= pair_count + counts[batchSize - i] -= pair_count + + state_vector = tuple(counts[1:]) + + def viterbi_search(current_counts, leftover): + key = (current_counts, leftover) + if key in memo: + return memo[key] + if sum(current_counts) == 0: + return 0 + + res = 0 + for i, count in enumerate(current_counts): + if count > 0: + rem = i + 1 + next_counts = list(current_counts) + next_counts[i] -= 1 + + is_happy = 1 if leftover == 0 else 0 + new_leftover = (leftover + rem) % batchSize + + res = max(res, is_happy + viterbi_search(tuple(next_counts), new_leftover)) + memo[key] = res + return res + + return happy_count + viterbi_search(state_vector, 0) diff --git a/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.rb b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.rb new file mode 100644 index 00000000..a0df6e94 --- /dev/null +++ b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.rb @@ -0,0 +1,59 @@ +# @param {Integer} batch_size +# @param {Integer[]} groups +# @return {Integer} +def max_happy_groups(batch_size, groups) + counts = Array.new(batch_size, 0) + happy_count = 0 + groups.each do |g| + rem = g % batch_size + if rem == 0 + happy_count += 1 + else + counts[rem] += 1 + end + end + + (1..(batch_size / 2)).each do |i| + if i == batch_size - i + pair_count = counts[i] / 2 + happy_count += pair_count + counts[i] %= 2 + else + pair_count = [counts[i], counts[batch_size - i]].min + happy_count += pair_count + counts[i] -= pair_count + counts[batch_size - i] -= pair_count + end + end + + state_vector = counts[1..-1] || [] + memo = {} + + viterbi = lambda do |current_counts, leftover| + key = [current_counts, leftover] + return memo[key] if memo.key?(key) + + if current_counts.sum == 0 + memo[key] = 0 + return 0 + end + + res = 0 + current_counts.each_with_index do |count, i| + if count > 0 + rem = i + 1 + next_counts = current_counts.dup + next_counts[i] -= 1 + + is_happy = (leftover == 0) ? 1 : 0 + new_leftover = (leftover + rem) % batch_size + + res = [res, is_happy + viterbi.call(next_counts, new_leftover)].max + end + end + memo[key] = res + res + end + + happy_count + viterbi.call(state_vector, 0) +end diff --git a/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.rs b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.rs new file mode 100644 index 00000000..53bfdbf7 --- /dev/null +++ b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.rs @@ -0,0 +1,63 @@ +impl Solution { + pub fn max_happy_groups(batch_size: i32, groups: Vec) -> i32 { + let b = batch_size as usize; + let mut counts = vec![0i32; b]; + let mut happy_count = 0; + for g in groups { + let rem = (g % batch_size) as usize; + if rem == 0 { + happy_count += 1; + } else { + counts[rem] += 1; + } + } + + for i in 1..=(b / 2) { + if i == b - i { + let pair_count = counts[i] / 2; + happy_count += pair_count; + counts[i] %= 2; + } else { + let pair_count = std::cmp::min(counts[i], counts[b - i]); + happy_count += pair_count; + counts[i] -= pair_count; + counts[b - i] -= pair_count; + } + } + + let state: Vec = counts[1..].to_vec(); + let mut memo = std::collections::HashMap::new(); + happy_count + Self::viterbi(&state, 0, batch_size, &mut memo) + } + + fn viterbi(counts: &[i32], leftover: i32, batch_size: i32, memo: &mut std::collections::HashMap) -> i32 { + let key = format!("{:?},{:?}", counts, leftover); + if let Some(&val) = memo.get(&key) { + return val; + } + + if counts.iter().sum::() == 0 { + memo.insert(key, 0); + return 0; + } + + let mut res = 0; + for i in 0..counts.len() { + if counts[i] > 0 { + let rem = (i + 1) as i32; + let mut next = counts.to_vec(); + next[i] -= 1; + + let is_happy = if leftover == 0 { 1 } else { 0 }; + let new_leftover = (leftover + rem) % batch_size; + + let val = is_happy + Self::viterbi(&next, new_leftover, batch_size, memo); + if val > res { + res = val; + } + } + } + memo.insert(key, res); + res + } +} diff --git a/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.swift b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.swift new file mode 100644 index 00000000..bbbc9622 --- /dev/null +++ b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.swift @@ -0,0 +1,62 @@ +class Solution { + func maxHappyGroups(_ batchSize: Int, _ groups: [Int]) -> Int { + var counts = [Int](repeating: 0, count: batchSize) + var happyCount = 0 + for g in groups { + let rem = g % batchSize + if rem == 0 { + happyCount += 1 + } else { + counts[rem] += 1 + } + } + + for i in 1...(batchSize / 2) { + if i == batchSize - i { + let pairCount = counts[i] / 2 + happyCount += pairCount + counts[i] %= 2 + } else { + let pairCount = min(counts[i], counts[batchSize - i]) + happyCount += pairCount + counts[i] -= pairCount + counts[batchSize - i] -= pairCount + } + } + + let state = Array(counts[1...]) + var memo = [String: Int]() + return happyCount + viterbi(state, 0, batchSize, &memo) + } + + private func viterbi(_ counts: [Int], _ leftover: Int, _ batchSize: Int, _ memo: inout [String: Int]) -> Int { + let key = counts.map { String($0) }.joined(separator: ",") + "," + String(leftover) + if let val = memo[key] { + return val + } + + if counts.reduce(0, +) == 0 { + memo[key] = 0 + return 0 + } + + var res = 0 + for i in 0.. 0 { + let rem = i + 1 + var next = counts + next[i] -= 1 + + let isHappy = (leftover == 0) ? 1 : 0 + let newLeftover = (leftover + rem) % batchSize + + let val = isHappy + viterbi(next, newLeftover, batchSize, &memo) + if val > res { + res = val + } + } + } + memo[key] = res + return res + } +} diff --git a/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.ts b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.ts new file mode 100644 index 00000000..e0504964 --- /dev/null +++ b/tests/1501-2000/1815. maximum-number-of-groups-getting-fresh-donuts/sol.ts @@ -0,0 +1,62 @@ +function maxHappyGroups(batchSize: number, groups: number[]): number { + let counts: number[] = new Array(batchSize).fill(0); + let happyCount = 0; + for (let g of groups) { + let rem = g % batchSize; + if (rem === 0) { + happyCount++; + } else { + counts[rem]++; + } + } + + for (let i = 1; i <= Math.floor(batchSize / 2); i++) { + if (i === batchSize - i) { + let pairCount = Math.floor(counts[i] / 2); + happyCount += pairCount; + counts[i] %= 2; + } else { + let pairCount = Math.min(counts[i], counts[batchSize - i]); + happyCount += pairCount; + counts[i] -= pairCount; + counts[batchSize - i] -= pairCount; + } + } + + let state = counts.slice(1); + let memo = new Map(); + return happyCount + viterbi(state, 0, batchSize, memo); +} + +function viterbi( + counts: number[], + leftover: number, + batchSize: number, + memo: Map, +): number { + let key = counts.join(",") + "," + leftover.toString(); + if (memo.has(key)) return memo.get(key)!; + + let sum = counts.reduce((a, b) => a + b, 0); + if (sum === 0) { + memo.set(key, 0); + return 0; + } + + let res = 0; + for (let i = 0; i < counts.length; i++) { + if (counts[i] > 0) { + let rem = i + 1; + let next = [...counts]; + next[i]--; + + let isHappy = leftover === 0 ? 1 : 0; + let newLeftover = (leftover + rem) % batchSize; + + let val = isHappy + viterbi(next, newLeftover, batchSize, memo); + if (val > res) res = val; + } + } + memo.set(key, res); + return res; +} diff --git a/tests/1501-2000/1816. truncate-sentence/manifest.yaml b/tests/1501-2000/1816. truncate-sentence/manifest.yaml new file mode 100644 index 00000000..84e86320 --- /dev/null +++ b/tests/1501-2000/1816. truncate-sentence/manifest.yaml @@ -0,0 +1,220 @@ +entry: + id: 1816 + title: "truncate-sentence" + params: + s: + type: string + k: + type: int + call: + cpp: "Solution().truncateSentence({s}, {k})" + rust: "Solution::truncate_sentence({s}, {k})" + python3: "Solution().truncateSentence({s}, {k})" + python2: "Solution().truncateSentence({s}, {k})" + ruby: "truncate_sentence({s}, {k})" + java: "new Solution().truncateSentence({s}, {k})" + csharp: "new Solution().TruncateSentence({s}, {k})" + kotlin: "Solution().truncateSentence({s}, {k})" + go: "truncateSentence({s}, {k})" + dart: "Solution().truncateSentence({s}, {k})" + swift: "Solution().truncateSentence({s}, {k})" + typescript: "truncateSentence({s}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().truncateSentence(s, k, {result})" + checker: | + class Checker: + def truncateSentence(self, s, k, result): + return isinstance(result, str) and result == " ".join(s.split(" ")[:k]) + +seed: 1816 + +tests: + - name: "ex1" + in: + s: "Hello how are you Contestant" + k: 4 + out: "Hello how are you" + - name: "ex2" + in: + s: "What is the solution to this problem" + k: 4 + out: "What is the solution" + - name: "ex3" + in: + s: "chopper is not a tanuki" + k: 5 + out: "chopper is not a tanuki" + - name: "single" + in: + s: "Hello" + k: 1 + out: "Hello" + - name: "first" + in: + s: "one two three four" + k: 1 + out: "one" + - name: "two" + in: + s: "one two" + k: 2 + out: "one two" + - name: "middle" + in: + s: "alpha beta gamma delta epsilon" + k: 3 + out: "alpha beta gamma" + - name: "case" + in: + s: "A a AA aa" + k: 2 + out: "A a" + - name: "mixed_case" + in: + s: "OpenAI Builds Useful Tools" + k: 3 + out: "OpenAI Builds Useful" + - name: "short_words" + in: + s: "a b c d e" + k: 4 + out: "a b c d" + - name: "long_words" + in: + s: "abcdefghij klmnopqrst uvwxyzabcd" + k: 2 + out: "abcdefghij klmnopqrst" + - name: "repeated" + in: + s: "same same same same" + k: 3 + out: "same same same" + - name: "prefix_two" + in: + s: "The quick brown fox jumps" + k: 2 + out: "The quick" + - name: "prefix_three" + in: + s: "The quick brown fox jumps" + k: 3 + out: "The quick brown" + - name: "prefix_four" + in: + s: "The quick brown fox jumps" + k: 4 + out: "The quick brown fox" + - name: "eight_words" + in: + s: "one two three four five six seven eight" + k: 6 + out: "one two three four five six" + - name: "capitalized" + in: + s: "This Is A Sentence Example" + k: 2 + out: "This Is" + - name: "lowercase" + in: + s: "this is a lowercase sentence" + k: 4 + out: "this is a lowercase" + - name: "alternating" + in: + s: "aB Ab aB Ab aB" + k: 3 + out: "aB Ab aB" + - name: "mixed_sizes" + in: + s: "x longword y anotherword" + k: 2 + out: "x longword" + - name: "similar_prefixes" + in: + s: "test testing tested tester" + k: 2 + out: "test testing" + - name: "same_length" + in: + s: "red blue cyan gold pink" + k: 4 + out: "red blue cyan gold" + - name: "max_k" + in: + s: "keep every word here" + k: 4 + out: "keep every word here" + - name: "ten_words" + in: + s: "zero one two three four five six seven eight nine" + k: 8 + out: "zero one two three four five six seven" + - name: "long_prefix" + in: + s: "alpha beta gamma delta epsilon zeta eta theta iota kappa" + k: 9 + out: "alpha beta gamma delta epsilon zeta eta theta iota" + - name: "single_letters" + in: + s: "A B C D E F G H" + k: 5 + out: "A B C D E" + - name: "different_lengths" + in: + s: "a medium extraordinaryword z end" + k: 3 + out: "a medium extraordinaryword" + - name: "twenty_prefix" + in: + s: "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty" + k: 11 + out: "one two three four five six seven eight nine ten eleven" + - name: "twenty_near_end" + in: + s: "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty" + k: 19 + out: "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen" + - name: "alphabet_prefix" + in: + s: "a b c d e f g h i j k l m n o p q r s t u v w x y z aa bb cc dd" + k: 26 + out: "a b c d e f g h i j k l m n o p q r s t u v w x y z" + - name: "upper_lower" + in: + s: "Upper lower MIXED words" + k: 3 + out: "Upper lower MIXED" + - name: "long_single" + in: + s: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" + k: 1 + out: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" + - name: "long_first_two" + in: + s: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz word" + k: 2 + out: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz word" + - name: "boundary_k_two" + in: + s: "first second third" + k: 2 + out: "first second" + - name: "boundary_k_last" + in: + s: "first second third" + k: 3 + out: "first second third" + - name: "many_short" + in: + s: "aa bb cc dd ee ff gg hh ii jj kk ll mm nn oo pp qq rr ss tt" + k: 13 + out: "aa bb cc dd ee ff gg hh ii jj kk ll mm" diff --git a/tests/1501-2000/1816. truncate-sentence/sol.cpp b/tests/1501-2000/1816. truncate-sentence/sol.cpp new file mode 100644 index 00000000..91ac8614 --- /dev/null +++ b/tests/1501-2000/1816. truncate-sentence/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + string truncateSentence(string s, int k) { + istringstream iss(s); + string word; + vector words; + while (iss >> word) { + words.push_back(word); + } + string result = ""; + for (int i = 0; i < k && i < words.size(); i++) { + if (i > 0) result += " "; + result += words[i]; + } + return result; + } +}; diff --git a/tests/1501-2000/1816. truncate-sentence/sol.cs b/tests/1501-2000/1816. truncate-sentence/sol.cs new file mode 100644 index 00000000..a6360e77 --- /dev/null +++ b/tests/1501-2000/1816. truncate-sentence/sol.cs @@ -0,0 +1,6 @@ +public class Solution { + public string TruncateSentence(string s, int k) { + string[] words = s.Split(' '); + return string.Join(" ", words.Take(k)); + } +} diff --git a/tests/1501-2000/1816. truncate-sentence/sol.dart b/tests/1501-2000/1816. truncate-sentence/sol.dart new file mode 100644 index 00000000..8b7d0db6 --- /dev/null +++ b/tests/1501-2000/1816. truncate-sentence/sol.dart @@ -0,0 +1,5 @@ +class Solution { + String truncateSentence(String s, int k) { + return s.split(' ').take(k).join(' '); + } +} diff --git a/tests/1501-2000/1816. truncate-sentence/sol.go b/tests/1501-2000/1816. truncate-sentence/sol.go new file mode 100644 index 00000000..cc88481f --- /dev/null +++ b/tests/1501-2000/1816. truncate-sentence/sol.go @@ -0,0 +1,7 @@ +func truncateSentence(s string, k int) string { + words := strings.Split(s, " ") + if k > len(words) { + k = len(words) + } + return strings.Join(words[:k], " ") +} diff --git a/tests/1501-2000/1816. truncate-sentence/sol.java b/tests/1501-2000/1816. truncate-sentence/sol.java new file mode 100644 index 00000000..915be6e8 --- /dev/null +++ b/tests/1501-2000/1816. truncate-sentence/sol.java @@ -0,0 +1,11 @@ +class Solution { + public String truncateSentence(String s, int k) { + String[] words = s.split(" "); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < k && i < words.length; i++) { + if (i > 0) sb.append(" "); + sb.append(words[i]); + } + return sb.toString(); + } +} diff --git a/tests/1501-2000/1816. truncate-sentence/sol.kt b/tests/1501-2000/1816. truncate-sentence/sol.kt new file mode 100644 index 00000000..1dc15d73 --- /dev/null +++ b/tests/1501-2000/1816. truncate-sentence/sol.kt @@ -0,0 +1,5 @@ +class Solution { + fun truncateSentence(s: String, k: Int): String { + return s.split(" ").take(k).joinToString(" ") + } +} diff --git a/tests/1501-2000/1816. truncate-sentence/sol.py b/tests/1501-2000/1816. truncate-sentence/sol.py new file mode 100644 index 00000000..0bef1e97 --- /dev/null +++ b/tests/1501-2000/1816. truncate-sentence/sol.py @@ -0,0 +1,4 @@ +class Solution: + def truncateSentence(self, s: str, k: int) -> str: + s = s.split(" ")[:k] + return " ".join(s) diff --git a/tests/1501-2000/1816. truncate-sentence/sol.py2 b/tests/1501-2000/1816. truncate-sentence/sol.py2 new file mode 100644 index 00000000..337119eb --- /dev/null +++ b/tests/1501-2000/1816. truncate-sentence/sol.py2 @@ -0,0 +1,9 @@ +class Solution(object): + def truncateSentence(self, s, k): + """ + :type s: str + :type k: int + :rtype: str + """ + s = s.split(" ")[:k] + return " ".join(s) diff --git a/tests/1501-2000/1816. truncate-sentence/sol.rb b/tests/1501-2000/1816. truncate-sentence/sol.rb new file mode 100644 index 00000000..935ac6cd --- /dev/null +++ b/tests/1501-2000/1816. truncate-sentence/sol.rb @@ -0,0 +1,6 @@ +# @param {String} s +# @param {Integer} k +# @return {String} +def truncate_sentence(s, k) + s.split(" ").first(k).join(" ") +end diff --git a/tests/1501-2000/1816. truncate-sentence/sol.rs b/tests/1501-2000/1816. truncate-sentence/sol.rs new file mode 100644 index 00000000..f8428ec3 --- /dev/null +++ b/tests/1501-2000/1816. truncate-sentence/sol.rs @@ -0,0 +1,5 @@ +impl Solution { + pub fn truncate_sentence(s: String, k: i32) -> String { + s.split_whitespace().take(k as usize).collect::>().join(" ") + } +} diff --git a/tests/1501-2000/1816. truncate-sentence/sol.swift b/tests/1501-2000/1816. truncate-sentence/sol.swift new file mode 100644 index 00000000..f1633aee --- /dev/null +++ b/tests/1501-2000/1816. truncate-sentence/sol.swift @@ -0,0 +1,6 @@ +class Solution { + func truncateSentence(_ s: String, _ k: Int) -> String { + let words = s.split(separator: " ") + return words.prefix(k).joined(separator: " ") + } +} diff --git a/tests/1501-2000/1816. truncate-sentence/sol.ts b/tests/1501-2000/1816. truncate-sentence/sol.ts new file mode 100644 index 00000000..73608df2 --- /dev/null +++ b/tests/1501-2000/1816. truncate-sentence/sol.ts @@ -0,0 +1,3 @@ +function truncateSentence(s: string, k: number): string { + return s.split(" ").slice(0, k).join(" "); +} diff --git a/tests/1501-2000/1817. finding-the-users-active-minutes/manifest.yaml b/tests/1501-2000/1817. finding-the-users-active-minutes/manifest.yaml new file mode 100644 index 00000000..4c27d239 --- /dev/null +++ b/tests/1501-2000/1817. finding-the-users-active-minutes/manifest.yaml @@ -0,0 +1,525 @@ +entry: + id: 1817 + title: "finding-the-users-active-minutes" + params: + logs: + type: array + items: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().findingUsersActiveMinutes({logs}, {k})" + rust: "Solution::finding_users_active_minutes({logs}, {k})" + python3: "Solution().findingUsersActiveMinutes({logs}, {k})" + python2: "Solution().findingUsersActiveMinutes({logs}, {k})" + ruby: "finding_users_active_minutes({logs}, {k})" + java: "new Solution().findingUsersActiveMinutes({logs}, {k})" + csharp: "new Solution().FindingUsersActiveMinutes({logs}, {k})" + kotlin: "Solution().findingUsersActiveMinutes({logs}, {k})" + go: "findingUsersActiveMinutes({logs}, {k})" + dart: "Solution().findingUsersActiveMinutes({logs}, {k})" + swift: "Solution().findingUsersActiveMinutes({logs}, {k})" + typescript: "findingUsersActiveMinutes({logs}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().findingUsersActiveMinutes(logs, k, {result})" + checker: | + class Checker: + def findingUsersActiveMinutes(self, logs, k, result): + if not isinstance(result, list) or len(result) != k: + return False + counts = {} + for pair in logs: + if not isinstance(pair, list) or len(pair) != 2: + return False + user, minute = pair + counts.setdefault(user, set()).add(minute) + expected = [0] * k + for minutes in counts.values(): + if len(minutes) > k: + return False + expected[len(minutes) - 1] += 1 + return result == expected + +seed: 1817 + +tests: + - name: example-one + in: + logs: + - [0, 5] + - [1, 2] + - [0, 2] + - [0, 5] + - [1, 3] + k: 5 + out: [0, 2, 0, 0, 0] + judge: + type: "exact" + - name: example-two + in: + logs: + - [1, 1] + - [2, 2] + - [2, 3] + k: 4 + out: [1, 1, 0, 0] + judge: + type: "exact" + - name: one-user-one-minute + in: + logs: + - [7, 4] + k: 1 + out: [1] + judge: + type: "exact" + - name: duplicate-only + in: + logs: + - [3, 9] + - [3, 9] + - [3, 9] + k: 3 + out: [1, 0, 0] + judge: + type: "exact" + - name: two-users-same-minute + in: + logs: + - [1, 8] + - [2, 8] + k: 2 + out: [2, 0] + judge: + type: "exact" + - name: one-user-all-minutes + in: + logs: + - [5, 1] + - [5, 2] + - [5, 3] + - [5, 4] + k: 4 + out: [0, 0, 0, 1] + judge: + type: "exact" + - name: unused-buckets + in: + logs: + - [1, 10] + - [1, 11] + - [2, 20] + k: 6 + out: [1, 1, 0, 0, 0, 0] + judge: + type: "exact" + - name: same-user-interleaved + in: + logs: + - [9, 4] + - [2, 1] + - [9, 7] + - [9, 4] + - [2, 1] + - [2, 3] + k: 3 + out: [0, 2, 0] + judge: + type: "exact" + - name: large-user-ids + in: + logs: + - [1000000000, 1] + - [999999999, 2] + - [1000000000, 3] + k: 3 + out: [1, 1, 0] + judge: + type: "exact" + - name: time-boundaries + in: + logs: + - [0, 1] + - [0, 100000] + - [1, 100000] + k: 2 + out: [1, 1] + judge: + type: "exact" + - name: five-distinct + in: + logs: + - [4, 1] + - [4, 2] + - [4, 3] + - [4, 4] + - [4, 5] + k: 5 + out: [0, 0, 0, 0, 1] + judge: + type: "exact" + - name: mixed-three-users + in: + logs: + - [1, 1] + - [1, 2] + - [1, 3] + - [2, 1] + - [2, 2] + - [3, 9] + k: 3 + out: [1, 1, 1] + judge: + type: "exact" + - name: repeated-blocks + in: + logs: + - [8, 2] + - [8, 2] + - [8, 3] + - [8, 3] + - [8, 4] + - [7, 6] + - [7, 6] + k: 3 + out: [1, 0, 1] + judge: + type: "exact" + - name: k-one + in: + logs: + - [1, 4] + - [1, 4] + - [2, 8] + - [2, 9] + k: 1 + out: [1] + judge: + type: "exact" + - name: ten-users-one-minute + in: + logs: + - [0, 1] + - [1, 1] + - [2, 1] + - [3, 1] + - [4, 1] + - [5, 1] + - [6, 1] + - [7, 1] + - [8, 1] + - [9, 1] + k: 2 + out: [10, 0] + judge: + type: "exact" + - name: ten-minutes-two-users + in: + logs: + - [1, 1] + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [2, 6] + - [2, 7] + - [2, 8] + - [2, 9] + - [2, 10] + k: 5 + out: [0, 0, 0, 0, 2] + judge: + type: "exact" + - name: nonconsecutive-minutes + in: + logs: + - [1, 100] + - [1, 1] + - [1, 50000] + - [2, 2] + - [2, 4] + k: 3 + out: [0, 1, 1] + judge: + type: "exact" + - name: duplicate-users-and-times + in: + logs: + - [0, 0] + - [0, 0] + - [0, 1] + - [1, 0] + - [1, 0] + - [2, 2] + - [2, 3] + k: 3 + out: [1, 2, 0] + judge: + type: "exact" + - name: bucket-at-k + in: + logs: + - [77, 10] + - [77, 20] + - [77, 30] + - [77, 40] + - [77, 50] + - [77, 60] + k: 6 + out: [0, 0, 0, 0, 0, 1] + judge: + type: "exact" + - name: isolated-singletons + in: + logs: + - [11, 1] + - [22, 2] + - [33, 3] + - [44, 4] + k: 4 + out: [4, 0, 0, 0] + judge: + type: "exact" + - name: four-users-different-uam + in: + logs: + - [1, 1] + - [2, 1] + - [2, 2] + - [3, 1] + - [3, 2] + - [3, 3] + - [4, 1] + - [4, 2] + - [4, 3] + - [4, 4] + k: 4 + out: [1, 1, 1, 1] + judge: + type: "exact" + - name: sparse-ids + in: + logs: + - [17, 5] + - [100, 5] + - [1000000000, 5] + - [17, 6] + k: 2 + out: [2, 1] + judge: + type: "exact" + - name: all-duplicates-many-actions + in: + logs: + - [1, 1] + - [1, 1] + - [1, 1] + - [2, 2] + - [2, 2] + - [2, 2] + - [3, 3] + k: 2 + out: [3, 0] + judge: + type: "exact" + - name: five-users-two-minutes + in: + logs: + - [1, 1] + - [1, 2] + - [2, 2] + - [2, 3] + - [3, 3] + - [3, 4] + - [4, 4] + - [4, 5] + - [5, 5] + - [5, 6] + k: 3 + out: [0, 5, 0] + judge: + type: "exact" + - name: repeated-interleaving + in: + logs: + - [1, 1] + - [2, 1] + - [1, 2] + - [2, 1] + - [1, 1] + - [2, 3] + - [3, 3] + k: 3 + out: [1, 2, 0] + judge: + type: "exact" + - name: six-users-uam-three + in: + logs: + - [1, 1] + - [1, 2] + - [1, 3] + - [2, 4] + - [2, 5] + - [2, 6] + - [3, 7] + - [3, 8] + - [3, 9] + - [4, 10] + - [4, 11] + - [4, 12] + - [5, 13] + - [5, 14] + - [5, 15] + - [6, 16] + - [6, 17] + - [6, 18] + k: 3 + out: [0, 0, 6] + judge: + type: "exact" + - name: high-time-duplicates + in: + logs: + - [8, 99999] + - [8, 100000] + - [8, 100000] + - [9, 99999] + k: 2 + out: [1, 1] + judge: + type: "exact" + - name: id-zero + in: + logs: + - [0, 1] + - [0, 2] + - [0, 2] + k: 2 + out: [0, 1] + judge: + type: "exact" + - name: mixed-zero-and-large-id + in: + logs: + - [0, 100000] + - [1000000000, 1] + - [1000000000, 2] + - [0, 100000] + k: 2 + out: [1, 1] + judge: + type: "exact" + - name: nine-actions-four-users + in: + logs: + - [1, 1] + - [1, 2] + - [2, 1] + - [2, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [4, 6] + - [4, 7] + k: 3 + out: [1, 1, 2] + judge: + type: "exact" + - name: generated-small + in: + logs: + gen: "array" + len: 80 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 9 + elemType: "int" + k: 10 + judge: + type: "exact" + seed: 181701 + - name: generated-medium + in: + logs: + gen: "array" + len: 1000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 999 + elemType: "int" + k: 1000 + judge: + type: "exact" + seed: 181702 + - name: generated-large + in: + logs: + gen: "array" + len: 10000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" + k: 100000 + judge: + type: "exact" + seed: 181703 + - name: generated-duplicate-heavy + in: + logs: + gen: "array" + len: 5000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 19 + elemType: "int" + k: 100 + judge: + type: "exact" + seed: 181704 + - name: generated-boundary-times + in: + logs: + gen: "array" + len: 7000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 100000 + elemType: "int" + k: 100000 + judge: + type: "exact" + seed: 181705 diff --git a/tests/1501-2000/1817. finding-the-users-active-minutes/sol.cpp b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.cpp new file mode 100644 index 00000000..08a4b30d --- /dev/null +++ b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector findingUsersActiveMinutes(vector>& logs, int k) { + unordered_map> mp; + for (auto& log : logs) { + mp[log[0]].insert(log[1]); + } + vector ans(k, 0); + for (auto& entry : mp) { + int size = entry.second.size(); + if (size <= k) { + ans[size - 1]++; + } + } + return ans; + } +}; diff --git a/tests/1501-2000/1817. finding-the-users-active-minutes/sol.cs b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.cs new file mode 100644 index 00000000..5fbe38d1 --- /dev/null +++ b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public int[] FindingUsersActiveMinutes(int[][] logs, int k) { + var mp = new Dictionary>(); + foreach (var log in logs) { + if (!mp.ContainsKey(log[0])) { + mp[log[0]] = new HashSet(); + } + mp[log[0]].Add(log[1]); + } + var ans = new int[k]; + foreach (var set in mp.Values) { + int size = set.Count; + if (size <= k) { + ans[size - 1]++; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1817. finding-the-users-active-minutes/sol.dart b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.dart new file mode 100644 index 00000000..9135de00 --- /dev/null +++ b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.dart @@ -0,0 +1,16 @@ +class Solution { + List findingUsersActiveMinutes(List> logs, int k) { + Map> mp = {}; + for (var log in logs) { + mp.putIfAbsent(log[0], () => {}).add(log[1]); + } + List ans = List.filled(k, 0); + for (var set in mp.values) { + int size = set.length; + if (size <= k) { + ans[size - 1]++; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1817. finding-the-users-active-minutes/sol.go b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.go new file mode 100644 index 00000000..2262cfea --- /dev/null +++ b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.go @@ -0,0 +1,19 @@ +func findingUsersActiveMinutes(logs [][]int, k int) []int { + mp := make(map[int]map[int]bool) + for _, log := range logs { + user := log[0] + minute := log[1] + if mp[user] == nil { + mp[user] = make(map[int]bool) + } + mp[user][minute] = true + } + ans := make([]int, k) + for _, set := range mp { + size := len(set) + if size <= k { + ans[size-1]++ + } + } + return ans +} diff --git a/tests/1501-2000/1817. finding-the-users-active-minutes/sol.java b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.java new file mode 100644 index 00000000..02f51aad --- /dev/null +++ b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.java @@ -0,0 +1,16 @@ +class Solution { + public int[] findingUsersActiveMinutes(int[][] logs, int k) { + Map> mp = new HashMap<>(); + for (int[] log : logs) { + mp.computeIfAbsent(log[0], x -> new HashSet<>()).add(log[1]); + } + int[] ans = new int[k]; + for (Set set : mp.values()) { + int size = set.size(); + if (size <= k) { + ans[size - 1]++; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1817. finding-the-users-active-minutes/sol.kt b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.kt new file mode 100644 index 00000000..11649a77 --- /dev/null +++ b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun findingUsersActiveMinutes(logs: Array, k: Int): IntArray { + val mp = HashMap>() + for (log in logs) { + mp.getOrPut(log[0]) { HashSet() }.add(log[1]) + } + val ans = IntArray(k) + for (set in mp.values) { + val size = set.size + if (size <= k) { + ans[size - 1]++ + } + } + return ans + } +} diff --git a/tests/1501-2000/1817. finding-the-users-active-minutes/sol.py b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.py new file mode 100644 index 00000000..9831ab16 --- /dev/null +++ b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.py @@ -0,0 +1,13 @@ +class Solution: + def findingUsersActiveMinutes(self, logs, k): + mp = {} + for user, minute in logs: + if user not in mp: + mp[user] = set() + mp[user].add(minute) + ans = [0] * k + for user in mp: + size = len(mp[user]) + if size <= k: + ans[size - 1] += 1 + return ans diff --git a/tests/1501-2000/1817. finding-the-users-active-minutes/sol.py2 b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.py2 new file mode 100644 index 00000000..73227fc9 --- /dev/null +++ b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def findingUsersActiveMinutes(self, logs, k): + """ + :type logs: List[List[int]] + :type k: int + :rtype: List[int] + """ + mp = {} + for user, minute in logs: + if user not in mp: + mp[user] = set() + mp[user].add(minute) + ans = [0] * k + for user in mp: + size = len(mp[user]) + if size <= k: + ans[size - 1] += 1 + return ans diff --git a/tests/1501-2000/1817. finding-the-users-active-minutes/sol.rb b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.rb new file mode 100644 index 00000000..9233c5e7 --- /dev/null +++ b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.rb @@ -0,0 +1,17 @@ +# @param {Integer[][]} logs +# @param {Integer} k +# @return {Integer[]} +def finding_users_active_minutes(logs, k) + mp = Hash.new { |h, key| h[key] = Set.new } + logs.each do |user, minute| + mp[user] << minute + end + ans = Array.new(k, 0) + mp.each do |user, set| + size = set.size + if size <= k + ans[size - 1] += 1 + end + end + ans +end diff --git a/tests/1501-2000/1817. finding-the-users-active-minutes/sol.rs b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.rs new file mode 100644 index 00000000..63ba52cb --- /dev/null +++ b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn finding_users_active_minutes(logs: Vec>, k: i32) -> Vec { + use std::collections::HashMap; + use std::collections::HashSet; + let mut mp: HashMap> = HashMap::new(); + for log in &logs { + mp.entry(log[0]).or_insert_with(HashSet::new).insert(log[1]); + } + let mut ans = vec![0; k as usize]; + for set in mp.values() { + let size = set.len(); + if (size as i32) <= k { + ans[size - 1] += 1; + } + } + ans + } +} diff --git a/tests/1501-2000/1817. finding-the-users-active-minutes/sol.swift b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.swift new file mode 100644 index 00000000..13d8781c --- /dev/null +++ b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func findingUsersActiveMinutes(_ logs: [[Int]], _ k: Int) -> [Int] { + var mp: [Int: Set] = [:] + for log in logs { + mp[log[0], default: []].insert(log[1]) + } + var ans = Array(repeating: 0, count: k) + for set in mp.values { + let size = set.count + if size <= k { + ans[size - 1] += 1 + } + } + return ans + } +} diff --git a/tests/1501-2000/1817. finding-the-users-active-minutes/sol.ts b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.ts new file mode 100644 index 00000000..ceeba68f --- /dev/null +++ b/tests/1501-2000/1817. finding-the-users-active-minutes/sol.ts @@ -0,0 +1,17 @@ +function findingUsersActiveMinutes(logs: number[][], k: number): number[] { + const mp = new Map>(); + for (const [user, minute] of logs) { + if (!mp.has(user)) { + mp.set(user, new Set()); + } + mp.get(user)!.add(minute); + } + const ans = new Array(k).fill(0); + for (const set of mp.values()) { + const size = set.size; + if (size <= k) { + ans[size - 1]++; + } + } + return ans; +} diff --git a/tests/1501-2000/1818. minimum-absolute-sum-difference/manifest.yaml b/tests/1501-2000/1818. minimum-absolute-sum-difference/manifest.yaml new file mode 100644 index 00000000..5d80428f --- /dev/null +++ b/tests/1501-2000/1818. minimum-absolute-sum-difference/manifest.yaml @@ -0,0 +1,219 @@ +entry: + id: 1818 + title: "minimum-absolute-sum-difference" + params: + nums1: + type: array + items: + type: int + nums2: + type: array + items: + type: int + call: + cpp: "Solution().minAbsoluteSumDiff({nums1}, {nums2})" + rust: "Solution::min_absolute_sum_diff({nums1}, {nums2})" + python3: "Solution().minAbsoluteSumDiff({nums1}, {nums2})" + python2: "Solution().minAbsoluteSumDiff({nums1}, {nums2})" + ruby: "min_absolute_sum_diff({nums1}, {nums2})" + java: "new Solution().minAbsoluteSumDiff({nums1}, {nums2})" + csharp: "new Solution().MinAbsoluteSumDiff({nums1}, {nums2})" + kotlin: "Solution().minAbsoluteSumDiff({nums1}, {nums2})" + go: "minAbsoluteSumDiff({nums1}, {nums2})" + dart: "Solution().minAbsoluteSumDiff({nums1}, {nums2})" + swift: "Solution().minAbsoluteSumDiff({nums1}, {nums2})" + typescript: "minAbsoluteSumDiff({nums1}, {nums2})" +judge: + type: "exact" +limits: + time_ms: 3000 + memory_mb: 512 +oracle: + python3: + call: "Checker().check(nums1, nums2, {result})" + checker: | + class Checker: + def check(self, nums1, nums2, result): + return isinstance(result, int) and not isinstance(result, bool) +seed: 1818 +tests: + - name: example-one + in: + nums1: [1, 7, 5] + nums2: [2, 3, 5] + out: 3 + - name: equal-arrays + in: + nums1: [2, 4, 6, 8, 10] + nums2: [2, 4, 6, 8, 10] + out: 0 + - name: example-three + in: + nums1: [1, 10, 4, 4, 2, 7] + nums2: [9, 3, 5, 1, 7, 4] + out: 20 + - name: single-equal + in: + nums1: [5] + nums2: [5] + out: 0 + - name: single-different + in: + nums1: [1] + nums2: [100000] + out: 99999 + - name: already-optimal + in: + nums1: [1, 2, 3] + nums2: [3, 2, 1] + out: 2 + - name: no-useful-replacement + in: + nums1: [1, 1, 1] + nums2: [100000, 99999, 99998] + out: 299994 + - name: duplicates + in: + nums1: [10, 10, 20, 20] + nums2: [1, 19, 2, 18] + out: 28 + - name: increasing-shift + in: + nums1: [1, 2, 3, 4, 5] + nums2: [6, 7, 8, 9, 10] + out: 21 + - name: decreasing-shift + in: + nums1: [6, 7, 8, 9, 10] + nums2: [1, 2, 3, 4, 5] + out: 21 + - name: nearest-left + in: + nums1: [1, 4, 9] + nums2: [3, 8, 10] + out: 4 + - name: nearest-right + in: + nums1: [2, 8, 20] + nums2: [5, 5, 17] + out: 9 + - name: repeated-targets + in: + nums1: [1, 50, 100] + nums2: [49, 49, 49] + out: 50 + - name: extremes + in: + nums1: [1, 100000, 1, 100000] + nums2: [100000, 1, 50000, 50001] + out: 199997 + - name: alternating + in: + nums1: [1, 100, 2, 99, 3, 98] + nums2: [50, 50, 50, 50, 50, 50] + out: 288 + - name: all-low + in: + nums1: [1, 2, 3, 4, 5, 6] + nums2: [100, 99, 98, 97, 96, 95] + out: 559 + - name: all-high + in: + nums1: [99995, 99996, 99997, 99998, 99999, 100000] + nums2: [1, 2, 3, 4, 5, 6] + out: 599959 + - name: one-perfect-source + in: + nums1: [7, 20, 30, 40] + nums2: [100, 20, 100, 100] + out: 190 + - name: zero-and-one-gaps + in: + nums1: [1, 3, 5, 7, 9] + nums2: [2, 4, 6, 8, 10] + out: 5 + - name: unsorted-source + in: + nums1: [50, 1, 40, 10, 30] + nums2: [45, 35, 5, 25, 15] + out: 73 + - name: large-gaps + in: + nums1: [100000, 50000, 25000, 12500] + nums2: [1, 99999, 2, 99998] + out: 174994 + - name: many-equal + in: + nums1: [4, 4, 4, 100] + nums2: [1, 2, 3, 4] + out: 6 + - name: source-covers-targets + in: + nums1: [1, 5, 10, 20, 50] + nums2: [2, 6, 9, 19, 49] + out: 5 + - name: odd-length + in: + nums1: [11, 22, 33, 44, 55, 66, 77] + nums2: [70, 60, 50, 40, 30, 20, 10] + out: 190 + - name: even-length + in: + nums1: [8, 16, 24, 32, 40, 48, 56, 64] + nums2: [64, 56, 48, 40, 32, 24, 16, 8] + out: 200 + - name: close-values + in: + nums1: [100, 101, 102, 103] + nums2: [104, 105, 106, 107] + out: 13 + - name: far-single-improvement + in: + nums1: [1, 2, 3, 1000] + nums2: [1000, 1000, 1000, 1] + out: 2994 + - name: low-bound-values + in: + nums1: [1, 1, 2, 2] + nums2: [1, 2, 1, 2] + out: 1 + - name: high-bound-values + in: + nums1: [100000, 99999, 100000] + nums2: [99999, 100000, 1] + out: 100000 + - name: six-mixed + in: + nums1: [12, 87, 43, 5, 66, 31] + nums2: [70, 20, 40, 90, 2, 60] + out: 224 + - name: seven-mixed + in: + nums1: [3, 14, 159, 26, 535, 89, 79] + nums2: [2, 71, 8, 28, 182, 84, 6] + out: 312 + - name: eight-mixed + in: + nums1: [17, 29, 41, 53, 65, 77, 89, 101] + nums2: [100, 90, 80, 70, 60, 50, 40, 30] + out: 270 + - name: nine-duplicates + in: + nums1: [9, 9, 18, 18, 27, 27, 36, 36, 45] + nums2: [1, 10, 20, 30, 40, 50, 60, 70, 80] + out: 134 + - name: ten-balanced + in: + nums1: [5, 15, 25, 35, 45, 55, 65, 75, 85, 95] + nums2: [95, 85, 75, 65, 55, 45, 35, 25, 15, 5] + out: 410 + - name: modulo-scale + in: + nums1: [1, 100000, 1, 100000, 1, 100000, 1, 100000, 1, 100000] + nums2: [100000, 1, 100000, 1, 100000, 1, 100000, 1, 100000, 1] + out: 899991 + - name: asymmetric + in: + nums1: [2, 11, 23, 47, 71] + nums2: [100, 3, 19, 50, 1] + out: 114 diff --git a/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.cpp b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.cpp new file mode 100644 index 00000000..f70c21d0 --- /dev/null +++ b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.cpp @@ -0,0 +1,33 @@ +#include +#include +#include + +class Solution { +public: + int minAbsoluteSumDiff(vector& nums1, vector& nums2) { + const int MOD = 1000000007; + int n = nums1.size(); + vector sortedNums1 = nums1; + sort(sortedNums1.begin(), sortedNums1.end()); + long long total = 0; + long long maxReduction = 0; + + for (int i = 0; i < n; i++) { + int a = nums1[i]; + int b = nums2[i]; + long long currDiff = abs(a - b); + total += currDiff; + + int idx = lower_bound(sortedNums1.begin(), sortedNums1.end(), b) - sortedNums1.begin(); + + if (idx < n) { + maxReduction = max(maxReduction, currDiff - abs(sortedNums1[idx] - b)); + } + if (idx > 0) { + maxReduction = max(maxReduction, currDiff - abs(sortedNums1[idx - 1] - b)); + } + } + + return (int)((total - maxReduction) % MOD); + } +}; diff --git a/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.cs b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.cs new file mode 100644 index 00000000..6dc3a5ca --- /dev/null +++ b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.cs @@ -0,0 +1,31 @@ +using System; + +public class Solution { + public int MinAbsoluteSumDiff(int[] nums1, int[] nums2) { + const int MOD = 1000000007; + int n = nums1.Length; + int[] sortedNums1 = (int[])nums1.Clone(); + Array.Sort(sortedNums1); + long total = 0; + long maxReduction = 0; + + for (int i = 0; i < n; i++) { + int a = nums1[i]; + int b = nums2[i]; + long currDiff = Math.Abs(a - b); + total += currDiff; + + int idx = Array.BinarySearch(sortedNums1, b); + if (idx < 0) idx = ~idx; + + if (idx < n) { + maxReduction = Math.Max(maxReduction, currDiff - Math.Abs(sortedNums1[idx] - b)); + } + if (idx > 0) { + maxReduction = Math.Max(maxReduction, currDiff - Math.Abs(sortedNums1[idx - 1] - b)); + } + } + + return (int)((total - maxReduction) % MOD); + } +} diff --git a/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.dart b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.dart new file mode 100644 index 00000000..6a96e8a7 --- /dev/null +++ b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.dart @@ -0,0 +1,42 @@ +class Solution { + int minAbsoluteSumDiff(List nums1, List nums2) { + const int MOD = 1000000007; + int n = nums1.length; + List sortedNums1 = List.from(nums1)..sort(); + int total = 0; + int maxReduction = 0; + + for (int i = 0; i < n; i++) { + int a = nums1[i]; + int b = nums2[i]; + int currDiff = (a - b).abs(); + total += currDiff; + + int idx = _lowerBound(sortedNums1, b); + + if (idx < n) { + maxReduction = _max(maxReduction, currDiff - (sortedNums1[idx] - b).abs()); + } + if (idx > 0) { + maxReduction = _max(maxReduction, currDiff - (sortedNums1[idx - 1] - b).abs()); + } + } + + return (total - maxReduction) % MOD; + } + + int _lowerBound(List arr, int target) { + int low = 0, high = arr.length; + while (low < high) { + int mid = (low + high) ~/ 2; + if (arr[mid] < target) { + low = mid + 1; + } else { + high = mid; + } + } + return low; + } + + int _max(int a, int b) => a > b ? a : b; +} diff --git a/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.go b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.go new file mode 100644 index 00000000..802d5eac --- /dev/null +++ b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.go @@ -0,0 +1,41 @@ +func minAbsoluteSumDiff(nums1 []int, nums2 []int) int { + const MOD = 1000000007 + n := len(nums1) + sortedNums1 := make([]int, n) + copy(sortedNums1, nums1) + sort.Ints(sortedNums1) + + total := int64(0) + maxReduction := int64(0) + + for i := 0; i < n; i++ { + a := nums1[i] + b := nums2[i] + currDiff := abs1818(a - b) + total += int64(currDiff) + + idx := sort.SearchInts(sortedNums1, b) + + if idx < n { + reduction := int64(currDiff - abs1818(sortedNums1[idx]-b)) + if reduction > maxReduction { + maxReduction = reduction + } + } + if idx > 0 { + reduction := int64(currDiff - abs1818(sortedNums1[idx-1]-b)) + if reduction > maxReduction { + maxReduction = reduction + } + } + } + + return int((total - maxReduction) % int64(MOD)) +} + +func abs1818(x int) int { + if x < 0 { + return -x + } + return x +} diff --git a/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.java b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.java new file mode 100644 index 00000000..6fc17b31 --- /dev/null +++ b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.java @@ -0,0 +1,31 @@ +import java.util.Arrays; + +class Solution { + public int minAbsoluteSumDiff(int[] nums1, int[] nums2) { + final int MOD = 1_000_000_007; + int n = nums1.length; + int[] sortedNums1 = nums1.clone(); + Arrays.sort(sortedNums1); + long total = 0; + long maxReduction = 0; + + for (int i = 0; i < n; i++) { + int a = nums1[i]; + int b = nums2[i]; + long currDiff = Math.abs(a - b); + total += currDiff; + + int idx = Arrays.binarySearch(sortedNums1, b); + if (idx < 0) idx = -idx - 1; + + if (idx < n) { + maxReduction = Math.max(maxReduction, currDiff - Math.abs(sortedNums1[idx] - b)); + } + if (idx > 0) { + maxReduction = Math.max(maxReduction, currDiff - Math.abs(sortedNums1[idx - 1] - b)); + } + } + + return (int)((total - maxReduction) % MOD); + } +} diff --git a/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.kt b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.kt new file mode 100644 index 00000000..df9bb4c7 --- /dev/null +++ b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.kt @@ -0,0 +1,30 @@ +import kotlin.math.abs + +class Solution { + fun minAbsoluteSumDiff(nums1: IntArray, nums2: IntArray): Int { + val MOD = 1_000_000_007 + val n = nums1.size + val sortedNums1 = nums1.copyOf().sorted() + var total = 0L + var maxReduction = 0L + + for (i in 0 until n) { + val a = nums1[i] + val b = nums2[i] + val currDiff = abs(a - b).toLong() + total += currDiff + + var idx = sortedNums1.binarySearch(b) + if (idx < 0) idx = -idx - 1 + + if (idx < n) { + maxReduction = maxOf(maxReduction, currDiff - abs(sortedNums1[idx] - b).toLong()) + } + if (idx > 0) { + maxReduction = maxOf(maxReduction, currDiff - abs(sortedNums1[idx - 1] - b).toLong()) + } + } + + return ((total - maxReduction) % MOD).toInt() + } +} diff --git a/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.py b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.py new file mode 100644 index 00000000..8e7ad0cb --- /dev/null +++ b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.py @@ -0,0 +1,32 @@ +import bisect + + +class Solution(object): + def minAbsoluteSumDiff(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: int + """ + MOD = 10**9 + 7 + n = len(nums1) + sorted_nums1 = sorted(nums1) + total = 0 + max_reduction = 0 + + for i in range(n): + a, b = nums1[i], nums2[i] + curr_diff = abs(a - b) + total += curr_diff + + idx = bisect.bisect_left(sorted_nums1, b) + if idx < n: + max_reduction = max( + max_reduction, curr_diff - abs(sorted_nums1[idx] - b) + ) + if idx > 0: + max_reduction = max( + max_reduction, curr_diff - abs(sorted_nums1[idx - 1] - b) + ) + + return (total - max_reduction) % MOD diff --git a/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.py2 b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.py2 new file mode 100644 index 00000000..43bb2614 --- /dev/null +++ b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.py2 @@ -0,0 +1,26 @@ +class Solution(object): + def minAbsoluteSumDiff(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: int + """ + MOD = 10**9 + 7 + n = len(nums1) + sorted_nums1 = sorted(nums1) + total = 0 + max_reduction = 0 + + for i in range(n): + a, b = nums1[i], nums2[i] + curr_diff = abs(a - b) + total += curr_diff + + import bisect + idx = bisect.bisect_left(sorted_nums1, b) + if idx < n: + max_reduction = max(max_reduction, curr_diff - abs(sorted_nums1[idx] - b)) + if idx > 0: + max_reduction = max(max_reduction, curr_diff - abs(sorted_nums1[idx - 1] - b)) + + return (total - max_reduction) % MOD diff --git a/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.rb b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.rb new file mode 100644 index 00000000..46a53733 --- /dev/null +++ b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.rb @@ -0,0 +1,27 @@ +# @param {Integer[]} nums1 +# @param {Integer[]} nums2 +# @return {Integer} +def min_absolute_sum_diff(nums1, nums2) + mod = 10**9 + 7 + n = nums1.length + sorted_nums1 = nums1.sort + total = 0 + max_reduction = 0 + + n.times do |i| + a = nums1[i] + b = nums2[i] + curr_diff = (a - b).abs + total += curr_diff + + idx = sorted_nums1.bsearch_index { |x| x >= b } || n + if idx < n + max_reduction = [max_reduction, curr_diff - (sorted_nums1[idx] - b).abs].max + end + if idx > 0 + max_reduction = [max_reduction, curr_diff - (sorted_nums1[idx - 1] - b).abs].max + end + end + + (total - max_reduction) % mod +end diff --git a/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.rs b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.rs new file mode 100644 index 00000000..97db4661 --- /dev/null +++ b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.rs @@ -0,0 +1,28 @@ +impl Solution { + pub fn min_absolute_sum_diff(nums1: Vec, nums2: Vec) -> i32 { + const MOD: i64 = 1_000_000_007; + let n = nums1.len(); + let mut sorted_nums1 = nums1.clone(); + sorted_nums1.sort(); + let mut total: i64 = 0; + let mut max_reduction: i64 = 0; + + for i in 0..n { + let a = nums1[i]; + let b = nums2[i]; + let curr_diff = (a - b).abs() as i64; + total += curr_diff; + + let idx = sorted_nums1.binary_search(&b).unwrap_or_else(|x| x); + + if idx < n { + max_reduction = max_reduction.max(curr_diff - (sorted_nums1[idx] - b).abs() as i64); + } + if idx > 0 { + max_reduction = max_reduction.max(curr_diff - (sorted_nums1[idx - 1] - b).abs() as i64); + } + } + + ((total - max_reduction) % MOD) as i32 + } +} diff --git a/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.swift b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.swift new file mode 100644 index 00000000..7dc36d8b --- /dev/null +++ b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.swift @@ -0,0 +1,44 @@ +class Solution { + func minAbsoluteSumDiff(_ nums1: [Int], _ nums2: [Int]) -> Int { + let MOD = 1_000_000_007 + let n = nums1.count + let sortedNums1 = nums1.sorted() + var total = 0 + var maxReduction = 0 + + for i in 0.. 0 { + maxReduction = max(maxReduction, currDiff - abs(sortedNums1[idx - 1] - b)) + } + } + + return (total - maxReduction) % MOD + } +} + +extension Array where Element: Comparable { + func binarySearch(_ target: Element) -> Int { + var low = 0 + var high = self.count + while low < high { + let mid = (low + high) / 2 + if self[mid] < target { + low = mid + 1 + } else { + high = mid + } + } + return low < self.count && self[low] == target ? low : -low - 1 + } +} diff --git a/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.ts b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.ts new file mode 100644 index 00000000..26774328 --- /dev/null +++ b/tests/1501-2000/1818. minimum-absolute-sum-difference/sol.ts @@ -0,0 +1,42 @@ +function minAbsoluteSumDiff(nums1: number[], nums2: number[]): number { + const MOD = 1_000_000_007; + const n = nums1.length; + const sortedNums1 = [...nums1].sort((a, b) => a - b); + let total = 0; + let maxReduction = 0; + + for (let i = 0; i < n; i++) { + const a = nums1[i]; + const b = nums2[i]; + const currDiff = Math.abs(a - b); + total += currDiff; + + let idx = lowerBound(sortedNums1, b); + + if (idx < n) { + maxReduction = Math.max( + maxReduction, + currDiff - Math.abs(sortedNums1[idx] - b), + ); + } + if (idx > 0) { + maxReduction = Math.max( + maxReduction, + currDiff - Math.abs(sortedNums1[idx - 1] - b), + ); + } + } + + return (total - maxReduction) % MOD; +} + +function lowerBound(arr: number[], target: number): number { + let low = 0, + high = arr.length; + while (low < high) { + const mid = Math.floor((low + high) / 2); + if (arr[mid] < target) low = mid + 1; + else high = mid; + } + return low; +} diff --git a/tests/1501-2000/1819. number-of-different-subsequences-gcds/manifest.yaml b/tests/1501-2000/1819. number-of-different-subsequences-gcds/manifest.yaml new file mode 100644 index 00000000..c72207b2 --- /dev/null +++ b/tests/1501-2000/1819. number-of-different-subsequences-gcds/manifest.yaml @@ -0,0 +1,249 @@ +entry: + id: 1819 + title: number-of-different-subsequences-gcds + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().countDifferentSubsequenceGCDs({nums})" + rust: "Solution::count_different_subsequence_gc_ds({nums})" + python3: "Solution().countDifferentSubsequenceGCDs({nums})" + python2: "Solution().countDifferentSubsequenceGCDs({nums})" + ruby: "count_different_subsequence_gc_ds({nums})" + java: "new Solution().countDifferentSubsequenceGCDs({nums})" + csharp: "new Solution().CountDifferentSubsequenceGCDs({nums})" + kotlin: "Solution().countDifferentSubsequenceGCDs({nums})" + go: "countDifferentSubsequenceGCDs({nums})" + dart: "Solution().countDifferentSubsequenceGCDs({nums})" + swift: "Solution().countDifferentSubsequenceGCDs({nums})" + typescript: "countDifferentSubsequenceGCDs({nums})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().check(nums, {result})" + checker: | + from math import gcd + class Checker: + def check(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + seen = set(nums) + maximum = max(nums) + expected = 0 + for value in range(1, maximum + 1): + current = 0 + for multiple in range(value, maximum + 1, value): + if multiple in seen: + current = gcd(current, multiple) + if current == value: + expected += 1 + return result == expected + +seed: 1819 + +tests: + - name: single-one + in: + nums: [1] + out: 1 + - name: single-two + in: + nums: [2] + out: 1 + - name: single-six + in: + nums: [6] + out: 1 + - name: example-one + in: + nums: [6, 10, 3] + out: 5 + - name: example-two + in: + nums: [5, 15, 40, 5, 6] + out: 7 + - name: duplicate-ones + in: + nums: [1, 1, 1] + out: 1 + - name: duplicate-twos + in: + nums: [2, 2, 2] + out: 1 + - name: coprime-pair + in: + nums: [2, 3] + out: 3 + - name: multiples-four + in: + nums: [4, 8] + out: 2 + - name: pair-six-ten + in: + nums: [6, 10] + out: 3 + - name: three-overlapping + in: + nums: [6, 10, 15] + out: 7 + - name: evens + in: + nums: [2, 4, 6, 8, 10] + out: 5 + - name: multiples-three + in: + nums: [3, 6, 9, 12] + out: 4 + - name: multiples-five + in: + nums: [5, 10, 15, 20, 25] + out: 5 + - name: multiples-seven + in: + nums: [7, 14, 21, 28] + out: 4 + - name: one-and-maximum + in: + nums: [1, 200000] + out: 2 + - name: large-prime + in: + nums: [199999] + out: 1 + - name: large-multiple-pair + in: + nums: [200000, 100000] + out: 2 + - name: multiples-twelve + in: + nums: [12, 18, 24, 30] + out: 5 + - name: sparse-even-gcds + in: + nums: [6, 10, 14, 22] + out: 5 + - name: mixed-eight + in: + nums: [8, 12, 20, 28, 44] + out: 6 + - name: odd-multiples + in: + nums: [9, 15, 21, 27, 33] + out: 6 + - name: multiples-ten + in: + nums: [10, 20, 30, 40, 50, 60] + out: 6 + - name: multiples-eleven + in: + nums: [11, 22, 33, 44, 55] + out: 5 + - name: multiples-thirteen + in: + nums: [13, 26, 39, 52, 65] + out: 5 + - name: dense-sixteen + in: + nums: [16, 24, 36, 48, 60, 72] + out: 9 + - name: multiples-twenty-five + in: + nums: [25, 50, 75, 100, 125] + out: 5 + - name: multiples-seventeen + in: + nums: [17, 34, 51, 68, 85] + out: 5 + - name: powers-of-three + in: + nums: [2, 6, 18, 54, 162] + out: 5 + - name: factor-rich + in: + nums: [30, 42, 70, 105] + out: 15 + - name: mixed-small + in: + nums: [4, 6, 8, 9, 12, 15, 18] + out: 10 + - name: large-related-values + in: + nums: [99991, 199982, 149986] + out: 5 + - name: large-round-values + in: + nums: [100000, 150000, 200000] + out: 4 + - name: first-ten + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + out: 10 + - name: generated-small + in: + nums: + gen: "array" + len: 25 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + - name: generated-medium + in: + nums: + gen: "array" + len: 250 + of: + gen: "int" + min: 1 + max: 2000 + distinct: false + sorted: false + elemType: "int" + - name: generated-dense + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" + - name: generated-large-values + in: + nums: + gen: "array" + len: 5000 + of: + gen: "int" + min: 100000 + max: 200000 + distinct: false + sorted: false + elemType: "int" + - name: generated-maximum + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 200000 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.cpp b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.cpp new file mode 100644 index 00000000..1de52181 --- /dev/null +++ b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int countDifferentSubsequenceGCDs(vector& nums) { + unordered_set seen(nums.begin(), nums.end()); + int maxi = *max_element(nums.begin(), nums.end()); + int cnt = 0; + for (int i = 1; i <= maxi; i++) { + int gd = 0; + for (int j = i; j <= maxi; j += i) { + if (seen.count(j)) { + gd = gcd(gd, j); + } + } + if (gd == i) cnt++; + } + return cnt; + } + +private: + int gcd(int a, int b) { + while (b != 0) { + int temp = a % b; + a = b; + b = temp; + } + return a; + } +}; diff --git a/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.cs b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.cs new file mode 100644 index 00000000..f86278d5 --- /dev/null +++ b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.cs @@ -0,0 +1,26 @@ +public class Solution { + public int CountDifferentSubsequenceGCDs(int[] nums) { + HashSet seen = new HashSet(nums); + int maxi = nums.Max(); + int cnt = 0; + for (int i = 1; i <= maxi; i++) { + int gd = 0; + for (int j = i; j <= maxi; j += i) { + if (seen.Contains(j)) { + gd = Gcd(gd, j); + } + } + if (gd == i) cnt++; + } + return cnt; + } + + private int Gcd(int a, int b) { + while (b != 0) { + int temp = a % b; + a = b; + b = temp; + } + return a; + } +} diff --git a/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.dart b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.dart new file mode 100644 index 00000000..45973a8f --- /dev/null +++ b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.dart @@ -0,0 +1,26 @@ +class Solution { + int countDifferentSubsequenceGCDs(List nums) { + Set seen = nums.toSet(); + int maxi = nums.reduce((a, b) => a > b ? a : b); + int cnt = 0; + for (int i = 1; i <= maxi; i++) { + int gd = 0; + for (int j = i; j <= maxi; j += i) { + if (seen.contains(j)) { + gd = _gcd(gd, j); + } + } + if (gd == i) cnt++; + } + return cnt; + } + + int _gcd(int a, int b) { + while (b != 0) { + int temp = a % b; + a = b; + b = temp; + } + return a; + } +} diff --git a/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.go b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.go new file mode 100644 index 00000000..804bce27 --- /dev/null +++ b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.go @@ -0,0 +1,30 @@ +func countDifferentSubsequenceGCDs(nums []int) int { + seen := make(map[int]bool) + maxi := 0 + for _, num := range nums { + seen[num] = true + if num > maxi { + maxi = num + } + } + cnt := 0 + for i := 1; i <= maxi; i++ { + gd := 0 + for j := i; j <= maxi; j += i { + if seen[j] { + gd = gcd(gd, j) + } + } + if gd == i { + cnt++ + } + } + return cnt +} + +func gcd(a, b int) int { + for b != 0 { + a, b = b, a%b + } + return a +} diff --git a/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.java b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.java new file mode 100644 index 00000000..b57cf279 --- /dev/null +++ b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.java @@ -0,0 +1,30 @@ +class Solution { + public int countDifferentSubsequenceGCDs(int[] nums) { + Set seen = new HashSet<>(); + int maxi = 0; + for (int num : nums) { + seen.add(num); + maxi = Math.max(maxi, num); + } + int cnt = 0; + for (int i = 1; i <= maxi; i++) { + int gd = 0; + for (int j = i; j <= maxi; j += i) { + if (seen.contains(j)) { + gd = gcd(gd, j); + } + } + if (gd == i) cnt++; + } + return cnt; + } + + private int gcd(int a, int b) { + while (b != 0) { + int temp = a % b; + a = b; + b = temp; + } + return a; + } +} diff --git a/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.kt b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.kt new file mode 100644 index 00000000..3633bc8c --- /dev/null +++ b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.kt @@ -0,0 +1,30 @@ +class Solution { + fun countDifferentSubsequenceGCDs(nums: IntArray): Int { + val seen = nums.toHashSet() + val maxi = nums.max() ?: 0 + var cnt = 0 + for (i in 1..maxi) { + var gd = 0 + var j = i + while (j <= maxi) { + if (j in seen) { + gd = gcd(gd, j) + } + j += i + } + if (gd == i) cnt++ + } + return cnt + } + + private fun gcd(a: Int, b: Int): Int { + var x = a + var y = b + while (y != 0) { + val temp = x % y + x = y + y = temp + } + return x + } +} diff --git a/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.py b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.py new file mode 100644 index 00000000..04c706a5 --- /dev/null +++ b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.py @@ -0,0 +1,16 @@ +from math import gcd + + +class Solution: + def countDifferentSubsequenceGCDs(self, nums: List[int]) -> int: + seen = set(nums) + maxi = max(nums) + cnt = 0 + for i in range(1, maxi + 1): + gd = 0 + for j in range(i, maxi + 1, i): + if j in seen: + gd = gcd(gd, j) + if gd == i: + cnt += 1 + return cnt diff --git a/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.py2 b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.py2 new file mode 100644 index 00000000..1640b8ee --- /dev/null +++ b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def countDifferentSubsequenceGCDs(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + seen = set(nums) + maxi = max(nums) + cnt = 0 + for i in range(1, maxi+1): + gd = 0 + for j in range(i, maxi+1, i): + if j in seen: + gd = self._gcd(gd, j) + if gd == i: + cnt += 1 + return cnt + + def _gcd(self, a, b): + while b: + a, b = b, a % b + return a diff --git a/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.rb b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.rb new file mode 100644 index 00000000..df061b67 --- /dev/null +++ b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.rb @@ -0,0 +1,17 @@ +# @param {Integer[]} nums +# @return {Integer} +def count_different_subsequence_gc_ds(nums) + seen = nums.to_set + maxi = nums.max + cnt = 0 + (1..maxi).each do |i| + gd = 0 + (i..maxi).step(i).each do |j| + if seen.include?(j) + gd = gd.gcd(j) + end + end + cnt += 1 if gd == i + end + cnt +end diff --git a/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.rs b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.rs new file mode 100644 index 00000000..ac66772d --- /dev/null +++ b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.rs @@ -0,0 +1,32 @@ +impl Solution { + pub fn count_different_subsequence_gc_ds(nums: Vec) -> i32 { + let seen: std::collections::HashSet = nums.iter().cloned().collect(); + let maxi = *nums.iter().max().unwrap_or(&0); + let mut cnt = 0; + for i in 1..=maxi { + let mut gd = 0; + let mut j = i; + while j <= maxi { + if seen.contains(&j) { + gd = Self::gcd(gd, j); + } + j += i; + } + if gd == i { + cnt += 1; + } + } + cnt + } + + fn gcd(a: i32, b: i32) -> i32 { + let mut x = a; + let mut y = b; + while y != 0 { + let temp = x % y; + x = y; + y = temp; + } + x + } +} diff --git a/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.swift b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.swift new file mode 100644 index 00000000..6e4c4d03 --- /dev/null +++ b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.swift @@ -0,0 +1,32 @@ +class Solution { + func countDifferentSubsequenceGCDs(_ nums: [Int]) -> Int { + let seen = Set(nums) + let maxi = nums.max() ?? 0 + var cnt = 0 + for i in 1...maxi { + var gd = 0 + var j = i + while j <= maxi { + if seen.contains(j) { + gd = gcd(gd, j) + } + j += i + } + if gd == i { + cnt += 1 + } + } + return cnt + } + + private func gcd(_ a: Int, _ b: Int) -> Int { + var x = a + var y = b + while y != 0 { + let temp = x % y + x = y + y = temp + } + return x + } +} diff --git a/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.ts b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.ts new file mode 100644 index 00000000..b0eb1ac9 --- /dev/null +++ b/tests/1501-2000/1819. number-of-different-subsequences-gcds/sol.ts @@ -0,0 +1,22 @@ +function countDifferentSubsequenceGCDs(nums: number[]): number { + const seen = new Set(nums); + const maxi = Math.max(...nums); + let cnt = 0; + for (let i = 1; i <= maxi; i++) { + let gd = 0; + for (let j = i; j <= maxi; j += i) { + if (seen.has(j)) { + gd = gcd(gd, j); + } + } + if (gd === i) cnt++; + } + return cnt; +} + +function gcd(a: number, b: number): number { + while (b !== 0) { + [a, b] = [b, a % b]; + } + return a; +} diff --git a/tests/1501-2000/1822. sign-of-the-product-of-an-array/manifest.yaml b/tests/1501-2000/1822. sign-of-the-product-of-an-array/manifest.yaml new file mode 100644 index 00000000..94ebcab9 --- /dev/null +++ b/tests/1501-2000/1822. sign-of-the-product-of-an-array/manifest.yaml @@ -0,0 +1,274 @@ +entry: + id: 1822 + title: "sign-of-the-product-of-an-array" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().arraySign({nums})" + rust: "Solution::array_sign({nums})" + python3: "Solution().arraySign({nums})" + python2: "Solution().arraySign({nums})" + ruby: "array_sign({nums})" + java: "new Solution().arraySign({nums})" + csharp: "new Solution().ArraySign({nums})" + kotlin: "Solution().arraySign({nums})" + go: "arraySign({nums})" + dart: "Solution().arraySign({nums})" + swift: "Solution().arraySign({nums})" + typescript: "arraySign({nums})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().arraySign(nums, {result})" + checker: | + class Checker: + def arraySign(self, nums, result): + expected = 0 if 0 in nums else (-1 if sum(x < 0 for x in nums) % 2 else 1) + return result == expected + +seed: 1822 + +tests: + - name: example-positive + in: + nums: [-1, -2, -3, -4, 3, 2, 1] + out: 1 + - name: example-zero + in: + nums: [1, 5, 0, 2, -3] + out: 0 + - name: example-negative + in: + nums: [-1, 1, -1, 1, -1] + out: -1 + - name: single-positive + in: + nums: [1] + out: 1 + - name: single-negative + in: + nums: [-1] + out: -1 + - name: single-zero + in: + nums: [0] + out: 0 + - name: positive-bound + in: + nums: [100] + out: 1 + - name: negative-bound + in: + nums: [-100] + out: -1 + - name: zero-first + in: + nums: [0, -100, 100] + out: 0 + - name: zero-middle + in: + nums: [-2, 0, -3] + out: 0 + - name: zero-last + in: + nums: [100, -1, 0] + out: 0 + - name: two-positive + in: + nums: [2, 3] + out: 1 + - name: two-negative + in: + nums: [-2, -3] + out: 1 + - name: one-negative + in: + nums: [-2, 3, 4] + out: -1 + - name: three-negative + in: + nums: [-2, -3, -4] + out: -1 + - name: four-negative + in: + nums: [-2, -3, -4, -5] + out: 1 + - name: all-ones + in: + nums: [1, 1, 1, 1, 1, 1] + out: 1 + - name: all-negative-ones-even + in: + nums: [-1, -1, -1, -1, -1, -1] + out: 1 + - name: all-negative-ones-odd + in: + nums: [-1, -1, -1, -1, -1] + out: -1 + - name: mixed-even-negatives + in: + nums: [-100, 100, -99, 99, 1] + out: 1 + - name: mixed-odd-negatives + in: + nums: [-100, 100, -99, 98] + out: 1 + - name: min-values + in: + nums: [-100, -100, -100] + out: -1 + - name: max-values + in: + nums: [100, 100, 100, 100] + out: 1 + - name: alternating-signs + in: + nums: [1, -2, 3, -4, 5, -6, 7] + out: -1 + - name: negative-with-zero + in: + nums: [-100, -99, -98, 0, -97] + out: 0 + - name: zero-with-only-positives + in: + nums: [1, 2, 3, 4, 0] + out: 0 + - name: repeated-positive + in: + nums: [7, 7, 7, 7, 7] + out: 1 + - name: repeated-negative-even + in: + nums: [-7, -7, -7, -7] + out: 1 + - name: repeated-negative-odd + in: + nums: [-7, -7, -7] + out: -1 + - name: small-magnitudes + in: + nums: [-1, 2, -3, 4, -5, 6] + out: -1 + - name: negative-zero-negative + in: + nums: [-1, 0, -1] + out: 0 + - name: long-static-positive + in: + nums: + [ + 2, + 4, + 6, + 8, + 10, + 12, + 14, + 16, + 18, + 20, + 22, + 24, + 26, + 28, + 30, + 32, + 34, + 36, + 38, + 40, + ] + out: 1 + - name: long-static-negative + in: + nums: + [ + -2, + 4, + 6, + -8, + 10, + 12, + 14, + 16, + -18, + 20, + 22, + 24, + 26, + 28, + 30, + 32, + 34, + 36, + 38, + 40, + -42, + ] + out: 1 + - name: boundary-mix + in: + nums: [-100, -1, 0, 1, 100] + out: 0 + - name: positive-after-cancellation + in: + nums: [-100, -1, 1, 100] + out: 1 + - name: negative-boundary-odd + in: + nums: [-100, 1, 1, 1] + out: -1 + - name: generated-small + in: + nums: + gen: "array" + len: 7 + of: + gen: "int" + min: -100 + max: 100 + distinct: false + elemType: "int" + - name: generated-medium + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: -100 + max: 100 + distinct: false + elemType: "int" + - name: generated-large + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: -100 + max: 100 + distinct: false + elemType: "int" + - name: generated-large-nonzero + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: -100 + max: 100 + distinct: false + elemType: "int" diff --git a/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.cpp b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.cpp new file mode 100644 index 00000000..46fab005 --- /dev/null +++ b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int arraySign(vector& nums) { + for (int num : nums) { + if (num == 0) return 0; + } + int negatives = 0; + for (int num : nums) negatives += num < 0; + return negatives % 2 == 0 ? 1 : -1; + } +}; diff --git a/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.cs b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.cs new file mode 100644 index 00000000..3ef5a9b4 --- /dev/null +++ b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.cs @@ -0,0 +1,10 @@ +public class Solution { + public int ArraySign(int[] nums) { + foreach (int num in nums) { + if (num == 0) return 0; + } + int negatives = 0; + foreach (int num in nums) if (num < 0) negatives++; + return negatives % 2 == 0 ? 1 : -1; + } +} diff --git a/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.dart b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.dart new file mode 100644 index 00000000..d0144e02 --- /dev/null +++ b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.dart @@ -0,0 +1,8 @@ +class Solution { + int arraySign(List nums) { + if (nums.contains(0)) return 0; + int negatives = 0; + for (int num in nums) if (num < 0) negatives++; + return negatives.isEven ? 1 : -1; + } +} diff --git a/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.go b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.go new file mode 100644 index 00000000..90d9da5d --- /dev/null +++ b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.go @@ -0,0 +1,13 @@ +func arraySign(nums []int) int { + for _, num := range nums { + if num == 0 { + return 0 + } + } + negatives := 0 + for _, num := range nums { if num < 0 { negatives++ } } + if negatives%2 == 0 { + return 1 + } + return -1 +} diff --git a/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.java b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.java new file mode 100644 index 00000000..af5d6a55 --- /dev/null +++ b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.java @@ -0,0 +1,10 @@ +class Solution { + public int arraySign(int[] nums) { + for (int num : nums) { + if (num == 0) return 0; + } + int negatives = 0; + for (int num : nums) if (num < 0) negatives++; + return negatives % 2 == 0 ? 1 : -1; + } +} diff --git a/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.kt b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.kt new file mode 100644 index 00000000..e8495692 --- /dev/null +++ b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.kt @@ -0,0 +1,8 @@ +class Solution { + fun arraySign(nums: IntArray): Int { + if (nums.contains(0)) return 0 + var negatives = 0 + for (num in nums) if (num < 0) negatives++ + return if (negatives % 2 == 0) 1 else -1 + } +} diff --git a/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.py b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.py new file mode 100644 index 00000000..77536d6b --- /dev/null +++ b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.py @@ -0,0 +1,5 @@ +class Solution: + def arraySign(self, nums: List[int]) -> int: + if 0 in nums: + return 0 + return 1 if sum(i < 0 for i in nums) % 2 == 0 else -1 diff --git a/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.py2 b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.py2 new file mode 100644 index 00000000..dae8f89b --- /dev/null +++ b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.py2 @@ -0,0 +1,9 @@ +class Solution(object): + def arraySign(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + if 0 in nums: + return 0 + return 1 if sum(i < 0 for i in nums) % 2 == 0 else -1 diff --git a/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.rb b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.rb new file mode 100644 index 00000000..446516af --- /dev/null +++ b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.rb @@ -0,0 +1,6 @@ +# @param {Integer[]} nums +# @return {Integer} +def array_sign(nums) + return 0 if nums.include?(0) + nums.count { |i| i < 0 }.even? ? 1 : -1 +end diff --git a/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.rs b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.rs new file mode 100644 index 00000000..54aaf996 --- /dev/null +++ b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn array_sign(nums: Vec) -> i32 { + if nums.contains(&0) { + return 0; + } + let negatives = nums.iter().filter(|&&num| num < 0).count(); + if negatives % 2 == 0 { + 1 + } else { + -1 + } + } +} diff --git a/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.swift b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.swift new file mode 100644 index 00000000..72a04892 --- /dev/null +++ b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.swift @@ -0,0 +1,9 @@ +class Solution { + func arraySign(_ nums: [Int]) -> Int { + if nums.contains(0) { + return 0 + } + let negatives = nums.filter { $0 < 0 }.count + return negatives % 2 == 0 ? 1 : -1 + } +} diff --git a/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.ts b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.ts new file mode 100644 index 00000000..f85af482 --- /dev/null +++ b/tests/1501-2000/1822. sign-of-the-product-of-an-array/sol.ts @@ -0,0 +1,5 @@ +function arraySign(nums: number[]): number { + if (nums.includes(0)) return 0; + const negatives = nums.filter((num) => num < 0).length; + return negatives % 2 === 0 ? 1 : -1; +} diff --git a/tests/1501-2000/1823. find-the-winner-of-the-circular-game/manifest.yaml b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/manifest.yaml new file mode 100644 index 00000000..a88a6ed6 --- /dev/null +++ b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/manifest.yaml @@ -0,0 +1,245 @@ +entry: + id: 1823 + title: "find-the-winner-of-the-circular-game" + params: + n: + type: int + k: + type: int + call: + cpp: "Solution().findTheWinner({n}, {k})" + rust: "Solution::find_the_winner({n}, {k})" + python3: "Solution().findTheWinner({n}, {k})" + python2: "Solution().findTheWinner({n}, {k})" + ruby: "find_the_winner({n}, {k})" + java: "new Solution().findTheWinner({n}, {k})" + csharp: "new Solution().FindTheWinner({n}, {k})" + kotlin: "Solution().findTheWinner({n}, {k})" + go: "findTheWinner({n}, {k})" + dart: "Solution().findTheWinner({n}, {k})" + swift: "Solution().findTheWinner({n}, {k})" + typescript: "findTheWinner({n}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().findTheWinner(n, k, {result})" + checker: | + class Checker: + def findTheWinner(self, n, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + winner = 0 + for size in range(2, n + 1): + winner = (winner + k) % size + return result == winner + 1 + +seed: 1823 + +tests: + - name: single + in: + n: 1 + k: 1 + out: 1 + - name: two-k-one + in: + n: 2 + k: 1 + out: 2 + - name: two-k-two + in: + n: 2 + k: 2 + out: 1 + - name: three-k-one + in: + n: 3 + k: 1 + out: 3 + - name: three-k-two + in: + n: 3 + k: 2 + out: 3 + - name: three-k-three + in: + n: 3 + k: 3 + out: 2 + - name: four-k-two + in: + n: 4 + k: 2 + out: 1 + - name: four-k-three + in: + n: 4 + k: 3 + out: 1 + - name: four-k-four + in: + n: 4 + k: 4 + out: 2 + - name: example-one + in: + n: 5 + k: 2 + out: 3 + - name: five-k-three + in: + n: 5 + k: 3 + out: 4 + - name: five-k-five + in: + n: 5 + k: 5 + out: 2 + - name: example-two + in: + n: 6 + k: 5 + out: 1 + - name: seven-k-one + in: + n: 7 + k: 1 + out: 7 + - name: seven-k-two + in: + n: 7 + k: 2 + out: 7 + - name: seven-k-seven + in: + n: 7 + k: 7 + out: 5 + - name: eight-k-three + in: + n: 8 + k: 3 + out: 7 + - name: eight-k-eight + in: + n: 8 + k: 8 + out: 4 + - name: nine-k-four + in: + n: 9 + k: 4 + out: 1 + - name: ten-k-two + in: + n: 10 + k: 2 + out: 5 + - name: ten-k-five + in: + n: 10 + k: 5 + out: 3 + - name: ten-k-ten + in: + n: 10 + k: 10 + out: 8 + - name: eleven-k-three + in: + n: 11 + k: 3 + out: 7 + - name: twelve-k-seven + in: + n: 12 + k: 7 + out: 12 + - name: thirteen-k-two + in: + n: 13 + k: 2 + out: 11 + - name: fifteen-k-four + in: + n: 15 + k: 4 + out: 13 + - name: sixteen-k-nine + in: + n: 16 + k: 9 + out: 8 + - name: twenty-k-one + in: + n: 20 + k: 1 + out: 20 + - name: twenty-k-two + in: + n: 20 + k: 2 + out: 9 + - name: twenty-k-seven + in: + n: 20 + k: 7 + out: 3 + - name: twenty-five-k-thirteen + in: + n: 25 + k: 13 + out: 14 + - name: fifty-k-seventeen + in: + n: 50 + k: 17 + out: 8 + - name: hundred-k-one + in: + n: 100 + k: 1 + out: 100 + - name: hundred-k-thirty-seven + in: + n: 100 + k: 37 + out: 45 + - name: two-hundred-k-two + in: + n: 200 + k: 2 + out: 145 + - name: two-hundred-k-one-ninety-nine + in: + n: 200 + k: 199 + out: 163 + - name: three-hundred-k-one-twenty-seven + in: + n: 300 + k: 127 + out: 150 + - name: four-hundred-k-two-fifty-one + in: + n: 400 + k: 251 + out: 234 + - name: maximum-k-one + in: + n: 500 + k: 1 + out: 500 + - name: maximum-k-maximum + in: + n: 500 + k: 500 + out: 69 diff --git a/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.cpp b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.cpp new file mode 100644 index 00000000..3dfb522e --- /dev/null +++ b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + int findTheWinner(int n, int k) { + int res = 0; + for (int i = 2; i <= n; i++) { + res = (res + k) % i; + } + return res + 1; + } +}; diff --git a/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.cs b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.cs new file mode 100644 index 00000000..147c48d4 --- /dev/null +++ b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.cs @@ -0,0 +1,9 @@ +public class Solution { + public int FindTheWinner(int n, int k) { + int res = 0; + for (int i = 2; i <= n; i++) { + res = (res + k) % i; + } + return res + 1; + } +} diff --git a/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.dart b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.dart new file mode 100644 index 00000000..8bd55340 --- /dev/null +++ b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.dart @@ -0,0 +1,9 @@ +class Solution { + int findTheWinner(int n, int k) { + int res = 0; + for (int i = 2; i <= n; i++) { + res = (res + k) % i; + } + return res + 1; + } +} diff --git a/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.go b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.go new file mode 100644 index 00000000..11e7fafa --- /dev/null +++ b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.go @@ -0,0 +1,7 @@ +func findTheWinner(n int, k int) int { + res := 0 + for i := 2; i <= n; i++ { + res = (res + k) % i + } + return res + 1 +} diff --git a/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.java b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.java new file mode 100644 index 00000000..4dfb17b0 --- /dev/null +++ b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.java @@ -0,0 +1,9 @@ +class Solution { + public int findTheWinner(int n, int k) { + int res = 0; + for (int i = 2; i <= n; i++) { + res = (res + k) % i; + } + return res + 1; + } +} diff --git a/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.kt b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.kt new file mode 100644 index 00000000..6b41ddb0 --- /dev/null +++ b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.kt @@ -0,0 +1,9 @@ +class Solution { + fun findTheWinner(n: Int, k: Int): Int { + var res = 0 + for (i in 2..n) { + res = (res + k) % i + } + return res + 1 + } +} diff --git a/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.py b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.py new file mode 100644 index 00000000..6c9ec78d --- /dev/null +++ b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.py @@ -0,0 +1,6 @@ +class Solution: + def findTheWinner(self, n: int, k: int) -> int: + res = 0 # this is the base case where n == 1 + for i in range(2, n + 1): + res = (res + k) % i + return res + 1 diff --git a/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.py2 b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.py2 new file mode 100644 index 00000000..03cad8b1 --- /dev/null +++ b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def findTheWinner(self, n, k): + """ + :type n: int + :type k: int + :rtype: int + """ + res = 0 + for i in range(2, n+1): + res = (res + k) % i + return res + 1 diff --git a/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.rb b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.rb new file mode 100644 index 00000000..b926ba28 --- /dev/null +++ b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.rb @@ -0,0 +1,7 @@ +def find_the_winner(n, k) + res = 0 + (2..n).each do |i| + res = (res + k) % i + end + res + 1 +end diff --git a/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.rs b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.rs new file mode 100644 index 00000000..775160ed --- /dev/null +++ b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.rs @@ -0,0 +1,9 @@ +impl Solution { + pub fn find_the_winner(n: i32, k: i32) -> i32 { + let mut res = 0; + for i in 2..=n { + res = (res + k) % i; + } + res + 1 + } +} diff --git a/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.swift b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.swift new file mode 100644 index 00000000..170d3a61 --- /dev/null +++ b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.swift @@ -0,0 +1,10 @@ +class Solution { + func findTheWinner(_ n: Int, _ k: Int) -> Int { + if n == 1 { return 1 } + var res = 0 + for i in 2...n { + res = (res + k) % i + } + return res + 1 + } +} diff --git a/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.ts b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.ts new file mode 100644 index 00000000..5f6815d7 --- /dev/null +++ b/tests/1501-2000/1823. find-the-winner-of-the-circular-game/sol.ts @@ -0,0 +1,7 @@ +function findTheWinner(n: number, k: number): number { + let res = 0; + for (let i = 2; i <= n; i++) { + res = (res + k) % i; + } + return res + 1; +} diff --git a/tests/1501-2000/1824. minimum-sideway-jumps/manifest.yaml b/tests/1501-2000/1824. minimum-sideway-jumps/manifest.yaml new file mode 100644 index 00000000..24aa66c0 --- /dev/null +++ b/tests/1501-2000/1824. minimum-sideway-jumps/manifest.yaml @@ -0,0 +1,231 @@ +entry: + id: 1824 + title: "minimum-sideway-jumps" + params: + obstacles: + type: array + items: + type: int + call: + cpp: "Solution().minSideJumps({obstacles})" + rust: "Solution::min_side_jumps({obstacles})" + python3: "Solution().minSideJumps({obstacles})" + python2: "Solution().minSideJumps({obstacles})" + ruby: "min_side_jumps({obstacles})" + java: "new Solution().minSideJumps({obstacles})" + csharp: "new Solution().MinSideJumps({obstacles})" + kotlin: "Solution().minSideJumps({obstacles})" + go: "minSideJumps({obstacles})" + dart: "Solution().minSideJumps({obstacles})" + swift: "Solution().minSideJumps({obstacles})" + typescript: "minSideJumps({obstacles})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().minSideJumps(obstacles, {result})" + checker: | + class Checker: + def minSideJumps(self, obstacles, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not isinstance(obstacles, list) or len(obstacles) < 2: + return False + if obstacles[0] != 0 or obstacles[-1] != 0: + return False + dp = [1, 0, 1] + inf = 10 ** 9 + for obstacle in obstacles[1:]: + if obstacle not in (0, 1, 2, 3): + return False + for lane in range(3): + if obstacle == lane + 1: + dp[lane] = inf + for lane in range(3): + if obstacle != lane + 1: + dp[lane] = min(dp[lane], min(dp[(lane + 1) % 3], dp[(lane + 2) % 3]) + 1) + return result == min(dp) + +seed: 1824 + +tests: + - name: "example_one" + in: + obstacles: [0, 1, 2, 3, 0] + out: 2 + - name: "example_two" + in: + obstacles: [0, 1, 1, 3, 3, 0] + out: 0 + - name: "example_three" + in: + obstacles: [0, 2, 1, 0, 3, 0] + out: 2 + - name: "empty_road" + in: + obstacles: [0, 0] + out: 0 + - name: "single_lane_one" + in: + obstacles: [0, 1, 0] + out: 0 + - name: "single_lane_two" + in: + obstacles: [0, 2, 0] + out: 1 + - name: "single_lane_three" + in: + obstacles: [0, 3, 0] + out: 0 + - name: "all_clear_short" + in: + obstacles: [0, 0, 0, 0] + out: 0 + - name: "repeat_lane_one" + in: + obstacles: [0, 1, 0, 1, 0] + out: 0 + - name: "repeat_lane_two" + in: + obstacles: [0, 2, 0, 2, 0] + out: 1 + - name: "repeat_lane_three" + in: + obstacles: [0, 3, 0, 3, 0] + out: 0 + - name: "three_points_lane_one_two" + in: + obstacles: [0, 1, 2, 0] + out: 1 + - name: "three_points_lane_two_three" + in: + obstacles: [0, 2, 3, 0] + out: 1 + - name: "three_points_lane_three_two" + in: + obstacles: [0, 3, 2, 0] + out: 1 + - name: "forced_three_jumps_a" + in: + obstacles: [0, 1, 2, 3, 1, 0] + out: 3 + - name: "forced_three_jumps_b" + in: + obstacles: [0, 3, 2, 1, 3, 0] + out: 3 + - name: "alternating_low" + in: + obstacles: [0, 1, 2, 1, 2, 0] + out: 1 + - name: "alternating_high" + in: + obstacles: [0, 2, 3, 2, 3, 0] + out: 1 + - name: "safe_lane_one" + in: + obstacles: [0, 3, 1, 3, 1, 0] + out: 0 + - name: "mixed_switches_one" + in: + obstacles: [0, 1, 3, 2, 1, 0] + out: 2 + - name: "mixed_switches_two" + in: + obstacles: [0, 2, 1, 3, 2, 0] + out: 3 + - name: "mixed_switches_three" + in: + obstacles: [0, 3, 2, 1, 3, 0] + out: 3 + - name: "duplicate_obstacles_one" + in: + obstacles: [0, 1, 1, 2, 2, 3, 0] + out: 2 + - name: "duplicate_obstacles_two" + in: + obstacles: [0, 3, 3, 2, 2, 1, 0] + out: 2 + - name: "periodic_pattern_one" + in: + obstacles: [0, 1, 2, 3, 0, 1, 2, 0] + out: 3 + - name: "periodic_pattern_two" + in: + obstacles: [0, 2, 3, 1, 0, 2, 3, 0] + out: 3 + - name: "periodic_pattern_three" + in: + obstacles: [0, 3, 1, 2, 0, 3, 1, 0] + out: 2 + - name: "deep_switches_one" + in: + obstacles: [0, 1, 2, 1, 3, 2, 1, 0] + out: 4 + - name: "deep_switches_two" + in: + obstacles: [0, 2, 3, 2, 1, 3, 2, 0] + out: 4 + - name: "deep_switches_three" + in: + obstacles: [0, 3, 1, 3, 2, 1, 3, 0] + out: 3 + - name: "zero_gaps_one" + in: + obstacles: [0, 1, 0, 2, 0, 3, 0, 1, 0] + out: 2 + - name: "zero_gaps_two" + in: + obstacles: [0, 2, 0, 3, 0, 1, 0, 2, 0] + out: 2 + - name: "zero_gaps_three" + in: + obstacles: [0, 3, 0, 1, 0, 2, 0, 3, 0] + out: 1 + - name: "long_forced_one" + in: + obstacles: [0, 1, 2, 3, 1, 2, 3, 1, 0] + out: 6 + - name: "long_forced_two" + in: + obstacles: [0, 3, 2, 1, 3, 2, 1, 3, 0] + out: 6 + - name: "long_mixed_one" + in: + obstacles: [0, 1, 3, 1, 2, 3, 2, 1, 0] + out: 3 + - name: "long_mixed_two" + in: + obstacles: [0, 2, 1, 2, 3, 1, 3, 2, 0] + out: 4 + - name: "long_mixed_three" + in: + obstacles: [0, 3, 2, 3, 1, 2, 1, 3, 0] + out: 4 + - name: "stress_all_clear_a" + in: + obstacles: + gen: "array" + len: 500000 + of: + gen: "int" + min: 0 + max: 0 + elemType: "int" + out: 0 + - name: "stress_all_clear_b" + in: + obstacles: + gen: "array" + len: 499999 + of: + gen: "int" + min: 0 + max: 0 + elemType: "int" + out: 0 diff --git a/tests/1501-2000/1824. minimum-sideway-jumps/sol.cpp b/tests/1501-2000/1824. minimum-sideway-jumps/sol.cpp new file mode 100644 index 00000000..270cf79a --- /dev/null +++ b/tests/1501-2000/1824. minimum-sideway-jumps/sol.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int minSideJumps(vector& obstacles) { + const int INF = INT_MAX / 2; + vector dp = {1, 0, 1}; + for (int i = 1; i < obstacles.size(); i++) { + int obs = obstacles[i]; + for (int j = 0; j < 3; j++) { + if (obs == j + 1) dp[j] = INF; + } + for (int j = 0; j < 3; j++) { + if (obs != j + 1) { + dp[j] = min(dp[j], min(dp[(j + 1) % 3], dp[(j + 2) % 3]) + 1); + } + } + } + return min({dp[0], dp[1], dp[2]}); + } +}; diff --git a/tests/1501-2000/1824. minimum-sideway-jumps/sol.cs b/tests/1501-2000/1824. minimum-sideway-jumps/sol.cs new file mode 100644 index 00000000..029fadca --- /dev/null +++ b/tests/1501-2000/1824. minimum-sideway-jumps/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public int MinSideJumps(int[] obstacles) { + int INF = int.MaxValue / 2; + int[] dp = { 1, 0, 1 }; + for (int i = 1; i < obstacles.Length; i++) { + int obs = obstacles[i]; + for (int j = 0; j < 3; j++) { + if (obs == j + 1) dp[j] = INF; + } + for (int j = 0; j < 3; j++) { + if (obs != j + 1) { + dp[j] = Math.Min(dp[j], Math.Min(dp[(j + 1) % 3], dp[(j + 2) % 3]) + 1); + } + } + } + return Math.Min(dp[0], Math.Min(dp[1], dp[2])); + } +} diff --git a/tests/1501-2000/1824. minimum-sideway-jumps/sol.dart b/tests/1501-2000/1824. minimum-sideway-jumps/sol.dart new file mode 100644 index 00000000..18aeb7a8 --- /dev/null +++ b/tests/1501-2000/1824. minimum-sideway-jumps/sol.dart @@ -0,0 +1,19 @@ +class Solution { + int minSideJumps(List obstacles) { + final INF = 1 << 30; + List dp = [1, 0, 1]; + for (int i = 1; i < obstacles.length; i++) { + int obs = obstacles[i]; + for (int j = 0; j < 3; j++) { + if (obs == j + 1) dp[j] = INF; + } + for (int j = 0; j < 3; j++) { + if (obs != j + 1) { + int minVal = (dp[(j + 1) % 3] < dp[(j + 2) % 3]) ? dp[(j + 1) % 3] : dp[(j + 2) % 3]; + if (dp[j] > minVal + 1) dp[j] = minVal + 1; + } + } + } + return dp.reduce((a, b) => a < b ? a : b); + } +} diff --git a/tests/1501-2000/1824. minimum-sideway-jumps/sol.go b/tests/1501-2000/1824. minimum-sideway-jumps/sol.go new file mode 100644 index 00000000..03474cac --- /dev/null +++ b/tests/1501-2000/1824. minimum-sideway-jumps/sol.go @@ -0,0 +1,30 @@ +func minSideJumps(obstacles []int) int { + INF := int(^uint(0) >> 1) / 2 + dp := []int{1, 0, 1} + for i := 1; i < len(obstacles); i++ { + obs := obstacles[i] + for j := 0; j < 3; j++ { + if obs == j+1 { + dp[j] = INF + } + } + for j := 0; j < 3; j++ { + if obs != j+1 { + minVal := dp[(j+1)%3] + if dp[(j+2)%3] < minVal { + minVal = dp[(j+2)%3] + } + if dp[j] > minVal+1 { + dp[j] = minVal + 1 + } + } + } + } + result := dp[0] + for _, v := range dp { + if v < result { + result = v + } + } + return result +} diff --git a/tests/1501-2000/1824. minimum-sideway-jumps/sol.java b/tests/1501-2000/1824. minimum-sideway-jumps/sol.java new file mode 100644 index 00000000..c6893623 --- /dev/null +++ b/tests/1501-2000/1824. minimum-sideway-jumps/sol.java @@ -0,0 +1,18 @@ +class Solution { + public int minSideJumps(int[] obstacles) { + int INF = Integer.MAX_VALUE / 2; + int[] dp = {1, 0, 1}; + for (int i = 1; i < obstacles.length; i++) { + int obs = obstacles[i]; + for (int j = 0; j < 3; j++) { + if (obs == j + 1) dp[j] = INF; + } + for (int j = 0; j < 3; j++) { + if (obs != j + 1) { + dp[j] = Math.min(dp[j], Math.min(dp[(j + 1) % 3], dp[(j + 2) % 3]) + 1); + } + } + } + return Math.min(dp[0], Math.min(dp[1], dp[2])); + } +} diff --git a/tests/1501-2000/1824. minimum-sideway-jumps/sol.kt b/tests/1501-2000/1824. minimum-sideway-jumps/sol.kt new file mode 100644 index 00000000..936b5d46 --- /dev/null +++ b/tests/1501-2000/1824. minimum-sideway-jumps/sol.kt @@ -0,0 +1,18 @@ +class Solution { + fun minSideJumps(obstacles: IntArray): Int { + val INF = Int.MAX_VALUE / 2 + var dp = intArrayOf(1, 0, 1) + for (i in 1 until obstacles.size) { + val obs = obstacles[i] + for (j in 0..2) { + if (obs == j + 1) dp[j] = INF + } + for (j in 0..2) { + if (obs != j + 1) { + dp[j] = minOf(dp[j], minOf(dp[(j + 1) % 3], dp[(j + 2) % 3]) + 1) + } + } + } + return dp.minOrNull() ?: 0 + } +} diff --git a/tests/1501-2000/1824. minimum-sideway-jumps/sol.py b/tests/1501-2000/1824. minimum-sideway-jumps/sol.py new file mode 100644 index 00000000..59aeeb61 --- /dev/null +++ b/tests/1501-2000/1824. minimum-sideway-jumps/sol.py @@ -0,0 +1,20 @@ +class Solution(object): + def minSideJumps(self, obstacles): + """ + :type obstacles: List[int] + :rtype: int + """ + INF = float("inf") + dp = [1, 0, 1] + + for i in range(1, len(obstacles)): + obs = obstacles[i] + for j in range(3): + if obs == j + 1: + dp[j] = INF + + for j in range(3): + if obs != j + 1: + dp[j] = min(dp[j], min(dp[(j + 1) % 3], dp[(j + 2) % 3]) + 1) + + return min(dp) diff --git a/tests/1501-2000/1824. minimum-sideway-jumps/sol.py2 b/tests/1501-2000/1824. minimum-sideway-jumps/sol.py2 new file mode 100644 index 00000000..ff14def5 --- /dev/null +++ b/tests/1501-2000/1824. minimum-sideway-jumps/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def minSideJumps(self, obstacles): + """ + :type obstacles: List[int] + :rtype: int + """ + INF = float('inf') + dp = [1, 0, 1] + + for i in range(1, len(obstacles)): + obs = obstacles[i] + for j in range(3): + if obs == j + 1: + dp[j] = INF + + for j in range(3): + if obs != j + 1: + dp[j] = min(dp[j], min(dp[(j + 1) % 3], dp[(j + 2) % 3]) + 1) + + return min(dp) diff --git a/tests/1501-2000/1824. minimum-sideway-jumps/sol.rb b/tests/1501-2000/1824. minimum-sideway-jumps/sol.rb new file mode 100644 index 00000000..eb461b8c --- /dev/null +++ b/tests/1501-2000/1824. minimum-sideway-jumps/sol.rb @@ -0,0 +1,18 @@ +# @param {Integer[]} obstacles +# @return {Integer} +def min_side_jumps(obstacles) + inf = 1.0/0.0 + dp = [1, 0, 1] + (1...obstacles.length).each do |i| + obs = obstacles[i] + (0...3).each do |j| + dp[j] = inf if obs == j + 1 + end + (0...3).each do |j| + if obs != j + 1 + dp[j] = [dp[j], [dp[(j + 1) % 3], dp[(j + 2) % 3]].min + 1].min + end + end + end + dp.min +end diff --git a/tests/1501-2000/1824. minimum-sideway-jumps/sol.rs b/tests/1501-2000/1824. minimum-sideway-jumps/sol.rs new file mode 100644 index 00000000..b3a0d113 --- /dev/null +++ b/tests/1501-2000/1824. minimum-sideway-jumps/sol.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn min_side_jumps(obstacles: Vec) -> i32 { + let inf = i32::MAX / 2; + let mut dp = vec![1, 0, 1]; + for i in 1..obstacles.len() { + let obs = obstacles[i]; + for j in 0..3 { + if obs == (j + 1) as i32 { + dp[j] = inf; + } + } + for j in 0..3 { + if obs != (j + 1) as i32 { + let min_val = dp[(j + 1) % 3].min(dp[(j + 2) % 3]); + dp[j] = dp[j].min(min_val + 1); + } + } + } + dp.into_iter().min().unwrap() + } +} diff --git a/tests/1501-2000/1824. minimum-sideway-jumps/sol.swift b/tests/1501-2000/1824. minimum-sideway-jumps/sol.swift new file mode 100644 index 00000000..9b3ca1af --- /dev/null +++ b/tests/1501-2000/1824. minimum-sideway-jumps/sol.swift @@ -0,0 +1,18 @@ +class Solution { + func minSideJumps(_ obstacles: [Int]) -> Int { + let INF = Int.max / 2 + var dp = [1, 0, 1] + for i in 1.. 10000 for x in nums): + return False + current = nums[0] + expected = 0 + for value in nums[1:]: + current = max(current + 1, value) + expected += current - value + return result == expected + +seed: 1827 + +tests: + - name: "example_equal_three" + in: + nums: [1, 1, 1] + out: 3 + - name: "example_mixed" + in: + nums: [1, 5, 2, 4, 1] + out: 14 + - name: "example_single" + in: + nums: [8] + out: 0 + - name: "already_increasing" + in: + nums: [1, 2, 3, 4, 5] + out: 0 + - name: "strict_decrease" + in: + nums: [5, 4, 3, 2, 1] + out: 20 + - name: "two_equal" + in: + nums: [7, 7] + out: 1 + - name: "two_increasing" + in: + nums: [9999, 10000] + out: 0 + - name: "two_decreasing" + in: + nums: [10000, 1] + out: 10000 + - name: "all_ones_four" + in: + nums: [1, 1, 1, 1] + out: 6 + - name: "all_ones_ten" + in: + nums: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 45 + - name: "constant_five" + in: + nums: [5, 5, 5, 5, 5] + out: 10 + - name: "plateau_then_jump" + in: + nums: [2, 2, 2, 10] + out: 3 + - name: "jump_then_plateau" + in: + nums: [2, 10, 10, 10] + out: 3 + - name: "late_low" + in: + nums: [1, 2, 3, 1] + out: 3 + - name: "low_after_large" + in: + nums: [1, 100, 1] + out: 100 + - name: "alternating_low_high" + in: + nums: [1, 10, 1, 10, 1] + out: 24 + - name: "alternating_high_low" + in: + nums: [10, 1, 10, 1, 10, 1] + out: 42 + - name: "minimum_values" + in: + nums: [1, 2] + out: 0 + - name: "maximum_values_equal" + in: + nums: [10000, 10000] + out: 1 + - name: "maximum_values_three" + in: + nums: [10000, 10000, 10000] + out: 3 + - name: "large_gap" + in: + nums: [1, 10000, 1] + out: 10000 + - name: "interleaved" + in: + nums: [3, 1, 4, 1, 5, 1] + out: 18 + - name: "descending_four" + in: + nums: [4, 3, 2, 1] + out: 12 + - name: "one_drop" + in: + nums: [1, 2, 8, 3, 4] + out: 12 + - name: "already_high_start" + in: + nums: [100, 101, 102] + out: 0 + - name: "repeated_boundary" + in: + nums: [9998, 9998, 9998, 9998] + out: 6 + - name: "small_wave" + in: + nums: [2, 1, 2, 1, 2] + out: 12 + - name: "long_ramp_after_drop" + in: + nums: [1, 2, 3, 4, 1, 2, 3] + out: 12 + - name: "large_first" + in: + nums: [10000, 1, 1, 1] + out: 30003 + - name: "single_max" + in: + nums: [10000] + out: 0 + - name: "strict_steps" + in: + nums: [2, 4, 6, 8, 10] + out: 0 + - name: "duplicate_middle" + in: + nums: [1, 3, 3, 5] + out: 1 + - name: "multiple_duplicate_blocks" + in: + nums: [1, 1, 3, 3, 5, 5] + out: 3 + - name: "decrease_at_end" + in: + nums: [4, 5, 6, 1] + out: 6 + - name: "large_monotone_values" + in: + nums: [9990, 9991, 9992, 9993, 9994] + out: 0 + - name: "generated_small" + seed: 1001 + in: + nums: + gen: "array" + len: + gen: "int" + min: 1 + max: 25 + of: + gen: "int" + min: 1 + max: 50 + - name: "generated_medium" + seed: 1002 + in: + nums: + gen: "array" + len: + gen: "int" + min: 100 + max: 300 + of: + gen: "int" + min: 1 + max: 10000 + - name: "generated_large" + seed: 1003 + in: + nums: + gen: "array" + len: 5000 + of: + gen: "int" + min: 1 + max: 10000 + - name: "generated_large_low_range" + seed: 1004 + in: + nums: + gen: "array" + len: 5000 + of: + gen: "int" + min: 1 + max: 5 + - name: "generated_large_high_range" + seed: 1005 + in: + nums: + gen: "array" + len: 5000 + of: + gen: "int" + min: 9990 + max: 10000 diff --git a/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.cpp b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.cpp new file mode 100644 index 00000000..7ec6e48a --- /dev/null +++ b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int minOperations(vector& nums) { + int c = nums[0]; + int s = 0; + for (int i = 1; i < nums.size(); i++) { + if (nums[i] > c) { + c = nums[i]; + } else { + c++; + s += c - nums[i]; + } + } + return s; + } +}; diff --git a/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.cs b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.cs new file mode 100644 index 00000000..a73445e2 --- /dev/null +++ b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int MinOperations(int[] nums) { + int c = nums[0]; + int s = 0; + for (int i = 1; i < nums.Length; i++) { + if (nums[i] > c) { + c = nums[i]; + } else { + c++; + s += c - nums[i]; + } + } + return s; + } +} diff --git a/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.dart b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.dart new file mode 100644 index 00000000..83b6b3eb --- /dev/null +++ b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.dart @@ -0,0 +1,15 @@ +class Solution { + int minOperations(List nums) { + int current = nums[0]; + int operations = 0; + for (int i = 1; i < nums.length; i++) { + if (nums[i] <= current) { + current++; + operations += current - nums[i]; + } else { + current = nums[i]; + } + } + return operations; + } +} diff --git a/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.go b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.go new file mode 100644 index 00000000..b6446212 --- /dev/null +++ b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.go @@ -0,0 +1,13 @@ +func minOperations(nums []int) int { + c := nums[0] + s := 0 + for i := 1; i < len(nums); i++ { + if nums[i] > c { + c = nums[i] + } else { + c++ + s += c - nums[i] + } + } + return s +} diff --git a/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.java b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.java new file mode 100644 index 00000000..49792ce5 --- /dev/null +++ b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.java @@ -0,0 +1,15 @@ +class Solution { + public int minOperations(int[] nums) { + int c = nums[0]; + int s = 0; + for (int i = 1; i < nums.length; i++) { + if (nums[i] > c) { + c = nums[i]; + } else { + c++; + s += c - nums[i]; + } + } + return s; + } +} diff --git a/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.kt b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.kt new file mode 100644 index 00000000..031167eb --- /dev/null +++ b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun minOperations(nums: IntArray): Int { + var c = nums[0] + var s = 0 + for (i in 1 until nums.size) { + if (nums[i] > c) { + c = nums[i] + } else { + c++ + s += c - nums[i] + } + } + return s + } +} diff --git a/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.py b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.py new file mode 100644 index 00000000..eadc44e2 --- /dev/null +++ b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.py @@ -0,0 +1,11 @@ +class Solution(object): + def minOperations(self, nums): + c = nums[0] + s = 0 + for i in range(1, len(nums)): + if nums[i] > c: + c = nums[i] + else: + c += 1 + s += abs(c - nums[i]) + return s diff --git a/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.py2 b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.py2 new file mode 100644 index 00000000..4d5816b3 --- /dev/null +++ b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def minOperations(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + c=nums[0] + s=0 + for i in range(1,len(nums)): + if nums[i]>c: + c=nums[i] + else: + c+=1 + s+=abs(c-nums[i]) + return s diff --git a/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.rb b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.rb new file mode 100644 index 00000000..725f1665 --- /dev/null +++ b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.rb @@ -0,0 +1,15 @@ +# @param {Integer[]} nums +# @return {Integer} +def min_operations(nums) + c = nums[0] + s = 0 + (1...nums.length).each do |i| + if nums[i] > c + c = nums[i] + else + c += 1 + s += (c - nums[i]).abs + end + end + s +end diff --git a/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.rs b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.rs new file mode 100644 index 00000000..b5bee996 --- /dev/null +++ b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn min_operations(nums: Vec) -> i32 { + let mut c = nums[0]; + let mut s = 0; + for i in 1..nums.len() { + if nums[i] > c { + c = nums[i]; + } else { + c += 1; + s += c - nums[i]; + } + } + s + } +} diff --git a/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.swift b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.swift new file mode 100644 index 00000000..def12c2e --- /dev/null +++ b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func minOperations(_ nums: [Int]) -> Int { + var c = nums[0] + var s = 0 + for i in 1.. c { + c = nums[i] + } else { + c += 1 + s += c - nums[i] + } + } + return s + } +} diff --git a/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.ts b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.ts new file mode 100644 index 00000000..6786740a --- /dev/null +++ b/tests/1501-2000/1827. minimum-operations-to-make-the-array-increasing/sol.ts @@ -0,0 +1,13 @@ +function minOperations(nums: number[]): number { + let c = nums[0]; + let s = 0; + for (let i = 1; i < nums.length; i++) { + if (nums[i] > c) { + c = nums[i]; + } else { + c++; + s += c - nums[i]; + } + } + return s; +} diff --git a/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/manifest.yaml b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/manifest.yaml new file mode 100644 index 00000000..15ed9258 --- /dev/null +++ b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/manifest.yaml @@ -0,0 +1,543 @@ +entry: + id: 1828 + title: "queries-on-number-of-points-inside-a-circle" + params: + points: + type: array + items: + type: array + items: + type: int + queries: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().countPoints({points}, {queries})" + rust: "Solution::count_points({points}, {queries})" + python3: "Solution().countPoints({points}, {queries})" + python2: "Solution().countPoints({points}, {queries})" + ruby: "count_points({points}, {queries})" + java: "new Solution().countPoints({points}, {queries})" + csharp: "new Solution().CountPoints({points}, {queries})" + kotlin: "Solution().countPoints({points}, {queries})" + go: "countPoints({points}, {queries})" + dart: "Solution().countPoints({points}, {queries})" + swift: "Solution().countPoints({points}, {queries})" + typescript: "countPoints({points}, {queries})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().countPoints(points, queries, {result})" + checker: | + class Checker: + def countPoints(self, points, queries, result): + if not isinstance(result, list) or len(result) != len(queries): + return False + expected = [] + for qx, qy, r in queries: + rr = r * r + expected.append(sum((qx - x) * (qx - x) + (qy - y) * (qy - y) <= rr for x, y in points)) + return result == expected + +seed: 1828 + +tests: + - name: "example_one" + in: + points: + - [1, 3] + - [3, 3] + - [5, 3] + - [2, 2] + queries: + - [2, 3, 1] + - [4, 3, 1] + - [1, 1, 2] + out: [3, 2, 2] + - name: "example_two" + in: + points: + - [1, 1] + - [2, 2] + - [3, 3] + - [4, 4] + - [5, 5] + queries: + - [1, 2, 2] + - [2, 2, 2] + - [4, 3, 2] + - [4, 3, 3] + out: [2, 3, 2, 4] + - name: "single_inside" + in: + points: + - [0, 0] + queries: + - [0, 0, 1] + out: [1] + - name: "single_outside" + in: + points: + - [0, 0] + queries: + - [1, 1, 1] + out: [0] + - name: "border_horizontal" + in: + points: + - [0, 0] + - [2, 0] + - [1, 0] + - [3, 0] + queries: + - [1, 0, 1] + out: [3] + - name: "border_vertical" + in: + points: + - [0, 0] + - [0, 2] + - [0, 1] + - [0, 3] + queries: + - [0, 1, 1] + out: [3] + - name: "corner_border" + in: + points: + - [0, 0] + - [1, 1] + - [2, 2] + queries: + - [0, 0, 1] + out: [1] + - name: "duplicates" + in: + points: + - [5, 5] + - [5, 5] + - [5, 5] + - [5, 6] + queries: + - [5, 5, 1] + - [0, 0, 1] + out: [4, 0] + - name: "zero_radius_not_allowed_radius_one" + in: + points: + - [10, 10] + - [10, 11] + - [11, 10] + - [11, 11] + queries: + - [10, 10, 1] + out: [3] + - name: "far_apart" + in: + points: + - [0, 0] + - [500, 500] + queries: + - [0, 0, 1] + - [500, 500, 1] + - [250, 250, 500] + out: [1, 1, 2] + - name: "max_radius_covers_all" + in: + points: + - [0, 0] + - [500, 0] + - [0, 500] + - [500, 500] + queries: + - [250, 250, 500] + out: [4] + - name: "max_coordinates" + in: + points: + - [500, 500] + - [499, 500] + - [500, 499] + - [0, 0] + queries: + - [500, 500, 1] + - [0, 0, 1] + out: [3, 1] + - name: "negative_relative_positions" + in: + points: + - [0, 0] + - [0, 1] + - [1, 0] + - [1, 1] + queries: + - [0, 0, 2] + - [1, 1, 1] + out: [4, 3] + - name: "nested_circles" + in: + points: + - [2, 2] + - [3, 2] + - [4, 2] + - [5, 2] + - [6, 2] + queries: + - [4, 2, 1] + - [4, 2, 2] + - [4, 2, 3] + out: [3, 5, 5] + - name: "many_queries_same_center" + in: + points: + - [0, 0] + - [1, 0] + - [2, 0] + - [3, 0] + - [4, 0] + queries: + - [0, 0, 1] + - [0, 0, 2] + - [0, 0, 3] + - [0, 0, 4] + out: [2, 3, 4, 5] + - name: "many_points_same_query" + in: + points: + - [1, 1] + - [1, 1] + - [2, 1] + - [2, 2] + - [3, 3] + queries: + - [1, 1, 1] + - [1, 1, 2] + out: [3, 4] + - name: "diagonal_border" + in: + points: + - [0, 0] + - [3, 4] + - [4, 3] + - [6, 8] + queries: + - [0, 0, 5] + - [0, 0, 4] + out: [3, 1] + - name: "asymmetric_cluster" + in: + points: + - [10, 10] + - [10, 20] + - [20, 10] + - [20, 20] + - [15, 15] + queries: + - [15, 15, 7] + - [15, 15, 8] + out: [1, 5] + - name: "queries_order_preserved" + in: + points: + - [0, 0] + - [10, 0] + - [20, 0] + queries: + - [20, 0, 1] + - [0, 0, 20] + - [10, 0, 1] + out: [1, 3, 1] + - name: "small_grid" + in: + points: + - [0, 0] + - [0, 1] + - [0, 2] + - [1, 0] + - [1, 1] + - [1, 2] + - [2, 0] + - [2, 1] + - [2, 2] + queries: + - [1, 1, 1] + - [1, 1, 2] + out: [5, 9] + - name: "thin_strip" + in: + points: + - [0, 250] + - [100, 250] + - [200, 250] + - [300, 250] + - [400, 250] + - [500, 250] + queries: + - [250, 250, 100] + - [250, 250, 250] + out: [2, 6] + - name: "corner_query" + in: + points: + - [0, 0] + - [0, 1] + - [1, 0] + - [1, 1] + - [2, 2] + queries: + - [0, 0, 1] + - [0, 0, 2] + out: [3, 4] + - name: "overlap_regions" + in: + points: + - [4, 4] + - [5, 4] + - [6, 4] + - [5, 5] + - [5, 6] + queries: + - [5, 4, 1] + - [5, 5, 1] + out: [4, 3] + - name: "large_radius_center_edge" + in: + points: + - [0, 0] + - [500, 0] + - [0, 500] + - [500, 500] + - [250, 250] + queries: + - [0, 0, 500] + - [500, 500, 500] + out: [4, 4] + - name: "alternating_queries" + in: + points: + - [1, 1] + - [9, 9] + - [5, 5] + - [1, 9] + - [9, 1] + queries: + - [1, 1, 1] + - [5, 5, 6] + - [9, 9, 1] + - [0, 0, 20] + out: [1, 5, 1, 5] + - name: "repeated_boundary_points" + in: + points: + - [2, 0] + - [2, 0] + - [-2, 0] + - [-2, 0] + - [0, 2] + - [0, -2] + queries: + - [0, 0, 2] + - [0, 0, 1] + out: [6, 0] + - name: "offset_circle" + in: + points: + - [10, 10] + - [11, 10] + - [10, 11] + - [12, 12] + - [13, 10] + queries: + - [10, 10, 2] + - [11, 11, 1] + out: [3, 2] + - name: "two_point_queries" + in: + points: + - [100, 100] + - [400, 400] + queries: + - [100, 100, 1] + - [250, 250, 500] + - [400, 400, 1] + out: [1, 2, 1] + - name: "dense_center" + in: + points: + - [250, 250] + - [250, 250] + - [249, 250] + - [251, 250] + - [250, 249] + - [250, 251] + - [248, 248] + queries: + - [250, 250, 1] + - [250, 250, 3] + out: [6, 7] + - name: "far_query_order" + in: + points: + - [1, 1] + - [2, 2] + - [3, 3] + - [100, 100] + queries: + - [500, 500, 1] + - [1, 1, 1] + - [50, 50, 500] + out: [0, 1, 4] + - name: "generated_small" + seed: 182801 + in: + points: + gen: "array" + len: + gen: "int" + min: 1 + max: 20 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 20 + elemType: "int" + queries: + gen: "array" + len: + gen: "int" + min: 1 + max: 15 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 0 + max: 20 + elemType: "int" + + - name: "generated_medium" + seed: 182802 + in: + points: + gen: "array" + len: + gen: "int" + min: 100 + max: 150 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 500 + elemType: "int" + queries: + gen: "array" + len: + gen: "int" + min: 80 + max: 120 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 0 + max: 500 + elemType: "int" + - name: "generated_large_a" + seed: 182803 + in: + points: + gen: "array" + len: 500 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 500 + elemType: "int" + queries: + gen: "array" + len: 500 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 0 + max: 500 + elemType: "int" + - name: "generated_large_b" + seed: 182804 + in: + points: + gen: "array" + len: 500 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 0 + max: 500 + elemType: "int" + queries: + gen: "array" + len: 500 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 0 + max: 500 + elemType: "int" + - name: "generated_duplicates" + seed: 182805 + in: + points: + gen: "array" + len: + gen: "int" + min: 200 + max: 300 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 245 + max: 255 + elemType: "int" + queries: + gen: "array" + len: + gen: "int" + min: 100 + max: 200 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 245 + max: 255 + elemType: "int" diff --git a/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.cpp b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.cpp new file mode 100644 index 00000000..adbcade4 --- /dev/null +++ b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector countPoints(vector>& points, vector>& queries) { + vector result(queries.size(), 0); + for (int i = 0; i < queries.size(); i++) { + for (int j = 0; j < points.size(); j++) { + int dx = queries[i][0] - points[j][0]; + int dy = queries[i][1] - points[j][1]; + if (dx * dx + dy * dy <= queries[i][2] * queries[i][2]) { + result[i]++; + } + } + } + return result; + } +}; diff --git a/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.cs b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.cs new file mode 100644 index 00000000..981ce372 --- /dev/null +++ b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int[] CountPoints(int[][] points, int[][] queries) { + int[] result = new int[queries.Length]; + for (int i = 0; i < queries.Length; i++) { + for (int j = 0; j < points.Length; j++) { + int dx = queries[i][0] - points[j][0]; + int dy = queries[i][1] - points[j][1]; + if (dx * dx + dy * dy <= queries[i][2] * queries[i][2]) { + result[i]++; + } + } + } + return result; + } +} diff --git a/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.dart b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.dart new file mode 100644 index 00000000..c7bb564f --- /dev/null +++ b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.dart @@ -0,0 +1,15 @@ +class Solution { + List countPoints(List> points, List> queries) { + List result = List.filled(queries.length, 0); + for (int i = 0; i < queries.length; i++) { + for (int j = 0; j < points.length; j++) { + int dx = queries[i][0] - points[j][0]; + int dy = queries[i][1] - points[j][1]; + if (dx * dx + dy * dy <= queries[i][2] * queries[i][2]) { + result[i]++; + } + } + } + return result; + } +} diff --git a/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.go b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.go new file mode 100644 index 00000000..fd60f8ba --- /dev/null +++ b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.go @@ -0,0 +1,13 @@ +func countPoints(points [][]int, queries [][]int) []int { + result := make([]int, len(queries)) + for i := 0; i < len(queries); i++ { + for j := 0; j < len(points); j++ { + dx := queries[i][0] - points[j][0] + dy := queries[i][1] - points[j][1] + if dx*dx + dy*dy <= queries[i][2]*queries[i][2] { + result[i]++ + } + } + } + return result +} diff --git a/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.java b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.java new file mode 100644 index 00000000..3d581328 --- /dev/null +++ b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int[] countPoints(int[][] points, int[][] queries) { + int[] result = new int[queries.length]; + for (int i = 0; i < queries.length; i++) { + for (int j = 0; j < points.length; j++) { + if ((Math.pow(queries[i][0] - points[j][0], 2) + Math.pow(queries[i][1] - points[j][1], 2)) <= Math.pow(queries[i][2], 2)) { + result[i]++; + } + } + } + return result; + } +} diff --git a/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.kt b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.kt new file mode 100644 index 00000000..78d0d206 --- /dev/null +++ b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun countPoints(points: Array, queries: Array): IntArray { + val result = IntArray(queries.size) + for (i in queries.indices) { + for (j in points.indices) { + if ((Math.pow((queries[i][0] - points[j][0]).toDouble(), 2.0) + Math.pow((queries[i][1] - points[j][1]).toDouble(), 2.0)) <= Math.pow(queries[i][2].toDouble(), 2.0)) { + result[i]++ + } + } + } + return result + } +} diff --git a/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.py b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.py new file mode 100644 index 00000000..51dcd24c --- /dev/null +++ b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.py @@ -0,0 +1,16 @@ +class Solution(object): + def countPoints(self, points, queries): + """ + :type points: List[List[int]] + :type queries: List[List[int]] + :rtype: List[int] + """ + b = [0] * len(queries) + for i in range(len(queries)): + for j in range(len(points)): + if ( + ((queries[i][0] - points[j][0]) ** 2) + + ((queries[i][1] - points[j][1]) ** 2) + ) <= queries[i][2] ** 2: + b[i] += 1 + return b diff --git a/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.py2 b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.py2 new file mode 100644 index 00000000..2556c604 --- /dev/null +++ b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.py2 @@ -0,0 +1,13 @@ +class Solution(object): + def countPoints(self, points, queries): + """ + :type points: List[List[int]] + :type queries: List[List[int]] + :rtype: List[int] + """ + b=[0]*len(queries) + for i in range(len(queries)): + for j in range(len(points)): + if (((queries[i][0]-points[j][0])**2)+((queries[i][1]-points[j][1])**2))<=queries[i][2]**2: + b[i]+=1 + return b diff --git a/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.rb b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.rb new file mode 100644 index 00000000..b164799a --- /dev/null +++ b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[][]} points +# @param {Integer[][]} queries +# @return {Integer[]} +def count_points(points, queries) + b = Array.new(queries.length, 0) + (0...queries.length).each do |i| + (0...points.length).each do |j| + if ((queries[i][0]-points[j][0])**2 + (queries[i][1]-points[j][1])**2) <= queries[i][2]**2 + b[i] += 1 + end + end + end + b +end diff --git a/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.rs b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.rs new file mode 100644 index 00000000..bfde2cfb --- /dev/null +++ b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn count_points(points: Vec>, queries: Vec>) -> Vec { + let mut result = vec![0; queries.len()]; + for i in 0..queries.len() { + for j in 0..points.len() { + let dx = queries[i][0] - points[j][0]; + let dy = queries[i][1] - points[j][1]; + if dx * dx + dy * dy <= queries[i][2] * queries[i][2] { + result[i] += 1; + } + } + } + result + } +} diff --git a/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.swift b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.swift new file mode 100644 index 00000000..105efeaf --- /dev/null +++ b/tests/1501-2000/1828. queries-on-number-of-points-inside-a-circle/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func countPoints(_ points: [[Int]], _ queries: [[Int]]) -> [Int] { + var result = Array(repeating: 0, count: queries.count) + for i in 0.. getMaximumXor(vector& nums, int maximumBit) { + int n = nums.size(); + vector ans(n); + int mask = (1 << maximumBit) - 1; + int curr = 0; + for (int i = 0; i < n; i++) { + curr ^= nums[i]; + ans[n - 1 - i] = mask ^ curr; + } + return ans; + } +}; diff --git a/tests/1501-2000/1829. maximum-xor-for-each-query/sol.cs b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.cs new file mode 100644 index 00000000..a6edf089 --- /dev/null +++ b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public int[] GetMaximumXor(int[] nums, int maximumBit) { + int n = nums.Length; + int[] ans = new int[n]; + int mask = (1 << maximumBit) - 1; + int curr = 0; + for (int i = 0; i < n; i++) { + curr ^= nums[i]; + ans[n - 1 - i] = mask ^ curr; + } + return ans; + } +} diff --git a/tests/1501-2000/1829. maximum-xor-for-each-query/sol.dart b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.dart new file mode 100644 index 00000000..b50bc605 --- /dev/null +++ b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.dart @@ -0,0 +1,13 @@ +class Solution { + List getMaximumXor(List nums, int maximumBit) { + int n = nums.length; + List ans = List.filled(n, 0); + int mask = (1 << maximumBit) - 1; + int curr = 0; + for (int i = 0; i < n; i++) { + curr ^= nums[i]; + ans[n - 1 - i] = mask ^ curr; + } + return ans; + } +} diff --git a/tests/1501-2000/1829. maximum-xor-for-each-query/sol.go b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.go new file mode 100644 index 00000000..46346c30 --- /dev/null +++ b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.go @@ -0,0 +1,11 @@ +func getMaximumXor(nums []int, maximumBit int) []int { + n := len(nums) + ans := make([]int, n) + mask := (1 << maximumBit) - 1 + curr := 0 + for i, num := range nums { + curr ^= num + ans[n - 1 - i] = mask ^ curr + } + return ans +} diff --git a/tests/1501-2000/1829. maximum-xor-for-each-query/sol.java b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.java new file mode 100644 index 00000000..bd9b271f --- /dev/null +++ b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int[] getMaximumXor(int[] nums, int maximumBit) { + int n = nums.length; + int[] ans = new int[n]; + int mask = (1 << maximumBit) - 1; + int curr = 0; + for (int i = 0; i < n; i++) { + curr ^= nums[i]; + ans[n - 1 - i] = mask ^ curr; + } + return ans; + } +} diff --git a/tests/1501-2000/1829. maximum-xor-for-each-query/sol.kt b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.kt new file mode 100644 index 00000000..a21c432a --- /dev/null +++ b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun getMaximumXor(nums: IntArray, maximumBit: Int): IntArray { + val n = nums.size + val ans = IntArray(n) + val mask = (1 shl maximumBit) - 1 + var curr = 0 + for (i in 0 until n) { + curr = curr xor nums[i] + ans[n - 1 - i] = mask xor curr + } + return ans + } +} diff --git a/tests/1501-2000/1829. maximum-xor-for-each-query/sol.py b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.py new file mode 100644 index 00000000..06f08181 --- /dev/null +++ b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.py @@ -0,0 +1,14 @@ +class Solution(object): + def getMaximumXor(self, nums, maximumBit): + ans = [] + s = [] + a = nums[0] + s.append(a) + mask = 2**maximumBit - 1 + for i in range(1, len(nums)): + a ^= nums[i] + s.append(a) + for i in range(len(nums)): + m = s[len(nums) - i - 1] + ans.append(mask ^ m) + return ans diff --git a/tests/1501-2000/1829. maximum-xor-for-each-query/sol.py2 b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.py2 new file mode 100644 index 00000000..1c6cce97 --- /dev/null +++ b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def getMaximumXor(self, nums, maximumBit): + """ + :type nums: List[int] + :type maximumBit: int + :rtype: List[int] + """ + ans = [] + n = len(nums) + mask = (1 << maximumBit) - 1 + curr = 0 + for i in range(n): + curr ^= nums[i] + ans.append(mask ^ curr) + ans.reverse() + return ans diff --git a/tests/1501-2000/1829. maximum-xor-for-each-query/sol.rb b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.rb new file mode 100644 index 00000000..d5db287d --- /dev/null +++ b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.rb @@ -0,0 +1,13 @@ +# @param {Integer[]} nums +# @param {Integer} maximum_bit +# @return {Integer[]} +def get_maximum_xor(nums, maximum_bit) + ans = [] + mask = (1 << maximum_bit) - 1 + curr = 0 + nums.each do |num| + curr ^= num + ans.unshift(mask ^ curr) + end + ans +end diff --git a/tests/1501-2000/1829. maximum-xor-for-each-query/sol.rs b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.rs new file mode 100644 index 00000000..b71e4825 --- /dev/null +++ b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn get_maximum_xor(nums: Vec, maximum_bit: i32) -> Vec { + let n = nums.len(); + let mut ans = vec![0; n]; + let mask = (1 << maximum_bit) - 1; + let mut curr = 0; + for i in 0..n { + curr ^= nums[i]; + ans[n - 1 - i] = mask ^ curr; + } + ans + } +} diff --git a/tests/1501-2000/1829. maximum-xor-for-each-query/sol.swift b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.swift new file mode 100644 index 00000000..fac7c7b5 --- /dev/null +++ b/tests/1501-2000/1829. maximum-xor-for-each-query/sol.swift @@ -0,0 +1,13 @@ +class Solution { + func getMaximumXor(_ nums: [Int], _ maximumBit: Int) -> [Int] { + let n = nums.count + var ans = [Int](repeating: 0, count: n) + let mask = (1 << maximumBit) - 1 + var curr = 0 + for i in 0.. fac(n + 1, 1); + vector invFac(n + 1, 1); + + for (int i = 1; i <= n; i++) { + fac[i] = (fac[i - 1] * i) % MOD; + } + invFac[n] = modPow(fac[n], MOD - 2); + for (int i = n; i > 0; i--) { + invFac[i - 1] = (invFac[i] * i) % MOD; + } + + vector freq(26, 0); + for (char c : s) { + freq[c - 'a']++; + } + + long long ans = 0; + for (int i = 0; i < n; i++) { + int smallRight = 0; + for (int j = 0; j < s[i] - 'a'; j++) { + smallRight = (smallRight + freq[j]) % MOD; + } + + int rem = n - i - 1; + long long temp = 1; + temp = (temp * fac[rem]) % MOD; + temp = (temp * smallRight) % MOD; + + for (int x : freq) { + if (x > 1) { + temp = (temp * invFac[x]) % MOD; + } + } + + freq[s[i] - 'a']--; + ans = (ans + temp) % MOD; + } + + return (int) ans; + } + +private: + long long modPow(long long x, long long n) { + const int MOD = 1000000007; + if (x == 1 || n == 0) return 1; + if (n == 1) return x % MOD; + if (n % 2 == 1) { + return (x * modPow((x * x) % MOD, n / 2)) % MOD; + } + return modPow((x * x) % MOD, n / 2) % MOD; + } +}; diff --git a/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.cs b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.cs new file mode 100644 index 00000000..54304ea6 --- /dev/null +++ b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.cs @@ -0,0 +1,55 @@ +public class Solution { + private const int MOD = 1000000007; + + public int MakeStringSorted(string s) { + int n = s.Length; + long[] fac = new long[n + 1]; + long[] invFac = new long[n + 1]; + fac[0] = 1; + for (int i = 1; i <= n; i++) { + fac[i] = (fac[i - 1] * i) % MOD; + } + invFac[n] = ModPow(fac[n], MOD - 2); + for (int i = n; i > 0; i--) { + invFac[i - 1] = (invFac[i] * i) % MOD; + } + + int[] freq = new int[26]; + foreach (char c in s) { + freq[c - 'a']++; + } + + long ans = 0; + for (int i = 0; i < n; i++) { + int smallRight = 0; + for (int j = 0; j < s[i] - 'a'; j++) { + smallRight = (smallRight + freq[j]) % MOD; + } + + int rem = n - i - 1; + long temp = 1; + temp = (temp * fac[rem]) % MOD; + temp = (temp * smallRight) % MOD; + + foreach (int x in freq) { + if (x > 1) { + temp = (temp * invFac[x]) % MOD; + } + } + + freq[s[i] - 'a']--; + ans = (ans + temp) % MOD; + } + + return (int) ans; + } + + private long ModPow(long x, long n) { + if (x == 1 || n == 0) return 1; + if (n == 1) return x % MOD; + if (n % 2 == 1) { + return (x * ModPow((x * x) % MOD, n / 2)) % MOD; + } + return ModPow((x * x) % MOD, n / 2) % MOD; + } +} diff --git a/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.dart b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.dart new file mode 100644 index 00000000..46aad927 --- /dev/null +++ b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.dart @@ -0,0 +1,54 @@ +class Solution { + int makeStringSorted(String s) { + const int MOD = 1000000007; + int n = s.length; + List fac = List.filled(n + 1, 1); + List invFac = List.filled(n + 1, 1); + + for (int i = 1; i <= n; i++) { + fac[i] = (fac[i - 1] * i) % MOD; + } + invFac[n] = modPow(fac[n], MOD - 2, MOD); + for (int i = n; i > 0; i--) { + invFac[i - 1] = (invFac[i] * i) % MOD; + } + + List freq = List.filled(26, 0); + for (int i = 0; i < n; i++) { + freq[s.codeUnitAt(i) - 97]++; + } + + int ans = 0; + for (int i = 0; i < n; i++) { + int smallRight = 0; + for (int j = 0; j < s.codeUnitAt(i) - 97; j++) { + smallRight = (smallRight + freq[j]) % MOD; + } + + int rem = n - i - 1; + int temp = 1; + temp = (temp * fac[rem]) % MOD; + temp = (temp * smallRight) % MOD; + + for (int x in freq) { + if (x > 1) { + temp = (temp * invFac[x]) % MOD; + } + } + + freq[s.codeUnitAt(i) - 97]--; + ans = (ans + temp) % MOD; + } + + return ans; + } + + int modPow(int x, int n, int mod) { + if (x == 1 || n == 0) return 1; + if (n == 1) return x % mod; + if (n % 2 == 1) { + return (x * modPow((x * x) % mod, n ~/ 2, mod)) % mod; + } + return modPow((x * x) % mod, n ~/ 2, mod) % mod; + } +} diff --git a/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.go b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.go new file mode 100644 index 00000000..3148cd91 --- /dev/null +++ b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.go @@ -0,0 +1,56 @@ +func makeStringSorted(s string) int { + const MOD = 1000000007 + n := len(s) + fac := make([]int64, n+1) + invFac := make([]int64, n+1) + fac[0] = 1 + for i := 1; i <= n; i++ { + fac[i] = (fac[i-1] * int64(i)) % MOD + } + invFac[n] = modPow(fac[n], int64(MOD-2), int64(MOD)) + for i := n; i > 0; i-- { + invFac[i-1] = (invFac[i] * int64(i)) % MOD + } + + freq := make([]int, 26) + for _, ch := range s { + freq[ch-'a']++ + } + + var ans int64 = 0 + for i := 0; i < n; i++ { + smallRight := 0 + for j := 0; j < int(s[i]-'a'); j++ { + smallRight = (smallRight + freq[j]) % MOD + } + + rem := n - i - 1 + temp := int64(1) + temp = (temp * fac[rem]) % MOD + temp = (temp * int64(smallRight)) % MOD + + for _, x := range freq { + if x > 1 { + temp = (temp * invFac[x]) % MOD + } + } + + freq[s[i]-'a']-- + ans = (ans + temp) % MOD + } + + return int(ans) +} + +func modPow(x int64, n int64, mod int64) int64 { + if x == 1 || n == 0 { + return 1 + } + if n == 1 { + return x % mod + } + if n%2 == 1 { + return (x * modPow((x*x)%mod, n/2, mod)) % mod + } + return modPow((x*x)%mod, n/2, mod) % mod +} diff --git a/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.java b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.java new file mode 100644 index 00000000..168638ce --- /dev/null +++ b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.java @@ -0,0 +1,55 @@ +class Solution { + private static final int MOD = 1_000_000_007; + + public int makeStringSorted(String s) { + int n = s.length(); + long[] fac = new long[n + 1]; + long[] invFac = new long[n + 1]; + fac[0] = 1; + for (int i = 1; i <= n; i++) { + fac[i] = (fac[i - 1] * i) % MOD; + } + invFac[n] = modPow(fac[n], MOD - 2); + for (int i = n; i > 0; i--) { + invFac[i - 1] = (invFac[i] * i) % MOD; + } + + int[] freq = new int[26]; + for (char c : s.toCharArray()) { + freq[c - 'a']++; + } + + long ans = 0; + for (int i = 0; i < n; i++) { + int smallRight = 0; + for (int j = 0; j < s.charAt(i) - 'a'; j++) { + smallRight = (smallRight + freq[j]) % MOD; + } + + int rem = n - i - 1; + long temp = 1; + temp = (temp * fac[rem]) % MOD; + temp = (temp * smallRight) % MOD; + + for (int x : freq) { + if (x > 1) { + temp = (temp * invFac[x]) % MOD; + } + } + + freq[s.charAt(i) - 'a']--; + ans = (ans + temp) % MOD; + } + + return (int) ans; + } + + private long modPow(long x, long n) { + if (x == 1 || n == 0) return 1; + if (n == 1) return x % MOD; + if (n % 2 == 1) { + return (x * modPow((x * x) % MOD, n / 2)) % MOD; + } + return modPow((x * x) % MOD, n / 2) % MOD; + } +} diff --git a/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.kt b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.kt new file mode 100644 index 00000000..31394559 --- /dev/null +++ b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.kt @@ -0,0 +1,54 @@ +class Solution { + fun makeStringSorted(s: String): Int { + val MOD = 1_000_000_007 + val n = s.length + val fac = LongArray(n + 1) + val invFac = LongArray(n + 1) + fac[0] = 1 + for (i in 1..n) { + fac[i] = (fac[i - 1] * i) % MOD + } + invFac[n] = modPow(fac[n], (MOD - 2).toLong(), MOD) + for (i in n downTo 1) { + invFac[i - 1] = (invFac[i] * i) % MOD + } + + val freq = IntArray(26) + for (c in s) { + freq[c - 'a']++ + } + + var ans = 0L + for (i in 0 until n) { + var smallRight = 0 + for (j in 0 until s[i] - 'a') { + smallRight = (smallRight + freq[j]) % MOD + } + + val rem = n - i - 1 + var temp = 1L + temp = (temp * fac[rem]) % MOD + temp = (temp * smallRight) % MOD + + for (x in freq) { + if (x > 1) { + temp = (temp * invFac[x]) % MOD + } + } + + freq[s[i] - 'a']-- + ans = (ans + temp) % MOD + } + + return ans.toInt() + } + + private fun modPow(x: Long, n: Long, mod: Int): Long { + if (x == 1L || n == 0L) return 1L + if (n == 1L) return x % mod + if (n % 2L == 1L) { + return (x * modPow((x * x) % mod, n / 2, mod)) % mod + } + return modPow((x * x) % mod, n / 2, mod) % mod + } +} diff --git a/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.py b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.py new file mode 100644 index 00000000..df026267 --- /dev/null +++ b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.py @@ -0,0 +1,49 @@ +class Solution: + MOD = 10**9 + 7 + + def makeStringSorted(self, s): + n = len(s) + fac = [1] * (n + 1) + invFac = [1] * (n + 1) + self.fillFactorial(fac, invFac, n) + + freq = [0] * 26 + for ch in s: + freq[ord(ch) - ord("a")] += 1 + + ans = 0 + for i in range(n): + smallRight = 0 + for j in range(ord(s[i]) - ord("a")): + smallRight += freq[j] % self.MOD + + rem = n - i - 1 + temp = 1 + temp = (temp * fac[rem]) % self.MOD + temp = (temp * smallRight) % self.MOD + + for x in freq: + if x > 1: + temp = (temp * invFac[x]) % self.MOD + + freq[ord(s[i]) - ord("a")] -= 1 + ans = (ans + temp) % self.MOD + + return ans % self.MOD + + def modPow(self, x, n): + if x == 1 or n == 0: + return 1 + if n == 1: + return x % self.MOD + + if n % 2: + return (x * self.modPow((x * x) % self.MOD, n // 2)) % self.MOD + return self.modPow((x * x) % self.MOD, n // 2) % self.MOD + + def fillFactorial(self, fac, invFac, n): + for i in range(1, n + 1): + fac[i] = (fac[i - 1] * i) % self.MOD + invFac[n] = self.modPow(fac[n], self.MOD - 2) + for i in range(n, 0, -1): + invFac[i - 1] = (invFac[i] * i) % self.MOD diff --git a/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.py2 b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.py2 new file mode 100644 index 00000000..73bc6515 --- /dev/null +++ b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.py2 @@ -0,0 +1,53 @@ +class Solution(object): + def makeStringSorted(self, s): + """ + :type s: str + :rtype: int + """ + MOD = 10**9 + 7 + self.MOD = MOD + n = len(s) + fac = [1] * (n + 1) + invFac = [1] * (n + 1) + self.fillFactorial(fac, invFac, n) + + freq = [0] * 26 + for ch in s: + freq[ord(ch) - ord('a')] += 1 + + ans = 0 + for i in range(n): + smallRight = 0 + for j in range(ord(s[i]) - ord('a')): + smallRight += freq[j] % MOD + + rem = n - i - 1 + temp = 1 + temp = (temp * fac[rem]) % MOD + temp = (temp * smallRight) % MOD + + for x in freq: + if x > 1: + temp = (temp * invFac[x]) % MOD + + freq[ord(s[i]) - ord('a')] -= 1 + ans = (ans + temp) % MOD + + return ans % MOD + + def modPow(self, x, n): + if x == 1 or n == 0: + return 1 + if n == 1: + return x % self.MOD + + if n % 2: + return (x * self.modPow((x * x) % self.MOD, n // 2)) % self.MOD + return self.modPow((x * x) % self.MOD, n // 2) % self.MOD + + def fillFactorial(self, fac, invFac, n): + for i in range(1, n + 1): + fac[i] = (fac[i - 1] * i) % self.MOD + invFac[n] = self.modPow(fac[n], self.MOD - 2) + for i in range(n, 0, -1): + invFac[i - 1] = (invFac[i] * i) % self.MOD diff --git a/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.rb b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.rb new file mode 100644 index 00000000..2e0c8171 --- /dev/null +++ b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.rb @@ -0,0 +1,59 @@ +# @param {String} s +# @return {Integer} +def make_string_sorted(s) + mod = 10**9 + 7 + n = s.length + fac = Array.new(n + 1, 1) + inv_fac = Array.new(n + 1, 1) + + (1..n).each do |i| + fac[i] = (fac[i-1] * i) % mod + end + inv_fac[n] = mod_pow(fac[n], mod - 2, mod) + (n).downto(1) do |i| + inv_fac[i-1] = (inv_fac[i] * i) % mod + end + + freq = Array.new(26, 0) + s.each_char do |ch| + freq[ch.ord - 'a'.ord] += 1 + end + + ans = 0 + (0...n).each do |i| + small_right = 0 + (0...(s[i].ord - 'a'.ord)).each do |j| + small_right += freq[j] % mod + end + + rem = n - i - 1 + temp = 1 + temp = (temp * fac[rem]) % mod + temp = (temp * small_right) % mod + + freq.each do |x| + if x > 1 + temp = (temp * inv_fac[x]) % mod + end + end + + freq[s[i].ord - 'a'.ord] -= 1 + ans = (ans + temp) % mod + end + + ans % mod +end + +def mod_pow(x, n, mod) + if x == 1 || n == 0 + return 1 + end + if n == 1 + return x % mod + end + + if n % 2 == 1 + return (x * mod_pow((x * x) % mod, n / 2, mod)) % mod + end + mod_pow((x * x) % mod, n / 2, mod) % mod +end diff --git a/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.rs b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.rs new file mode 100644 index 00000000..47302082 --- /dev/null +++ b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.rs @@ -0,0 +1,60 @@ +impl Solution { + pub fn make_string_sorted(s: String) -> i32 { + const MOD: i64 = 1_000_000_007; + let n = s.len(); + let chars: Vec = s.chars().collect(); + let mut fac = vec![1i64; n + 1]; + let mut inv_fac = vec![1i64; n + 1]; + + for i in 1..=n { + fac[i] = (fac[i - 1] * i as i64) % MOD; + } + inv_fac[n] = Solution::mod_pow(fac[n], MOD - 2); + for i in (1..=n).rev() { + inv_fac[i - 1] = (inv_fac[i] * i as i64) % MOD; + } + + let mut freq = vec![0i64; 26]; + for &ch in &chars { + freq[ch as usize - 97] += 1; + } + + let mut ans = 0i64; + for i in 0..n { + let mut small_right = 0i64; + for j in 0..(chars[i] as usize - 97) { + small_right = (small_right + freq[j]) % MOD; + } + + let rem = n - i - 1; + let mut temp = 1i64; + temp = (temp * fac[rem]) % MOD; + temp = (temp * small_right) % MOD; + + for &x in &freq { + if x > 1 { + temp = (temp * inv_fac[x as usize]) % MOD; + } + } + + freq[chars[i] as usize - 97] -= 1; + ans = (ans + temp) % MOD; + } + + ans as i32 + } + + fn mod_pow(mut x: i64, mut n: i64) -> i64 { + const MOD: i64 = 1_000_000_007; + if x == 1 || n == 0 { + return 1; + } + if n == 1 { + return x % MOD; + } + if n % 2 == 1 { + return (x * Solution::mod_pow((x * x) % MOD, n / 2)) % MOD; + } + Solution::mod_pow((x * x) % MOD, n / 2) % MOD + } +} diff --git a/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.swift b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.swift new file mode 100644 index 00000000..de2b37a4 --- /dev/null +++ b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.swift @@ -0,0 +1,60 @@ +class Solution { + func makeStringSorted(_ s: String) -> Int { + let MOD = 1_000_000_007 + let n = s.count + let chars = Array(s) + var fac = Array(repeating: 1, count: n + 1) + var invFac = Array(repeating: 1, count: n + 1) + + for i in 1...n { + fac[i] = (fac[i - 1] * i) % MOD + } + invFac[n] = modPow(fac[n], MOD - 2) + for i in stride(from: n, through: 1, by: -1) { + invFac[i - 1] = (invFac[i] * i) % MOD + } + + var freq = Array(repeating: 0, count: 26) + for ch in chars { + freq[Int(ch.asciiValue! - Character("a").asciiValue!)] += 1 + } + + var ans = 0 + for i in 0.. 1 { + temp = (temp * invFac[x]) % MOD + } + } + + freq[Int(chars[i].asciiValue! - Character("a").asciiValue!)] -= 1 + ans = (ans + temp) % MOD + } + + return ans + } + + private func modPow(_ x: Int, _ n: Int) -> Int { + let MOD = 1_000_000_007 + if x == 1 || n == 0 { + return 1 + } + if n == 1 { + return x % MOD + } + if n % 2 == 1 { + return (x * modPow((x * x) % MOD, n / 2)) % MOD + } + return modPow((x * x) % MOD, n / 2) % MOD + } +} diff --git a/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.ts b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.ts new file mode 100644 index 00000000..75110c56 --- /dev/null +++ b/tests/1501-2000/1830. minimum-number-of-operations-to-make-string-sorted/sol.ts @@ -0,0 +1,59 @@ +function makeStringSorted(s: string): number { + const MOD = 1000000007n; + const n = s.length; + const fac: number[] = Array(n + 1).fill(1); + const invFac: number[] = Array(n + 1).fill(1); + + for (let i = 1; i <= n; i++) { + fac[i] = Number((BigInt(fac[i - 1]) * BigInt(i)) % MOD); + } + invFac[n] = modPow(fac[n], Number(MOD) - 2); + for (let i = n; i > 0; i--) { + invFac[i - 1] = Number((BigInt(invFac[i]) * BigInt(i)) % MOD); + } + + const freq: number[] = Array(26).fill(0); + for (let i = 0; i < n; i++) { + freq[s.charCodeAt(i) - 97]++; + } + + let ans = 0; + for (let i = 0; i < n; i++) { + let smallRight = 0; + for (let j = 0; j < s.charCodeAt(i) - 97; j++) { + smallRight += freq[j]; + } + + const rem = n - i - 1; + let temp = 1; + temp = Number((BigInt(temp) * BigInt(fac[rem])) % MOD); + temp = Number((BigInt(temp) * BigInt(smallRight)) % MOD); + + for (const x of freq) { + if (x > 1) { + temp = Number((BigInt(temp) * BigInt(invFac[x])) % MOD); + } + } + + freq[s.charCodeAt(i) - 97]--; + ans = Number((BigInt(ans) + BigInt(temp)) % MOD); + } + + return ans; +} + +function modPow(x: number, n: number): number { + const MOD = 1000000007n; + if (x === 1 || n === 0) return 1; + if (n === 1) return Number(BigInt(x) % MOD); + if (n % 2 === 1) { + return Number( + (BigInt(x) * + BigInt( + modPow(Number((BigInt(x) * BigInt(x)) % MOD), Math.floor(n / 2)), + )) % + MOD, + ); + } + return modPow(Number((BigInt(x) * BigInt(x)) % MOD), Math.floor(n / 2)); +} diff --git a/tests/1501-2000/1832. check-if-the-sentence-is-pangram/manifest.yaml b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/manifest.yaml new file mode 100644 index 00000000..c077dda7 --- /dev/null +++ b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/manifest.yaml @@ -0,0 +1,196 @@ +entry: + id: 1832 + title: "check-if-the-sentence-is-pangram" + params: + sentence: + type: string + call: + cpp: "Solution().checkIfPangram({sentence})" + rust: "Solution::check_if_pangram({sentence})" + python3: "Solution().checkIfPangram({sentence})" + python2: "Solution().checkIfPangram({sentence})" + ruby: "check_if_pangram({sentence})" + java: "new Solution().checkIfPangram({sentence})" + csharp: "new Solution().CheckIfPangram({sentence})" + kotlin: "Solution().checkIfPangram({sentence})" + go: "checkIfPangram({sentence})" + dart: "Solution().checkIfPangram({sentence})" + swift: "Solution().checkIfPangram({sentence})" + typescript: "checkIfPangram({sentence})" +judge: + type: "exact" +limits: + time_ms: 200 + memory_mb: 300 +seed: 1832 +oracle: + python3: + call: "Checker().checkIfPangram(sentence, {result})" + checker: | + class Checker: + def checkIfPangram(self, sentence, result): + if not isinstance(result, bool): + return False + return result == (len(sentence) >= 26 and set(sentence) == set("abcdefghijklmnopqrstuvwxyz")) +tests: + - name: "example_full" + in: + sentence: "thequickbrownfoxjumpsoverthelazydog" + out: true + - name: "example_short" + in: + sentence: "leetcode" + out: false + - name: "alphabet" + in: + sentence: "abcdefghijklmnopqrstuvwxyz" + out: true + - name: "reverse" + in: + sentence: "zyxwvutsrqponmlkjihgfedcba" + out: true + - name: "missing_a" + in: + sentence: "bcdefghijklmnopqrstuvwxyz" + out: false + - name: "missing_z" + in: + sentence: "abcdefghijklmnopqrstuvwxy" + out: false + - name: "all_a" + in: + sentence: "aaaaaaaaaaaaaaaaaaaaaaaaaa" + out: false + - name: "single" + in: + sentence: "a" + out: false + - name: "two_extremes" + in: + sentence: "az" + out: false + - name: "each_twice" + in: + sentence: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" + out: true + - name: "rotated" + in: + sentence: "mnopqrstuvwxyzabcdefghijkl" + out: true + - name: "duplicate_a_missing_z" + in: + sentence: "abcdefghijklmnopqrstuvwxyza" + out: true + - name: "duplicate_z_missing_y" + in: + sentence: "abcdefghijklmnopqrstuvwxzz" + out: false + - name: "missing_b" + in: + sentence: "acdefghijklmnopqrstuvwxyz" + out: false + - name: "missing_m" + in: + sentence: "abcdefghijklssnopqrstuvwxyz" + out: false + - name: "missing_q" + in: + sentence: "abcdefghijklmnoprstuvwxyz" + out: false + - name: "missing_x" + in: + sentence: "abcdefghijklmnopqrstuvwyz" + out: false + - name: "chunks" + in: + sentence: "abcxyzdefuvwghistujklmnopqr" + out: true + - name: "alternating" + in: + sentence: "azbycxdwevfugthsirjqkplomn" + out: true + - name: "long_prefix" + in: + sentence: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabcdefghijklmnopqrstuvwxyz" + out: true + - name: "long_suffix" + in: + sentence: "abcdefghijklmnopqrstuvwxyz" + out: true + - name: "length_25" + in: + sentence: "abcdefghijklmnopqrstuvwxy" + out: false + - name: "length_26_duplicate" + in: + sentence: "abcdefghijklmnopqrstuvwxya" + out: false + - name: "first_half" + in: + sentence: "abcdefghijklm" + out: false + - name: "last_half" + in: + sentence: "nopqrstuvwxyz" + out: false + - name: "repeated_first" + in: + sentence: "abcdefghijklmnopqrstuvwxyzaaaaa" + out: true + - name: "repeated_last" + in: + sentence: "zzzzabcdefghijklmnopqrstuvwxyz" + out: true + - name: "almost_without_c" + in: + sentence: "abdefghijklmnopqrstuvwxyz" + out: false + - name: "almost_without_t" + in: + sentence: "abcdefghijklmnopqrsuvwxyz" + out: false + - name: "permuted_blocks" + in: + sentence: "zyxwvutsrqponmlkjihgfedcbaabcdefghijklmnopqrstuvwxyz" + out: true + - name: "gen_small" + seed: 1 + in: + sentence: + gen: "str" + len: + gen: "int" + min: 1 + max: 25 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: "gen_medium" + seed: 2 + in: + sentence: + gen: "str" + len: + gen: "int" + min: 26 + max: 100 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: "gen_large" + seed: 3 + in: + sentence: + gen: "str" + len: 1000 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: "gen_large_biased" + seed: 4 + in: + sentence: + gen: "str" + len: 1000 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: "gen_boundary" + seed: 5 + in: + sentence: + gen: "str" + len: 26 + alphabet: "abcdefghijklmnopqrstuvwxyz" diff --git a/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.cpp b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.cpp new file mode 100644 index 00000000..c1b364c9 --- /dev/null +++ b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + bool checkIfPangram(string sentence) { + if (sentence.length() < 26) return false; + + for (int i = 0; i < 26; i++) { + if (sentence.find((char)(97+i)) == string::npos) return false; + } + return true; + } +}; diff --git a/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.cs b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.cs new file mode 100644 index 00000000..6d8b49ab --- /dev/null +++ b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.cs @@ -0,0 +1,10 @@ +public class Solution { + public bool CheckIfPangram(string sentence) { + if (sentence.Length < 26) return false; + + for (int i = 0; i < 26; i++) { + if (!sentence.Contains((char)(97+i))) return false; + } + return true; + } +} diff --git a/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.dart b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.dart new file mode 100644 index 00000000..4c32280b --- /dev/null +++ b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.dart @@ -0,0 +1,10 @@ +class Solution { + bool checkIfPangram(String sentence) { + if (sentence.length < 26) return false; + + for (int i = 0; i < 26; i++) { + if (!sentence.contains(String.fromCharCode(97+i))) return false; + } + return true; + } +} diff --git a/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.go b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.go new file mode 100644 index 00000000..f1ab0d9c --- /dev/null +++ b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.go @@ -0,0 +1,12 @@ +func checkIfPangram(sentence string) bool { + if len(sentence) < 26 { + return false + } + + for i := 0; i < 26; i++ { + if !strings.ContainsRune(sentence, rune(97+i)) { + return false + } + } + return true +} diff --git a/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.java b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.java new file mode 100644 index 00000000..72b28272 --- /dev/null +++ b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.java @@ -0,0 +1,10 @@ +class Solution { + public boolean checkIfPangram(String sentence) { + if (sentence.length() < 26) return false; + + for (int i = 0; i < 26; i++) { + if (sentence.indexOf((char)(97+i)) == -1) return false; + } + return true; + } +} diff --git a/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.kt b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.kt new file mode 100644 index 00000000..ab7d77cd --- /dev/null +++ b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.kt @@ -0,0 +1,10 @@ +class Solution { + fun checkIfPangram(sentence: String): Boolean { + if (sentence.length < 26) return false + + for (i in 0 until 26) { + if ((97+i).toChar() !in sentence) return false + } + return true + } +} diff --git a/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.py b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.py new file mode 100644 index 00000000..25016958 --- /dev/null +++ b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.py @@ -0,0 +1,9 @@ +class Solution(object): + def checkIfPangram(self, sentence: str) -> bool: + if len(sentence) < 26: + return False + + for i in range(26): + if chr(97 + i) not in sentence: + return False + return True diff --git a/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.py2 b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.py2 new file mode 100644 index 00000000..03e5877d --- /dev/null +++ b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.py2 @@ -0,0 +1,13 @@ +class Solution(object): + def checkIfPangram(self, sentence): + """ + :type sentence: str + :rtype: bool + """ + if len(sentence) < 26: + return False + + for i in range(26): + if chr(97+i) not in sentence: + return False + return True diff --git a/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.rb b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.rb new file mode 100644 index 00000000..a09b4107 --- /dev/null +++ b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.rb @@ -0,0 +1,10 @@ +# @param {String} sentence +# @return {Boolean} +def check_if_pangram(sentence) + return false if sentence.length < 26 + + (0...26).each do |i| + return false unless sentence.include?((97+i).chr) + end + true +end diff --git a/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.rs b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.rs new file mode 100644 index 00000000..39624197 --- /dev/null +++ b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.rs @@ -0,0 +1,10 @@ +impl Solution { + pub fn check_if_pangram(sentence: String) -> bool { + if sentence.len() < 26 { return false; } + + for i in 0..26 { + if !sentence.contains((97+i as u8) as char) { return false; } + } + true + } +} diff --git a/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.swift b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.swift new file mode 100644 index 00000000..7b16eea3 --- /dev/null +++ b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.swift @@ -0,0 +1,10 @@ +class Solution { + func checkIfPangram(_ sentence: String) -> Bool { + if sentence.count < 26 { return false } + + for i in 0..<26 { + if !sentence.contains(String(UnicodeScalar(97+i)!)) { return false } + } + return true + } +} diff --git a/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.ts b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.ts new file mode 100644 index 00000000..85aae258 --- /dev/null +++ b/tests/1501-2000/1832. check-if-the-sentence-is-pangram/sol.ts @@ -0,0 +1,8 @@ +function checkIfPangram(sentence: string): boolean { + if (sentence.length < 26) return false; + + for (let i = 0; i < 26; i++) { + if (!sentence.includes(String.fromCharCode(97 + i))) return false; + } + return true; +} diff --git a/tests/1501-2000/1833. maximum-ice-cream-bars/manifest.yaml b/tests/1501-2000/1833. maximum-ice-cream-bars/manifest.yaml new file mode 100644 index 00000000..8ad6c59d --- /dev/null +++ b/tests/1501-2000/1833. maximum-ice-cream-bars/manifest.yaml @@ -0,0 +1,379 @@ +entry: + id: 1833 + title: maximum-ice-cream-bars + params: + costs: + type: array + items: + type: int + coins: + type: int + call: + cpp: "Solution().maxIceCream({costs}, {coins})" + rust: "Solution::max_ice_cream({costs}, {coins})" + python3: "Solution().maxIceCream({costs}, {coins})" + python2: "Solution().maxIceCream({costs}, {coins})" + ruby: "max_ice_cream({costs}, {coins})" + java: "new Solution().maxIceCream({costs}, {coins})" + csharp: "new Solution().MaxIceCream({costs}, {coins})" + kotlin: "Solution().maxIceCream({costs}, {coins})" + go: "maxIceCream({costs}, {coins})" + dart: "Solution().maxIceCream({costs}, {coins})" + swift: "Solution().maxIceCream({costs}, {coins})" + typescript: "maxIceCream({costs}, {coins})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxIceCream(costs, coins, {result})" + checker: | + class Checker: + def maxIceCream(self, costs, coins, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + remaining = coins + count = 0 + for cost in sorted(costs): + if cost > remaining: + break + remaining -= cost + count += 1 + return result == count + +seed: 1833 + +tests: + - name: example-one + in: + costs: [1, 3, 2, 4, 1] + coins: 7 + out: 4 + judge: + type: "exact" + - name: example-two-none + in: + costs: [10, 6, 8, 7, 7, 8] + coins: 5 + out: 0 + judge: + type: "exact" + - name: example-three-all + in: + costs: [1, 6, 3, 1, 2, 5] + coins: 20 + out: 6 + judge: + type: "exact" + - name: minimum-size-affordable + in: + costs: [1, 1] + coins: 1 + out: 1 + judge: + type: "exact" + - name: minimum-size-both + in: + costs: [100000, 100000] + coins: 100000 + out: 1 + judge: + type: "exact" + - name: all-equal-exact + in: + costs: [5, 5, 5, 5, 5] + coins: 15 + out: 3 + judge: + type: "exact" + - name: all-equal-too-small + in: + costs: [5, 5, 5, 5] + coins: 4 + out: 0 + judge: + type: "exact" + - name: all-equal-all + in: + costs: [7, 7, 7, 7] + coins: 28 + out: 4 + judge: + type: "exact" + - name: unsorted-cheap-late + in: + costs: [9, 8, 7, 1, 2, 3] + coins: 6 + out: 3 + judge: + type: "exact" + - name: cheapest-single + in: + costs: [100, 1, 100, 100] + coins: 1 + out: 1 + judge: + type: "exact" + - name: exact-total + in: + costs: [4, 1, 3, 2] + coins: 10 + out: 4 + judge: + type: "exact" + - name: one-short-of-total + in: + costs: [4, 1, 3, 2] + coins: 9 + out: 3 + judge: + type: "exact" + - name: duplicate-cheapest + in: + costs: [2, 2, 2, 9, 9] + coins: 7 + out: 3 + judge: + type: "exact" + - name: gaps-in-costs + in: + costs: [1, 100, 50, 25, 75] + coins: 76 + out: 3 + judge: + type: "exact" + - name: max-cost-values + in: + costs: [100000, 99999, 99998, 1] + coins: 199999 + out: 3 + judge: + type: "exact" + - name: coin-limit-one + in: + costs: [1, 2, 3, 4, 5] + coins: 1 + out: 1 + judge: + type: "exact" + - name: coin-limit-large + in: + costs: [1, 2, 3, 4, 5] + coins: 100000000 + out: 5 + judge: + type: "exact" + - name: many-ones + in: + costs: [1, 1, 1, 1, 1, 1, 50] + coins: 5 + out: 5 + judge: + type: "exact" + - name: cheap-plus-expensive + in: + costs: [1, 100000, 99999, 99998, 2] + coins: 100000 + out: 2 + judge: + type: "exact" + - name: balanced-six + in: + costs: [6, 5, 4, 3, 2, 1] + coins: 12 + out: 4 + judge: + type: "exact" + - name: repeated-small + in: + costs: [3, 3, 3, 4, 4, 4] + coins: 13 + out: 4 + judge: + type: "exact" + - name: zero-leftover + in: + costs: [2, 4, 6, 8] + coins: 12 + out: 3 + judge: + type: "exact" + - name: order-independent + in: + costs: [8, 1, 7, 2, 6, 3, 5, 4] + coins: 15 + out: 5 + judge: + type: "exact" + - name: one-affordable-among-max + in: + costs: [100000, 100000, 100000, 99999] + coins: 99999 + out: 1 + judge: + type: "exact" + - name: all-affordable-with-slack + in: + costs: [11, 13, 17, 19, 23] + coins: 100 + out: 5 + judge: + type: "exact" + - name: threshold-between-items + in: + costs: [2, 3, 5, 7, 11] + coins: 10 + out: 3 + judge: + type: "exact" + - name: large-count-small-cost + in: + costs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + coins: 7 + out: 7 + judge: + type: "exact" + - name: descending-costs + in: + costs: [20, 19, 18, 17, 16, 15, 14, 13] + coins: 65 + out: 4 + judge: + type: "exact" + - name: high-range-mix + in: + costs: [99990, 99991, 99992, 99993, 99994, 10, 11, 12] + coins: 99999 + out: 3 + judge: + type: "exact" + - name: single-cheapest + in: + costs: [42, 100, 99, 98, 97] + coins: 42 + out: 1 + judge: + type: "exact" + - name: all-cost-one + in: + costs: [1, 1, 1, 1, 1, 1, 1, 1] + coins: 8 + out: 8 + judge: + type: "exact" + - name: all-cost-max + in: + costs: [100000, 100000, 100000] + coins: 100000000 + out: 3 + judge: + type: "exact" + - name: five-with-remainder + in: + costs: [1, 2, 2, 3, 8, 13] + coins: 9 + out: 4 + judge: + type: "exact" + - name: alternating-extremes + in: + costs: [1, 100000, 1, 100000, 1, 100000] + coins: 100002 + out: 3 + judge: + type: "exact" + - name: max-n-small-prefix + in: + costs: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 3 + distinct: false + sorted: false + elemType: "int" + coins: + gen: "int" + min: 1 + max: 100000000 + judge: + type: "exact" + - name: max-n-wide-costs + in: + costs: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + coins: + gen: "int" + min: 1 + max: 100000000 + judge: + type: "exact" + - name: large-budget-small-range + in: + costs: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + coins: + gen: "int" + min: 1 + max: 100000000 + judge: + type: "exact" + - name: medium-random-costs + in: + costs: + gen: "array" + len: 25000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + coins: + gen: "int" + min: 1 + max: 100000000 + judge: + type: "exact" + - name: near-zero-budget-large + in: + costs: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + coins: + gen: "int" + min: 1 + max: 100 + judge: + type: "exact" diff --git a/tests/1501-2000/1833. maximum-ice-cream-bars/sol.cpp b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.cpp new file mode 100644 index 00000000..725383e6 --- /dev/null +++ b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int maxIceCream(vector& costs, int coins) { + int xMin = *min_element(costs.begin(), costs.end()); + int xMax = *max_element(costs.begin(), costs.end()); + vector freq(xMax + 1, 0); + for (int x : costs) { + freq[x]++; + xMin = min(xMin, x); + } + int cnt = 0; + for (int x = xMin; x <= xMax; x++) { + int f = freq[x]; + if (f == 0) continue; + int buy = min(coins / x, f); + if (buy == 0) break; + cnt += buy; + coins -= buy * x; + } + return cnt; + } +}; diff --git a/tests/1501-2000/1833. maximum-ice-cream-bars/sol.cs b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.cs new file mode 100644 index 00000000..5416fbb2 --- /dev/null +++ b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.cs @@ -0,0 +1,21 @@ +public class Solution { + public int MaxIceCream(int[] costs, int coins) { + int xMin = costs.Min(); + int xMax = costs.Max(); + int[] freq = new int[xMax + 1]; + foreach (int x in costs) { + freq[x]++; + xMin = Math.Min(xMin, x); + } + int cnt = 0; + for (int x = xMin; x <= xMax; x++) { + int f = freq[x]; + if (f == 0) continue; + int buy = Math.Min(coins / x, f); + if (buy == 0) break; + cnt += buy; + coins -= buy * x; + } + return cnt; + } +} diff --git a/tests/1501-2000/1833. maximum-ice-cream-bars/sol.dart b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.dart new file mode 100644 index 00000000..8293033f --- /dev/null +++ b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.dart @@ -0,0 +1,26 @@ +class Solution { + int maxIceCream(List costs, int coins) { + int xMin = costs[0]; + int xMax = costs[0]; + for (int x in costs) { + if (x < xMin) xMin = x; + if (x > xMax) xMax = x; + } + List freq = List.filled(xMax + 1, 0); + for (int x in costs) { + freq[x]++; + if (x < xMin) xMin = x; + } + int cnt = 0; + for (int x = xMin; x <= xMax; x++) { + int f = freq[x]; + if (f == 0) continue; + int buy = coins ~/ x; + if (buy > f) buy = f; + if (buy == 0) break; + cnt += buy; + coins -= buy * x; + } + return cnt; + } +} diff --git a/tests/1501-2000/1833. maximum-ice-cream-bars/sol.go b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.go new file mode 100644 index 00000000..d34abd78 --- /dev/null +++ b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.go @@ -0,0 +1,24 @@ +func maxIceCream(costs []int, coins int) int { + xMin := costs[0] + xMax := costs[0] + for _, x := range costs { + if x < xMin { xMin = x } + if x > xMax { xMax = x } + } + freq := make([]int, xMax+1) + for _, x := range costs { + freq[x]++ + if x < xMin { xMin = x } + } + cnt := 0 + for x := xMin; x <= xMax; x++ { + f := freq[x] + if f == 0 { continue } + buy := coins / x + if buy > f { buy = f } + if buy == 0 { break } + cnt += buy + coins -= buy * x + } + return cnt +} diff --git a/tests/1501-2000/1833. maximum-ice-cream-bars/sol.java b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.java new file mode 100644 index 00000000..ba667d43 --- /dev/null +++ b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.java @@ -0,0 +1,24 @@ +class Solution { + public int maxIceCream(int[] costs, int coins) { + int xMin = costs[0], xMax = costs[0]; + for (int x : costs) { + xMin = Math.min(xMin, x); + xMax = Math.max(xMax, x); + } + int[] freq = new int[xMax + 1]; + for (int x : costs) { + freq[x]++; + xMin = Math.min(xMin, x); + } + int cnt = 0; + for (int x = xMin; x <= xMax; x++) { + int f = freq[x]; + if (f == 0) continue; + int buy = Math.min(coins / x, f); + if (buy == 0) break; + cnt += buy; + coins -= buy * x; + } + return cnt; + } +} diff --git a/tests/1501-2000/1833. maximum-ice-cream-bars/sol.kt b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.kt new file mode 100644 index 00000000..c9d90797 --- /dev/null +++ b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.kt @@ -0,0 +1,26 @@ +class Solution { + fun maxIceCream(costs: IntArray, coins: Int): Int { + var xMin = costs[0] + var xMax = costs[0] + for (x in costs) { + xMin = minOf(xMin, x) + xMax = maxOf(xMax, x) + } + val freq = IntArray(xMax + 1) + for (x in costs) { + freq[x]++ + xMin = minOf(xMin, x) + } + var cnt = 0 + var remaining = coins + for (x in xMin..xMax) { + val f = freq[x] + if (f == 0) continue + val buy = minOf(remaining / x, f) + if (buy == 0) break + cnt += buy + remaining -= buy * x + } + return cnt + } +} diff --git a/tests/1501-2000/1833. maximum-ice-cream-bars/sol.py b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.py new file mode 100644 index 00000000..ebbabe96 --- /dev/null +++ b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.py @@ -0,0 +1,17 @@ +class Solution: + def maxIceCream(self, costs: List[int], coins: int) -> int: + xMin = xMax = max(costs) + freq = [0] * (xMax + 1) + for x in costs: + freq[x] += 1 + xMin = min(xMin, x) + cnt = 0 + for x, f in enumerate(freq[xMin:], start=xMin): + if f == 0: + continue + buy = min(coins // x, f) + if buy == 0: + break + cnt += buy + coins -= buy * x + return cnt diff --git a/tests/1501-2000/1833. maximum-ice-cream-bars/sol.py2 b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.py2 new file mode 100644 index 00000000..8c86a485 --- /dev/null +++ b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def maxIceCream(self, costs, coins): + """ + :type costs: List[int] + :type coins: int + :rtype: int + """ + x_min = x_max = max(costs) + freq = [0] * (x_max + 1) + for x in costs: + freq[x] += 1 + x_min = min(x_min, x) + cnt = 0 + for x in range(x_min, x_max + 1): + f = freq[x] + if f == 0: + continue + buy = min(coins // x, f) + if buy == 0: + break + cnt += buy + coins -= buy * x + return cnt diff --git a/tests/1501-2000/1833. maximum-ice-cream-bars/sol.rb b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.rb new file mode 100644 index 00000000..1be9c5dc --- /dev/null +++ b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.rb @@ -0,0 +1,21 @@ +# @param {Integer[]} costs +# @param {Integer} coins +# @return {Integer} +def max_ice_cream(costs, coins) + x_min = x_max = costs.max + freq = Array.new(x_max + 1, 0) + costs.each do |x| + freq[x] += 1 + x_min = [x_min, x].min + end + cnt = 0 + (x_min..x_max).each do |x| + f = freq[x] + next if f == 0 + buy = [coins / x, f].min + break if buy == 0 + cnt += buy + coins -= buy * x + end + cnt +end diff --git a/tests/1501-2000/1833. maximum-ice-cream-bars/sol.rs b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.rs new file mode 100644 index 00000000..dce7fa6f --- /dev/null +++ b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn max_ice_cream(costs: Vec, coins: i32) -> i32 { + let x_min = *costs.iter().min().unwrap(); + let x_max = *costs.iter().max().unwrap(); + let mut freq = vec![0; (x_max + 1) as usize]; + for &x in &costs { + freq[x as usize] += 1; + } + let mut cnt = 0; + let mut coins_left = coins; + for x in x_min..=x_max { + let f = freq[x as usize]; + if f == 0 { continue; } + let buy = (coins_left / x).min(f); + if buy == 0 { break; } + cnt += buy; + coins_left -= buy * x; + } + cnt + } +} diff --git a/tests/1501-2000/1833. maximum-ice-cream-bars/sol.swift b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.swift new file mode 100644 index 00000000..b2ebd2c9 --- /dev/null +++ b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.swift @@ -0,0 +1,26 @@ +class Solution { + func maxIceCream(_ costs: [Int], _ coins: Int) -> Int { + var xMin = costs[0] + var xMax = costs[0] + for x in costs { + xMin = min(xMin, x) + xMax = max(xMax, x) + } + var freq = [Int](repeating: 0, count: xMax + 1) + for x in costs { + freq[x] += 1 + xMin = min(xMin, x) + } + var cnt = 0 + var remaining = coins + for x in xMin...xMax { + let f = freq[x] + if f == 0 { continue } + let buy = min(remaining / x, f) + if buy == 0 { break } + cnt += buy + remaining -= buy * x + } + return cnt + } +} diff --git a/tests/1501-2000/1833. maximum-ice-cream-bars/sol.ts b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.ts new file mode 100644 index 00000000..f63a5819 --- /dev/null +++ b/tests/1501-2000/1833. maximum-ice-cream-bars/sol.ts @@ -0,0 +1,19 @@ +function maxIceCream(costs: number[], coins: number): number { + let xMin = Math.min(...costs); + let xMax = Math.max(...costs); + const freq: number[] = new Array(xMax + 1).fill(0); + for (const x of costs) { + freq[x]++; + xMin = Math.min(xMin, x); + } + let cnt = 0; + for (let x = xMin; x <= xMax; x++) { + const f = freq[x]; + if (f === 0) continue; + const buy = Math.min(Math.floor(coins / x), f); + if (buy === 0) break; + cnt += buy; + coins -= buy * x; + } + return cnt; +} diff --git a/tests/1501-2000/1834. single-threaded-cpu/manifest.yaml b/tests/1501-2000/1834. single-threaded-cpu/manifest.yaml new file mode 100644 index 00000000..38eca5bc --- /dev/null +++ b/tests/1501-2000/1834. single-threaded-cpu/manifest.yaml @@ -0,0 +1,442 @@ +entry: + id: 1834 + title: "single-threaded-cpu" + params: + tasks: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().getOrder({tasks})" + rust: "Solution::get_order({tasks})" + python3: "Solution().getOrder({tasks})" + python2: "Solution().getOrder({tasks})" + ruby: "get_order({tasks})" + java: "new Solution().getOrder({tasks})" + csharp: "new Solution().GetOrder({tasks})" + kotlin: "Solution().getOrder({tasks})" + go: "getOrder({tasks})" + dart: "Solution().getOrder({tasks})" + swift: "Solution().getOrder({tasks})" + typescript: "getOrder({tasks})" + +judge: + type: "exact" + +limits: + time_ms: 10000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().getOrder(tasks, {result})" + checker: | + import heapq + + class Checker: + def getOrder(self, tasks, result): + indexed = sorted((t[0], t[1], i) for i, t in enumerate(tasks)) + heap = [] + expected = [] + now = 0 + i = 0 + while i < len(indexed) or heap: + if not heap and now < indexed[i][0]: + now = indexed[i][0] + while i < len(indexed) and indexed[i][0] <= now: + _, duration, index = indexed[i] + heapq.heappush(heap, (duration, index)) + i += 1 + duration, index = heapq.heappop(heap) + expected.append(index) + now += duration + return result == expected + +seed: 1834 + +tests: + - name: example-one + in: + tasks: + - [1, 2] + - [2, 4] + - [3, 2] + - [4, 1] + out: [0, 2, 3, 1] + - name: example-two + in: + tasks: + - [7, 10] + - [7, 12] + - [7, 5] + - [7, 4] + - [7, 2] + out: [4, 3, 2, 0, 1] + - name: one-task + in: + tasks: + - [1, 1] + out: [0] + - name: equal-arrivals-index-tie + in: + tasks: + - [1, 3] + - [1, 3] + - [1, 3] + - [1, 3] + out: [0, 1, 2, 3] + - name: equal-duration-late-arrivals + in: + tasks: + - [1, 2] + - [2, 2] + - [3, 2] + - [4, 2] + out: [0, 1, 2, 3] + - name: idle-gap + in: + tasks: + - [5, 2] + - [20, 1] + - [30, 3] + out: [0, 1, 2] + - name: arrival-during-long-task + in: + tasks: + - [1, 10] + - [2, 1] + - [3, 2] + - [4, 1] + out: [0, 1, 3, 2] + - name: shortest-arrives-first + in: + tasks: + - [1, 1] + - [1, 5] + - [1, 2] + out: [0, 2, 1] + - name: later-shortest-available + in: + tasks: + - [1, 5] + - [1, 4] + - [2, 1] + out: [1, 2, 0] + - name: chain-no-idle + in: + tasks: + - [1, 2] + - [3, 2] + - [5, 2] + - [7, 2] + - [9, 2] + out: [0, 1, 2, 3, 4] + - name: same-arrival-varied + in: + tasks: + - [4, 9] + - [4, 1] + - [4, 7] + - [4, 3] + - [4, 5] + out: [1, 3, 4, 2, 0] + - name: zero-overlap-by-large-gaps + in: + tasks: + - [2, 8] + - [100, 9] + - [1000, 1] + - [10000, 2] + out: [0, 1, 2, 3] + - name: duplicate-arrival-duration-index + in: + tasks: + - [2, 2] + - [2, 1] + - [2, 2] + - [2, 1] + - [2, 3] + out: [1, 3, 0, 2, 4] + - name: cascading-choice + in: + tasks: + - [1, 8] + - [2, 7] + - [3, 6] + - [4, 1] + - [5, 2] + - [6, 3] + out: [0, 3, 4, 5, 2, 1] + - name: large-processing-values + in: + tasks: + - [1, 1000000000] + - [2, 999999999] + - [3, 1] + - [1000000000, 2] + out: [0, 2, 3, 1] + - name: large-enqueue-values + in: + tasks: + - [1000000000, 5] + - [1000000000, 1] + - [1000000000, 3] + out: [1, 2, 0] + - name: all-arrive-after-first-finishes + in: + tasks: + - [1, 3] + - [2, 2] + - [3, 1] + - [4, 1] + out: [0, 2, 3, 1] + - name: first-task-not-index-zero + in: + tasks: + - [5, 9] + - [1, 4] + - [1, 2] + - [1, 7] + out: [2, 1, 3, 0] + - name: many-ties + in: + tasks: + - [1, 2] + - [1, 1] + - [1, 2] + - [2, 1] + - [2, 2] + - [3, 1] + out: [1, 3, 5, 0, 2, 4] + - name: staggered-short-jobs + in: + tasks: + - [1, 9] + - [2, 8] + - [3, 7] + - [4, 6] + - [5, 5] + - [6, 1] + out: [0, 5, 4, 3, 2, 1] + - name: negative-not-allowed-boundary + in: + tasks: + - [1, 1] + - [1, 1000000000] + out: [0, 1] + - name: late-task-becomes-available + in: + tasks: + - [10, 10] + - [10, 1] + - [11, 1] + - [12, 1] + - [13, 1] + out: [1, 2, 3, 4, 0] + - name: repeated-same-time + in: + tasks: + - [6, 6] + - [6, 5] + - [6, 4] + - [6, 3] + - [6, 2] + - [6, 1] + out: [5, 4, 3, 2, 1, 0] + - name: alternating-arrivals + in: + tasks: + - [1, 4] + - [2, 3] + - [10, 2] + - [11, 1] + - [20, 5] + - [20, 1] + out: [0, 1, 2, 3, 5, 4] + - name: all-processing-one + in: + tasks: + - [1, 1] + - [100, 1] + - [200, 1] + - [300, 1] + - [400, 1] + out: [0, 1, 2, 3, 4] + - name: priority-changes + in: + tasks: + - [1, 6] + - [1, 5] + - [4, 1] + - [5, 2] + - [6, 3] + - [7, 4] + out: [1, 2, 3, 4, 5, 0] + - name: exact-finish-boundary + in: + tasks: + - [2, 3] + - [5, 1] + - [5, 2] + - [6, 1] + out: [0, 1, 3, 2] + - name: two-independent-batches + in: + tasks: + - [1, 2] + - [1, 4] + - [1, 3] + - [20, 2] + - [20, 1] + - [20, 3] + out: [0, 2, 1, 4, 3, 5] + - name: all-max-values + in: + tasks: + - [1000000000, 1000000000] + - [1000000000, 999999999] + - [1000000000, 999999998] + out: [2, 1, 0] + - name: thirty-small-tasks + in: + tasks: + - [1, 3] + - [1, 1] + - [1, 2] + - [2, 3] + - [2, 1] + - [3, 2] + - [3, 1] + - [4, 3] + - [4, 2] + - [5, 1] + - [5, 3] + - [6, 2] + - [6, 1] + - [7, 3] + - [7, 2] + - [8, 1] + - [8, 3] + - [9, 2] + - [9, 1] + - [10, 3] + - [10, 2] + - [11, 1] + - [11, 3] + - [12, 2] + - [12, 1] + - [13, 3] + - [13, 2] + - [14, 1] + - [14, 3] + - [14, 2] + out: + [ + 1, + 4, + 6, + 2, + 9, + 12, + 15, + 18, + 5, + 21, + 24, + 27, + 8, + 11, + 14, + 17, + 20, + 23, + 26, + 29, + 0, + 3, + 7, + 10, + 13, + 16, + 19, + 22, + 25, + 28, + ] + - name: generated-random-small + in: + tasks: + gen: "array" + len: 25 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 50 + elemType: "int" + judge: + type: "exact" + - name: generated-random-medium + in: + tasks: + gen: "array" + len: 1000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + judge: + type: "exact" + - name: generated-maximal + in: + tasks: + gen: "array" + len: 1000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 1000000000 + elemType: "int" + judge: + type: "exact" + - name: generated-equal-arrivals + in: + tasks: + gen: "array" + len: 1000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 1000000000 + elemType: "int" + judge: + type: "exact" + - name: generated-wide-gaps + in: + tasks: + gen: "array" + len: 1000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 1000000000 + elemType: "int" + judge: + type: "exact" diff --git a/tests/1501-2000/1834. single-threaded-cpu/sol.cpp b/tests/1501-2000/1834. single-threaded-cpu/sol.cpp new file mode 100644 index 00000000..6714e98f --- /dev/null +++ b/tests/1501-2000/1834. single-threaded-cpu/sol.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + vector getOrder(vector>& tasks) { + int n = tasks.size(); + vector> indexed(n, vector(3)); + for (int i = 0; i < n; i++) { + indexed[i][0] = tasks[i][0]; + indexed[i][1] = tasks[i][1]; + indexed[i][2] = i; + } + sort(indexed.begin(), indexed.end(), [](const vector& a, const vector& b) { + return a[0] < b[0]; + }); + + vector result; + priority_queue, vector>, greater>> heap; + long long time = 0; + int idx = 0; + + while (idx < n || !heap.empty()) { + if (heap.empty() && time < indexed[idx][0]) { + time = indexed[idx][0]; + } + + while (idx < n && indexed[idx][0] <= time) { + heap.push({indexed[idx][1], indexed[idx][2]}); + idx++; + } + + auto [process, index] = heap.top(); + heap.pop(); + result.push_back(index); + time += process; + } + + return result; + } +}; diff --git a/tests/1501-2000/1834. single-threaded-cpu/sol.cs b/tests/1501-2000/1834. single-threaded-cpu/sol.cs new file mode 100644 index 00000000..fbaad84f --- /dev/null +++ b/tests/1501-2000/1834. single-threaded-cpu/sol.cs @@ -0,0 +1,33 @@ +public class Solution { + public int[] GetOrder(int[][] tasks) { + int n = tasks.Length; + var indexed = new (int, int, int)[n]; + for (int i = 0; i < n; i++) { + indexed[i] = (tasks[i][0], tasks[i][1], i); + } + Array.Sort(indexed, (a, b) => a.Item1.CompareTo(b.Item1)); + + var result = new List(); + var heap = new SortedSet<(int, int)>(); + long time = 0; + int idx = 0; + + while (idx < n || heap.Count > 0) { + if (heap.Count == 0 && time < indexed[idx].Item1) { + time = indexed[idx].Item1; + } + + while (idx < n && indexed[idx].Item1 <= time) { + heap.Add((indexed[idx].Item2, indexed[idx].Item3)); + idx++; + } + + var (process, index) = heap.Min; + heap.Remove(heap.Min); + result.Add(index); + time += process; + } + + return result.ToArray(); + } +} diff --git a/tests/1501-2000/1834. single-threaded-cpu/sol.dart b/tests/1501-2000/1834. single-threaded-cpu/sol.dart new file mode 100644 index 00000000..6425aaa4 --- /dev/null +++ b/tests/1501-2000/1834. single-threaded-cpu/sol.dart @@ -0,0 +1,53 @@ +class Solution { + List getOrder(List> tasks) { + int n = tasks.length; + List> indexed = List.generate(n, (i) => [tasks[i][0], tasks[i][1], i]); + indexed.sort((a, b) => a[0] - b[0]); + + List result = []; + PriorityQueue> heap = PriorityQueue((a, b) { + if (a[1] != b[1]) return a[1] - b[1]; + return a[2] - b[2]; + }); + + int time = 0; + int idx = 0; + + while (idx < n || heap.isNotEmpty) { + if (heap.isEmpty && time < indexed[idx][0]) { + time = indexed[idx][0]; + } + + while (idx < n && indexed[idx][0] <= time) { + heap.add(indexed[idx]); + idx++; + } + + List task = heap.removeFirst(); + result.add(task[2]); + time += task[1]; + } + + return result; + } +} + +class PriorityQueue { + final List _list = []; + final Comparator _comparator; + + PriorityQueue(this._comparator); + + bool get isNotEmpty => _list.isNotEmpty; + bool get isEmpty => _list.isEmpty; + + void add(T item) { + _list.add(item); + _list.sort(_comparator); + } + + T removeFirst() { + T item = _list.removeAt(0); + return item; + } +} diff --git a/tests/1501-2000/1834. single-threaded-cpu/sol.go b/tests/1501-2000/1834. single-threaded-cpu/sol.go new file mode 100644 index 00000000..131f420a --- /dev/null +++ b/tests/1501-2000/1834. single-threaded-cpu/sol.go @@ -0,0 +1,54 @@ +func getOrder(tasks [][]int) []int { + n := len(tasks) + indexed := make([][3]int, n) + for i := 0; i < n; i++ { + indexed[i] = [3]int{tasks[i][0], tasks[i][1], i} + } + sort.Slice(indexed, func(a, b int) bool { + if indexed[a][0] != indexed[b][0] { return indexed[a][0] < indexed[b][0] } + if indexed[a][1] != indexed[b][1] { return indexed[a][1] < indexed[b][1] } + return indexed[a][2] < indexed[b][2] + }) + + result := make([]int, 0, n) + heap := &taskHeap{} + heap.Init() + time := int64(0) + idx := 0 + + for idx < n || heap.Len() > 0 { + if heap.Len() == 0 && time < int64(indexed[idx][0]) { + time = int64(indexed[idx][0]) + } + + for idx < n && int64(indexed[idx][0]) <= time { + heap.Push([2]int{indexed[idx][1], indexed[idx][2]}) + idx++ + } + + item := heap.Pop().([2]int) + result = append(result, item[1]) + time += int64(item[0]) + } + + return result +} + +type taskHeap [][2]int + +func (h taskHeap) Len() int { return len(h) } +func (h taskHeap) Less(i, j int) bool { + if h[i][0] != h[j][0] { + return h[i][0] < h[j][0] + } + return h[i][1] < h[j][1] +} +func (h taskHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *taskHeap) Push(x interface{}) { *h = append(*h, x.([2]int)); sort.Sort(h) } +func (h *taskHeap) Pop() interface{} { + old := *h + item := old[0] + *h = old[1:] + return item +} +func (h *taskHeap) Init() { sort.Sort(h) } diff --git a/tests/1501-2000/1834. single-threaded-cpu/sol.java b/tests/1501-2000/1834. single-threaded-cpu/sol.java new file mode 100644 index 00000000..f71acc84 --- /dev/null +++ b/tests/1501-2000/1834. single-threaded-cpu/sol.java @@ -0,0 +1,39 @@ +class Solution { + public int[] getOrder(int[][] tasks) { + int n = tasks.length; + int[][] indexed = new int[n][3]; + for (int i = 0; i < n; i++) { + indexed[i][0] = tasks[i][0]; + indexed[i][1] = tasks[i][1]; + indexed[i][2] = i; + } + Arrays.sort(indexed, (a, b) -> Integer.compare(a[0], b[0])); + + int[] result = new int[n]; + PriorityQueue heap = new PriorityQueue<>((a, b) -> { + if (a[1] != b[1]) return Integer.compare(a[1], b[1]); + return Integer.compare(a[2], b[2]); + }); + + long time = 0; + int idx = 0; + int resIdx = 0; + + while (idx < n || !heap.isEmpty()) { + if (heap.isEmpty() && time < indexed[idx][0]) { + time = indexed[idx][0]; + } + + while (idx < n && indexed[idx][0] <= time) { + heap.offer(indexed[idx]); + idx++; + } + + int[] task = heap.poll(); + result[resIdx++] = task[2]; + time += task[1]; + } + + return result; + } +} diff --git a/tests/1501-2000/1834. single-threaded-cpu/sol.kt b/tests/1501-2000/1834. single-threaded-cpu/sol.kt new file mode 100644 index 00000000..df246130 --- /dev/null +++ b/tests/1501-2000/1834. single-threaded-cpu/sol.kt @@ -0,0 +1,38 @@ +class Solution { + fun getOrder(tasks: Array): IntArray { + val n = tasks.size + val indexed = Array(n) { IntArray(3) } + for (i in 0 until n) { + indexed[i][0] = tasks[i][0] + indexed[i][1] = tasks[i][1] + indexed[i][2] = i + } + indexed.sortBy { it[0] } + + val result = IntArray(n) + val heap = PriorityQueue { a, b -> + if (a[1] != b[1]) a[1] - b[1] else a[2] - b[2] + } + + var time = 0L + var idx = 0 + var resIdx = 0 + + while (idx < n || heap.isNotEmpty()) { + if (heap.isEmpty() && time < indexed[idx][0]) { + time = indexed[idx][0].toLong() + } + + while (idx < n && indexed[idx][0] <= time) { + heap.offer(indexed[idx]) + idx++ + } + + val task = heap.poll() + result[resIdx++] = task[2] + time += task[1].toLong() + } + + return result + } +} diff --git a/tests/1501-2000/1834. single-threaded-cpu/sol.py b/tests/1501-2000/1834. single-threaded-cpu/sol.py new file mode 100644 index 00000000..e5b55d14 --- /dev/null +++ b/tests/1501-2000/1834. single-threaded-cpu/sol.py @@ -0,0 +1,37 @@ +import heapq +from typing import List + + +class Solution: + def getOrder(self, tasks: List[List[int]]) -> List[int]: + n = len(tasks) + + # Store (enqueueTime, processingTime, originalIndex) + indexed_tasks = [(tasks[i][0], tasks[i][1], i) for i in range(n)] + + # Sort by enqueue time + indexed_tasks.sort() + + result = [] + heap = [] + + time = 0 + i = 0 + + while i < n or heap: + # If no task is available, jump to the next enqueue time + if not heap and time < indexed_tasks[i][0]: + time = indexed_tasks[i][0] + + # Add all tasks that have become available + while i < n and indexed_tasks[i][0] <= time: + enqueue, process, index = indexed_tasks[i] + heapq.heappush(heap, (process, index)) + i += 1 + + # Process the task with smallest processing time + process, index = heapq.heappop(heap) + result.append(index) + time += process + + return result diff --git a/tests/1501-2000/1834. single-threaded-cpu/sol.py2 b/tests/1501-2000/1834. single-threaded-cpu/sol.py2 new file mode 100644 index 00000000..80668146 --- /dev/null +++ b/tests/1501-2000/1834. single-threaded-cpu/sol.py2 @@ -0,0 +1,30 @@ +class Solution(object): + def getOrder(self, tasks): + """ + :type tasks: List[List[int]] + :rtype: List[int] + """ + n = len(tasks) + indexed_tasks = [(tasks[i][0], tasks[i][1], i) for i in range(n)] + indexed_tasks.sort(key=lambda x: x[0]) + + result = [] + import heapq + heap = [] + time = 0 + i = 0 + + while i < n or heap: + if not heap and time < indexed_tasks[i][0]: + time = indexed_tasks[i][0] + + while i < n and indexed_tasks[i][0] <= time: + enqueue, process, index = indexed_tasks[i] + heapq.heappush(heap, (process, index)) + i += 1 + + process, index = heapq.heappop(heap) + result.append(index) + time += process + + return result diff --git a/tests/1501-2000/1834. single-threaded-cpu/sol.rb b/tests/1501-2000/1834. single-threaded-cpu/sol.rb new file mode 100644 index 00000000..b4c6a264 --- /dev/null +++ b/tests/1501-2000/1834. single-threaded-cpu/sol.rb @@ -0,0 +1,31 @@ +# @param {Integer[][]} tasks +# @return {Integer[]} +def get_order(tasks) + n = tasks.length + indexed_tasks = tasks.each_with_index.map { |task, idx| [task[0], task[1], idx] } + indexed_tasks.sort_by! { |task| task[0] } + + result = [] + heap = [] + time = 0 + i = 0 + + while i < n || !heap.empty? + if heap.empty? && time < indexed_tasks[i][0] + time = indexed_tasks[i][0] + end + + while i < n && indexed_tasks[i][0] <= time + enqueue, process, index = indexed_tasks[i] + heap << [process, index] + heap.sort! + i += 1 + end + + process, index = heap.shift + result << index + time += process + end + + result +end diff --git a/tests/1501-2000/1834. single-threaded-cpu/sol.rs b/tests/1501-2000/1834. single-threaded-cpu/sol.rs new file mode 100644 index 00000000..c6cb704b --- /dev/null +++ b/tests/1501-2000/1834. single-threaded-cpu/sol.rs @@ -0,0 +1,33 @@ +impl Solution { + pub fn get_order(tasks: Vec>) -> Vec { + let n = tasks.len(); + let mut indexed: Vec<(i32, i32, i32)> = tasks.iter().enumerate() + .map(|(i, task)| (task[0], task[1], i as i32)) + .collect(); + indexed.sort_by_key(|&(a, _, _)| a); + + let mut result = Vec::with_capacity(n); + let mut heap: std::collections::BinaryHeap> = + std::collections::BinaryHeap::new(); + let mut time: i64 = 0; + let mut idx = 0; + + while idx < n || !heap.is_empty() { + if heap.is_empty() && (time as i32) < indexed[idx].0 { + time = indexed[idx].0 as i64; + } + + while idx < n && (indexed[idx].0 as i64) <= time { + heap.push(std::cmp::Reverse((indexed[idx].1, indexed[idx].2))); + idx += 1; + } + + if let Some(std::cmp::Reverse((process, index))) = heap.pop() { + result.push(index); + time += process as i64; + } + } + + result + } +} diff --git a/tests/1501-2000/1834. single-threaded-cpu/sol.swift b/tests/1501-2000/1834. single-threaded-cpu/sol.swift new file mode 100644 index 00000000..7f5c0592 --- /dev/null +++ b/tests/1501-2000/1834. single-threaded-cpu/sol.swift @@ -0,0 +1,36 @@ +class Solution { + func getOrder(_ tasks: [[Int]]) -> [Int] { + let n = tasks.count + var indexed = [(Int, Int, Int)]() + for i in 0.. [task[0], task[1], i]); + indexed.sort((a, b) => a[0] - b[0]); + + const result: number[] = []; + const heap: [number, number][] = []; + let time = 0; + let idx = 0; + + function heapPush(item: [number, number]) { + heap.push(item); + heap.sort((a, b) => { + if (a[0] !== b[0]) return a[0] - b[0]; + return a[1] - b[1]; + }); + } + + function heapPop(): [number, number] { + return heap.shift()!; + } + + while (idx < n || heap.length > 0) { + if (heap.length === 0 && time < indexed[idx][0]) { + time = indexed[idx][0]; + } + + while (idx < n && indexed[idx][0] <= time) { + heapPush([indexed[idx][1], indexed[idx][2]]); + idx++; + } + + const [process, index] = heapPop(); + result.push(index); + time += process; + } + + return result; +} diff --git a/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/manifest.yaml b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/manifest.yaml new file mode 100644 index 00000000..c4ae2c7f --- /dev/null +++ b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/manifest.yaml @@ -0,0 +1,314 @@ +entry: + id: 1835 + title: "find-xor-sum-of-all-pairs-bitwise-and" + params: + arr1: + type: array + items: + type: int + arr2: + type: array + items: + type: int + call: + cpp: "Solution().getXORSum({arr1}, {arr2})" + rust: "Solution::get_xor_sum({arr1}, {arr2})" + python3: "Solution().getXORSum({arr1}, {arr2})" + python2: "Solution().getXORSum({arr1}, {arr2})" + ruby: "get_xor_sum({arr1}, {arr2})" + java: "new Solution().getXORSum({arr1}, {arr2})" + csharp: "new Solution().GetXORSum({arr1}, {arr2})" + kotlin: "Solution().getXORSum({arr1}, {arr2})" + go: "getXORSum({arr1}, {arr2})" + dart: "Solution().getXORSum({arr1}, {arr2})" + swift: "Solution().getXORSum({arr1}, {arr2})" + typescript: "getXORSum({arr1}, {arr2})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().getXORSum(arr1, arr2, {result})" + checker: | + class Checker: + def getXORSum(self, arr1, arr2, result): + x = 0 + for value in arr1: + x ^= value + y = 0 + for value in arr2: + y ^= value + return result == (x & y) + +seed: 1835 + +tests: + - name: examples-one + in: + arr1: [1, 2, 3] + arr2: [6, 5] + out: 0 + - name: examples-two + in: + arr1: [12] + arr2: [4] + out: 4 + - name: both-single-zero + in: + arr1: [0] + arr2: [0] + out: 0 + - name: one-zero-array + in: + arr1: [0, 0, 0, 0] + arr2: [1, 2, 4, 8] + out: 0 + - name: duplicate-cancellation + in: + arr1: [7, 7] + arr2: [3] + out: 0 + - name: duplicate-other-cancellation + in: + arr1: [5] + arr2: [9, 9, 1] + out: 1 + - name: powers-of-two + in: + arr1: [1, 2, 4, 8] + arr2: [16, 32, 64] + out: 0 + - name: overlapping-powers + in: + arr1: [3, 12] + arr2: [5, 10] + out: 15 + - name: all-low-bits + in: + arr1: [1, 3, 7, 15] + arr2: [31] + out: 10 + - name: mixed-small + in: + arr1: [2, 5, 9] + arr2: [3, 6, 12] + out: 8 + - name: odd-cardinality + in: + arr1: [1, 2, 4, 8, 16] + arr2: [31, 7, 3] + out: 27 + - name: even-cardinality + in: + arr1: [1, 2, 4, 8] + arr2: [31, 7] + out: 8 + - name: high-bit-single + in: + arr1: [536870912] + arr2: [536870912] + out: 536870912 + - name: max-values-single + in: + arr1: [1000000000] + arr2: [1000000000] + out: 1000000000 + - name: max-values-different + in: + arr1: [1000000000] + arr2: [999999999] + out: 999999488 + - name: alternating-bits + in: + arr1: [143165576, 286331153] + arr2: [143165576, 286331153] + out: 429496729 + - name: repeated-mixed + in: + arr1: [1023, 1023, 511] + arr2: [768, 768, 255] + out: 255 + - name: xor-zero-first + in: + arr1: [10, 10, 3] + arr2: [7, 12, 5] + out: 2 + - name: xor-zero-second + in: + arr1: [7, 12, 5] + arr2: [10, 10, 3] + out: 2 + - name: nested-bit-pattern + in: + arr1: [255, 3855, 61680] + arr2: [4095, 61440, 65535] + out: 0 + - name: one-element-against-many + in: + arr1: [85] + arr2: [170, 85, 255, 0, 1] + out: 1 + - name: many-elements-against-one + in: + arr1: [170, 85, 255, 0, 1] + arr2: [85] + out: 1 + - name: signed-width-boundary + in: + arr1: [536870911, 268435456, 134217728] + arr2: [402653183, 134217727, 1] + out: 1 + - name: decimal-patterns + in: + arr1: [123456789, 987654321] + arr2: [555555555, 444444444] + out: 956343716 + - name: sparse-high-bits + in: + arr1: [67108865, 134217730, 268435460] + arr2: [402653187, 201326594] + out: 335544321 + - name: all-equal-odd + in: + arr1: [42, 42, 42] + arr2: [21, 21, 21] + out: 0 + - name: zero-intersection + in: + arr1: [240, 3840] + arr2: [15, 255] + out: 240 + - name: nonzero-intersection + in: + arr1: [240, 3841] + arr2: [15, 255] + out: 240 + - name: bit-31-safe + in: + arr1: [999999937, 1] + arr2: [999999937, 2, 4] + out: 999999936 + - name: asymmetrical-lengths + in: + arr1: [31, 62, 124, 248, 496, 992, 1984] + arr2: [1023, 2047] + out: 1024 + - name: alternating-small + in: + arr1: [1, 4, 1, 4, 16] + arr2: [2, 8, 2, 8, 32] + out: 0 + - name: dense-low-range + in: + arr1: [6, 13, 24, 31] + arr2: [7, 14, 28, 30] + out: 8 + - name: max-xor-mask + in: + arr1: [0, 1000000000, 1000000000, 536870911] + arr2: [536870911, 0, 536870911] + out: 0 + - name: singleton-overlap + in: + arr1: [123456] + arr2: [654321] + out: 123456 + - name: large-static-pattern + in: + arr1: [1048575, 2097151, 4194303, 8388607, 16777215] + arr2: [524287, 1048575, 2097151, 4194303, 8388607] + out: 524287 + - name: generated-random-small + in: + arr1: + gen: "array" + len: + gen: "int" + min: 1 + max: 30 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" + arr2: + gen: "array" + len: + gen: "int" + min: 1 + max: 30 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" + - name: generated-medium + in: + arr1: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" + arr2: + gen: "array" + len: 997 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" + - name: generated-large-unequal + in: + arr1: + gen: "array" + len: 100000 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" + arr2: + gen: "array" + len: 99991 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" + - name: generated-large-singleton + in: + arr1: + gen: "array" + len: 99999 + of: + gen: "int" + min: 0 + max: 1000000000 + elemType: "int" + arr2: [1073741823] + - name: generated-max-both + in: + arr1: + gen: "array" + len: 100000 + of: + gen: "int" + min: 999999900 + max: 1000000000 + elemType: "int" + arr2: + gen: "array" + len: 100000 + of: + gen: "int" + min: 999999900 + max: 1000000000 + elemType: "int" diff --git a/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.cpp b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.cpp new file mode 100644 index 00000000..4e4cca70 --- /dev/null +++ b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int getXORSum(vector& arr1, vector& arr2) { + int x = 0, y = 0; + for (int v : arr1) { + x ^= v; + } + for (int v : arr2) { + y ^= v; + } + return x & y; + } +}; diff --git a/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.cs b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.cs new file mode 100644 index 00000000..dcc6e5ff --- /dev/null +++ b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.cs @@ -0,0 +1,12 @@ +public class Solution { + public int GetXORSum(int[] arr1, int[] arr2) { + int x = 0, y = 0; + foreach (int v in arr1) { + x ^= v; + } + foreach (int v in arr2) { + y ^= v; + } + return x & y; + } +} diff --git a/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.dart b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.dart new file mode 100644 index 00000000..92c9f174 --- /dev/null +++ b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.dart @@ -0,0 +1,12 @@ +class Solution { + int getXORSum(List arr1, List arr2) { + int x = 0, y = 0; + for (int v in arr1) { + x ^= v; + } + for (int v in arr2) { + y ^= v; + } + return x & y; + } +} diff --git a/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.go b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.go new file mode 100644 index 00000000..aa67cd3f --- /dev/null +++ b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.go @@ -0,0 +1,10 @@ +func getXORSum(arr1 []int, arr2 []int) int { + x, y := 0, 0 + for _, v := range arr1 { + x ^= v + } + for _, v := range arr2 { + y ^= v + } + return x & y +} diff --git a/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.java b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.java new file mode 100644 index 00000000..34266a74 --- /dev/null +++ b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.java @@ -0,0 +1,12 @@ +class Solution { + public int getXORSum(int[] arr1, int[] arr2) { + int x = 0, y = 0; + for (int v : arr1) { + x ^= v; + } + for (int v : arr2) { + y ^= v; + } + return x & y; + } +} diff --git a/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.kt b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.kt new file mode 100644 index 00000000..bc012b64 --- /dev/null +++ b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun getXORSum(arr1: IntArray, arr2: IntArray): Int { + var x = 0 + var y = 0 + for (v in arr1) { + x = x xor v + } + for (v in arr2) { + y = y xor v + } + return x and y + } +} diff --git a/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.py b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.py new file mode 100644 index 00000000..f30bfb79 --- /dev/null +++ b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.py @@ -0,0 +1,8 @@ +class Solution: + def getXORSum(self, arr1: list[int], arr2: list[int]) -> int: + x, y = 0, 0 + for v in arr1: + x ^= v + for v in arr2: + y ^= v + return x & y diff --git a/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.py2 b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.py2 new file mode 100644 index 00000000..cd39478f --- /dev/null +++ b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.py2 @@ -0,0 +1,13 @@ +class Solution(object): + def getXORSum(self, arr1, arr2): + """ + :type arr1: List[int] + :type arr2: List[int] + :rtype: int + """ + x, y = 0, 0 + for v in arr1: + x ^= v + for v in arr2: + y ^= v + return x & y diff --git a/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.rb b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.rb new file mode 100644 index 00000000..44f23c8a --- /dev/null +++ b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.rb @@ -0,0 +1,9 @@ +# @param {Integer[]} arr1 +# @param {Integer[]} arr2 +# @return {Integer} +def get_xor_sum(arr1, arr2) + x, y = 0, 0 + arr1.each { |v| x ^= v } + arr2.each { |v| y ^= v } + x & y +end diff --git a/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.rs b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.rs new file mode 100644 index 00000000..f29fbacb --- /dev/null +++ b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn get_xor_sum(arr1: Vec, arr2: Vec) -> i32 { + let mut x = 0; + let mut y = 0; + for v in arr1 { + x ^= v; + } + for v in arr2 { + y ^= v; + } + x & y + } +} diff --git a/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.swift b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.swift new file mode 100644 index 00000000..bc210cb2 --- /dev/null +++ b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.swift @@ -0,0 +1,12 @@ +class Solution { + func getXORSum(_ arr1: [Int], _ arr2: [Int]) -> Int { + var x = 0, y = 0 + for v in arr1 { + x ^= v + } + for v in arr2 { + y ^= v + } + return x & y + } +} diff --git a/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.ts b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.ts new file mode 100644 index 00000000..816f0f20 --- /dev/null +++ b/tests/1501-2000/1835. find-xor-sum-of-all-pairs-bitwise-and/sol.ts @@ -0,0 +1,11 @@ +function getXORSum(arr1: number[], arr2: number[]): number { + let x = 0, + y = 0; + for (const v of arr1) { + x ^= v; + } + for (const v of arr2) { + y ^= v; + } + return x & y; +} diff --git a/tests/1501-2000/1837. sum-of-digits-in-base-k/manifest.yaml b/tests/1501-2000/1837. sum-of-digits-in-base-k/manifest.yaml new file mode 100644 index 00000000..2d03eb47 --- /dev/null +++ b/tests/1501-2000/1837. sum-of-digits-in-base-k/manifest.yaml @@ -0,0 +1,272 @@ +entry: + id: 1837 + title: "sum-of-digits-in-base-k" + params: + n: + type: int + k: + type: int + call: + cpp: "Solution().sumBase({n}, {k})" + rust: "Solution::sum_base({n}, {k})" + python3: "Solution().sumBase({n}, {k})" + python2: "Solution().sumBase({n}, {k})" + ruby: "sum_base({n}, {k})" + java: "new Solution().sumBase({n}, {k})" + csharp: "new Solution().SumBase({n}, {k})" + kotlin: "Solution().sumBase({n}, {k})" + go: "sumBase({n}, {k})" + dart: "Solution().sumBase({n}, {k})" + swift: "Solution().sumBase({n}, {k})" + typescript: "sumBase({n}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().sumBase(n, k, {result})" + checker: | + class Checker: + def sumBase(self, n, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + total = 0 + value = n + while value > 0: + total += value % k + value //= k + return result == total + +seed: 1837 + +tests: + - name: example-34-base-6 + in: + n: 34 + k: 6 + out: 9 + - name: example-10-base-10 + in: + n: 10 + k: 10 + out: 1 + - name: minimum-n + in: + n: 1 + k: 2 + out: 1 + - name: minimum-base + in: + n: 100 + k: 2 + out: 3 + - name: maximum-base + in: + n: 100 + k: 10 + out: 1 + - name: n-one-base-ten + in: + n: 1 + k: 10 + out: 1 + - name: exact-power-two + in: + n: 64 + k: 2 + out: 1 + - name: exact-power-ten + in: + n: 100 + k: 10 + out: 1 + - name: base-two-odd + in: + n: 37 + k: 2 + out: 3 + - name: base-three + in: + n: 50 + k: 3 + out: 6 + - name: base-four + in: + n: 63 + k: 4 + out: 9 + - name: base-five + in: + n: 99 + k: 5 + out: 11 + - name: base-six + in: + n: 35 + k: 6 + out: 10 + - name: base-seven + in: + n: 48 + k: 7 + out: 12 + - name: base-eight + in: + n: 81 + k: 8 + out: 4 + - name: base-nine + in: + n: 82 + k: 9 + out: 2 + - name: all-digits-nine + in: + n: 99 + k: 10 + out: 18 + - name: binary-popcount + in: + n: 85 + k: 2 + out: 4 + - name: ternary-mixed + in: + n: 88 + k: 3 + out: 4 + - name: four-compact + in: + n: 42 + k: 4 + out: 6 + - name: five-remainder + in: + n: 76 + k: 5 + out: 4 + - name: six-remainder + in: + n: 92 + k: 6 + out: 7 + - name: seven-remainder + in: + n: 97 + k: 7 + out: 13 + - name: eight-remainder + in: + n: 73 + k: 8 + out: 3 + - name: nine-remainder + in: + n: 91 + k: 9 + out: 3 + - name: n-ten-base-two + in: + n: 10 + k: 2 + out: 2 + - name: n-ten-base-three + in: + n: 10 + k: 3 + out: 2 + - name: n-ten-base-four + in: + n: 10 + k: 4 + out: 4 + - name: n-ten-base-eight + in: + n: 10 + k: 8 + out: 3 + - name: n-ten-base-nine + in: + n: 10 + k: 9 + out: 2 + - name: max-n-base-three + in: + n: 100 + k: 3 + out: 4 + - name: max-n-base-four + in: + n: 100 + k: 4 + out: 4 + - name: max-n-base-five + in: + n: 100 + k: 5 + out: 4 + - name: max-n-base-six + in: + n: 100 + k: 6 + out: 10 + - name: max-n-base-seven + in: + n: 100 + k: 7 + out: 4 + - name: generated-boundary + in: + n: + gen: "int" + min: 1 + max: 100 + k: + gen: "int" + min: 2 + max: 10 + - name: generated-small + in: + n: + gen: "int" + min: 1 + max: 20 + k: + gen: "int" + min: 2 + max: 10 + - name: generated-binary-range + in: + n: + gen: "int" + min: 80 + max: 100 + k: + gen: "int" + min: 2 + max: 2 + - name: generated-decimal-range + in: + n: + gen: "int" + min: 80 + max: 100 + k: + gen: "int" + min: 9 + max: 10 + - name: generated-mid-range + in: + n: + gen: "int" + min: 21 + max: 79 + k: + gen: "int" + min: 3 + max: 8 diff --git a/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.cpp b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.cpp new file mode 100644 index 00000000..3336dfac --- /dev/null +++ b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int sumBase(int n, int k) { + int total = 0; + while (n > 0) { + total += n % k; + n /= k; + } + return total; + } +}; diff --git a/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.cs b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.cs new file mode 100644 index 00000000..73d6adcd --- /dev/null +++ b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.cs @@ -0,0 +1,10 @@ +public class Solution { + public int SumBase(int n, int k) { + int total = 0; + while (n > 0) { + total += n % k; + n /= k; + } + return total; + } +} diff --git a/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.dart b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.dart new file mode 100644 index 00000000..006f12dd --- /dev/null +++ b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.dart @@ -0,0 +1,10 @@ +class Solution { + int sumBase(int n, int k) { + int total = 0; + while (n > 0) { + total += n % k; + n ~/= k; + } + return total; + } +} diff --git a/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.go b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.go new file mode 100644 index 00000000..6aadc64d --- /dev/null +++ b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.go @@ -0,0 +1,8 @@ +func sumBase(n int, k int) int { + total := 0 + for n > 0 { + total += n % k + n /= k + } + return total +} diff --git a/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.java b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.java new file mode 100644 index 00000000..6b359f25 --- /dev/null +++ b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.java @@ -0,0 +1,10 @@ +class Solution { + public int sumBase(int n, int k) { + int total = 0; + while (n > 0) { + total += n % k; + n /= k; + } + return total; + } +} diff --git a/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.kt b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.kt new file mode 100644 index 00000000..7de65fee --- /dev/null +++ b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.kt @@ -0,0 +1,11 @@ +class Solution { + fun sumBase(n: Int, k: Int): Int { + var total = 0 + var num = n + while (num > 0) { + total += num % k + num /= k + } + return total + } +} diff --git a/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.py b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.py new file mode 100644 index 00000000..0c484d34 --- /dev/null +++ b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.py @@ -0,0 +1,7 @@ +class Solution: + def sumBase(self, n: int, k: int) -> int: + total = 0 + while n > 0: + total += n % k # get last digit + n //= k # remove last digit + return total diff --git a/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.py2 b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.py2 new file mode 100644 index 00000000..8546c41e --- /dev/null +++ b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def sumBase(self, n, k): + """ + :type n: int + :type k: int + :rtype: int + """ + total = 0 + while n > 0: + total += n % k + n //= k + return total diff --git a/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.rb b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.rb new file mode 100644 index 00000000..3463ae32 --- /dev/null +++ b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.rb @@ -0,0 +1,11 @@ +# @param {Integer} n +# @param {Integer} k +# @return {Integer} +def sum_base(n, k) + total = 0 + while n > 0 + total += n % k + n /= k + end + total +end diff --git a/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.rs b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.rs new file mode 100644 index 00000000..61358016 --- /dev/null +++ b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn sum_base(n: i32, k: i32) -> i32 { + let mut total = 0; + let mut num = n; + while num > 0 { + total += num % k; + num /= k; + } + total + } +} diff --git a/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.swift b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.swift new file mode 100644 index 00000000..c598d41e --- /dev/null +++ b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.swift @@ -0,0 +1,11 @@ +class Solution { + func sumBase(_ n: Int, _ k: Int) -> Int { + var total = 0 + var num = n + while num > 0 { + total += num % k + num /= k + } + return total + } +} diff --git a/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.ts b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.ts new file mode 100644 index 00000000..437e5365 --- /dev/null +++ b/tests/1501-2000/1837. sum-of-digits-in-base-k/sol.ts @@ -0,0 +1,8 @@ +function sumBase(n: number, k: number): number { + let total = 0; + while (n > 0) { + total += n % k; + n = Math.floor(n / k); + } + return total; +} diff --git a/tests/1501-2000/1838. frequency-of-the-most-frequent-element/manifest.yaml b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/manifest.yaml new file mode 100644 index 00000000..edf2bcae --- /dev/null +++ b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/manifest.yaml @@ -0,0 +1,326 @@ +entry: + id: 1838 + title: "frequency-of-the-most-frequent-element" + params: + nums: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().maxFrequency({nums}, {k})" + rust: "Solution::max_frequency({nums}, {k})" + python3: "Solution().maxFrequency({nums}, {k})" + python2: "Solution().maxFrequency({nums}, {k})" + ruby: "max_frequency({nums}, {k})" + java: "new Solution().maxFrequency({nums}, {k})" + csharp: "new Solution().MaxFrequency({nums}, {k})" + kotlin: "Solution().maxFrequency({nums}, {k})" + go: "maxFrequency({nums}, {k})" + dart: "Solution().maxFrequency({nums}, {k})" + swift: "Solution().maxFrequency({nums}, {k})" + typescript: "maxFrequency({nums}, {k})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().maxFrequency(nums, k, {result})" + checker: | + class Checker: + def maxFrequency(self, nums, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not nums or result < 1 or result > len(nums): + return False + values = sorted(nums) + + def feasible(width): + window_sum = sum(values[:width]) + for right in range(width, len(values) + 1): + if values[right - 1] * width - window_sum <= k: + return True + if right < len(values): + window_sum += values[right] - values[right - width] + return False + + if not feasible(result) or (result < len(values) and feasible(result + 1)): + return False + return True +seed: 1838 +tests: + - name: example-1 + in: + nums: [1, 2, 4] + k: 5 + out: 3 + - name: example-2 + in: + nums: [1, 4, 8, 13] + k: 5 + out: 2 + - name: example-3 + in: + nums: [3, 9, 6] + k: 2 + out: 1 + - name: singleton + in: + nums: [7] + k: 1 + out: 1 + - name: all-equal + in: + nums: [5, 5, 5, 5] + k: 1 + out: 4 + - name: k-minimum + in: + nums: [1, 2, 3, 4, 5] + k: 1 + out: 2 + - name: all-ones + in: + nums: [1, 1, 1, 1, 1, 1] + k: 100000 + out: 6 + - name: two-adjacent + in: + nums: [1, 2] + k: 1 + out: 2 + - name: two-too-far + in: + nums: [1, 100000] + k: 99998 + out: 1 + - name: two-exact + in: + nums: [1, 100000] + k: 99999 + out: 2 + - name: duplicate-low + in: + nums: [1, 1, 10, 10] + k: 8 + out: 2 + - name: duplicate-low-insufficient + in: + nums: [1, 1, 10, 10] + k: 7 + out: 2 + - name: sorted-increasing + in: + nums: [1, 2, 3, 4, 5, 6, 7] + k: 6 + out: 4 + - name: sorted-decreasing + in: + nums: [9, 8, 7, 6, 5, 4, 3] + k: 6 + out: 4 + - name: high-values + in: + nums: [99998, 99999, 100000] + k: 2 + out: 2 + - name: high-values-short + in: + nums: [99998, 100000] + k: 1 + out: 1 + - name: cluster-beats-duplicates + in: + nums: [1, 2, 2, 3, 9] + k: 3 + out: 3 + - name: zero-gap + in: + nums: [2, 2, 4, 4, 6] + k: 0 + out: 2 + - name: small-budget + in: + nums: [1, 3, 6, 10] + k: 2 + out: 2 + - name: exact-window + in: + nums: [1, 2, 4, 7] + k: 8 + out: 3 + - name: one-short + in: + nums: [1, 2, 4, 7] + k: 7 + out: 3 + - name: repeated-gaps + in: + nums: [2, 5, 5, 8, 8, 8] + k: 6 + out: 5 + - name: negative-not-allowed-boundary + in: + nums: [1, 100, 101, 102] + k: 3 + out: 3 + - name: large-budget-not-enough + in: + nums: [1, 50000, 100000] + k: 100000 + out: 2 + - name: broad-small-range + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + k: 15 + out: 6 + - name: broad-small-range-tight + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + k: 14 + out: 5 + - name: alternating + in: + nums: [1, 100, 2, 99, 3, 98] + k: 6 + out: 3 + - name: plateau + in: + nums: [4, 4, 5, 5, 6, 6, 7, 7] + k: 4 + out: 5 + - name: plateau-tight + in: + nums: [4, 4, 5, 5, 6, 6, 7, 7] + k: 3 + out: 4 + - name: near-max-run + in: + nums: + [ + 99990, + 99991, + 99992, + 99993, + 99994, + 99995, + 99996, + 99997, + 99998, + 99999, + 100000, + ] + k: 55 + out: 11 + - name: near-max-run-tight + in: + nums: + [ + 99990, + 99991, + 99992, + 99993, + 99994, + 99995, + 99996, + 99997, + 99998, + 99999, + 100000, + ] + k: 54 + out: 10 + - name: four-copies + in: + nums: [1, 1, 1, 1, 100000] + k: 99999 + out: 4 + - name: four-copies-tight + in: + nums: [1, 1, 1, 1, 100000] + k: 99998 + out: 4 + - name: medium-cluster + in: + nums: [10, 11, 12, 20, 21, 22, 23, 24] + k: 10 + out: 5 + - name: medium-cluster-tight + in: + nums: [10, 11, 12, 20, 21, 22, 23, 24] + k: 9 + out: 4 + - name: huge-identical + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 77777 + max: 77777 + distinct: false + sorted: false + elemType: "int" + k: 100000 + - name: huge-consecutive + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: true + sorted: true + elemType: "int" + k: 100000 + - name: huge-two-values + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 2 + distinct: false + sorted: false + elemType: "int" + k: 99999 + - name: random-large + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 100000 + - name: random-medium + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 100000 diff --git a/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.cpp b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.cpp new file mode 100644 index 00000000..479ae8ce --- /dev/null +++ b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int maxFrequency(vector& nums, int k) { + sort(nums.begin(), nums.end()); + int left = 0, right = 0, res = 0; + long long total = 0; + + while (right < nums.size()) { + total += nums[right]; + + while ((long long)nums[right] * (right - left + 1) > total + k) { + total -= nums[left]; + left++; + } + + res = max(res, right - left + 1); + right++; + } + + return res; + } +}; diff --git a/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.cs b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.cs new file mode 100644 index 00000000..87b0c64c --- /dev/null +++ b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.cs @@ -0,0 +1,21 @@ +public class Solution { + public int MaxFrequency(int[] nums, int k) { + Array.Sort(nums); + int left = 0, right = 0, res = 0; + long total = 0; + + while (right < nums.Length) { + total += nums[right]; + + while ((long)nums[right] * (right - left + 1) > total + k) { + total -= nums[left]; + left++; + } + + res = Math.Max(res, right - left + 1); + right++; + } + + return res; + } +} diff --git a/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.dart b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.dart new file mode 100644 index 00000000..2446dbe2 --- /dev/null +++ b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.dart @@ -0,0 +1,23 @@ +class Solution { + int maxFrequency(List nums, int k) { + nums.sort(); + int left = 0; + int right = 0; + int res = 0; + int total = 0; + + while (right < nums.length) { + total += nums[right]; + + while (nums[right] * (right - left + 1) > total + k) { + total -= nums[left]; + left++; + } + + res = (right - left + 1) > res ? (right - left + 1) : res; + right++; + } + + return res; + } +} diff --git a/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.go b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.go new file mode 100644 index 00000000..9881978c --- /dev/null +++ b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.go @@ -0,0 +1,23 @@ +func maxFrequency(nums []int, k int) int { + sort.Ints(nums) + left := 0 + right := 0 + res := 0 + total := int64(0) + + for right < len(nums) { + total += int64(nums[right]) + + for int64(nums[right]) * int64(right-left+1) > total + int64(k) { + total -= int64(nums[left]) + left++ + } + + if right-left+1 > res { + res = right-left+1 + } + right++ + } + + return res +} diff --git a/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.java b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.java new file mode 100644 index 00000000..bde5a8bf --- /dev/null +++ b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.java @@ -0,0 +1,21 @@ +class Solution { + public int maxFrequency(int[] nums, int k) { + Arrays.sort(nums); + int left = 0, right = 0, res = 0; + long total = 0; + + while (right < nums.length) { + total += nums[right]; + + while ((long)nums[right] * (right - left + 1) > total + k) { + total -= nums[left]; + left++; + } + + res = Math.max(res, right - left + 1); + right++; + } + + return res; + } +} diff --git a/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.kt b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.kt new file mode 100644 index 00000000..ed8d2392 --- /dev/null +++ b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.kt @@ -0,0 +1,23 @@ +class Solution { + fun maxFrequency(nums: IntArray, k: Int): Int { + nums.sort() + var left = 0 + var right = 0 + var res = 0 + var total = 0L + + while (right < nums.size) { + total += nums[right] + + while (nums[right].toLong() * (right - left + 1) > total + k) { + total -= nums[left] + left++ + } + + res = maxOf(res, right - left + 1) + right++ + } + + return res + } +} diff --git a/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.py b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.py new file mode 100644 index 00000000..451c4dac --- /dev/null +++ b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.py @@ -0,0 +1,17 @@ +class Solution: + def maxFrequency(self, nums: List[int], k: int) -> int: + + nums.sort() + left = right = res = total = 0 + + while right < len(nums): + total += nums[right] + + while nums[right] * (right - left + 1) > total + k: + total -= nums[left] + left += 1 + + res = max(res, right - left + 1) + right += 1 + + return res diff --git a/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.py2 b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.py2 new file mode 100644 index 00000000..18f43a1b --- /dev/null +++ b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def maxFrequency(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + nums.sort() + left = right = res = total = 0 + + while right < len(nums): + total += nums[right] + + while nums[right] * (right - left + 1) > total + k: + total -= nums[left] + left += 1 + + res = max(res, right - left + 1) + right += 1 + + return res diff --git a/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.rb b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.rb new file mode 100644 index 00000000..54e97025 --- /dev/null +++ b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.rb @@ -0,0 +1,24 @@ +# @param {Integer[]} nums +# @param {Integer} k +# @return {Integer} +def max_frequency(nums, k) + nums.sort! + left = 0 + right = 0 + res = 0 + total = 0 + + while right < nums.length + total += nums[right] + + while nums[right] * (right - left + 1) > total + k + total -= nums[left] + left += 1 + end + + res = [res, right - left + 1].max + right += 1 + end + + res +end diff --git a/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.rs b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.rs new file mode 100644 index 00000000..8f130e93 --- /dev/null +++ b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn max_frequency(nums: Vec, k: i32) -> i32 { + let mut nums = nums; + nums.sort(); + let mut left = 0; + let mut right = 0; + let mut res = 0; + let mut total: i64 = 0; + + while right < nums.len() { + total += nums[right] as i64; + + while (nums[right] as i64) * ((right - left + 1) as i64) > total + k as i64 { + total -= nums[left] as i64; + left += 1; + } + + res = res.max((right - left + 1) as i32); + right += 1; + } + + res + } +} diff --git a/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.swift b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.swift new file mode 100644 index 00000000..5526c6c8 --- /dev/null +++ b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func maxFrequency(_ nums: [Int], _ k: Int) -> Int { + var nums = nums.sorted() + var left = 0 + var right = 0 + var res = 0 + var total = 0 + + while right < nums.count { + total += nums[right] + + while nums[right] * (right - left + 1) > total + k { + total -= nums[left] + left += 1 + } + + res = max(res, right - left + 1) + right += 1 + } + + return res + } +} diff --git a/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.ts b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.ts new file mode 100644 index 00000000..43a64708 --- /dev/null +++ b/tests/1501-2000/1838. frequency-of-the-most-frequent-element/sol.ts @@ -0,0 +1,21 @@ +function maxFrequency(nums: number[], k: number): number { + nums.sort((a, b) => a - b); + let left = 0; + let right = 0; + let res = 0; + let total = 0; + + while (right < nums.length) { + total += nums[right]; + + while (nums[right] * (right - left + 1) > total + k) { + total -= nums[left]; + left++; + } + + res = Math.max(res, right - left + 1); + right++; + } + + return res; +} diff --git a/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/manifest.yaml b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/manifest.yaml new file mode 100644 index 00000000..03d2205e --- /dev/null +++ b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/manifest.yaml @@ -0,0 +1,305 @@ +entry: + id: 1839 + title: "longest-substring-of-all-vowels-in-order" + params: + word: + type: string + call: + cpp: "Solution().longestBeautifulSubstring({word})" + rust: "Solution::longest_beautiful_substring({word})" + python3: "Solution().longestBeautifulSubstring({word})" + python2: "Solution().longestBeautifulSubstring({word})" + ruby: "longest_beautiful_substring({word})" + java: "new Solution().longestBeautifulSubstring({word})" + csharp: "new Solution().LongestBeautifulSubstring({word})" + kotlin: "Solution().longestBeautifulSubstring({word})" + go: "longestBeautifulSubstring({word})" + dart: "Solution().longestBeautifulSubstring({word})" + swift: "Solution().longestBeautifulSubstring({word})" + typescript: "longestBeautifulSubstring({word})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(word, {result})" + checker: | + class Checker: + def check(self, word, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + best = 0 + n = len(word) + start = 0 + while start < n: + if word[start] != "a": + start += 1 + continue + end = start + seen = 1 + while end + 1 < n and word[end + 1] >= word[end]: + if word[end + 1] != word[end]: + seen += 1 + end += 1 + if seen == 5: + best = max(best, end - start + 1) + start = end + 1 + return result == best + +seed: 1839 + +tests: + - name: example-1 + in: + word: "aeiaaioaaaaeiiiiouuuooaauuaeiu" + out: 13 + judge: + type: "exact" + - name: example-2 + in: + word: "aeeeiiiioooauuuaeiou" + out: 5 + judge: + type: "exact" + - name: one-character + in: + word: "a" + out: 0 + judge: + type: "exact" + - name: minimum-beautiful + in: + word: "aeiou" + out: 5 + judge: + type: "exact" + - name: all-a + in: + word: "aaaaaa" + out: 0 + judge: + type: "exact" + - name: all-u + in: + word: "uuuuuu" + out: 0 + judge: + type: "exact" + - name: missing-i + in: + word: "aaeeoouu" + out: 0 + judge: + type: "exact" + - name: starts-after-invalid + in: + word: "ueeeaeeiioouu" + out: 9 + judge: + type: "exact" + - name: repeated-vowels + in: + word: "aaaaeeeeeiiiooooouuuuuu" + out: 23 + judge: + type: "exact" + - name: two-beautiful-runs + in: + word: "aeiouaeiou" + out: 5 + judge: + type: "exact" + - name: longest-second-run + in: + word: "aeiouaaeeeeiiiiioooooouuuuu" + out: 22 + judge: + type: "exact" + - name: descending-break + in: + word: "aaaaeeeiioouuuaeio" + out: 14 + judge: + type: "exact" + - name: repeated-boundary + in: + word: "aaeeiioouu" + out: 10 + judge: + type: "exact" + - name: isolated-a-after-run + in: + word: "aeioua" + out: 5 + judge: + type: "exact" + - name: invalid-leading-e + in: + word: "eiaouaeiou" + out: 5 + judge: + type: "exact" + - name: invalid-middle-order + in: + word: "aeiouoaeiou" + out: 5 + judge: + type: "exact" + - name: duplicate-runs + in: + word: "aaaeiioouuuaeeiioouuuu" + out: 11 + judge: + type: "exact" + - name: one-vowel-groups + in: + word: "aeeiioou" + out: 8 + judge: + type: "exact" + - name: exact-long-groups + in: + word: "aaaeeeeiiiooouuuu" + out: 17 + judge: + type: "exact" + - name: alternating-invalid + in: + word: "aiaiaiaiaeiou" + out: 5 + judge: + type: "exact" + - name: many-short-runs + in: + word: "aeioaeiouuaeioou" + out: 6 + judge: + type: "exact" + - name: all-vowels-long + in: + word: "aeeeeeeeeiiiiiiiiioooooooooouuuuuuuuu" + out: 37 + judge: + type: "exact" + - name: only-prefix + in: + word: "aaaaee" + out: 0 + judge: + type: "exact" + - name: only-suffix + in: + word: "iiioouuu" + out: 0 + judge: + type: "exact" + - name: vowel-order-reset + in: + word: "aeiouuooaeiou" + out: 6 + judge: + type: "exact" + - name: multiple-resets + in: + word: "aeioaeiouaeioaeiou" + out: 5 + judge: + type: "exact" + - name: long-a-prefix + in: + word: "aaaaaaaaaaaaaaaaaaaeiou" + out: 23 + judge: + type: "exact" + - name: long-u-suffix + in: + word: "aeioouuuuuuuuuuuuuuu" + out: 20 + judge: + type: "exact" + - name: two-complete-groups + in: + word: "aaeeiioouuaeeiioouu" + out: 10 + judge: + type: "exact" + - name: starts-with-all-order + in: + word: "aeiouuuuu" + out: 9 + judge: + type: "exact" + - name: repeated-reset-at-a + in: + word: "aeiouaaaeiou" + out: 7 + judge: + type: "exact" + - name: near-complete-final + in: + word: "aaeeiioou" + out: 9 + judge: + type: "exact" + - name: longest-with-noise + in: + word: "aeeeiioouuaaaeeeeiiiiioouuu" + out: 17 + judge: + type: "exact" + - name: maximum-shaped-static + in: + word: "aaaaaeeeeeeeeeeiiiiiiiiiiioooooooooooouuuuuuuuuuu" + out: 49 + judge: + type: "exact" + - name: gen-random-vowels-1 + in: + word: + gen: "str" + len: 500000 + alphabet: "aeiou" + judge: + type: "exact" + seed: 1840 + - name: gen-random-vowels-2 + in: + word: + gen: "str" + len: 100000 + alphabet: "aeiou" + judge: + type: "exact" + seed: 1841 + - name: gen-random-vowels-3 + in: + word: + gen: "str" + len: 75000 + alphabet: "aeiou" + judge: + type: "exact" + seed: 1842 + - name: gen-random-vowels-4 + in: + word: + gen: "str" + len: 50000 + alphabet: "aeiou" + judge: + type: "exact" + seed: 1843 + - name: gen-random-vowels-5 + in: + word: + gen: "str" + len: 25000 + alphabet: "aeiou" + judge: + type: "exact" + seed: 1844 diff --git a/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.cpp b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.cpp new file mode 100644 index 00000000..5913bd46 --- /dev/null +++ b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int longestBeautifulSubstring(string word) { + int n = word.size(); + int i = 0; + int length = 0; + + while (i < n) { + if (word[i] != 'a') { + i++; + continue; + } + + int j = i; + int unique = 1; + while (j + 1 < n && word[j + 1] >= word[j]) { + if (word[j + 1] != word[j]) { + unique++; + } + j++; + } + + if (unique == 5) { + length = max(length, j - i + 1); + } + + i = j + 1; + } + + return length; + } +}; diff --git a/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.cs b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.cs new file mode 100644 index 00000000..53fb20cb --- /dev/null +++ b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.cs @@ -0,0 +1,31 @@ +public class Solution { + public int LongestBeautifulSubstring(string word) { + int n = word.Length; + int i = 0; + int length = 0; + + while (i < n) { + if (word[i] != 'a') { + i++; + continue; + } + + int j = i; + int unique = 1; + while (j + 1 < n && word[j + 1] >= word[j]) { + if (word[j + 1] != word[j]) { + unique++; + } + j++; + } + + if (unique == 5) { + length = Math.Max(length, j - i + 1); + } + + i = j + 1; + } + + return length; + } +} diff --git a/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.dart b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.dart new file mode 100644 index 00000000..c74dbcad --- /dev/null +++ b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.dart @@ -0,0 +1,31 @@ +class Solution { + int longestBeautifulSubstring(String word) { + int n = word.length; + int i = 0; + int length = 0; + + while (i < n) { + if (word[i] != 'a') { + i++; + continue; + } + + int j = i; + int unique = 1; + while (j + 1 < n && word[j + 1].compareTo(word[j]) >= 0) { + if (word[j + 1] != word[j]) { + unique++; + } + j++; + } + + if (unique == 5) { + length = (j - i + 1 > length) ? j - i + 1 : length; + } + + i = j + 1; + } + + return length; + } +} diff --git a/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.go b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.go new file mode 100644 index 00000000..58ce1586 --- /dev/null +++ b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.go @@ -0,0 +1,31 @@ +func longestBeautifulSubstring(word string) int { + n := len(word) + i := 0 + length := 0 + + for i < n { + if word[i] != 'a' { + i++ + continue + } + + j := i + unique := 1 + for j+1 < n && word[j+1] >= word[j] { + if word[j+1] != word[j] { + unique++ + } + j++ + } + + if unique == 5 { + if j-i+1 > length { + length = j - i + 1 + } + } + + i = j + 1 + } + + return length +} diff --git a/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.java b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.java new file mode 100644 index 00000000..2129fba2 --- /dev/null +++ b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.java @@ -0,0 +1,31 @@ +class Solution { + public int longestBeautifulSubstring(String word) { + int n = word.length(); + int i = 0; + int length = 0; + + while (i < n) { + if (word.charAt(i) != 'a') { + i++; + continue; + } + + int j = i; + int unique = 1; + while (j + 1 < n && word.charAt(j + 1) >= word.charAt(j)) { + if (word.charAt(j + 1) != word.charAt(j)) { + unique++; + } + j++; + } + + if (unique == 5) { + length = Math.max(length, j - i + 1); + } + + i = j + 1; + } + + return length; + } +} diff --git a/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.kt b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.kt new file mode 100644 index 00000000..9b3c8b05 --- /dev/null +++ b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.kt @@ -0,0 +1,31 @@ +class Solution { + fun longestBeautifulSubstring(word: String): Int { + val n = word.length + var i = 0 + var length = 0 + + while (i < n) { + if (word[i] != 'a') { + i++ + continue + } + + var j = i + var unique = 1 + while (j + 1 < n && word[j + 1] >= word[j]) { + if (word[j + 1] != word[j]) { + unique++ + } + j++ + } + + if (unique == 5) { + length = maxOf(length, j - i + 1) + } + + i = j + 1 + } + + return length + } +} diff --git a/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.py b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.py new file mode 100644 index 00000000..0b8ec2b4 --- /dev/null +++ b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.py @@ -0,0 +1,24 @@ +class Solution: + def longestBeautifulSubstring(self, word: str) -> int: + n = len(word) + i = 0 + length = 0 + + while i < n: + if word[i] != "a": + i += 1 + continue + + j = i + unique = 1 + while j + 1 < n and word[j + 1] >= word[j]: + if word[j + 1] != word[j]: + unique += 1 + j += 1 + + if unique == 5: + length = max(length, j - i + 1) + + i = j + 1 + + return length diff --git a/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.py2 b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.py2 new file mode 100644 index 00000000..54987dcd --- /dev/null +++ b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.py2 @@ -0,0 +1,28 @@ +class Solution(object): + def longestBeautifulSubstring(self, word): + """ + :type word: str + :rtype: int + """ + n = len(word) + i = 0 + length = 0 + + while i < n: + if word[i] != "a": + i += 1 + continue + + j = i + unique = 1 + while j + 1 < n and word[j + 1] >= word[j]: + if word[j + 1] != word[j]: + unique += 1 + j += 1 + + if unique == 5: + length = max(length, j - i + 1) + + i = j + 1 + + return length diff --git a/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.rb b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.rb new file mode 100644 index 00000000..915cf222 --- /dev/null +++ b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.rb @@ -0,0 +1,31 @@ +# @param {String} word +# @return {Integer} +def longest_beautiful_substring(word) + n = word.length + i = 0 + length = 0 + + while i < n + if word[i] != "a" + i += 1 + next + end + + j = i + unique = 1 + while j + 1 < n && word[j + 1] >= word[j] + if word[j + 1] != word[j] + unique += 1 + end + j += 1 + end + + if unique == 5 + length = [length, j - i + 1].max + end + + i = j + 1 + end + + length +end diff --git a/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.rs b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.rs new file mode 100644 index 00000000..85792677 --- /dev/null +++ b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.rs @@ -0,0 +1,32 @@ +impl Solution { + pub fn longest_beautiful_substring(word: String) -> i32 { + let chars: Vec = word.chars().collect(); + let n = chars.len(); + let mut i = 0; + let mut length = 0; + + while i < n { + if chars[i] != 'a' { + i += 1; + continue; + } + + let mut j = i; + let mut unique = 1; + while j + 1 < n && chars[j + 1] >= chars[j] { + if chars[j + 1] != chars[j] { + unique += 1; + } + j += 1; + } + + if unique == 5 { + length = length.max((j - i + 1) as i32); + } + + i = j + 1; + } + + length + } +} diff --git a/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.swift b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.swift new file mode 100644 index 00000000..7ec47dd6 --- /dev/null +++ b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.swift @@ -0,0 +1,32 @@ +class Solution { + func longestBeautifulSubstring(_ word: String) -> Int { + let chars = Array(word) + let n = chars.count + var i = 0 + var length = 0 + + while i < n { + if chars[i] != "a" { + i += 1 + continue + } + + var j = i + var unique = 1 + while j + 1 < n && chars[j + 1] >= chars[j] { + if chars[j + 1] != chars[j] { + unique += 1 + } + j += 1 + } + + if unique == 5 { + length = max(length, j - i + 1) + } + + i = j + 1 + } + + return length + } +} diff --git a/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.ts b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.ts new file mode 100644 index 00000000..90c09202 --- /dev/null +++ b/tests/1501-2000/1839. longest-substring-of-all-vowels-in-order/sol.ts @@ -0,0 +1,29 @@ +function longestBeautifulSubstring(word: string): number { + const n = word.length; + let i = 0; + let length = 0; + + while (i < n) { + if (word[i] !== "a") { + i++; + continue; + } + + let j = i; + let unique = 1; + while (j + 1 < n && word[j + 1] >= word[j]) { + if (word[j + 1] !== word[j]) { + unique++; + } + j++; + } + + if (unique === 5) { + length = Math.max(length, j - i + 1); + } + + i = j + 1; + } + + return length; +} diff --git a/tests/1501-2000/1840. maximum-building-height/manifest.yaml b/tests/1501-2000/1840. maximum-building-height/manifest.yaml new file mode 100644 index 00000000..d60d6323 --- /dev/null +++ b/tests/1501-2000/1840. maximum-building-height/manifest.yaml @@ -0,0 +1,330 @@ +entry: + id: 1840 + title: maximum-building-height + params: + n: + type: int + restrictions: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().maxBuilding({n}, {restrictions})" + rust: "Solution::max_building({n}, {restrictions})" + python3: "Solution().maxBuilding({n}, {restrictions})" + python2: "Solution().maxBuilding({n}, {restrictions})" + ruby: "max_building({n}, {restrictions})" + java: "new Solution().maxBuilding({n}, {restrictions})" + csharp: "new Solution().MaxBuilding({n}, {restrictions})" + kotlin: "Solution().maxBuilding({n}, {restrictions})" + go: "maxBuilding({n}, {restrictions})" + dart: "Solution().maxBuilding({n}, {restrictions})" + swift: "Solution().maxBuilding({n}, {restrictions})" + typescript: "maxBuilding({n}, {restrictions})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 512 +oracle: + python3: + call: "Checker().maxBuilding(n, restrictions, {result})" + checker: | + class Checker: + def maxBuilding(self, n, restrictions, result): + points = [[1, 0]] + [list(x) for x in restrictions] + points.sort() + for i in range(1, len(points)): + points[i][1] = min(points[i][1], points[i - 1][1] + points[i][0] - points[i - 1][0]) + for i in range(len(points) - 2, -1, -1): + points[i][1] = min(points[i][1], points[i + 1][1] + points[i + 1][0] - points[i][0]) + best = 0 + for left, right in zip(points, points[1:]): + best = max(best, (left[1] + right[1] + right[0] - left[0]) // 2) + best = max(best, points[-1][1] + n - points[-1][0]) + return isinstance(result, int) and result == best +seed: 1840 +tests: + - name: three-empty + in: + n: 3 + restrictions: [] + out: 2 + - name: four-empty + in: + n: 4 + restrictions: [] + out: 3 + - name: ten-empty + in: + n: 10 + restrictions: [] + out: 9 + - name: example-one + in: + n: 5 + restrictions: + - [2, 1] + - [4, 1] + out: 2 + - name: example-two + in: + n: 6 + restrictions: [] + out: 5 + - name: example-three + in: + n: 10 + restrictions: + - [5, 3] + - [2, 5] + - [7, 4] + - [10, 3] + out: 5 + - name: final-zero + in: + n: 5 + restrictions: + - [5, 0] + out: 2 + - name: early-zero + in: + n: 10 + restrictions: + - [2, 0] + out: 8 + - name: end-zero + in: + n: 10 + restrictions: + - [10, 0] + out: 4 + - name: middle-zero + in: + n: 10 + restrictions: + - [5, 0] + out: 5 + - name: two-low-peaks + in: + n: 10 + restrictions: + - [3, 1] + - [7, 1] + out: 4 + - name: three-boundaries + in: + n: 20 + restrictions: + - [2, 1] + - [10, 2] + - [20, 0] + out: 6 + - name: hundred-middle-cap + in: + n: 100 + restrictions: + - [50, 10] + out: 60 + - name: billion-empty + in: + n: 1000000000 + restrictions: [] + out: 999999999 + - name: billion-final-zero + in: + n: 1000000000 + restrictions: + - [1000000000, 0] + out: 499999999 + - name: billion-two-zeroes + in: + n: 1000000000 + restrictions: + - [2, 0] + - [999999999, 0] + out: 499999998 + - name: two-equal-caps + in: + n: 15 + restrictions: + - [5, 2] + - [10, 2] + out: 7 + - name: mixed-three + in: + n: 20 + restrictions: + - [4, 10] + - [8, 0] + - [15, 10] + out: 12 + - name: late-low-cap + in: + n: 12 + restrictions: + - [6, 1] + - [12, 1] + out: 4 + - name: high-caps-around-low + in: + n: 50 + restrictions: + - [2, 100] + - [25, 3] + - [49, 100] + out: 28 + - name: repeated-zero-barriers + in: + n: 30 + restrictions: + - [10, 0] + - [20, 0] + - [30, 0] + out: 5 + - name: early-and-late-zero + in: + n: 25 + restrictions: + - [2, 0] + - [3, 0] + - [24, 0] + out: 10 + - name: final-high-cap + in: + n: 7 + restrictions: + - [7, 100] + out: 6 + - name: central-cap + in: + n: 8 + restrictions: + - [4, 1] + out: 5 + - name: broad-equal-caps + in: + n: 9 + restrictions: + - [2, 5] + - [5, 5] + - [9, 5] + out: 6 + - name: thousand-three-caps + in: + n: 1000 + restrictions: + - [100, 1] + - [500, 100] + - [900, 1] + out: 250 + - name: hundred-thousand-caps + in: + n: 100000 + restrictions: + - [2, 1] + - [50000, 1000] + - [99999, 1] + out: 25500 + - name: odd-middle-zero + in: + n: 17 + restrictions: + - [9, 0] + out: 8 + - name: end-cap-almost-natural + in: + n: 18 + restrictions: + - [2, 0] + - [18, 17] + out: 16 + - name: close-low-caps + in: + n: 40 + restrictions: + - [5, 1] + - [6, 1] + - [35, 2] + out: 16 + - name: single-middle-zero-large + in: + n: 60 + restrictions: + - [30, 0] + out: 30 + - name: clustered-early-caps + in: + n: 11 + restrictions: + - [2, 1] + - [3, 1] + - [4, 1] + - [8, 2] + out: 5 + - name: adjacent-low-caps + in: + n: 22 + restrictions: + - [11, 4] + - [12, 0] + - [22, 5] + out: 7 + - name: odd-large-final + in: + n: 31 + restrictions: + - [16, 1] + - [31, 30] + out: 16 + - name: billion-large-cap + in: + n: 1000000000 + restrictions: + - [500000000, 123456789] + - [999999999, 999999999] + out: 623456789 + - name: generated-empty-small + in: + n: + gen: int + min: 3 + max: 1000 + restrictions: [] + - name: generated-empty-large + in: + n: + gen: int + min: 100000000 + max: 1000000000 + restrictions: [] + - name: generated-fixed-barrier + in: + n: + gen: int + min: 20 + max: 1000000000 + restrictions: + - [2, 0] + - [10, 1] + - name: generated-middle-cap + in: + n: + gen: int + min: 100 + max: 1000000000 + restrictions: + - [50, 10] + - [99, 0] + - name: generated-three-caps + in: + n: + gen: int + min: 1000 + max: 1000000000 + restrictions: + - [2, 1] + - [500, 100] + - [999, 1] diff --git a/tests/1501-2000/1840. maximum-building-height/sol.cpp b/tests/1501-2000/1840. maximum-building-height/sol.cpp new file mode 100644 index 00000000..1c21becb --- /dev/null +++ b/tests/1501-2000/1840. maximum-building-height/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int maxBuilding(int n, vector>& restrictions) { + restrictions.push_back({1, 0}); + sort(restrictions.begin(), restrictions.end()); + int m = restrictions.size(); + + for (int i = 1; i < m; i++) { + restrictions[i][1] = min(restrictions[i][1], restrictions[i-1][1] + abs(restrictions[i][0] - restrictions[i-1][0])); + } + + for (int i = m - 2; i >= 0; i--) { + restrictions[i][1] = min(restrictions[i][1], restrictions[i+1][1] + abs(restrictions[i+1][0] - restrictions[i][0])); + } + + int res = 0; + for (int i = 1; i < m; i++) { + res = max(res, (restrictions[i-1][1] + restrictions[i][1] + restrictions[i][0] - restrictions[i-1][0]) / 2); + } + + return max(res, restrictions[m-1][1] + n - restrictions[m-1][0]); + } +}; diff --git a/tests/1501-2000/1840. maximum-building-height/sol.cs b/tests/1501-2000/1840. maximum-building-height/sol.cs new file mode 100644 index 00000000..d693e4ab --- /dev/null +++ b/tests/1501-2000/1840. maximum-building-height/sol.cs @@ -0,0 +1,23 @@ +public class Solution { + public int MaxBuilding(int n, int[][] restrictions) { + var r = restrictions.ToList(); + r.Add(new int[]{1, 0}); + r.Sort((a, b) => a[0].CompareTo(b[0])); + int m = r.Count; + + for (int i = 1; i < m; i++) { + r[i][1] = Math.Min(r[i][1], r[i-1][1] + Math.Abs(r[i][0] - r[i-1][0])); + } + + for (int i = m - 2; i >= 0; i--) { + r[i][1] = Math.Min(r[i][1], r[i+1][1] + Math.Abs(r[i+1][0] - r[i][0])); + } + + int res = 0; + for (int i = 1; i < m; i++) { + res = Math.Max(res, (r[i-1][1] + r[i][1] + r[i][0] - r[i-1][0]) / 2); + } + + return Math.Max(res, r[m-1][1] + n - r[m-1][0]); + } +} diff --git a/tests/1501-2000/1840. maximum-building-height/sol.dart b/tests/1501-2000/1840. maximum-building-height/sol.dart new file mode 100644 index 00000000..e5221e88 --- /dev/null +++ b/tests/1501-2000/1840. maximum-building-height/sol.dart @@ -0,0 +1,26 @@ +import 'dart:math' as math; + +class Solution { + int maxBuilding(int n, List> restrictions) { + List> r = List.from(restrictions); + r.add([1, 0]); + r.sort((a, b) => a[0].compareTo(b[0])); + int m = r.length; + + for (int i = 1; i < m; i++) { + r[i][1] = math.min(r[i][1], r[i-1][1] + (r[i][0] - r[i-1][0]).abs()); + } + + for (int i = m - 2; i >= 0; i--) { + r[i][1] = math.min(r[i][1], r[i+1][1] + (r[i+1][0] - r[i][0]).abs()); + } + + int res = 0; + for (int i = 1; i < m; i++) { + int peak = (r[i-1][1] + r[i][1] + r[i][0] - r[i-1][0]) ~/ 2; + if (peak > res) res = peak; + } + + return math.max(res, r[m-1][1] + n - r[m-1][0]); + } +} diff --git a/tests/1501-2000/1840. maximum-building-height/sol.go b/tests/1501-2000/1840. maximum-building-height/sol.go new file mode 100644 index 00000000..bb1bde3f --- /dev/null +++ b/tests/1501-2000/1840. maximum-building-height/sol.go @@ -0,0 +1,34 @@ +func maxBuilding(n int, restrictions [][]int) int { + r := make([][]int, len(restrictions)+1) + copy(r[:len(restrictions)], restrictions) + r[len(restrictions)] = []int{1, 0} + sort.Slice(r, func(i, j int) bool { return r[i][0] < r[j][0] }) + m := len(r) + + for i := 1; i < m; i++ { + if r[i][1] > r[i-1][1] + absInt(r[i][0] - r[i-1][0]) { + r[i][1] = r[i-1][1] + absInt(r[i][0] - r[i-1][0]) + } + } + + for i := m - 2; i >= 0; i-- { + if r[i][1] > r[i+1][1] + absInt(r[i+1][0] - r[i][0]) { + r[i][1] = r[i+1][1] + absInt(r[i+1][0] - r[i][0]) + } + } + + res := 0 + for i := 1; i < m; i++ { + peak := (r[i-1][1] + r[i][1] + r[i][0] - r[i-1][0]) / 2 + if peak > res { + res = peak + } + } + + last := r[m-1][1] + n - r[m-1][0] + if last > res { + return last + } + return res +} + diff --git a/tests/1501-2000/1840. maximum-building-height/sol.java b/tests/1501-2000/1840. maximum-building-height/sol.java new file mode 100644 index 00000000..7d02f626 --- /dev/null +++ b/tests/1501-2000/1840. maximum-building-height/sol.java @@ -0,0 +1,26 @@ +class Solution { + public int maxBuilding(int n, int[][] restrictions) { + int[][] r = new int[restrictions.length + 1][2]; + for (int i = 0; i < restrictions.length; i++) { + r[i] = restrictions[i]; + } + r[restrictions.length] = new int[]{1, 0}; + java.util.Arrays.sort(r, (a, b) -> Integer.compare(a[0], b[0])); + int m = r.length; + + for (int i = 1; i < m; i++) { + r[i][1] = Math.min(r[i][1], r[i-1][1] + Math.abs(r[i][0] - r[i-1][0])); + } + + for (int i = m - 2; i >= 0; i--) { + r[i][1] = Math.min(r[i][1], r[i+1][1] + Math.abs(r[i+1][0] - r[i][0])); + } + + int res = 0; + for (int i = 1; i < m; i++) { + res = Math.max(res, (r[i-1][1] + r[i][1] + r[i][0] - r[i-1][0]) / 2); + } + + return Math.max(res, r[m-1][1] + n - r[m-1][0]); + } +} diff --git a/tests/1501-2000/1840. maximum-building-height/sol.kt b/tests/1501-2000/1840. maximum-building-height/sol.kt new file mode 100644 index 00000000..4c7c0c06 --- /dev/null +++ b/tests/1501-2000/1840. maximum-building-height/sol.kt @@ -0,0 +1,23 @@ +class Solution { + fun maxBuilding(n: Int, restrictions: Array): Int { + val r = restrictions.toMutableList() + r.add(intArrayOf(1, 0)) + r.sortBy { it[0] } + val m = r.size + + for (i in 1 until m) { + r[i][1] = minOf(r[i][1], r[i-1][1] + Math.abs(r[i][0] - r[i-1][0])) + } + + for (i in m - 2 downTo 0) { + r[i][1] = minOf(r[i][1], r[i+1][1] + Math.abs(r[i+1][0] - r[i][0])) + } + + var res = 0 + for (i in 1 until m) { + res = maxOf(res, (r[i-1][1] + r[i][1] + r[i][0] - r[i-1][0]) / 2) + } + + return maxOf(res, r[m-1][1] + n - r[m-1][0]) + } +} diff --git a/tests/1501-2000/1840. maximum-building-height/sol.py b/tests/1501-2000/1840. maximum-building-height/sol.py new file mode 100644 index 00000000..8fe7b492 --- /dev/null +++ b/tests/1501-2000/1840. maximum-building-height/sol.py @@ -0,0 +1,25 @@ +class Solution: + def maxBuilding(self, n: int, restrictions: list[list[int]]) -> int: + num = n + r = restrictions + r.append([1, 0]) + r.sort() + n = len(r) + + def yCap(x1, y1, x2, y2): + return min(y2, y1 + abs(x2 - x1)) + + def yPeak(x1, y1, x2, y2): + return (y1 + y2 + x2 - x1) >> 1 + + for i in range(1, n): + r[i][1] = yCap(*r[i - 1], *r[i]) + + for i in range(n - 2, -1, -1): + r[i][1] = yCap(*r[i + 1], *r[i]) + + res = 0 + for i in range(1, n): + res = max(res, yPeak(*r[i - 1], *r[i])) + + return max(res, r[-1][1] + num - r[-1][0]) diff --git a/tests/1501-2000/1840. maximum-building-height/sol.py2 b/tests/1501-2000/1840. maximum-building-height/sol.py2 new file mode 100644 index 00000000..c21adb3a --- /dev/null +++ b/tests/1501-2000/1840. maximum-building-height/sol.py2 @@ -0,0 +1,28 @@ +class Solution(object): + def maxBuilding(self, n, restrictions): + """ + :type n: int + :type restrictions: List[List[int]] + :rtype: int + """ + restrictions.append([1, 0]) + restrictions.sort() + m = len(restrictions) + + def yCap(x1, y1, x2, y2): + return min(y2, y1 + abs(x2 - x1)) + + def yPeak(x1, y1, x2, y2): + return (y1 + y2 + x2 - x1) >> 1 + + for i in range(1, m): + restrictions[i][1] = yCap(restrictions[i-1][0], restrictions[i-1][1], restrictions[i][0], restrictions[i][1]) + + for i in range(m-2, -1, -1): + restrictions[i][1] = yCap(restrictions[i+1][0], restrictions[i+1][1], restrictions[i][0], restrictions[i][1]) + + res = 0 + for i in range(1, m): + res = max(res, yPeak(restrictions[i-1][0], restrictions[i-1][1], restrictions[i][0], restrictions[i][1])) + + return max(res, restrictions[-1][1] + n - restrictions[-1][0]) diff --git a/tests/1501-2000/1840. maximum-building-height/sol.rb b/tests/1501-2000/1840. maximum-building-height/sol.rb new file mode 100644 index 00000000..8cea434d --- /dev/null +++ b/tests/1501-2000/1840. maximum-building-height/sol.rb @@ -0,0 +1,26 @@ +# @param {Integer} n +# @param {Integer[][]} restrictions +# @return {Integer} +def max_building(n, restrictions) + restrictions << [1, 0] + restrictions.sort! + m = restrictions.length + + y_cap = ->(x1, y1, x2, y2) { [y2, y1 + (x2 - x1).abs].min } + y_peak = ->(x1, y1, x2, y2) { (y1 + y2 + x2 - x1) >> 1 } + + (1...m).each do |i| + restrictions[i][1] = y_cap.call(restrictions[i-1][0], restrictions[i-1][1], restrictions[i][0], restrictions[i][1]) + end + + (m-2).downto(0) do |i| + restrictions[i][1] = y_cap.call(restrictions[i+1][0], restrictions[i+1][1], restrictions[i][0], restrictions[i][1]) + end + + res = 0 + (1...m).each do |i| + res = [res, y_peak.call(restrictions[i-1][0], restrictions[i-1][1], restrictions[i][0], restrictions[i][1])].max + end + + [res, restrictions[-1][1] + n - restrictions[-1][0]].max +end diff --git a/tests/1501-2000/1840. maximum-building-height/sol.rs b/tests/1501-2000/1840. maximum-building-height/sol.rs new file mode 100644 index 00000000..cb15e4eb --- /dev/null +++ b/tests/1501-2000/1840. maximum-building-height/sol.rs @@ -0,0 +1,36 @@ +impl Solution { + pub fn max_building(n: i32, restrictions: Vec>) -> i32 { + let mut r = restrictions.clone(); + r.push(vec![1, 0]); + r.sort_by(|a, b| a[0].cmp(&b[0])); + let m = r.len(); + + for i in 1..m { + let y = r[i-1][1] + (r[i][0] - r[i-1][0]).abs(); + if r[i][1] > y { + r[i][1] = y; + } + } + + for i in (0..m-1).rev() { + let y = r[i+1][1] + (r[i+1][0] - r[i][0]).abs(); + if r[i][1] > y { + r[i][1] = y; + } + } + + let mut res = 0; + for i in 1..m { + let peak = (r[i-1][1] + r[i][1] + r[i][0] - r[i-1][0]) / 2; + if peak > res { + res = peak; + } + } + + let last = r[m-1][1] + n - r[m-1][0]; + if last > res { + return last; + } + res + } +} diff --git a/tests/1501-2000/1840. maximum-building-height/sol.swift b/tests/1501-2000/1840. maximum-building-height/sol.swift new file mode 100644 index 00000000..00f5b968 --- /dev/null +++ b/tests/1501-2000/1840. maximum-building-height/sol.swift @@ -0,0 +1,24 @@ +class Solution { + func maxBuilding(_ n: Int, _ restrictions: [[Int]]) -> Int { + var r = restrictions + r.append([1, 0]) + r.sort { $0[0] < $1[0] } + let m = r.count + + for i in 1.. a[0] - b[0]); + const m = r.length; + + for (let i = 1; i < m; i++) { + r[i][1] = Math.min(r[i][1], r[i - 1][1] + Math.abs(r[i][0] - r[i - 1][0])); + } + + for (let i = m - 2; i >= 0; i--) { + r[i][1] = Math.min(r[i][1], r[i + 1][1] + Math.abs(r[i + 1][0] - r[i][0])); + } + + let res = 0; + for (let i = 1; i < m; i++) { + const peak = Math.floor( + (r[i - 1][1] + r[i][1] + r[i][0] - r[i - 1][0]) / 2, + ); + res = Math.max(res, peak); + } + + return Math.max(res, r[m - 1][1] + n - r[m - 1][0]); +} diff --git a/tests/1501-2000/1844. replace-all-digits-with-characters/manifest.yaml b/tests/1501-2000/1844. replace-all-digits-with-characters/manifest.yaml new file mode 100644 index 00000000..3d26771c --- /dev/null +++ b/tests/1501-2000/1844. replace-all-digits-with-characters/manifest.yaml @@ -0,0 +1,143 @@ +entry: + id: 1844 + title: "replace-all-digits-with-characters" + params: + s: + type: string + call: + cpp: "Solution().replaceDigits({s})" + rust: "Solution::replace_digits({s})" + python3: "Solution().replaceDigits({s})" + python2: "Solution().replaceDigits({s})" + ruby: "replace_digits({s})" + java: "new Solution().replaceDigits({s})" + csharp: "new Solution().ReplaceDigits({s})" + kotlin: "Solution().replaceDigits({s})" + go: "replaceDigits({s})" + dart: "Solution().replaceDigits({s})" + swift: "Solution().replaceDigits({s})" + typescript: "replaceDigits({s})" +judge: + type: "exact" +limits: + time_ms: 1000 + memory_mb: 256 +oracle: + python3: + call: "Checker().replaceDigits(s, {result})" + checker: | + class Checker: + def replaceDigits(self, s, result): + if not isinstance(result, str) or len(result) != len(s): + return False + expected = list(s) + for i in range(1, len(expected), 2): + expected[i] = chr(ord(expected[i - 1]) + int(expected[i])) + return result == ''.join(expected) +seed: 1844 +tests: + - name: single-letter + in: + s: "a" + - name: zero-shift + in: + s: "a0" + - name: maximum-shift + in: + s: "a9" + - name: example-one + in: + s: "a1c1e1" + - name: example-two + in: + s: "a1b2c3d4e" + - name: all-zero + in: + s: "a0b0c0d0e" + - name: consecutive-one + in: + s: "a1b1c1d1e" + - name: increasing-digits + in: + s: "a1b2c3d4e5" + - name: decreasing-digits + in: + s: "a5b4c3d2e1" + - name: high-start + in: + s: "q1r1s1t1u" + - name: boundary-z + in: + s: "q9" + - name: boundary-y + in: + s: "y1" + - name: mixed-zero-nine + in: + s: "a9j0k9t" + - name: short-even + in: + s: "d3e0" + - name: varied-letters + in: + s: "c2f4k1m3p" + - name: repeated-letter + in: + s: "m2m2m2m" + - name: zero-after-z + in: + s: "z0a0z0a" + - name: alternating-nine-one + in: + s: "a9j1k9t1u" + - name: no-final-digit + in: + s: "x0y1z" + - name: every-digit + in: + s: "a1b1c1d1e1f" + - name: low-letters + in: + s: "a1b2c1d2e" + - name: near-upper-limit + in: + s: "w3x2y1z" + - name: two-pairs + in: + s: "h4n3" + - name: four-pairs + in: + s: "a2c2e2g2i" + - name: mixed-digits + in: + s: "f1g2h3i4j" + - name: safe-nine-pairs + in: + s: "a9j9a9j" + - name: length-seven + in: + s: "b1d2f3h" + - name: length-eight + in: + s: "b1d2f3h4" + - name: boundary-pairs + in: + s: "r8s7t6u5v" + - name: long-zero-pattern + in: + s: "a0b0c0d0e0f0g0h0i0j0k0l0m0n0o0p0q0r0s0t0u0v0w0x0y0z" + - name: long-one-pattern + in: + s: "a1b1c1d1e1f1g1h1i1j1k1l1m1n1o1p1q1r1s1t1u1v1w1x1y1" + - name: long-small-shifts + in: + s: "a1b0c1d0e1f0g1h0i1j0k1l0m1n0o1p0q1r0s1t0u1v0w1x0y1z0" + - name: max-safe-start + in: + s: "a0b1c2d3e4f5g6h7i8j9" + - name: middle-letter-zero + in: + s: "p0" + - name: all-nine-safe + in: + s: "a9j0a9j0a9j" diff --git a/tests/1501-2000/1844. replace-all-digits-with-characters/sol.cpp b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.cpp new file mode 100644 index 00000000..01102c8a --- /dev/null +++ b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + string replaceDigits(string s) { + for (int i = 1; i < s.length(); i += 2) { + char ch = s[i - 1]; + int digit = s[i] - '0'; + s[i] = ch + digit; + } + return s; + } +}; diff --git a/tests/1501-2000/1844. replace-all-digits-with-characters/sol.cs b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.cs new file mode 100644 index 00000000..3e86a110 --- /dev/null +++ b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.cs @@ -0,0 +1,11 @@ +public class Solution { + public string ReplaceDigits(string s) { + char[] chars = s.ToCharArray(); + for (int i = 1; i < chars.Length; i += 2) { + char ch = chars[i - 1]; + int digit = chars[i] - '0'; + chars[i] = (char)(ch + digit); + } + return new string(chars); + } +} diff --git a/tests/1501-2000/1844. replace-all-digits-with-characters/sol.dart b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.dart new file mode 100644 index 00000000..1f79ab4d --- /dev/null +++ b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.dart @@ -0,0 +1,11 @@ +class Solution { + String replaceDigits(String s) { + List chars = s.split(''); + for (int i = 1; i < chars.length; i += 2) { + String ch = chars[i - 1]; + int digit = int.parse(chars[i]); + chars[i] = String.fromCharCode(ch.codeUnitAt(0) + digit); + } + return chars.join(); + } +} diff --git a/tests/1501-2000/1844. replace-all-digits-with-characters/sol.go b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.go new file mode 100644 index 00000000..20bc93f3 --- /dev/null +++ b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.go @@ -0,0 +1,9 @@ +func replaceDigits(s string) string { + chars := []byte(s) + for i := 1; i < len(chars); i += 2 { + ch := chars[i-1] + digit := chars[i] - '0' + chars[i] = ch + digit + } + return string(chars) +} diff --git a/tests/1501-2000/1844. replace-all-digits-with-characters/sol.java b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.java new file mode 100644 index 00000000..a980a0f1 --- /dev/null +++ b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.java @@ -0,0 +1,11 @@ +class Solution { + public String replaceDigits(String s) { + char[] chars = s.toCharArray(); + for (int i = 1; i < chars.length; i += 2) { + char ch = chars[i - 1]; + int digit = chars[i] - '0'; + chars[i] = (char)(ch + digit); + } + return new String(chars); + } +} diff --git a/tests/1501-2000/1844. replace-all-digits-with-characters/sol.kt b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.kt new file mode 100644 index 00000000..359d0de1 --- /dev/null +++ b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.kt @@ -0,0 +1,11 @@ +class Solution { + fun replaceDigits(s: String): String { + val chars = s.toCharArray() + for (i in 1 until chars.size step 2) { + val ch = chars[i - 1] + val digit = chars[i] - '0' + chars[i] = (ch + digit).toChar() + } + return String(chars) + } +} diff --git a/tests/1501-2000/1844. replace-all-digits-with-characters/sol.py b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.py new file mode 100644 index 00000000..d462d310 --- /dev/null +++ b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.py @@ -0,0 +1,11 @@ +class Solution: + def replaceDigits(self, s: str) -> str: + s = list(s) + + for i in range(1, len(s), 2): + ch = s[i - 1] + digit = int(s[i]) + + s[i] = chr(ord(ch) + digit) + + return "".join(s) diff --git a/tests/1501-2000/1844. replace-all-digits-with-characters/sol.py2 b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.py2 new file mode 100644 index 00000000..c8dd07fd --- /dev/null +++ b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def replaceDigits(self, s): + """ + :type s: str + :rtype: str + """ + s = list(s) + for i in range(1, len(s), 2): + ch = s[i - 1] + digit = int(s[i]) + s[i] = chr(ord(ch) + digit) + return ''.join(s) diff --git a/tests/1501-2000/1844. replace-all-digits-with-characters/sol.rb b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.rb new file mode 100644 index 00000000..2f545da3 --- /dev/null +++ b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.rb @@ -0,0 +1,11 @@ +# @param {String} s +# @return {String} +def replace_digits(s) + s = s.chars + (1...s.length).step(2).each do |i| + ch = s[i - 1] + digit = s[i].to_i + s[i] = (ch.ord + digit).chr + end + s.join +end diff --git a/tests/1501-2000/1844. replace-all-digits-with-characters/sol.rs b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.rs new file mode 100644 index 00000000..d20b412d --- /dev/null +++ b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.rs @@ -0,0 +1,12 @@ +impl Solution { + pub fn replace_digits(s: String) -> String { + let mut chars: Vec = s.chars().collect(); + for i in (1..chars.len()).step_by(2) { + let ch = chars[i - 1]; + let digit = chars[i].to_digit(10).unwrap(); + let new_char = (ch as u8 + digit as u8) as char; + chars[i] = new_char; + } + chars.into_iter().collect() + } +} diff --git a/tests/1501-2000/1844. replace-all-digits-with-characters/sol.swift b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.swift new file mode 100644 index 00000000..02d282db --- /dev/null +++ b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.swift @@ -0,0 +1,11 @@ +class Solution { + func replaceDigits(_ s: String) -> String { + var chars = Array(s) + for i in stride(from: 1, through: chars.count - 1, by: 2) { + let ch = chars[i - 1] + let digit = Int(String(chars[i]))! + chars[i] = Character(UnicodeScalar(Int(ch.asciiValue!) + digit)!) + } + return String(chars) + } +} diff --git a/tests/1501-2000/1844. replace-all-digits-with-characters/sol.ts b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.ts new file mode 100644 index 00000000..b18ae7af --- /dev/null +++ b/tests/1501-2000/1844. replace-all-digits-with-characters/sol.ts @@ -0,0 +1,9 @@ +function replaceDigits(s: string): string { + const chars = s.split(""); + for (let i = 1; i < chars.length; i += 2) { + const ch = chars[i - 1]; + const digit = parseInt(chars[i]); + chars[i] = String.fromCharCode(ch.charCodeAt(0) + digit); + } + return chars.join(""); +} diff --git a/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/manifest.yaml b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/manifest.yaml new file mode 100644 index 00000000..ac6ab616 --- /dev/null +++ b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/manifest.yaml @@ -0,0 +1,270 @@ +entry: + id: 1846 + title: "maximum-element-after-decreasing-and-rearranging" + params: + arr: + type: array + items: + type: int + call: + cpp: "Solution().maximumElementAfterDecrementingAndRearranging({arr})" + rust: "Solution::maximum_element_after_decrementing_and_rearranging({arr})" + python3: "Solution().maximumElementAfterDecrementingAndRearranging({arr})" + python2: "Solution().maximumElementAfterDecrementingAndRearranging({arr})" + ruby: "maximum_element_after_decrementing_and_rearranging({arr})" + java: "new Solution().maximumElementAfterDecrementingAndRearranging({arr})" + csharp: "new Solution().MaximumElementAfterDecrementingAndRearranging({arr})" + kotlin: "Solution().maximumElementAfterDecrementingAndRearranging({arr})" + go: "maximumElementAfterDecrementingAndRearranging({arr})" + dart: "Solution().maximumElementAfterDecrementingAndRearranging({arr})" + swift: "Solution().maximumElementAfterDecrementingAndRearranging({arr})" + typescript: "maximumElementAfterDecrementingAndRearranging({arr})" + +judge: + type: exact + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(arr, {result})" + checker: | + class Checker: + def check(self, arr, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + values = sorted(arr) + best = 0 + for value in values: + best = min(value, best + 1) if best else 1 + return result == best + +seed: 1846 + +tests: + - name: example-one + in: + arr: [2, 2, 1, 2, 1] + out: 2 + - name: example-two + in: + arr: [100, 1, 1000] + out: 3 + - name: example-three + in: + arr: [1, 2, 3, 4, 5] + out: 5 + - name: single-one + in: + arr: [1] + out: 1 + - name: single-large + in: + arr: [1000000000] + out: 1 + - name: all-ones + in: + arr: [1, 1, 1, 1, 1, 1, 1] + out: 1 + - name: consecutive-small + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8] + out: 8 + - name: consecutive-reversed + in: + arr: [8, 7, 6, 5, 4, 3, 2, 1] + out: 8 + - name: all-large-equal + in: + arr: [99, 99, 99, 99, 99] + out: 5 + - name: powers-of-ten + in: + arr: [1000000000, 100000000, 10000000, 1000000, 100000] + out: 5 + - name: sparse-two + in: + arr: [1, 1000000000] + out: 2 + - name: sparse-three + in: + arr: [1, 1, 1000000000] + out: 2 + - name: mixed-duplicates + in: + arr: [4, 4, 4, 4, 1, 1, 2, 8, 9] + out: 6 + - name: low-cluster + in: + arr: [1, 2, 2, 3, 3, 3, 4] + out: 4 + - name: gaps-filled + in: + arr: [1, 3, 5, 7, 9, 11] + out: 6 + - name: no-one + in: + arr: [2, 3, 4, 5] + out: 4 + - name: huge-gap + in: + arr: [2, 100, 1000, 1000000000] + out: 4 + - name: length-ten-equal + in: + arr: [50, 50, 50, 50, 50, 50, 50, 50, 50, 50] + out: 10 + - name: length-ten-chain + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + out: 10 + - name: many-low-values + in: + arr: [1, 1, 2, 2, 2, 3, 3, 4, 100] + out: 5 + - name: alternating-extremes + in: + arr: [1000000000, 1, 1000000000, 1, 1000000000, 1] + out: 4 + - name: exact-capacity + in: + arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + out: 12 + - name: repeated-two + in: + arr: [2, 2, 2, 2, 2, 2] + out: 2 + - name: repeated-three + in: + arr: [3, 3, 3, 3, 3, 3] + out: 3 + - name: near-boundary + in: + arr: [1, 1, 1, 2, 2, 3, 10, 10, 10, 10] + out: 7 + - name: unsorted-random-small + in: + arr: [7, 1, 4, 2, 9, 2, 6] + out: 6 + - name: unsorted-random-medium + in: + arr: [20, 1, 15, 3, 8, 2, 30, 4, 4, 12, 100] + out: 10 + - name: only-max-values + in: + arr: [1000000000, 999999999, 888888888, 777777777] + out: 4 + - name: one-through-fifteen + in: + arr: [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + out: 15 + - name: duplicates-with-tail + in: + arr: [1, 1, 1, 1, 1, 100, 100, 100] + out: 4 + - name: balanced-values + in: + arr: [1, 2, 2, 3, 4, 5, 6, 7, 8] + out: 8 + - name: length-twenty-large + in: + arr: + [ + 1000000000, + 999999999, + 999999998, + 999999997, + 999999996, + 999999995, + 999999994, + 999999993, + 999999992, + 999999991, + 999999990, + 999999989, + 999999988, + 999999987, + 999999986, + 999999985, + 999999984, + 999999983, + 999999982, + 999999981, + ] + out: 20 + - name: length-twenty-ones + in: + arr: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 1 + - name: gen-random-broad + in: + arr: + gen: array + len: 100000 + of: + gen: int + min: 1 + max: 1000000000 + distinct: false + elemType: int + judge: + type: exact + seed: 1846001 + - name: gen-small-values + in: + arr: + gen: array + len: 100000 + of: + gen: int + min: 1 + max: 10 + distinct: false + elemType: int + judge: + type: exact + seed: 1846002 + - name: gen-large-equal-range + in: + arr: + gen: array + len: 50000 + of: + gen: int + min: 900000000 + max: 1000000000 + distinct: false + elemType: int + judge: + type: exact + seed: 1846003 + - name: gen-single-digit-range + in: + arr: + gen: array + len: 99999 + of: + gen: int + min: 1 + max: 100 + distinct: false + elemType: int + judge: + type: exact + seed: 1846004 + - name: gen-maximal-values + in: + arr: + gen: array + len: 100000 + of: + gen: int + min: 999999900 + max: 1000000000 + distinct: false + elemType: int + judge: + type: exact + seed: 1846005 diff --git a/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.cpp b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.cpp new file mode 100644 index 00000000..605b02aa --- /dev/null +++ b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int maximumElementAfterDecrementingAndRearranging(vector& arr) { + sort(arr.begin(), arr.end()); + arr[0] = 1; + for (int i = 1; i < arr.size(); i++) { + arr[i] = min(arr[i], arr[i - 1] + 1); + } + return arr.back(); + } +}; diff --git a/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.cs b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.cs new file mode 100644 index 00000000..f6579e33 --- /dev/null +++ b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.cs @@ -0,0 +1,10 @@ +public class Solution { + public int MaximumElementAfterDecrementingAndRearranging(int[] arr) { + Array.Sort(arr); + arr[0] = 1; + for (int i = 1; i < arr.Length; i++) { + arr[i] = Math.Min(arr[i], arr[i - 1] + 1); + } + return arr[arr.Length - 1]; + } +} diff --git a/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.dart b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.dart new file mode 100644 index 00000000..82e14447 --- /dev/null +++ b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.dart @@ -0,0 +1,10 @@ +class Solution { + int maximumElementAfterDecrementingAndRearranging(List arr) { + arr.sort(); + arr[0] = 1; + for (int i = 1; i < arr.length; i++) { + arr[i] = arr[i] < arr[i - 1] + 1 ? arr[i] : arr[i - 1] + 1; + } + return arr[arr.length - 1]; + } +} diff --git a/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.go b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.go new file mode 100644 index 00000000..251eb1aa --- /dev/null +++ b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.go @@ -0,0 +1,10 @@ +func maximumElementAfterDecrementingAndRearranging(arr []int) int { + sort.Ints(arr) + arr[0] = 1 + for i := 1; i < len(arr); i++ { + if arr[i] > arr[i-1]+1 { + arr[i] = arr[i-1] + 1 + } + } + return arr[len(arr)-1] +} diff --git a/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.java b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.java new file mode 100644 index 00000000..52cfa6be --- /dev/null +++ b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.java @@ -0,0 +1,10 @@ +class Solution { + public int maximumElementAfterDecrementingAndRearranging(int[] arr) { + java.util.Arrays.sort(arr); + arr[0] = 1; + for (int i = 1; i < arr.length; i++) { + arr[i] = Math.min(arr[i], arr[i - 1] + 1); + } + return arr[arr.length - 1]; + } +} diff --git a/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.kt b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.kt new file mode 100644 index 00000000..56d89b1a --- /dev/null +++ b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.kt @@ -0,0 +1,10 @@ +class Solution { + fun maximumElementAfterDecrementingAndRearranging(arr: IntArray): Int { + arr.sort() + arr[0] = 1 + for (i in 1 until arr.size) { + arr[i] = minOf(arr[i], arr[i - 1] + 1) + } + return arr[arr.size - 1] + } +} diff --git a/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.py b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.py new file mode 100644 index 00000000..5aa58e04 --- /dev/null +++ b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.py @@ -0,0 +1,11 @@ +class Solution: + def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int: + + arr.sort() + + arr[0] = 1 + + for i in range(1, len(arr)): + arr[i] = min(arr[i], arr[i - 1] + 1) + + return arr[-1] diff --git a/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.py2 b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.py2 new file mode 100644 index 00000000..e288b347 --- /dev/null +++ b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def maximumElementAfterDecrementingAndRearranging(self, arr): + """ + :type arr: List[int] + :rtype: int + """ + arr.sort() + arr[0] = 1 + for i in range(1, len(arr)): + arr[i] = min(arr[i], arr[i - 1] + 1) + return arr[-1] diff --git a/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.rb b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.rb new file mode 100644 index 00000000..2af7b560 --- /dev/null +++ b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.rb @@ -0,0 +1,10 @@ +# @param {Integer[]} arr +# @return {Integer} +def maximum_element_after_decrementing_and_rearranging(arr) + arr.sort! + arr[0] = 1 + (1...arr.length).each do |i| + arr[i] = [arr[i], arr[i-1] + 1].min + end + arr[-1] +end diff --git a/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.rs b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.rs new file mode 100644 index 00000000..ade5301a --- /dev/null +++ b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn maximum_element_after_decrementing_and_rearranging(arr: Vec) -> i32 { + let mut arr = arr; + arr.sort(); + arr[0] = 1; + for i in 1..arr.len() { + arr[i] = arr[i].min(arr[i - 1] + 1); + } + arr[arr.len() - 1] + } +} diff --git a/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.swift b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.swift new file mode 100644 index 00000000..83240621 --- /dev/null +++ b/tests/1501-2000/1846. maximum-element-after-decreasing-and-rearranging/sol.swift @@ -0,0 +1,11 @@ +class Solution { + func maximumElementAfterDecrementingAndRearranging(_ arr: [Int]) -> Int { + var arr = arr + arr.sort() + arr[0] = 1 + for i in 1.. a - b); + arr[0] = 1; + for (let i = 1; i < arr.length; i++) { + arr[i] = Math.min(arr[i], arr[i - 1] + 1); + } + return arr[arr.length - 1]; +} diff --git a/tests/1501-2000/1847. closest-room/manifest.yaml b/tests/1501-2000/1847. closest-room/manifest.yaml new file mode 100644 index 00000000..a5efc958 --- /dev/null +++ b/tests/1501-2000/1847. closest-room/manifest.yaml @@ -0,0 +1,489 @@ +entry: + id: 1847 + title: closest-room + params: + rooms: + type: array + items: + type: array + items: + type: int + queries: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().closestRoom({rooms}, {queries})" + rust: "Solution::closest_room({rooms}, {queries})" + python3: "Solution().closestRoom({rooms}, {queries})" + python2: "Solution().closestRoom({rooms}, {queries})" + ruby: "closest_room({rooms}, {queries})" + java: "new Solution().closestRoom({rooms}, {queries})" + csharp: "new Solution().ClosestRoom({rooms}, {queries})" + kotlin: "Solution().closestRoom({rooms}, {queries})" + go: "closestRoom({rooms}, {queries})" + dart: "Solution().closestRoom({rooms}, {queries})" + swift: "Solution().closestRoom({rooms}, {queries})" + typescript: "closestRoom({rooms}, {queries})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 512 +oracle: + python3: + call: "Checker().closestRoom(rooms, queries, {result})" + checker: | + class Checker: + def closestRoom(self, rooms, queries, result): + if not isinstance(result, list) or len(result) != len(queries): + return False + for answer, query in zip(result, queries): + preferred, minimum = query + valid = [room_id for room_id, size in rooms if size >= minimum] + expected = min(valid, key=lambda room_id: (abs(room_id - preferred), room_id)) if valid else -1 + if answer != expected: + return False + return True +seed: 1847 +tests: + - name: example-one + in: + rooms: + - [2, 2] + - [1, 2] + - [3, 2] + queries: + - [3, 1] + - [3, 3] + - [5, 2] + - name: example-two + in: + rooms: + - [1, 4] + - [2, 3] + - [3, 5] + - [4, 1] + - [5, 2] + queries: + - [2, 3] + - [2, 4] + - [2, 5] + - name: one-room-match + in: + rooms: + - [10, 7] + queries: + - [1, 1] + - [10, 7] + - [100, 8] + - name: exact-preferred + in: + rooms: + - [4, 1] + - [9, 10] + - [15, 5] + queries: + - [9, 10] + - [15, 5] + - [4, 1] + - name: tie-chooses-smaller + in: + rooms: + - [2, 9] + - [8, 9] + - [20, 1] + queries: + - [5, 9] + - [6, 9] + - [5, 1] + - name: all-too-small + in: + rooms: + - [1, 1] + - [2, 2] + - [3, 3] + queries: + - [1, 4] + - [2, 10] + - name: duplicate-sizes + in: + rooms: + - [100, 5] + - [1, 5] + - [50, 5] + - [75, 2] + queries: + - [60, 5] + - [2, 5] + - [74, 2] + - name: descending-ids + in: + rooms: + - [90, 3] + - [70, 8] + - [50, 1] + - [30, 6] + queries: + - [60, 6] + - [80, 7] + - [40, 1] + - name: size-thresholds + in: + rooms: + - [1, 10] + - [2, 20] + - [3, 30] + - [4, 40] + queries: + - [2, 10] + - [2, 20] + - [2, 21] + - [4, 40] + - name: preferred-outside-left + in: + rooms: + - [100, 5] + - [200, 6] + - [300, 7] + queries: + - [1, 5] + - [50, 6] + - [250, 7] + - name: preferred-outside-right + in: + rooms: + - [10, 5] + - [20, 6] + - [30, 7] + queries: + - [100, 5] + - [99, 6] + - [31, 7] + - name: mixed-gaps + in: + rooms: + - [3, 4] + - [11, 9] + - [25, 4] + - [40, 12] + - [62, 2] + queries: + - [18, 4] + - [18, 9] + - [50, 3] + - [62, 3] + - name: minimum-values + in: + rooms: + - [1, 1] + - [2, 1] + - [10000000, 1] + queries: + - [1, 1] + - [3, 1] + - [9999999, 1] + - name: maximum-values + in: + rooms: + - [10000000, 10000000] + - [9999999, 9999999] + - [1, 10000000] + queries: + - [10000000, 10000000] + - [5000000, 10000000] + - [1, 9999999] + - name: interleaved-eligibility + in: + rooms: + - [5, 10] + - [10, 1] + - [15, 8] + - [20, 3] + - [25, 6] + queries: + - [12, 9] + - [12, 7] + - [12, 2] + - [12, 11] + - name: many-ties + in: + rooms: + - [2, 100] + - [4, 100] + - [6, 100] + - [8, 100] + - [10, 100] + queries: + - [5, 100] + - [7, 100] + - [9, 100] + - [1, 100] + - name: negative-not-allowed-boundary + in: + rooms: + - [1, 2] + - [7, 3] + - [13, 4] + queries: + - [1, 2] + - [7, 4] + - [13, 5] + - name: ten-rooms + in: + rooms: + - [1, 9] + - [7, 1] + - [13, 5] + - [21, 9] + - [34, 2] + - [55, 8] + - [89, 3] + - [144, 10] + - [233, 4] + - [377, 6] + queries: + - [8, 1] + - [20, 8] + - [100, 6] + - [200, 10] + - [400, 11] + - name: repeated-query-pattern + in: + rooms: + - [10, 5] + - [20, 10] + - [30, 15] + queries: + - [21, 10] + - [21, 10] + - [21, 15] + - [21, 16] + - name: close-and-far + in: + rooms: + - [49, 7] + - [51, 7] + - [100, 7] + - [1, 8] + queries: + - [50, 7] + - [50, 8] + - [2, 8] + - name: sparse-large-ids + in: + rooms: + - [100, 10] + - [1000, 20] + - [10000, 30] + - [100000, 40] + - [1000000, 50] + queries: + - [500, 15] + - [5000, 25] + - [50000, 35] + - [500000, 45] + - name: alternating-sizes + in: + rooms: + - [1, 100] + - [2, 1] + - [3, 100] + - [4, 1] + - [5, 100] + - [6, 1] + queries: + - [2, 100] + - [4, 2] + - [6, 100] + - name: threshold-one + in: + rooms: + - [17, 1] + - [19, 1] + - [23, 1] + queries: + - [18, 1] + - [22, 1] + - [30, 1] + - name: threshold-max + in: + rooms: + - [17, 10000000] + - [19, 9999999] + - [23, 10000000] + queries: + - [18, 10000000] + - [20, 10000000] + - [20, 10000001] + - name: uneven-query-count + in: + rooms: + - [2, 2] + - [9, 4] + - [18, 6] + - [31, 8] + queries: + - [1, 1] + - [8, 3] + - [20, 5] + - [30, 7] + - [100, 9] + - name: room-order-randomized + in: + rooms: + - [42, 3] + - [5, 10] + - [99, 1] + - [17, 7] + - [64, 5] + queries: + - [40, 2] + - [40, 6] + - [60, 4] + - [90, 8] + - name: all-query-no-match + in: + rooms: + - [4, 1] + - [8, 2] + - [12, 3] + queries: + - [4, 4] + - [8, 5] + - [12, 100] + - name: broad-eligibility + in: + rooms: + - [100, 50] + - [200, 40] + - [300, 30] + - [400, 20] + - [500, 10] + queries: + - [250, 10] + - [250, 25] + - [250, 35] + - [250, 45] + - name: adjacent-ids + in: + rooms: + - [100, 5] + - [101, 5] + - [102, 5] + - [103, 5] + queries: + - [100, 5] + - [101, 5] + - [103, 6] + - name: query-preferred-one + in: + rooms: + - [1, 9] + - [2, 8] + - [3, 7] + - [4, 6] + queries: + - [1, 8] + - [1, 7] + - [1, 10] + - name: query-preferred-max + in: + rooms: + - [9999997, 3] + - [9999998, 6] + - [9999999, 9] + - [10000000, 12] + queries: + - [10000000, 5] + - [10000000, 10] + - [10000000, 13] + - name: six-query-mix + in: + rooms: + - [6, 2] + - [14, 11] + - [27, 5] + - [39, 11] + - [52, 1] + - [68, 9] + queries: + - [10, 1] + - [10, 10] + - [30, 6] + - [45, 10] + - [60, 8] + - [70, 12] + - name: seven-query-mix + in: + rooms: + - [3, 3] + - [16, 12] + - [29, 6] + - [44, 2] + - [58, 12] + - [73, 7] + - [91, 1] + queries: + - [1, 1] + - [20, 10] + - [35, 5] + - [50, 3] + - [65, 8] + - [80, 12] + - [100, 20] + - name: same-preferred-thresholds + in: + rooms: + - [40, 1] + - [45, 3] + - [50, 5] + - [55, 7] + - [60, 9] + queries: + - [50, 1] + - [50, 3] + - [50, 5] + - [50, 7] + - [50, 9] + - name: large-room-count + in: + rooms: + - [11, 100] + - [22, 99] + - [33, 98] + - [44, 97] + - [55, 96] + - [66, 95] + - [77, 94] + - [88, 93] + - [99, 92] + - [110, 91] + - [121, 90] + - [132, 89] + - [143, 88] + - [154, 87] + - [165, 86] + - [176, 85] + - [187, 84] + - [198, 83] + - [209, 82] + queries: + - [100, 80] + - [100, 90] + - [100, 100] + - [1, 95] + - name: final-boundary-mix + in: + rooms: + - [1, 10000000] + - [5000000, 5000000] + - [9999999, 2] + - [10000000, 10000000] + queries: + - [5000001, 5000000] + - [5000001, 10000000] + - [9999998, 3] + - [10000000, 10000001] diff --git a/tests/1501-2000/1847. closest-room/sol.cpp b/tests/1501-2000/1847. closest-room/sol.cpp new file mode 100644 index 00000000..74f3e139 --- /dev/null +++ b/tests/1501-2000/1847. closest-room/sol.cpp @@ -0,0 +1,49 @@ +class Solution { +public: + vector closestRoom(vector>& rooms, vector>& queries) { + sort(rooms.begin(), rooms.end(), [](const vector& a, const vector& b) { + return a[1] > b[1]; + }); + + vector idx(queries.size()); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int a, int b) { + return queries[a][1] > queries[b][1]; + }); + + set active; + vector result(queries.size(), -1); + int roomPtr = 0; + + for (int qi : idx) { + int preferred = queries[qi][0]; + int minimum = queries[qi][1]; + + while (roomPtr < rooms.size() && rooms[roomPtr][1] >= minimum) { + active.insert(rooms[roomPtr][0]); + roomPtr++; + } + + vector candidates; + auto it = active.lower_bound(preferred); + if (it != active.end()) candidates.push_back(*it); + if (it != active.begin()) { + --it; + candidates.push_back(*it); + } + + if (!candidates.empty()) { + int best = candidates[0]; + for (int i = 1; i < candidates.size(); i++) { + int id = candidates[i]; + if (abs(id - preferred) < abs(best - preferred) || + (abs(id - preferred) == abs(best - preferred) && id < best)) { + best = id; + } + } + result[qi] = best; + } + } + return result; + } +}; diff --git a/tests/1501-2000/1847. closest-room/sol.cs b/tests/1501-2000/1847. closest-room/sol.cs new file mode 100644 index 00000000..234c3493 --- /dev/null +++ b/tests/1501-2000/1847. closest-room/sol.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; + +public class Solution { + public int[] ClosestRoom(int[][] rooms, int[][] queries) { + Array.Sort(rooms, (a, b) => b[1].CompareTo(a[1])); + + int[] idx = new int[queries.Length]; + for (int i = 0; i < queries.Length; i++) idx[i] = i; + Array.Sort(idx, (a, b) => queries[b][1].CompareTo(queries[a][1])); + + SortedSet active = new SortedSet(); + int[] result = new int[queries.Length]; + Array.Fill(result, -1); + int roomPtr = 0; + + foreach (int qi in idx) { + int preferred = queries[qi][0]; + int minimum = queries[qi][1]; + + while (roomPtr < rooms.Length && rooms[roomPtr][1] >= minimum) { + active.Add(rooms[roomPtr][0]); + roomPtr++; + } + + List candidates = new List(); + var view = active.GetViewBetween(preferred, int.MaxValue); + if (view.Count > 0) candidates.Add(view.Min); + var prevView = active.GetViewBetween(int.MinValue, preferred); + if (prevView.Count > 0) candidates.Add(prevView.Max); + + if (candidates.Count > 0) { + int best = candidates[0]; + for (int i = 1; i < candidates.Count; i++) { + int id = candidates[i]; + if (Math.Abs(id - preferred) < Math.Abs(best - preferred) || + (Math.Abs(id - preferred) == Math.Abs(best - preferred) && id < best)) { + best = id; + } + } + result[qi] = best; + } + } + return result; + } +} diff --git a/tests/1501-2000/1847. closest-room/sol.dart b/tests/1501-2000/1847. closest-room/sol.dart new file mode 100644 index 00000000..7c9eb207 --- /dev/null +++ b/tests/1501-2000/1847. closest-room/sol.dart @@ -0,0 +1,43 @@ +import 'dart:collection'; + +class Solution { + List closestRoom(List> rooms, List> queries) { + rooms.sort((a, b) => b[1].compareTo(a[1])); + + List idx = List.generate(queries.length, (i) => i); + idx.sort((a, b) => queries[b][1].compareTo(queries[a][1])); + + SplayTreeSet active = SplayTreeSet(); + List result = List.filled(queries.length, -1); + int roomPtr = 0; + + for (int qi in idx) { + int preferred = queries[qi][0]; + int minimum = queries[qi][1]; + + while (roomPtr < rooms.length && rooms[roomPtr][1] >= minimum) { + active.add(rooms[roomPtr][0]); + roomPtr++; + } + + int? pos = active.firstWhere((id) => id >= preferred, orElse: () => -1); + int? prev = active.lastWhere((id) => id <= preferred, orElse: () => -1); + + List candidates = []; + if (pos != -1) candidates.add(pos); + if (prev != -1) candidates.add(prev); + + if (candidates.isNotEmpty) { + int best = candidates.reduce((a, b) { + int diffA = (a - preferred).abs(); + int diffB = (b - preferred).abs(); + if (diffA < diffB) return a; + if (diffB < diffA) return b; + return a < b ? a : b; + }); + result[qi] = best; + } + } + return result; + } +} diff --git a/tests/1501-2000/1847. closest-room/sol.go b/tests/1501-2000/1847. closest-room/sol.go new file mode 100644 index 00000000..df720b53 --- /dev/null +++ b/tests/1501-2000/1847. closest-room/sol.go @@ -0,0 +1,67 @@ +func closestRoom(rooms [][]int, queries [][]int) []int { + // sort rooms descending by size + sort.Slice(rooms, func(i, j int) bool { + return rooms[i][1] > rooms[j][1] + }) + + // sort query indices descending by minimum size + idx := make([]int, len(queries)) + for i := range idx { + idx[i] = i + } + sort.Slice(idx, func(i, j int) bool { + return queries[idx[i]][1] > queries[idx[j]][1] + }) + + active := []int{} + result := make([]int, len(queries)) + for i := range result { + result[i] = -1 + } + roomPtr := 0 + + for _, qi := range idx { + preferred := queries[qi][0] + minimum := queries[qi][1] + + for roomPtr < len(rooms) && rooms[roomPtr][1] >= minimum { + // insert into sorted order + id := rooms[roomPtr][0] + // binary search insertion position + pos := sort.SearchInts(active, id) + active = append(active, 0) + copy(active[pos+1:], active[pos:]) + active[pos] = id + roomPtr++ + } + + // binary search for preferred + pos := sort.SearchInts(active, preferred) + candidates := []int{} + if pos < len(active) { + candidates = append(candidates, active[pos]) + } + if pos > 0 { + candidates = append(candidates, active[pos-1]) + } + + if len(candidates) > 0 { + best := candidates[0] + for _, id := range candidates[1:] { + if abs(id-preferred) < abs(best-preferred) || + (abs(id-preferred) == abs(best-preferred) && id < best) { + best = id + } + } + result[qi] = best + } + } + return result +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} diff --git a/tests/1501-2000/1847. closest-room/sol.java b/tests/1501-2000/1847. closest-room/sol.java new file mode 100644 index 00000000..49efc529 --- /dev/null +++ b/tests/1501-2000/1847. closest-room/sol.java @@ -0,0 +1,46 @@ +import java.util.*; + +class Solution { + public int[] closestRoom(int[][] rooms, int[][] queries) { + Arrays.sort(rooms, (a, b) -> Integer.compare(b[1], a[1])); + + Integer[] idx = new Integer[queries.length]; + for (int i = 0; i < queries.length; i++) idx[i] = i; + Arrays.sort(idx, (a, b) -> Integer.compare(queries[b][1], queries[a][1])); + + TreeSet active = new TreeSet<>(); + int[] result = new int[queries.length]; + Arrays.fill(result, -1); + int roomPtr = 0; + + for (int qi : idx) { + int preferred = queries[qi][0]; + int minimum = queries[qi][1]; + + while (roomPtr < rooms.length && rooms[roomPtr][1] >= minimum) { + active.add(rooms[roomPtr][0]); + roomPtr++; + } + + Integer pos = active.ceiling(preferred); + Integer prev = active.floor(preferred); + int[] candidates = new int[2]; + int count = 0; + if (pos != null) candidates[count++] = pos; + if (prev != null) candidates[count++] = prev; + + if (count > 0) { + int best = candidates[0]; + for (int i = 1; i < count; i++) { + int id = candidates[i]; + if (Math.abs(id - preferred) < Math.abs(best - preferred) || + (Math.abs(id - preferred) == Math.abs(best - preferred) && id < best)) { + best = id; + } + } + result[qi] = best; + } + } + return result; + } +} diff --git a/tests/1501-2000/1847. closest-room/sol.kt b/tests/1501-2000/1847. closest-room/sol.kt new file mode 100644 index 00000000..38f8e746 --- /dev/null +++ b/tests/1501-2000/1847. closest-room/sol.kt @@ -0,0 +1,31 @@ +class Solution { + fun closestRoom(rooms: Array, queries: Array): IntArray { + val sortedRooms = rooms.sortedByDescending { it[1] } + val indexed = queries.indices.sortedByDescending { queries[it][1] } + + val active = sortedSetOf() + val result = IntArray(queries.size) { -1 } + var roomIdx = 0 + + for (qi in indexed) { + val preferred = queries[qi][0] + val minimum = queries[qi][1] + + while (roomIdx < sortedRooms.size && sortedRooms[roomIdx][1] >= minimum) { + active.add(sortedRooms[roomIdx][0]) + roomIdx++ + } + + val pos = active.ceiling(preferred) + val prev = active.floor(preferred) + val candidates = mutableListOf() + if (pos != null) candidates.add(pos) + if (prev != null) candidates.add(prev) + + if (candidates.isNotEmpty()) { + result[qi] = candidates.minWith(compareBy({ Math.abs(it - preferred) }, { it })) + } + } + return result + } +} diff --git a/tests/1501-2000/1847. closest-room/sol.py b/tests/1501-2000/1847. closest-room/sol.py new file mode 100644 index 00000000..12b9246a --- /dev/null +++ b/tests/1501-2000/1847. closest-room/sol.py @@ -0,0 +1,23 @@ +class Solution: + def closestRoom(self, rooms, queries): + rooms = sorted(rooms, key=lambda x: x[1], reverse=True) + indexed = sorted(enumerate(queries), key=lambda x: x[1][1], reverse=True) + from sortedcontainers import SortedList + + active = SortedList() + result = [-1] * len(queries) + + for qi, (preferred, minimum) in indexed: + while rooms and rooms[0][1] >= minimum: + active.add(rooms.pop(0)[0]) + pos = active.bisect_left(preferred) + candidates = [] + if pos < len(active): + candidates.append(active[pos]) + if pos: + candidates.append(active[pos - 1]) + if candidates: + result[qi] = min( + candidates, key=lambda room_id: (abs(room_id - preferred), room_id) + ) + return result diff --git a/tests/1501-2000/1847. closest-room/sol.py2 b/tests/1501-2000/1847. closest-room/sol.py2 new file mode 100644 index 00000000..d3083b01 --- /dev/null +++ b/tests/1501-2000/1847. closest-room/sol.py2 @@ -0,0 +1,26 @@ +class Solution(object): + def closestRoom(self, rooms, queries): + """ + :type rooms: List[List[int]] + :type queries: List[List[int]] + :rtype: List[int] + """ + rooms = sorted(rooms, key=lambda x: x[1], reverse=True) + indexed = sorted(enumerate(queries), key=lambda x: x[1][1], reverse=True) + + from sortedcontainers import SortedList + active = SortedList() + result = [-1] * len(queries) + + for qi, (preferred, minimum) in indexed: + while rooms and rooms[0][1] >= minimum: + active.add(rooms.pop(0)[0]) + pos = active.bisect_left(preferred) + candidates = [] + if pos < len(active): + candidates.append(active[pos]) + if pos: + candidates.append(active[pos - 1]) + if candidates: + result[qi] = min(candidates, key=lambda room_id: (abs(room_id - preferred), room_id)) + return result diff --git a/tests/1501-2000/1847. closest-room/sol.rb b/tests/1501-2000/1847. closest-room/sol.rb new file mode 100644 index 00000000..0df8914b --- /dev/null +++ b/tests/1501-2000/1847. closest-room/sol.rb @@ -0,0 +1,38 @@ +# @param {Integer[][]} rooms +# @param {Integer[][]} queries +# @return {Integer[]} +def closest_room(rooms, queries) + rooms.sort_by! { |r| -r[1] } + indexed = queries.each_with_index.sort_by { |q, i| -q[1] } + + active = [] + result = Array.new(queries.length, -1) + + indexed.each do |query, qi| + preferred = query[0] + minimum = query[1] + + while !rooms.empty? && rooms[0][1] >= minimum + active << rooms.shift[0] + end + + active.sort! + + pos = active.bsearch_index { |x| x >= preferred } + candidates = [] + if pos + candidates << active[pos] + elsif !active.empty? + candidates << active[-1] + end + if pos && pos > 0 + candidates << active[pos - 1] + end + + if !candidates.empty? + result[qi] = candidates.min_by { |id| [(id - preferred).abs, id] } + end + end + + result +end diff --git a/tests/1501-2000/1847. closest-room/sol.rs b/tests/1501-2000/1847. closest-room/sol.rs new file mode 100644 index 00000000..bcdf937c --- /dev/null +++ b/tests/1501-2000/1847. closest-room/sol.rs @@ -0,0 +1,44 @@ +impl Solution { + pub fn closest_room(rooms: Vec>, queries: Vec>) -> Vec { + let mut rooms = rooms; + rooms.sort_by(|a, b| b[1].cmp(&a[1])); + + let mut idx: Vec = (0..queries.len()).collect(); + idx.sort_by(|&a, &b| queries[b][1].cmp(&queries[a][1])); + + let mut active = std::collections::BTreeSet::new(); + let mut result = vec![-1; queries.len()]; + let mut room_ptr = 0; + + for qi in idx { + let preferred = queries[qi][0]; + let minimum = queries[qi][1]; + + while room_ptr < rooms.len() && rooms[room_ptr][1] >= minimum { + active.insert(rooms[room_ptr][0]); + room_ptr += 1; + } + + let mut candidates = Vec::new(); + if let Some(&pos) = active.range(preferred..).next() { + candidates.push(pos); + } + if let Some(&prev) = active.range(..=preferred).next_back() { + candidates.push(prev); + } + + if !candidates.is_empty() { + let mut best = candidates[0]; + for &id in candidates.iter().skip(1) { + let diff = (id - preferred).abs(); + let best_diff = (best - preferred).abs(); + if diff < best_diff || (diff == best_diff && id < best) { + best = id; + } + } + result[qi] = best; + } + } + result + } +} diff --git a/tests/1501-2000/1847. closest-room/sol.swift b/tests/1501-2000/1847. closest-room/sol.swift new file mode 100644 index 00000000..84bb663d --- /dev/null +++ b/tests/1501-2000/1847. closest-room/sol.swift @@ -0,0 +1,65 @@ +class Solution { + func closestRoom(_ rooms: [[Int]], _ queries: [[Int]]) -> [Int] { + var rooms = rooms.sorted { $0[1] > $1[1] } + let indexed = queries.indices.sorted { queries[$0][1] > queries[$1][1] } + + var active = [Int]() + var result = Array(repeating: -1, count: queries.count) + var roomPtr = 0 + + for qi in indexed { + let preferred = queries[qi][0] + let minimum = queries[qi][1] + + while roomPtr < rooms.count && rooms[roomPtr][1] >= minimum { + let id = rooms[roomPtr][0] + // insert into sorted active + var lo = 0 + var hi = active.count + while lo < hi { + let mid = (lo + hi) / 2 + if active[mid] < id { + lo = mid + 1 + } else { + hi = mid + } + } + active.insert(id, at: lo) + roomPtr += 1 + } + + // find first >= preferred + var lo = 0 + var hi = active.count + while lo < hi { + let mid = (lo + hi) / 2 + if active[mid] < preferred { + lo = mid + 1 + } else { + hi = mid + } + } + let pos = lo + + var candidates = [Int]() + if pos < active.count { + candidates.append(active[pos]) + } + if pos > 0 { + candidates.append(active[pos - 1]) + } + + if !candidates.isEmpty { + result[qi] = candidates.min { (a, b) -> Bool in + let diffA = abs(a - preferred) + let diffB = abs(b - preferred) + if diffA != diffB { + return diffA < diffB + } + return a < b + }! + } + } + return result + } +} diff --git a/tests/1501-2000/1847. closest-room/sol.ts b/tests/1501-2000/1847. closest-room/sol.ts new file mode 100644 index 00000000..eb0dbb78 --- /dev/null +++ b/tests/1501-2000/1847. closest-room/sol.ts @@ -0,0 +1,59 @@ +function closestRoom(rooms: number[][], queries: number[][]): number[] { + rooms.sort((a, b) => b[1] - a[1]); + + const idx = queries + .map((_, i) => i) + .sort((a, b) => queries[b][1] - queries[a][1]); + + const active: number[] = []; + const result: number[] = Array(queries.length).fill(-1); + let roomPtr = 0; + + for (const qi of idx) { + const preferred = queries[qi][0]; + const minimum = queries[qi][1]; + + while (roomPtr < rooms.length && rooms[roomPtr][1] >= minimum) { + const id = rooms[roomPtr][0]; + // binary search insert + let lo = 0, + hi = active.length; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (active[mid] < id) lo = mid + 1; + else hi = mid; + } + active.splice(lo, 0, id); + roomPtr++; + } + + // binary search first >= preferred + let lo = 0, + hi = active.length; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (active[mid] < preferred) lo = mid + 1; + else hi = mid; + } + const pos = lo; + + const candidates: number[] = []; + if (pos < active.length) candidates.push(active[pos]); + if (pos > 0) candidates.push(active[pos - 1]); + + if (candidates.length > 0) { + let best = candidates[0]; + for (let i = 1; i < candidates.length; i++) { + const id = candidates[i]; + if ( + Math.abs(id - preferred) < Math.abs(best - preferred) || + (Math.abs(id - preferred) === Math.abs(best - preferred) && id < best) + ) { + best = id; + } + } + result[qi] = best; + } + } + return result; +} diff --git a/tests/1501-2000/1848. minimum-distance-to-the-target-element/manifest.yaml b/tests/1501-2000/1848. minimum-distance-to-the-target-element/manifest.yaml new file mode 100644 index 00000000..3e89e8da --- /dev/null +++ b/tests/1501-2000/1848. minimum-distance-to-the-target-element/manifest.yaml @@ -0,0 +1,287 @@ +entry: + id: 1848 + title: "minimum-distance-to-the-target-element" + params: + nums: + type: array + items: + type: int + target: + type: int + start: + type: int + call: + cpp: "Solution().getMinDistance({nums}, {target}, {start})" + rust: "Solution::get_min_distance({nums}, {target}, {start})" + python3: "Solution().getMinDistance({nums}, {target}, {start})" + python2: "Solution().getMinDistance({nums}, {target}, {start})" + ruby: "get_min_distance({nums}, {target}, {start})" + java: "new Solution().getMinDistance({nums}, {target}, {start})" + csharp: "new Solution().GetMinDistance({nums}, {target}, {start})" + kotlin: "Solution().getMinDistance({nums}, {target}, {start})" + go: "getMinDistance({nums}, {target}, {start})" + dart: "Solution().getMinDistance({nums}, {target}, {start})" + swift: "Solution().getMinDistance({nums}, {target}, {start})" + typescript: "getMinDistance({nums}, {target}, {start})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().getMinDistance(nums, target, start, {result})" + checker: | + class Checker: + def getMinDistance(self, nums, target, start, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + expected = min(abs(i - start) for i, value in enumerate(nums) if value == target) + return result == expected + +seed: 1848 + +tests: + - name: example-one + in: + nums: [1, 2, 3, 4, 5] + target: 5 + start: 3 + out: 1 + - name: example-two + in: + nums: [1, 1] + target: 1 + start: 0 + out: 0 + - name: example-three + in: + nums: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + target: 1 + start: 0 + out: 0 + - name: target-at-start + in: + nums: [7, 4, 9, 4, 2] + target: 4 + start: 3 + out: 0 + - name: target-left-only + in: + nums: [8, 6, 5, 4, 3] + target: 6 + start: 4 + out: 3 + - name: target-right-only + in: + nums: [8, 6, 5, 4, 3] + target: 8 + start: 1 + out: 1 + - name: equal-distance-left-wins-irrelevant + in: + nums: [2, 9, 1, 9, 2] + target: 9 + start: 2 + out: 1 + - name: nearest-among-three + in: + nums: [3, 5, 7, 5, 5, 8, 5] + target: 5 + start: 5 + out: 1 + - name: target-at-first + in: + nums: [10, 2, 3, 4, 5] + target: 10 + start: 4 + out: 4 + - name: target-at-last + in: + nums: [2, 3, 4, 5, 10] + target: 10 + start: 0 + out: 4 + - name: two-elements-left + in: + nums: [9, 1] + target: 9 + start: 1 + out: 1 + - name: two-elements-right + in: + nums: [1, 9] + target: 9 + start: 0 + out: 1 + - name: adjacent-left + in: + nums: [4, 7, 7, 2] + target: 7 + start: 2 + out: 0 + - name: adjacent-right + in: + nums: [4, 7, 2, 7] + target: 7 + start: 2 + out: 1 + - name: repeated-spaced + in: + nums: [1, 8, 2, 3, 8, 4, 5, 8, 6] + target: 8 + start: 6 + out: 1 + - name: target-value-one + in: + nums: [2, 3, 1, 4, 1, 5] + target: 1 + start: 0 + out: 2 + - name: target-value-ten-thousand + in: + nums: [10000, 2, 3, 10000, 4] + target: 10000 + start: 2 + out: 1 + - name: start-middle-odd + in: + nums: [6, 2, 6, 4, 5, 6, 7] + target: 6 + start: 4 + out: 1 + - name: start-middle-even + in: + nums: [6, 2, 3, 6, 5, 7] + target: 6 + start: 4 + out: 1 + - name: all-targets + in: + nums: [3, 3, 3, 3, 3, 3] + target: 3 + start: 5 + out: 0 + - name: alternating-target + in: + nums: [4, 1, 4, 1, 4, 1, 4, 1] + target: 4 + start: 7 + out: 1 + - name: alternating-target-start-zero + in: + nums: [2, 9, 2, 9, 2, 9, 2] + target: 9 + start: 0 + out: 1 + - name: long-gap-left + in: + nums: [5, 2, 2, 2, 2, 2, 2, 2] + target: 5 + start: 7 + out: 7 + - name: long-gap-right + in: + nums: [2, 2, 2, 2, 2, 2, 2, 5] + target: 5 + start: 0 + out: 7 + - name: target-near-left + in: + nums: [3, 8, 8, 8, 8, 8, 8, 8, 8] + target: 3 + start: 5 + out: 5 + - name: target-near-right + in: + nums: [8, 8, 8, 8, 8, 8, 8, 3, 8] + target: 3 + start: 0 + out: 7 + - name: values-at-bounds + in: + nums: [1, 10000, 5000, 10000, 1] + target: 10000 + start: 4 + out: 1 + - name: negative-not-allowed-but-small + in: + nums: [1, 2, 3, 2, 1, 4] + target: 2 + start: 5 + out: 2 + - name: target-at-start-one + in: + nums: [4, 1, 2, 3, 1, 5] + target: 1 + start: 1 + out: 0 + - name: target-at-start-late + in: + nums: [4, 1, 2, 3, 1, 5] + target: 1 + start: 4 + out: 0 + - name: close-right-over-far-left + in: + nums: [7, 1, 2, 7, 3, 4, 5, 7] + target: 7 + start: 5 + out: 2 + - name: close-left-over-far-right + in: + nums: [7, 1, 2, 7, 3, 4, 5, 7] + target: 7 + start: 2 + out: 1 + - name: length-ten-middle + in: + nums: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] + target: 2 + start: 5 + out: 5 + - name: length-ten-last-target + in: + nums: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] + target: 20 + start: 4 + out: 5 + - name: repeated-distance-two + in: + nums: [5, 1, 2, 5, 3, 4, 5, 6, 7] + target: 5 + start: 5 + out: 1 + - name: repeated-distance-three + in: + nums: [9, 1, 2, 3, 9, 4, 5, 6, 9] + target: 9 + start: 6 + out: 2 + - name: dense-target-near-start + in: + nums: [4, 4, 4, 9, 4, 4, 4, 4] + target: 4 + start: 3 + out: 1 + - name: dense-target-far-start + in: + nums: [4, 4, 4, 9, 4, 4, 4, 4] + target: 9 + start: 7 + out: 4 + - name: large-boundary-left + in: + nums: [9999, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + target: 9999 + start: 19 + out: 19 + - name: large-boundary-right + in: + nums: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9999] + target: 9999 + start: 0 + out: 19 diff --git a/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.cpp b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.cpp new file mode 100644 index 00000000..7144a48a --- /dev/null +++ b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int getMinDistance(vector& nums, int target, int start) { + if (nums[start] == target) { + return 0; + } + + int n = nums.size(); + int d = 1; + + while (true) { + if (start - d >= 0 && nums[start - d] == target) { + return d; + } + + if (start + d < n && nums[start + d] == target) { + return d; + } + + d++; + } + } +}; diff --git a/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.cs b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.cs new file mode 100644 index 00000000..da368f0b --- /dev/null +++ b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public int GetMinDistance(int[] nums, int target, int start) { + if (nums[start] == target) { + return 0; + } + + int n = nums.Length; + int d = 1; + + while (true) { + if (start - d >= 0 && nums[start - d] == target) { + return d; + } + + if (start + d < n && nums[start + d] == target) { + return d; + } + + d++; + } + } +} diff --git a/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.dart b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.dart new file mode 100644 index 00000000..b47847c3 --- /dev/null +++ b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.dart @@ -0,0 +1,22 @@ +class Solution { + int getMinDistance(List nums, int target, int start) { + if (nums[start] == target) { + return 0; + } + + int n = nums.length; + int d = 1; + + while (true) { + if (start - d >= 0 && nums[start - d] == target) { + return d; + } + + if (start + d < n && nums[start + d] == target) { + return d; + } + + d++; + } + } +} diff --git a/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.go b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.go new file mode 100644 index 00000000..c743187b --- /dev/null +++ b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.go @@ -0,0 +1,20 @@ +func getMinDistance(nums []int, target int, start int) int { + if nums[start] == target { + return 0 + } + + n := len(nums) + d := 1 + + for { + if start - d >= 0 && nums[start - d] == target { + return d + } + + if start + d < n && nums[start + d] == target { + return d + } + + d++ + } +} diff --git a/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.java b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.java new file mode 100644 index 00000000..811c123a --- /dev/null +++ b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.java @@ -0,0 +1,22 @@ +class Solution { + public int getMinDistance(int[] nums, int target, int start) { + if (nums[start] == target) { + return 0; + } + + int n = nums.length; + int d = 1; + + while (true) { + if (start - d >= 0 && nums[start - d] == target) { + return d; + } + + if (start + d < n && nums[start + d] == target) { + return d; + } + + d++; + } + } +} diff --git a/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.kt b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.kt new file mode 100644 index 00000000..c4d9dcd1 --- /dev/null +++ b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.kt @@ -0,0 +1,22 @@ +class Solution { + fun getMinDistance(nums: IntArray, target: Int, start: Int): Int { + if (nums[start] == target) { + return 0 + } + + val n = nums.size + var d = 1 + + while (true) { + if (start - d >= 0 && nums[start - d] == target) { + return d + } + + if (start + d < n && nums[start + d] == target) { + return d + } + + d++ + } + } +} diff --git a/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py new file mode 100644 index 00000000..7fffc7b6 --- /dev/null +++ b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py @@ -0,0 +1,17 @@ +class Solution: + def getMinDistance(self, nums: list[int], target: int, start: int) -> int: + + if nums[start] == target: + return 0 + + n = len(nums) + d = 1 + + while True: + if start - d >= 0 and nums[start - d] == target: + return d + + if start + d < n and nums[start + d] == target: + return d + + d += 1 diff --git a/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py2 b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py2 new file mode 100644 index 00000000..a412b43a --- /dev/null +++ b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def getMinDistance(self, nums, target, start): + """ + :type nums: List[int] + :type target: int + :type start: int + :rtype: int + """ + if nums[start] == target: + return 0 + + n = len(nums) + d = 1 + + while True: + if start - d >= 0 and nums[start - d] == target: + return d + + if start + d < n and nums[start + d] == target: + return d + + d += 1 diff --git a/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.rb b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.rb new file mode 100644 index 00000000..fa09fd71 --- /dev/null +++ b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.rb @@ -0,0 +1,16 @@ +# @param {Integer[]} nums +# @param {Integer} target +# @param {Integer} start +# @return {Integer} +def get_min_distance(nums, target, start) + return 0 if nums[start] == target + + n = nums.length + d = 1 + + loop do + return d if start - d >= 0 && nums[start - d] == target + return d if start + d < n && nums[start + d] == target + d += 1 + end +end diff --git a/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.rs b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.rs new file mode 100644 index 00000000..f5930e8e --- /dev/null +++ b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.rs @@ -0,0 +1,22 @@ +impl Solution { + pub fn get_min_distance(nums: Vec, target: i32, start: i32) -> i32 { + if nums[start as usize] == target { + return 0; + } + + let n = nums.len() as i32; + let mut d = 1; + + loop { + if start - d >= 0 && nums[(start - d) as usize] == target { + return d; + } + + if start + d < n && nums[(start + d) as usize] == target { + return d; + } + + d += 1; + } + } +} diff --git a/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.swift b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.swift new file mode 100644 index 00000000..ce2b68fb --- /dev/null +++ b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.swift @@ -0,0 +1,22 @@ +class Solution { + func getMinDistance(_ nums: [Int], _ target: Int, _ start: Int) -> Int { + if nums[start] == target { + return 0 + } + + let n = nums.count + var d = 1 + + while true { + if start - d >= 0 && nums[start - d] == target { + return d + } + + if start + d < n && nums[start + d] == target { + return d + } + + d += 1 + } + } +} diff --git a/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.ts b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.ts new file mode 100644 index 00000000..7387488e --- /dev/null +++ b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.ts @@ -0,0 +1,20 @@ +function getMinDistance(nums: number[], target: number, start: number): number { + if (nums[start] === target) { + return 0; + } + + const n = nums.length; + let d = 1; + + while (true) { + if (start - d >= 0 && nums[start - d] === target) { + return d; + } + + if (start + d < n && nums[start + d] === target) { + return d; + } + + d++; + } +} diff --git a/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/manifest.yaml b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/manifest.yaml new file mode 100644 index 00000000..ee01966e --- /dev/null +++ b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/manifest.yaml @@ -0,0 +1,307 @@ +entry: + id: 1849 + title: splitting-a-string-into-descending-consecutive-values + params: + s: + type: string + call: + cpp: "Solution().splitString({s})" + rust: "Solution::split_string({s})" + python3: "Solution().splitString({s})" + python2: "Solution().splitString({s})" + ruby: "split_string({s})" + java: "new Solution().splitString({s})" + csharp: "new Solution().SplitString({s})" + kotlin: "Solution().splitString({s})" + go: "splitString({s})" + dart: "Solution().splitString({s})" + swift: "Solution().splitString({s})" + typescript: "splitString({s})" + +judge: + type: exact + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().splitString(s, {result})" + checker: | + class Checker: + def splitString(self, s, result): + if not isinstance(result, bool): + return False + n = len(s) + def dfs(pos, prev): + if pos == n: + return True + value = 0 + for end in range(pos, n): + value = value * 10 + int(s[end]) + if prev - value == 1 and dfs(end + 1, value): + return True + if value >= prev: + break + return False + expected = False + for end in range(1, n): + if dfs(end, int(s[:end])): + expected = True + break + return result == expected + +seed: 1849 + +tests: + - name: example-1234 + in: + s: "1234" + out: false + judge: + type: exact + - name: example-050043 + in: + s: "050043" + out: true + judge: + type: exact + - name: example-9080701 + in: + s: "9080701" + out: false + judge: + type: exact + - name: two-digits-descending + in: + s: "10" + out: true + judge: + type: exact + - name: two-digits-ascending + in: + s: "01" + out: false + judge: + type: exact + - name: single-digit + in: + s: "7" + out: false + judge: + type: exact + - name: zero + in: + s: "0" + out: false + judge: + type: exact + - name: repeated-zero + in: + s: "00" + out: false + judge: + type: exact + - name: three-descending + in: + s: "210" + out: true + judge: + type: exact + - name: three-ascending + in: + s: "012" + out: false + judge: + type: exact + - name: four-descending + in: + s: "3210" + out: true + judge: + type: exact + - name: padded-descending + in: + s: "030201" + out: true + judge: + type: exact + - name: padded-single-step + in: + s: "0090089" + out: true + judge: + type: exact + - name: leading-zero-false + in: + s: "001" + out: false + judge: + type: exact + - name: equal-values + in: + s: "11" + out: false + judge: + type: exact + - name: separated-zero + in: + s: "1000" + out: true + judge: + type: exact + - name: nineteen-to-eighteen + in: + s: "1918" + out: true + judge: + type: exact + - name: ninety-to-eighty-nine + in: + s: "9089" + out: true + judge: + type: exact + - name: hundred-chain + in: + s: "1009998" + out: true + judge: + type: exact + - name: invalid-gap + in: + s: "3020" + out: false + judge: + type: exact + - name: invalid-large-first + in: + s: "9998" + out: true + judge: + type: exact + - name: no-split-large + in: + s: "9999" + out: false + judge: + type: exact + - name: all-nines + in: + s: "99999999999999999999" + out: false + judge: + type: exact + - name: all-zeros + in: + s: "00000000000000000000" + out: false + judge: + type: exact + - name: max-length-descending + in: + s: "20191817161514131211" + out: true + judge: + type: exact + - name: max-length-padded + in: + s: "020019018017016015014" + out: true + judge: + type: exact + - name: nine-eight-seven + in: + s: "987" + out: true + judge: + type: exact + - name: ninety-eight-seven + in: + s: "9897" + out: true + judge: + type: exact + - name: zero-one-zero + in: + s: "010" + out: true + judge: + type: exact + - name: branching-choice + in: + s: "10009998" + out: true + judge: + type: exact + - name: close-but-not-one + in: + s: "4321" + out: true + judge: + type: exact + - name: false-908 + in: + s: "908" + out: true + judge: + type: exact + - name: leading-zero-chain + in: + s: "005004003" + out: true + judge: + type: exact + - name: no-leading-split + in: + s: "543210" + out: true + judge: + type: exact + - name: ascending-long + in: + s: "12345678901234567890" + out: false + judge: + type: exact + - name: generator-short + in: + s: + gen: str + len: 8 + alphabet: "0123456789" + judge: + type: exact + - name: generator-medium + in: + s: + gen: str + len: 12 + alphabet: "0123456789" + judge: + type: exact + - name: generator-long + in: + s: + gen: str + len: 16 + alphabet: "0123456789" + judge: + type: exact + - name: generator-max + in: + s: + gen: str + len: 20 + alphabet: "0123456789" + judge: + type: exact + - name: generator-zero-heavy + in: + s: + gen: str + len: 20 + alphabet: "0001289" + judge: + type: exact diff --git a/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.cpp b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.cpp new file mode 100644 index 00000000..b3c082c1 --- /dev/null +++ b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + bool splitString(string s) { + return dfs(s, 0, -1, 0); + } + +private: + bool dfs(string& s, int index, long long prev, int count) { + if (index == s.size()) { + return count >= 2; + } + + long long curr = 0; + for (int i = index; i < s.size(); i++) { + curr = curr * 10 + (s[i] - '0'); + if (prev == -1 || prev - curr == 1) { + if (dfs(s, i + 1, curr, count + 1)) { + return true; + } + } else if (curr >= prev && prev != -1) { + break; + } + } + return false; + } +}; diff --git a/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.cs b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.cs new file mode 100644 index 00000000..5d97a326 --- /dev/null +++ b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.cs @@ -0,0 +1,24 @@ +public class Solution { + public bool SplitString(string s) { + return Dfs(s, 0, -1, 0); + } + + private bool Dfs(string s, int index, long prev, int count) { + if (index == s.Length) { + return count >= 2; + } + + long curr = 0; + for (int i = index; i < s.Length; i++) { + curr = curr * 10 + (s[i] - '0'); + if (prev == -1 || prev - curr == 1) { + if (Dfs(s, i + 1, curr, count + 1)) { + return true; + } + } else if (curr >= prev && prev != -1) { + break; + } + } + return false; + } +} diff --git a/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.dart b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.dart new file mode 100644 index 00000000..121d734f --- /dev/null +++ b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.dart @@ -0,0 +1,24 @@ +class Solution { + bool splitString(String s) { + bool dfs(int index, int prev, int count) { + if (index == s.length) { + return count >= 2; + } + + int curr = 0; + for (int i = index; i < s.length; i++) { + curr = curr * 10 + (s.codeUnitAt(i) - 48); + if (prev == -1 || prev - curr == 1) { + if (dfs(i + 1, curr, count + 1)) { + return true; + } + } else if (curr >= prev && prev != -1) { + break; + } + } + return false; + } + + return dfs(0, -1, 0); + } +} diff --git a/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.go b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.go new file mode 100644 index 00000000..05b0525c --- /dev/null +++ b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.go @@ -0,0 +1,23 @@ +func splitString(s string) bool { + var dfs func(index int, prev int64, count int) bool + dfs = func(index int, prev int64, count int) bool { + if index == len(s) { + return count >= 2 + } + + var curr int64 = 0 + for i := index; i < len(s); i++ { + curr = curr*10 + int64(s[i]-'0') + if prev == -1 || prev-curr == 1 { + if dfs(i+1, curr, count+1) { + return true + } + } else if curr >= prev && prev != -1 { + break + } + } + return false + } + + return dfs(0, -1, 0) +} diff --git a/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.java b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.java new file mode 100644 index 00000000..bcf52da1 --- /dev/null +++ b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.java @@ -0,0 +1,24 @@ +class Solution { + public boolean splitString(String s) { + return dfs(0, -1, s, 0); + } + + private boolean dfs(int index, long prev, String s, int count) { + if (index == s.length()) { + return count >= 2; + } + + long curr = 0; + for (int i = index; i < s.length(); i++) { + curr = curr * 10 + (s.charAt(i) - '0'); + if (prev == -1 || prev - curr == 1) { + if (dfs(i + 1, curr, s, count + 1)) { + return true; + } + } else if (curr >= prev && prev != -1) { + break; + } + } + return false; + } +} diff --git a/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.kt b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.kt new file mode 100644 index 00000000..58f4b9ca --- /dev/null +++ b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun splitString(s: String): Boolean { + fun dfs(index: Int, prev: Long, count: Int): Boolean { + if (index == s.length) return count >= 2 + + var curr = 0L + for (i in index until s.length) { + curr = curr * 10 + (s[i] - '0') + if (prev == -1L || prev - curr == 1L) { + if (dfs(i + 1, curr, count + 1)) return true + } else if (curr >= prev && prev != -1L) { + break + } + } + return false + } + + return dfs(0, -1, 0) + } +} diff --git a/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.py b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.py new file mode 100644 index 00000000..af2251fb --- /dev/null +++ b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.py @@ -0,0 +1,26 @@ +class Solution(object): + def splitString(self, s): + """ + :type s: str + :rtype: bool + """ + + def dfs(index, prev): + if index == len(s): + return True + + curr = 0 + for i in range(index, len(s)): + curr = curr * 10 + int(s[i]) + if prev - curr == 1: + if dfs(i + 1, curr): + return True + elif curr >= prev: + break + return False + + for i in range(len(s) - 1): + first = int(s[: i + 1]) + if dfs(i + 1, first): + return True + return False diff --git a/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.py2 b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.py2 new file mode 100644 index 00000000..989bfbd9 --- /dev/null +++ b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.py2 @@ -0,0 +1,25 @@ +class Solution(object): + def splitString(self, s): + """ + :type s: str + :rtype: bool + """ + def dfs(index, prev): + if index == len(s): + return True + + curr = 0 + for i in range(index, len(s)): + curr = curr * 10 + int(s[i]) + if prev - curr == 1: + if dfs(i + 1, curr): + return True + elif curr >= prev: + break + return False + + for i in range(len(s) - 1): + first = int(s[:i + 1]) + if dfs(i + 1, first): + return True + return False diff --git a/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.rb b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.rb new file mode 100644 index 00000000..cf0de4cd --- /dev/null +++ b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.rb @@ -0,0 +1,24 @@ +# @param {String} s +# @return {Boolean} +def split_string(s) + def dfs(index, prev, str) + return true if index == str.length + + curr = 0 + (index...str.length).each do |i| + curr = curr * 10 + str[i].to_i + if prev - curr == 1 + return true if dfs(i + 1, curr, str) + elsif curr >= prev + break + end + end + false + end + + (0...s.length - 1).each do |i| + first = s[0..i].to_i + return true if dfs(i + 1, first, s) + end + false +end diff --git a/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.rs b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.rs new file mode 100644 index 00000000..61d872ba --- /dev/null +++ b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn split_string(s: String) -> bool { + fn dfs(s: &[u8], index: usize, prev: i64, count: i32) -> bool { + if index == s.len() { + return count >= 2; + } + + let mut curr: i64 = 0; + for i in index..s.len() { + curr = curr * 10 + (s[i] - b'0') as i64; + if prev == -1 || prev - curr == 1 { + if dfs(s, i + 1, curr, count + 1) { + return true; + } + } else if curr >= prev && prev != -1 { + break; + } + } + false + } + + let bytes = s.as_bytes(); + dfs(bytes, 0, -1, 0) + } +} diff --git a/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.swift b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.swift new file mode 100644 index 00000000..2dc8e6f9 --- /dev/null +++ b/tests/1501-2000/1849. splitting-a-string-into-descending-consecutive-values/sol.swift @@ -0,0 +1,43 @@ +class Solution { + func splitString(_ s: String) -> Bool { + let chars = Array(s) + func normalized(_ value: String) -> String { + let trimmed = String(value.drop { $0 == "0" }) + return trimmed.isEmpty ? "0" : trimmed + } + func decrement(_ value: String) -> String? { + let digits = Array(value.utf8) + if normalized(value) == "0" { return nil } + var result = digits + var i = result.count - 1 + while result[i] == 48 { + result[i] = 57 + i -= 1 + } + result[i] -= 1 + return normalized(String(bytes: result, encoding: .utf8)!) + } + func dfs(_ index: Int, _ prev: String, _ count: Int) -> Bool { + if index == chars.count { + return count >= 2 + } + var current = "" + for i in index..= 2; + } + + let curr = 0; + for (let i = index; i < s.length; i++) { + curr = curr * 10 + (s.charCodeAt(i) - 48); + if (prev === -1 || prev - curr === 1) { + if (dfs(i + 1, curr, count + 1)) { + return true; + } + } else if (curr >= prev && prev !== -1) { + break; + } + } + return false; + } + + return dfs(0, -1, 0); +} diff --git a/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/manifest.yaml b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/manifest.yaml new file mode 100644 index 00000000..2d39403a --- /dev/null +++ b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/manifest.yaml @@ -0,0 +1,268 @@ +entry: + id: 1850 + title: minimum-adjacent-swaps-to-reach-the-kth-smallest-number + params: + num: + type: string + k: + type: int + call: + cpp: "Solution().getMinSwaps({num}, {k})" + rust: "Solution::get_min_swaps({num}, {k})" + python3: "Solution().getMinSwaps({num}, {k})" + python2: "Solution().getMinSwaps({num}, {k})" + ruby: "get_min_swaps({num}, {k})" + java: "new Solution().getMinSwaps({num}, {k})" + csharp: "new Solution().GetMinSwaps({num}, {k})" + kotlin: "Solution().getMinSwaps({num}, {k})" + go: "getMinSwaps({num}, {k})" + dart: "Solution().getMinSwaps({num}, {k})" + swift: "Solution().getMinSwaps({num}, {k})" + typescript: "getMinSwaps({num}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().check(num, k, {result})" + checker: | + class Checker: + def check(self, num, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + target = list(num) + for _ in range(k): + i = len(target) - 2 + while i >= 0 and target[i] >= target[i + 1]: + i -= 1 + if i < 0: + return False + j = len(target) - 1 + while target[j] <= target[i]: + j -= 1 + target[i], target[j] = target[j], target[i] + target[i + 1:] = reversed(target[i + 1:]) + current = list(num) + swaps = 0 + for i in range(len(current)): + if current[i] == target[i]: + continue + j = i + while j < len(current) and current[j] != target[i]: + j += 1 + if j == len(current): + return False + while j > i: + current[j], current[j - 1] = current[j - 1], current[j] + j -= 1 + swaps += 1 + return result == swaps + +seed: 1850 + +tests: + - name: example-one + in: + num: "5489355142" + k: 4 + out: 2 + - name: example-two + in: + num: "11112" + k: 4 + out: 4 + - name: example-three + in: + num: "00123" + k: 1 + out: 1 + - name: ascending-four-first + in: + num: "1234" + k: 1 + out: 1 + - name: ascending-four-fifth + in: + num: "1234" + k: 5 + out: 3 + - name: repeated-prefix-first + in: + num: "1123" + k: 1 + out: 1 + - name: repeated-prefix-fifth + in: + num: "1123" + k: 5 + out: 3 + - name: repeated-middle + in: + num: "1223" + k: 3 + out: 1 + - name: repeated-suffix + in: + num: "1233" + k: 4 + out: 2 + - name: zero-middle + in: + num: "1012" + k: 1 + out: 1 + - name: zero-middle-third + in: + num: "1012" + k: 3 + out: 2 + - name: mixed-small + in: + num: "1023" + k: 5 + out: 3 + - name: repeated-zeroes + in: + num: "102030" + k: 1 + out: 1 + - name: repeated-zeroes-larger-k + in: + num: "102030" + k: 20 + out: 3 + - name: alternating-large-digits + in: + num: "135790" + k: 1 + out: 2 + - name: even-digits + in: + num: "246810" + k: 1 + out: 4 + - name: four-digit-zero + in: + num: "1001" + k: 1 + out: 1 + - name: four-digit-zero-second + in: + num: "1001" + k: 2 + out: 2 + - name: varied-six-digit + in: + num: "121314" + k: 1 + out: 1 + - name: varied-six-digit-seventh + in: + num: "121314" + k: 7 + out: 4 + - name: ascending-five-first + in: + num: "12345" + k: 1 + out: 1 + - name: ascending-five-tenth + in: + num: "12345" + k: 10 + out: 3 + - name: ascending-ten-first + in: + num: "1234567890" + k: 1 + out: 2 + - name: ascending-ten-large-k + in: + num: "1234567890" + k: 1000 + out: 9 + - name: mixed-ten-first + in: + num: "1029384756" + k: 1 + out: 1 + - name: mixed-ten-large-k + in: + num: "1029384756" + k: 999 + out: 8 + - name: repeated-high-digits-first + in: + num: "55556667" + k: 1 + out: 1 + - name: repeated-high-digits-twentieth + in: + num: "55556667" + k: 20 + out: 2 + - name: pi-prefix-first + in: + num: "31415926" + k: 1 + out: 1 + - name: pi-prefix-hundredth + in: + num: "31415926" + k: 100 + out: 4 + - name: e-prefix-first + in: + num: "27182818" + k: 1 + out: 1 + - name: e-prefix-hundredth + in: + num: "27182818" + k: 100 + out: 8 + - name: long-zero-tail + in: + num: "1000000002" + k: 1 + out: 1 + - name: long-zero-tail-two-billion + in: + num: "2000000001" + k: 1 + out: 1 + - name: long-ascending + in: + num: "12345678901234567890" + k: 1 + out: 2 + - name: long-ascending-k-thousand + in: + num: "12345678901234567890" + k: 1000 + out: 9 + - name: long-repeated-prefix + in: + num: "1111222233334444" + k: 1 + out: 1 + - name: long-repeated-prefix-k-ten + in: + num: "1111222233334444" + k: 10 + out: 5 + - name: length-one-thousand-pattern + in: + num: "1234567890" + k: 999 + out: 8 + - name: duplicate-heavy-pattern + in: + num: "11223344556677889900" + k: 1000 + out: 11 diff --git a/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.cpp b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.cpp new file mode 100644 index 00000000..481503d5 --- /dev/null +++ b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + int getMinSwaps(string num, int k) { + string arr = num; + string target = num; + + for (int i = 0; i < k; i++) { + nextPermutation(target); + } + + int swaps = 0; + arr = num; + + for (int i = 0; i < arr.length(); i++) { + if (arr[i] == target[i]) continue; + + int j = i; + while (arr[j] != target[i]) j++; + + while (j > i) { + swap(arr[j], arr[j - 1]); + j--; + swaps++; + } + } + + return swaps; + } + +private: + void nextPermutation(string& arr) { + int i = arr.length() - 2; + while (i >= 0 && arr[i] >= arr[i + 1]) i--; + if (i == -1) return; + + int j = arr.length() - 1; + while (arr[j] <= arr[i]) j--; + + swap(arr[i], arr[j]); + + int left = i + 1, right = arr.length() - 1; + while (left < right) { + swap(arr[left], arr[right]); + left++; + right--; + } + } +}; diff --git a/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.cs b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.cs new file mode 100644 index 00000000..3c6a8cdb --- /dev/null +++ b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.cs @@ -0,0 +1,52 @@ +public class Solution { + public int GetMinSwaps(string num, int k) { + char[] arr = num.ToCharArray(); + char[] target = num.ToCharArray(); + + for (int i = 0; i < k; i++) { + NextPermutation(target); + } + + int swaps = 0; + arr = num.ToCharArray(); + + for (int i = 0; i < arr.Length; i++) { + if (arr[i] == target[i]) continue; + + int j = i; + while (arr[j] != target[i]) j++; + + while (j > i) { + char temp = arr[j]; + arr[j] = arr[j - 1]; + arr[j - 1] = temp; + j--; + swaps++; + } + } + + return swaps; + } + + private void NextPermutation(char[] arr) { + int i = arr.Length - 2; + while (i >= 0 && arr[i] >= arr[i + 1]) i--; + if (i == -1) return; + + int j = arr.Length - 1; + while (arr[j] <= arr[i]) j--; + + char temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + + int left = i + 1, right = arr.Length - 1; + while (left < right) { + temp = arr[left]; + arr[left] = arr[right]; + arr[right] = temp; + left++; + right--; + } + } +} diff --git a/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.dart b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.dart new file mode 100644 index 00000000..175bc90e --- /dev/null +++ b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.dart @@ -0,0 +1,52 @@ +class Solution { + int getMinSwaps(String num, int k) { + List arr = num.split(''); + List target = num.split(''); + + for (int i = 0; i < k; i++) { + nextPermutation(target); + } + + int swaps = 0; + arr = num.split(''); + + for (int i = 0; i < arr.length; i++) { + if (arr[i] == target[i]) continue; + + int j = i; + while (arr[j] != target[i]) j++; + + while (j > i) { + String temp = arr[j]; + arr[j] = arr[j - 1]; + arr[j - 1] = temp; + j--; + swaps++; + } + } + + return swaps; + } + + void nextPermutation(List arr) { + int i = arr.length - 2; + while (i >= 0 && arr[i].compareTo(arr[i + 1]) >= 0) i--; + if (i == -1) return; + + int j = arr.length - 1; + while (arr[j].compareTo(arr[i]) <= 0) j--; + + String temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + + int left = i + 1, right = arr.length - 1; + while (left < right) { + temp = arr[left]; + arr[left] = arr[right]; + arr[right] = temp; + left++; + right--; + } + } +} diff --git a/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.go b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.go new file mode 100644 index 00000000..02674f82 --- /dev/null +++ b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.go @@ -0,0 +1,54 @@ +func getMinSwaps(num string, k int) int { + arr := []byte(num) + target := []byte(num) + + for i := 0; i < k; i++ { + nextPermutation(target) + } + + swaps := 0 + arr = []byte(num) + + for i := 0; i < len(arr); i++ { + if arr[i] == target[i] { + continue + } + + j := i + for arr[j] != target[i] { + j++ + } + + for j > i { + arr[j], arr[j-1] = arr[j-1], arr[j] + j-- + swaps++ + } + } + + return swaps +} + +func nextPermutation(arr []byte) { + i := len(arr) - 2 + for i >= 0 && arr[i] >= arr[i+1] { + i-- + } + if i == -1 { + return + } + + j := len(arr) - 1 + for arr[j] <= arr[i] { + j-- + } + + arr[i], arr[j] = arr[j], arr[i] + + left, right := i+1, len(arr)-1 + for left < right { + arr[left], arr[right] = arr[right], arr[left] + left++ + right-- + } +} diff --git a/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.java b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.java new file mode 100644 index 00000000..b04e88e9 --- /dev/null +++ b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.java @@ -0,0 +1,52 @@ +class Solution { + public int getMinSwaps(String num, int k) { + char[] arr = num.toCharArray(); + char[] target = num.toCharArray(); + + for (int i = 0; i < k; i++) { + nextPermutation(target); + } + + int swaps = 0; + arr = num.toCharArray(); + + for (int i = 0; i < arr.length; i++) { + if (arr[i] == target[i]) continue; + + int j = i; + while (arr[j] != target[i]) j++; + + while (j > i) { + char temp = arr[j]; + arr[j] = arr[j - 1]; + arr[j - 1] = temp; + j--; + swaps++; + } + } + + return swaps; + } + + private void nextPermutation(char[] arr) { + int i = arr.length - 2; + while (i >= 0 && arr[i] >= arr[i + 1]) i--; + if (i == -1) return; + + int j = arr.length - 1; + while (arr[j] <= arr[i]) j--; + + char temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + + int left = i + 1, right = arr.length - 1; + while (left < right) { + temp = arr[left]; + arr[left] = arr[right]; + arr[right] = temp; + left++; + right--; + } + } +} diff --git a/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.kt b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.kt new file mode 100644 index 00000000..0d4ae0e8 --- /dev/null +++ b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.kt @@ -0,0 +1,53 @@ +class Solution { + fun getMinSwaps(num: String, k: Int): Int { + var arr = num.toCharArray() + val target = num.toCharArray() + + repeat(k) { + nextPermutation(target) + } + + var swaps = 0 + arr = num.toCharArray() + + for (i in arr.indices) { + if (arr[i] == target[i]) continue + + var j = i + while (arr[j] != target[i]) j++ + + while (j > i) { + val temp = arr[j] + arr[j] = arr[j - 1] + arr[j - 1] = temp + j-- + swaps++ + } + } + + return swaps + } + + private fun nextPermutation(arr: CharArray) { + var i = arr.size - 2 + while (i >= 0 && arr[i] >= arr[i + 1]) i-- + if (i == -1) return + + var j = arr.size - 1 + while (arr[j] <= arr[i]) j-- + + val temp = arr[i] + arr[i] = arr[j] + arr[j] = temp + + var left = i + 1 + var right = arr.size - 1 + while (left < right) { + val t = arr[left] + arr[left] = arr[right] + arr[right] = t + left++ + right-- + } + } +} diff --git a/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.py b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.py new file mode 100644 index 00000000..2c647a99 --- /dev/null +++ b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.py @@ -0,0 +1,44 @@ +class Solution(object): + def getMinSwaps(self, num, k): + """ + :type num: str + :type k: int + :rtype: int + """ + + def next_permutation(arr): + i = len(arr) - 2 + while i >= 0 and arr[i] >= arr[i + 1]: + i -= 1 + if i == -1: + return False + j = len(arr) - 1 + while arr[j] <= arr[i]: + j -= 1 + arr[i], arr[j] = arr[j], arr[i] + arr[i + 1 :] = reversed(arr[i + 1 :]) + return True + + num_list = list(num) + target = list(num) + + for _ in range(k): + next_permutation(target) + + swaps = 0 + num_list = list(num) + + for i in range(len(num_list)): + if num_list[i] == target[i]: + continue + + j = i + while num_list[j] != target[i]: + j += 1 + + while j > i: + num_list[j], num_list[j - 1] = num_list[j - 1], num_list[j] + j -= 1 + swaps += 1 + + return swaps diff --git a/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.py2 b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.py2 new file mode 100644 index 00000000..41c839a2 --- /dev/null +++ b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.py2 @@ -0,0 +1,43 @@ +class Solution(object): + def getMinSwaps(self, num, k): + """ + :type num: str + :type k: int + :rtype: int + """ + def next_permutation(arr): + i = len(arr) - 2 + while i >= 0 and arr[i] >= arr[i + 1]: + i -= 1 + if i == -1: + return False + j = len(arr) - 1 + while arr[j] <= arr[i]: + j -= 1 + arr[i], arr[j] = arr[j], arr[i] + arr[i + 1:] = reversed(arr[i + 1:]) + return True + + num_list = list(num) + target = list(num) + + for _ in range(k): + next_permutation(target) + + swaps = 0 + num_list = list(num) + + for i in range(len(num_list)): + if num_list[i] == target[i]: + continue + + j = i + while num_list[j] != target[i]: + j += 1 + + while j > i: + num_list[j], num_list[j - 1] = num_list[j - 1], num_list[j] + j -= 1 + swaps += 1 + + return swaps diff --git a/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.rb b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.rb new file mode 100644 index 00000000..2f352a6f --- /dev/null +++ b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.rb @@ -0,0 +1,48 @@ +# @param {String} num +# @param {Integer} k +# @return {Integer} +def get_min_swaps(num, k) + arr = num.chars + target = num.chars + + k.times do + next_permutation(target) + end + + swaps = 0 + arr = num.chars + + (0...arr.length).each do |i| + next if arr[i] == target[i] + + j = i + while arr[j] != target[i] + j += 1 + end + + while j > i + arr[j], arr[j - 1] = arr[j - 1], arr[j] + j -= 1 + swaps += 1 + end + end + + swaps +end + +def next_permutation(arr) + i = arr.length - 2 + while i >= 0 && arr[i] >= arr[i + 1] + i -= 1 + end + return false if i == -1 + + j = arr.length - 1 + while arr[j] <= arr[i] + j -= 1 + end + + arr[i], arr[j] = arr[j], arr[i] + arr[i + 1..] = arr[i + 1..].reverse + true +end diff --git a/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.rs b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.rs new file mode 100644 index 00000000..6c177e10 --- /dev/null +++ b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.rs @@ -0,0 +1,51 @@ +impl Solution { + pub fn get_min_swaps(num: String, k: i32) -> i32 { + let mut arr: Vec = num.chars().collect(); + let mut target: Vec = num.chars().collect(); + + for _ in 0..k { + Self::next_permutation(&mut target); + } + + let mut swaps = 0; + arr = num.chars().collect(); + + for i in 0..arr.len() { + if arr[i] == target[i] { continue; } + + let mut j = i; + while arr[j] != target[i] { j += 1; } + + while j > i { + arr.swap(j, j - 1); + j -= 1; + swaps += 1; + } + } + + swaps + } + + fn next_permutation(arr: &mut Vec) { + let mut i = arr.len() as i32 - 2; + while i >= 0 && arr[i as usize] >= arr[(i + 1) as usize] { + i -= 1; + } + if i == -1 { return; } + + let mut j = arr.len() as i32 - 1; + while arr[j as usize] <= arr[i as usize] { + j -= 1; + } + + arr.swap(i as usize, j as usize); + + let mut left = i as usize + 1; + let mut right = arr.len() - 1; + while left < right { + arr.swap(left, right); + left += 1; + right -= 1; + } + } +} diff --git a/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.swift b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.swift new file mode 100644 index 00000000..3e430b69 --- /dev/null +++ b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.swift @@ -0,0 +1,46 @@ +class Solution { + func getMinSwaps(_ num: String, _ k: Int) -> Int { + var arr = Array(num) + var target = Array(num) + + for _ in 0.. i { + arr.swapAt(j, j - 1) + j -= 1 + swaps += 1 + } + } + + return swaps + } + + private func nextPermutation(_ arr: inout [Character]) { + var i = arr.count - 2 + while i >= 0 && arr[i] >= arr[i + 1] { i -= 1 } + if i == -1 { return } + + var j = arr.count - 1 + while arr[j] <= arr[i] { j -= 1 } + + arr.swapAt(i, j) + + var left = i + 1, right = arr.count - 1 + while left < right { + arr.swapAt(left, right) + left += 1 + right -= 1 + } + } +} diff --git a/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.ts b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.ts new file mode 100644 index 00000000..3c897e1d --- /dev/null +++ b/tests/1501-2000/1850. minimum-adjacent-swaps-to-reach-the-kth-smallest-number/sol.ts @@ -0,0 +1,45 @@ +function getMinSwaps(num: string, k: number): number { + let arr = num.split(""); + let target = num.split(""); + + for (let i = 0; i < k; i++) { + nextPermutation(target); + } + + let swaps = 0; + arr = num.split(""); + + for (let i = 0; i < arr.length; i++) { + if (arr[i] === target[i]) continue; + + let j = i; + while (arr[j] !== target[i]) j++; + + while (j > i) { + [arr[j], arr[j - 1]] = [arr[j - 1], arr[j]]; + j--; + swaps++; + } + } + + return swaps; +} + +function nextPermutation(arr: string[]): void { + let i = arr.length - 2; + while (i >= 0 && arr[i] >= arr[i + 1]) i--; + if (i === -1) return; + + let j = arr.length - 1; + while (arr[j] <= arr[i]) j--; + + [arr[i], arr[j]] = [arr[j], arr[i]]; + + let left = i + 1, + right = arr.length - 1; + while (left < right) { + [arr[left], arr[right]] = [arr[right], arr[left]]; + left++; + right--; + } +} diff --git a/tests/1501-2000/1851. minimum-interval-to-include-each-query/manifest.yaml b/tests/1501-2000/1851. minimum-interval-to-include-each-query/manifest.yaml new file mode 100644 index 00000000..3a4ce4e6 --- /dev/null +++ b/tests/1501-2000/1851. minimum-interval-to-include-each-query/manifest.yaml @@ -0,0 +1,374 @@ +entry: + id: 1851 + title: "minimum-interval-to-include-each-query" + params: + intervals: + type: array + items: + type: array + items: + type: int + queries: + type: array + items: + type: int + call: + cpp: "Solution().minInterval({intervals}, {queries})" + rust: "Solution::min_interval({intervals}, {queries})" + python3: "Solution().minInterval({intervals}, {queries})" + python2: "Solution().minInterval({intervals}, {queries})" + ruby: "min_interval({intervals}, {queries})" + java: "new Solution().minInterval({intervals}, {queries})" + csharp: "new Solution().MinInterval({intervals}, {queries})" + kotlin: "Solution().minInterval({intervals}, {queries})" + go: "minInterval({intervals}, {queries})" + dart: "Solution().minInterval({intervals}, {queries})" + swift: "Solution().minInterval({intervals}, {queries})" + typescript: "minInterval({intervals}, {queries})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 512 +oracle: + python3: + call: "Checker().minInterval(intervals, queries, {result})" + checker: | + class Checker: + def minInterval(self, intervals, queries, result): + if not isinstance(result, list) or len(result) != len(queries): + return False + expected = [] + for q in queries: + best = None + for pair in intervals: + if not isinstance(pair, list) or len(pair) != 2: + return False + left, right = pair + if left <= q <= right: + size = right - left + 1 + best = size if best is None else min(best, size) + expected.append(-1 if best is None else best) + return result == expected +seed: 1851 +tests: + - name: example-one + in: + intervals: + - [1, 4] + - [2, 4] + - [3, 6] + - [4, 4] + queries: [2, 3, 4, 5] + out: [3, 3, 1, 4] + - name: example-two + in: + intervals: + - [2, 3] + - [2, 5] + - [1, 8] + - [20, 25] + queries: [2, 19, 5, 22] + out: [2, -1, 4, 6] + - name: single-point + in: + intervals: + - [7, 7] + queries: [1, 7, 8] + out: [-1, 1, -1] + - name: duplicates + in: + intervals: + - [1, 10] + - [1, 10] + - [3, 3] + - [4, 6] + queries: [1, 3, 4, 6, 10] + out: [10, 1, 3, 3, 10] + - name: boundary-inclusive + in: + intervals: + - [5, 9] + - [9, 12] + queries: [4, 5, 9, 12, 13] + out: [-1, 5, 4, 4, -1] + - name: nested + in: + intervals: + - [1, 100] + - [20, 80] + - [40, 60] + - [50, 50] + queries: [1, 20, 40, 50, 60, 80, 100] + out: [100, 61, 21, 1, 21, 61, 100] + - name: disjoint + in: + intervals: + - [1, 2] + - [10, 12] + - [20, 25] + queries: [0, 1, 2, 3, 10, 11, 12, 19, 20, 25, 26] + out: [-1, 2, 2, -1, 3, 3, 3, -1, 6, 6, -1] + - name: unsorted-input + in: + intervals: + - [12, 15] + - [1, 20] + - [6, 8] + - [4, 5] + queries: [15, 8, 5, 2, 16] + out: [4, 3, 2, 20, 20] + - name: repeated-queries + in: + intervals: + - [2, 9] + - [4, 4] + - [7, 10] + queries: [4, 4, 10, 10, 1] + out: [1, 1, 4, 4, -1] + - name: negative-not-allowed-boundary + in: + intervals: + - [1, 1] + - [2, 2] + queries: [1, 2] + out: [1, 1] + - name: max-values + in: + intervals: + - [9999990, 10000000] + - [1, 10000000] + queries: [1, 9999989, 9999990, 10000000] + out: [10000000, 10000000, 11, 11] + - name: touching-ranges + in: + intervals: + - [1, 3] + - [3, 5] + - [5, 7] + queries: [1, 2, 3, 4, 5, 6, 7] + out: [3, 3, 3, 3, 3, 3, 3] + - name: equal-size-overlap + in: + intervals: + - [1, 5] + - [3, 7] + - [5, 9] + queries: [1, 3, 5, 7, 9] + out: [5, 5, 5, 5, 5] + - name: narrow-wins + in: + intervals: + - [1, 100] + - [25, 75] + - [49, 51] + - [50, 50] + queries: [24, 25, 49, 50, 51, 75, 76] + out: [100, 51, 3, 1, 3, 51, 100] + - name: all-uncovered + in: + intervals: + - [100, 200] + queries: [1, 50, 99, 201, 1000] + out: [-1, -1, -1, -1, -1] + - name: all-covered-single + in: + intervals: + - [42, 42] + queries: [42, 42, 42] + out: [1, 1, 1] + - name: many-overlaps + in: + intervals: + - [1, 50] + - [2, 49] + - [3, 48] + - [4, 47] + - [5, 46] + - [25, 25] + queries: [1, 2, 4, 24, 25, 26, 46, 47, 50] + out: [50, 48, 44, 42, 1, 42, 42, 44, 50] + - name: sparse-large-coordinates + in: + intervals: + - [100, 100] + - [1000, 1005] + - [100000, 200000] + queries: [99, 100, 101, 1000, 1003, 1005, 100006, 200000] + out: [-1, 1, -1, 6, 6, 6, 100001, 100001] + - name: short-and-long + in: + intervals: + - [10, 30] + - [15, 16] + - [20, 20] + - [25, 27] + queries: [10, 15, 16, 20, 25, 26, 27, 30] + out: [21, 2, 2, 1, 3, 3, 3, 21] + - name: singleton-intervals + in: + intervals: + - [1, 1] + - [3, 3] + - [5, 5] + - [7, 7] + queries: [1, 2, 3, 4, 5, 6, 7, 8] + out: [1, -1, 1, -1, 1, -1, 1, -1] + - name: endpoint-priority + in: + intervals: + - [1, 10] + - [10, 10] + - [1, 1] + queries: [1, 10] + out: [1, 1] + - name: twenty-one + in: + intervals: + - [1, 21] + - [2, 20] + - [3, 19] + - [10, 12] + queries: [1, 2, 3, 9, 10, 12, 13, 19, 20, 21] + out: [21, 19, 17, 17, 3, 3, 17, 17, 19, 21] + - name: alternating-gaps + in: + intervals: + - [2, 4] + - [8, 10] + - [14, 18] + - [22, 22] + queries: [2, 4, 5, 8, 10, 11, 14, 17, 18, 22] + out: [3, 3, -1, 3, 3, -1, 5, 5, 5, 1] + - name: large-cover-with-points + in: + intervals: + - [1, 10000000] + - [5000000, 5000000] + - [7500000, 7500100] + queries: + [1, 4999999, 5000000, 5000050, 7500000, 7500050, 7500100, 10000000] + out: [10000000, 10000000, 1, 10000000, 101, 101, 101, 10000000] + - name: short-query-list + in: + intervals: + - [4, 9] + - [6, 6] + queries: [6] + out: [1] + - name: short-interval-list + in: + intervals: + - [4, 9] + queries: [3, 4, 9, 10] + out: [-1, 6, 6, -1] + - name: overlapping-rights + in: + intervals: + - [1, 8] + - [2, 9] + - [3, 10] + - [4, 11] + queries: [1, 2, 3, 4, 8, 9, 10, 11] + out: [8, 8, 8, 8, 8, 8, 8, 8] + - name: exact-multiple + in: + intervals: + - [10, 20] + - [12, 18] + - [14, 16] + queries: [10, 12, 14, 15, 16, 18, 20] + out: [11, 7, 3, 3, 3, 7, 11] + - name: wide-query-order + in: + intervals: + - [5, 15] + - [1, 3] + - [9, 9] + queries: [15, 1, 9, 4, 3, 5] + out: [11, 3, 1, -1, 3, 11] + - name: positive-lower-bound + in: + intervals: + - [1, 2] + - [2, 100] + queries: [1, 2, 100] + out: [2, 2, 99] + - name: same-left-different-right + in: + intervals: + - [3, 30] + - [3, 20] + - [3, 10] + - [3, 5] + queries: [3, 5, 6, 10, 20, 30] + out: [3, 3, 8, 8, 18, 28] + - name: same-right-different-left + in: + intervals: + - [1, 10] + - [5, 10] + - [8, 10] + queries: [1, 5, 8, 9, 10] + out: [10, 6, 3, 3, 3] + - name: mixed-dense + in: + intervals: + - [1, 50] + - [10, 20] + - [15, 15] + - [21, 40] + - [35, 60] + - [70, 80] + queries: [1, 10, 15, 20, 21, 35, 40, 50, 60, 70, 80] + out: [50, 11, 1, 11, 20, 20, 20, 26, 26, 11, 11] + - name: long-consecutive-ranges + in: + intervals: + - [1, 1000] + - [250, 750] + - [500, 500] + - [999, 1000] + queries: [1, 249, 250, 499, 500, 501, 749, 750, 999, 1000] + out: [1000, 1000, 501, 501, 1, 501, 501, 501, 2, 2] + - name: large-valid-stress-shape + in: + intervals: + - [1, 1000000] + - [1000001, 2000000] + - [2000001, 3000000] + - [3000001, 4000000] + - [4000001, 5000000] + - [5000001, 6000000] + - [6000001, 7000000] + - [7000001, 8000000] + - [8000001, 9000000] + - [9000001, 10000000] + - [123456, 123456] + - [5555555, 5555555] + queries: + [ + 1, + 123455, + 123456, + 123457, + 1000000, + 1000001, + 5555554, + 5555555, + 5555556, + 10000000, + ] + out: + [ + 1000000, + 1000000, + 1, + 1000000, + 1000000, + 1000000, + 1000000, + 1, + 1000000, + 1000000, + ] diff --git a/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.cpp b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.cpp new file mode 100644 index 00000000..899a2563 --- /dev/null +++ b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.cpp @@ -0,0 +1,33 @@ +#include +#include +#include +#include + +class Solution { +public: + vector minInterval(vector>& intervals, vector& queries) { + sort(intervals.begin(), intervals.end()); + priority_queue, vector>, greater>> minHeap; + unordered_map res; + int i = 0; + vector sortedQueries = queries; + sort(sortedQueries.begin(), sortedQueries.end()); + for (int q : sortedQueries) { + while (i < intervals.size() && intervals[i][0] <= q) { + int l = intervals[i][0]; + int r = intervals[i][1]; + minHeap.push({r - l + 1, r}); + i++; + } + while (!minHeap.empty() && minHeap.top().second < q) { + minHeap.pop(); + } + res[q] = minHeap.empty() ? -1 : minHeap.top().first; + } + vector ans(queries.size()); + for (int j = 0; j < queries.size(); j++) { + ans[j] = res[queries[j]]; + } + return ans; + } +}; diff --git a/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.cs b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.cs new file mode 100644 index 00000000..8b052375 --- /dev/null +++ b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +public class Solution { + public int[] MinInterval(int[][] intervals, int[] queries) { + Array.Sort(intervals, (a, b) => a[0] - b[0]); + var minHeap = new SortedSet<(int, int)>(); + var res = new Dictionary(); + int i = 0; + var sortedQueries = queries.OrderBy(q => q).ToArray(); + foreach (var q in sortedQueries) { + while (i < intervals.Length && intervals[i][0] <= q) { + int l = intervals[i][0]; + int r = intervals[i][1]; + minHeap.Add((r - l + 1, r)); + i++; + } + while (minHeap.Count > 0 && minHeap.Min.Item2 < q) { + minHeap.Remove(minHeap.Min); + } + res[q] = minHeap.Count == 0 ? -1 : minHeap.Min.Item1; + } + return queries.Select(q => res[q]).ToArray(); + } +} diff --git a/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.dart b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.dart new file mode 100644 index 00000000..bbf6495d --- /dev/null +++ b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.dart @@ -0,0 +1,24 @@ +import 'dart:collection'; + +class Solution { + List minInterval(List> intervals, List queries) { + intervals.sort((a, b) => a[0].compareTo(b[0])); + final minHeap = PriorityQueue>((a, b) => a[0].compareTo(b[0])); + final res = {}; + int i = 0; + final sortedQueries = List.from(queries)..sort(); + for (final q in sortedQueries) { + while (i < intervals.length && intervals[i][0] <= q) { + final l = intervals[i][0]; + final r = intervals[i][1]; + minHeap.add([r - l + 1, r]); + i++; + } + while (minHeap.isNotEmpty && minHeap.first[1] < q) { + minHeap.removeFirst(); + } + res[q] = minHeap.isEmpty ? -1 : minHeap.first[0]; + } + return queries.map((q) => res[q]!).toList(); + } +} diff --git a/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.go b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.go new file mode 100644 index 00000000..b80d7f21 --- /dev/null +++ b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.go @@ -0,0 +1,38 @@ +func minInterval(intervals [][]int, queries []int) []int { + sort.Slice(intervals, func(i, j int) bool { + return intervals[i][0] < intervals[j][0] + }) + type heapItem struct { + size int + r int + } + minHeap := []heapItem{} + res := map[int]int{} + i := 0 + sortedQueries := make([]int, len(queries)) + copy(sortedQueries, queries) + sort.Ints(sortedQueries) + for _, q := range sortedQueries { + for i < len(intervals) && intervals[i][0] <= q { + l, r := intervals[i][0], intervals[i][1] + minHeap = append(minHeap, heapItem{r - l + 1, r}) + i++ + } + sort.Slice(minHeap, func(a, b int) bool { + return minHeap[a].size < minHeap[b].size + }) + for len(minHeap) > 0 && minHeap[0].r < q { + minHeap = minHeap[1:] + } + if len(minHeap) == 0 { + res[q] = -1 + } else { + res[q] = minHeap[0].size + } + } + ans := make([]int, len(queries)) + for j, q := range queries { + ans[j] = res[q] + } + return ans +} diff --git a/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.java b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.java new file mode 100644 index 00000000..97db8cb6 --- /dev/null +++ b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.java @@ -0,0 +1,28 @@ +import java.util.*; + +class Solution { + public int[] minInterval(int[][] intervals, int[] queries) { + Arrays.sort(intervals, (a, b) -> a[0] - b[0]); + PriorityQueue minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]); + Map res = new HashMap<>(); + int i = 0; + int[] sortedQueries = queries.clone(); + Arrays.sort(sortedQueries); + for (int q : sortedQueries) { + while (i < intervals.length && intervals[i][0] <= q) { + int l = intervals[i][0], r = intervals[i][1]; + minHeap.offer(new int[]{r - l + 1, r}); + i++; + } + while (!minHeap.isEmpty() && minHeap.peek()[1] < q) { + minHeap.poll(); + } + res.put(q, minHeap.isEmpty() ? -1 : minHeap.peek()[0]); + } + int[] ans = new int[queries.length]; + for (int j = 0; j < queries.length; j++) { + ans[j] = res.get(queries[j]); + } + return ans; + } +} diff --git a/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.kt b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.kt new file mode 100644 index 00000000..c3e1c8f5 --- /dev/null +++ b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.kt @@ -0,0 +1,24 @@ +import java.util.* + +class Solution { + fun minInterval(intervals: Array, queries: IntArray): IntArray { + intervals.sortBy { it[0] } + val minHeap = PriorityQueue(compareBy { it[0] }) + val res = HashMap() + var i = 0 + val sortedQueries = queries.sorted() + for (q in sortedQueries) { + while (i < intervals.size && intervals[i][0] <= q) { + val l = intervals[i][0] + val r = intervals[i][1] + minHeap.offer(intArrayOf(r - l + 1, r)) + i++ + } + while (!minHeap.isEmpty() && minHeap.peek()[1] < q) { + minHeap.poll() + } + res[q] = if (minHeap.isEmpty()) -1 else minHeap.peek()[0] + } + return IntArray(queries.size) { res[queries[it]]!! } + } +} diff --git a/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.py b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.py new file mode 100644 index 00000000..c1051eaa --- /dev/null +++ b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.py @@ -0,0 +1,38 @@ +import heapq + + +class Solution: + def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]: + # Sort the intervals + intervals.sort() + + # Initialize minHeap = [], res = {} and index i = 0. + minHeap = [] + res = {} + i = 0 + + # Iterate for q in sorted(queries) + for q in sorted(queries): + # Iterate while i < len(intervals) and intervals[i][0] <= q + while i < len(intervals) and intervals[i][0] <= q: + # Initialize l, r to values of intervals[i] + l, r = intervals[i] + # Push (r - l + 1, r) which is (size, right interval) to minHeap + heapq.heappush(minHeap, (r - l + 1, r)) + # Update i pointer to +1 + i += 1 + + # Iterate while minHeap and minHeap[0][1] < q + while minHeap and minHeap[0][1] < q: + # Pop from minHeap + heapq.heappop(minHeap) + # Update res[q] = minHeap[0][0] if minHeap else -1 + res[q] = minHeap[0][0] if minHeap else -1 + + # Iterate for i in range(len(queries)) + for i in range(len(queries)): + # Update queries[i] = res[queries[i]] + queries[i] = res[queries[i]] + + # return queries + return queries diff --git a/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.py2 b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.py2 new file mode 100644 index 00000000..fefe8467 --- /dev/null +++ b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def minInterval(self, intervals, queries): + """ + :type intervals: List[List[int]] + :type queries: List[int] + :rtype: List[int] + """ + intervals.sort() + import heapq + minHeap = [] + res = {} + i = 0 + for q in sorted(queries): + while i < len(intervals) and intervals[i][0] <= q: + l, r = intervals[i] + heapq.heappush(minHeap, (r - l + 1, r)) + i += 1 + while minHeap and minHeap[0][1] < q: + heapq.heappop(minHeap) + res[q] = minHeap[0][0] if minHeap else -1 + for i in range(len(queries)): + queries[i] = res[queries[i]] + return queries diff --git a/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.rb b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.rb new file mode 100644 index 00000000..9e9e2c51 --- /dev/null +++ b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.rb @@ -0,0 +1,24 @@ +# @param {Integer[][]} intervals +# @param {Integer[]} queries +# @return {Integer[]} +def min_interval(intervals, queries) + intervals.sort! + min_heap = [] + res = {} + i = 0 + sorted_queries = queries.sort + sorted_queries.each do |q| + while i < intervals.length && intervals[i][0] <= q + l, r = intervals[i] + min_heap << [r - l + 1, r] + i += 1 + end + min_heap.sort! + while !min_heap.empty? && min_heap[0][1] < q + min_heap.shift + end + res[q] = min_heap.empty? ? -1 : min_heap[0][0] + end + queries.map! { |q| res[q] } + queries +end diff --git a/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.rs b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.rs new file mode 100644 index 00000000..de01b392 --- /dev/null +++ b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.rs @@ -0,0 +1,31 @@ +use std::collections::BinaryHeap; +use std::cmp::Reverse; + +impl Solution { + pub fn min_interval(intervals: Vec>, queries: Vec) -> Vec { + let mut intervals = intervals.clone(); + intervals.sort(); + let mut min_heap: BinaryHeap<(Reverse, i32)> = BinaryHeap::new(); + let mut res = std::collections::HashMap::new(); + let mut i = 0; + let mut sorted_queries = queries.clone(); + sorted_queries.sort(); + for q in sorted_queries { + while i < intervals.len() && intervals[i][0] <= q { + let l = intervals[i][0]; + let r = intervals[i][1]; + min_heap.push((Reverse(r - l + 1), r)); + i += 1; + } + while let Some(&(_, r)) = min_heap.peek() { + if r < q { + min_heap.pop(); + } else { + break; + } + } + res.insert(q, if let Some(&(Reverse(size), _)) = min_heap.peek() { size } else { -1 }); + } + queries.iter().map(|q| res[q]).collect() + } +} diff --git a/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.swift b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.swift new file mode 100644 index 00000000..3452de2f --- /dev/null +++ b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.swift @@ -0,0 +1,25 @@ +import Foundation + +class Solution { + func minInterval(_ intervals: [[Int]], _ queries: [Int]) -> [Int] { + let sortedIntervals = intervals.sorted { $0[0] < $1[0] } + var minHeap = [(Int, Int)]() + var res = [Int: Int]() + var i = 0 + let sortedQueries = queries.sorted() + for q in sortedQueries { + while i < sortedIntervals.count && sortedIntervals[i][0] <= q { + let l = sortedIntervals[i][0] + let r = sortedIntervals[i][1] + minHeap.append((r - l + 1, r)) + minHeap.sort { $0.0 < $1.0 } + i += 1 + } + while !minHeap.isEmpty && minHeap[0].1 < q { + minHeap.removeFirst() + } + res[q] = minHeap.isEmpty ? -1 : minHeap[0].0 + } + return queries.map { res[$0] ?? -1 } + } +} diff --git a/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.ts b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.ts new file mode 100644 index 00000000..e242e738 --- /dev/null +++ b/tests/1501-2000/1851. minimum-interval-to-include-each-query/sol.ts @@ -0,0 +1,20 @@ +function minInterval(intervals: number[][], queries: number[]): number[] { + intervals.sort((a, b) => a[0] - b[0]); + const minHeap: [number, number][] = []; + const res: { [key: number]: number } = {}; + let i = 0; + const sortedQueries = [...queries].sort((a, b) => a - b); + for (const q of sortedQueries) { + while (i < intervals.length && intervals[i][0] <= q) { + const [l, r] = intervals[i]; + minHeap.push([r - l + 1, r]); + minHeap.sort((a, b) => a[0] - b[0]); + i++; + } + while (minHeap.length > 0 && minHeap[0][1] < q) { + minHeap.shift(); + } + res[q] = minHeap.length === 0 ? -1 : minHeap[0][0]; + } + return queries.map((q) => res[q]); +} diff --git a/tests/1501-2000/1854. maximum-population-year/manifest.yaml b/tests/1501-2000/1854. maximum-population-year/manifest.yaml new file mode 100644 index 00000000..f4748445 --- /dev/null +++ b/tests/1501-2000/1854. maximum-population-year/manifest.yaml @@ -0,0 +1,347 @@ +entry: + id: 1854 + title: "maximum-population-year" + params: + logs: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().maximumPopulation({logs})" + rust: "Solution::maximum_population({logs})" + python3: "Solution().maximumPopulation({logs})" + python2: "Solution().maximumPopulation({logs})" + ruby: "maximum_population({logs})" + java: "new Solution().maximumPopulation({logs})" + csharp: "new Solution().MaximumPopulation({logs})" + kotlin: "Solution().maximumPopulation({logs})" + go: "maximumPopulation({logs})" + dart: "Solution().maximumPopulation({logs})" + swift: "Solution().maximumPopulation({logs})" + typescript: "maximumPopulation({logs})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().maximumPopulation(logs, {result})" + checker: | + class Checker: + def maximumPopulation(self, logs, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + best_year = None + best_count = -1 + for year in range(1950, 2050): + count = sum(birth <= year < death for birth, death in logs) + if count > best_count: + best_count = count + best_year = year + return result == best_year + +seed: 1854 + +tests: + - name: "example_one" + in: + logs: + - [1993, 1999] + - [2000, 2010] + out: 1993 + - name: "example_two" + in: + logs: + - [1950, 1961] + - [1960, 1971] + - [1970, 1981] + out: 1960 + - name: "single_short_life" + in: + logs: + - [1951, 1952] + out: 1951 + - name: "single_last_year" + in: + logs: + - [2049, 2050] + out: 2049 + - name: "same_births" + in: + logs: + - [2000, 2001] + - [2000, 2005] + - [2000, 2010] + out: 2000 + - name: "death_boundary" + in: + logs: + - [2000, 2005] + - [2005, 2010] + out: 2000 + - name: "overlap_at_one_year" + in: + logs: + - [1999, 2001] + - [2000, 2002] + out: 2000 + - name: "earliest_tie" + in: + logs: + - [1950, 1960] + - [1955, 1965] + - [1960, 1970] + out: 1955 + - name: "latest_tie_not_selected" + in: + logs: + - [2000, 2002] + - [2001, 2004] + - [2003, 2005] + out: 2001 + - name: "nested_intervals" + in: + logs: + - [1950, 2050] + - [1960, 2040] + - [1970, 2030] + - [1980, 2020] + out: 1980 + - name: "disjoint_periods" + in: + logs: + - [1950, 1955] + - [1960, 1965] + - [1970, 1975] + - [1980, 1985] + out: 1950 + - name: "long_and_short" + in: + logs: + - [1950, 2050] + - [2000, 2001] + - [2000, 2001] + - [2049, 2050] + out: 2000 + - name: "minimum_births" + in: + logs: + - [1950, 1951] + - [1950, 1960] + - [1951, 1961] + out: 1950 + - name: "maximum_deaths" + in: + logs: + - [2040, 2050] + - [2041, 2050] + - [2042, 2050] + out: 2042 + - name: "chain_overlap" + in: + logs: + - [1950, 1960] + - [1955, 1965] + - [1960, 1970] + - [1965, 1975] + - [1970, 1980] + out: 1955 + - name: "three_way_peak" + in: + logs: + - [1990, 2000] + - [1992, 2002] + - [1994, 2004] + - [1996, 2006] + - [1998, 2008] + out: 1998 + - name: "peak_at_first_year" + in: + logs: + - [1950, 2000] + - [1950, 1951] + - [1950, 1951] + - [1999, 2050] + out: 1950 + - name: "peak_at_last_birth" + in: + logs: + - [1950, 2000] + - [1951, 2001] + - [1999, 2050] + - [1999, 2050] + out: 1999 + - name: "equal_ranges" + in: + logs: + - [1980, 1990] + - [1980, 1990] + - [1980, 1990] + - [1980, 1990] + out: 1980 + - name: "alternating_ranges" + in: + logs: + - [1950, 1960] + - [1960, 1970] + - [1955, 1965] + - [1965, 1975] + - [1970, 1980] + - [1975, 1985] + out: 1955 + - name: "short_ranges" + in: + logs: + - [2001, 2002] + - [2002, 2003] + - [2003, 2004] + - [2002, 2004] + out: 2002 + - name: "wide_year_span" + in: + logs: + - [1950, 2050] + - [1950, 1960] + - [2040, 2050] + - [2000, 2010] + out: 1950 + - name: "late_cluster" + in: + logs: + - [2020, 2030] + - [2021, 2031] + - [2022, 2032] + - [2023, 2033] + - [2024, 2034] + - [2025, 2035] + out: 2025 + - name: "early_cluster" + in: + logs: + - [1950, 1960] + - [1951, 1961] + - [1952, 1962] + - [1953, 1963] + - [1954, 1964] + - [1955, 1965] + out: 1955 + - name: "peak_after_gap" + in: + logs: + - [1950, 1955] + - [1951, 1954] + - [1960, 1970] + - [1961, 1969] + - [1962, 1968] + out: 1962 + - name: "two_peaks_earliest" + in: + logs: + - [1950, 1955] + - [1951, 1956] + - [1952, 1957] + - [2000, 2005] + - [2001, 2006] + - [2002, 2007] + out: 1952 + - name: "death_year_excluded" + in: + logs: + - [1990, 1991] + - [1991, 1992] + - [1991, 1993] + out: 1991 + - name: "mixed_centuries" + in: + logs: + - [1950, 2050] + - [1950, 1951] + - [2000, 2001] + - [2049, 2050] + - [2000, 2049] + out: 2000 + - name: "peak_singleton_after_overlap" + in: + logs: + - [1950, 1960] + - [1955, 1965] + - [1960, 1970] + - [1965, 1975] + out: 1955 + - name: "many_same_start" + in: + logs: + - [2010, 2011] + - [2010, 2012] + - [2010, 2013] + - [2010, 2014] + - [2011, 2015] + - [2012, 2016] + out: 2010 + - name: "late_overlap" + in: + logs: + - [2030, 2040] + - [2035, 2045] + - [2036, 2046] + - [2037, 2047] + - [2038, 2048] + - [2039, 2049] + out: 2039 + - name: "all_nonoverlap_boundary" + in: + logs: + - [1950, 1951] + - [1951, 1952] + - [1952, 1953] + - [1953, 1954] + - [1954, 1955] + out: 1950 + - name: "peak_with_duplicate_intervals" + in: + logs: + - [1995, 2005] + - [1995, 2005] + - [1997, 2007] + - [1999, 2009] + - [2001, 2011] + out: 2001 + - name: "balanced_overlap" + in: + logs: + - [1980, 1990] + - [1982, 1992] + - [1984, 1994] + - [1986, 1996] + - [1988, 1998] + - [1990, 2000] + - [1992, 2002] + out: 1988 + - name: "max_count_at_boundary" + in: + logs: + - [2040, 2050] + - [2040, 2049] + - [2040, 2048] + - [2039, 2041] + out: 2040 + - name: "full_constraint_count" + in: + logs: + - [1950, 2050] + - [1950, 2050] + - [1950, 2050] + - [1950, 2050] + - [1950, 2050] + - [1950, 2050] + - [1950, 2050] + - [1950, 2050] + - [1950, 2050] + - [1950, 2050] + out: 1950 diff --git a/tests/1501-2000/1854. maximum-population-year/sol.cpp b/tests/1501-2000/1854. maximum-population-year/sol.cpp new file mode 100644 index 00000000..390e96d6 --- /dev/null +++ b/tests/1501-2000/1854. maximum-population-year/sol.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int maximumPopulation(vector>& logs) { + int l = logs.size(); + vector a; + int r = 0; + int y = 0; + for (auto& i : logs) { + a.push_back(i[0]); + } + for (int j = 0; j < l; j++) { + int c = 0; + for (int k = 0; k < l; k++) { + if (a[j] >= logs[k][0] && a[j] < logs[k][1] && j != k) { + c++; + } + } + if (c > r) { + r = c; + y = a[j]; + } + if (c == r && r > 0) { + if (a[j] < y) { + y = a[j]; + } + } + } + if (y == 0) { + return *min_element(a.begin(), a.end()); + } + return y; + } +}; diff --git a/tests/1501-2000/1854. maximum-population-year/sol.cs b/tests/1501-2000/1854. maximum-population-year/sol.cs new file mode 100644 index 00000000..6c8546c7 --- /dev/null +++ b/tests/1501-2000/1854. maximum-population-year/sol.cs @@ -0,0 +1,36 @@ +public class Solution { + public int MaximumPopulation(int[][] logs) { + int l = logs.Length; + int[] a = new int[l]; + int r = 0; + int y = 0; + for (int i = 0; i < l; i++) { + a[i] = logs[i][0]; + } + for (int j = 0; j < l; j++) { + int c = 0; + for (int k = 0; k < l; k++) { + if (a[j] >= logs[k][0] && a[j] < logs[k][1] && j != k) { + c++; + } + } + if (c > r) { + r = c; + y = a[j]; + } + if (c == r && r > 0) { + if (a[j] < y) { + y = a[j]; + } + } + } + if (y == 0) { + int min = a[0]; + for (int i = 1; i < l; i++) { + if (a[i] < min) min = a[i]; + } + return min; + } + return y; + } +} diff --git a/tests/1501-2000/1854. maximum-population-year/sol.dart b/tests/1501-2000/1854. maximum-population-year/sol.dart new file mode 100644 index 00000000..2cdb9d60 --- /dev/null +++ b/tests/1501-2000/1854. maximum-population-year/sol.dart @@ -0,0 +1,36 @@ +class Solution { + int maximumPopulation(List> logs) { + int l = logs.length; + List a = []; + int r = 0; + int y = 0; + for (var i in logs) { + a.add(i[0]); + } + for (int j = 0; j < l; j++) { + int c = 0; + for (int k = 0; k < l; k++) { + if (a[j] >= logs[k][0] && a[j] < logs[k][1] && j != k) { + c++; + } + } + if (c > r) { + r = c; + y = a[j]; + } + if (c == r && r > 0) { + if (a[j] < y) { + y = a[j]; + } + } + } + if (y == 0) { + int min = a[0]; + for (int i = 1; i < l; i++) { + if (a[i] < min) min = a[i]; + } + return min; + } + return y; + } +} diff --git a/tests/1501-2000/1854. maximum-population-year/sol.go b/tests/1501-2000/1854. maximum-population-year/sol.go new file mode 100644 index 00000000..3f64133f --- /dev/null +++ b/tests/1501-2000/1854. maximum-population-year/sol.go @@ -0,0 +1,36 @@ +func maximumPopulation(logs [][]int) int { + l := len(logs) + a := make([]int, l) + r := 0 + y := 0 + for i := 0; i < l; i++ { + a[i] = logs[i][0] + } + for j := 0; j < l; j++ { + c := 0 + for k := 0; k < l; k++ { + if a[j] >= logs[k][0] && a[j] < logs[k][1] && j != k { + c++ + } + } + if c > r { + r = c + y = a[j] + } + if c == r && r > 0 { + if a[j] < y { + y = a[j] + } + } + } + if y == 0 { + min := a[0] + for i := 1; i < l; i++ { + if a[i] < min { + min = a[i] + } + } + return min + } + return y +} diff --git a/tests/1501-2000/1854. maximum-population-year/sol.java b/tests/1501-2000/1854. maximum-population-year/sol.java new file mode 100644 index 00000000..f5565b83 --- /dev/null +++ b/tests/1501-2000/1854. maximum-population-year/sol.java @@ -0,0 +1,36 @@ +class Solution { + public int maximumPopulation(int[][] logs) { + int l = logs.length; + int[] a = new int[l]; + int r = 0; + int y = 0; + for (int i = 0; i < l; i++) { + a[i] = logs[i][0]; + } + for (int j = 0; j < l; j++) { + int c = 0; + for (int k = 0; k < l; k++) { + if (a[j] >= logs[k][0] && a[j] < logs[k][1] && j != k) { + c++; + } + } + if (c > r) { + r = c; + y = a[j]; + } + if (c == r && r > 0) { + if (a[j] < y) { + y = a[j]; + } + } + } + if (y == 0) { + int min = a[0]; + for (int i = 1; i < l; i++) { + if (a[i] < min) min = a[i]; + } + return min; + } + return y; + } +} diff --git a/tests/1501-2000/1854. maximum-population-year/sol.kt b/tests/1501-2000/1854. maximum-population-year/sol.kt new file mode 100644 index 00000000..dddb05b7 --- /dev/null +++ b/tests/1501-2000/1854. maximum-population-year/sol.kt @@ -0,0 +1,36 @@ +class Solution { + fun maximumPopulation(logs: Array): Int { + val l = logs.size + val a = IntArray(l) + var r = 0 + var y = 0 + for (i in 0 until l) { + a[i] = logs[i][0] + } + for (j in 0 until l) { + var c = 0 + for (k in 0 until l) { + if (a[j] >= logs[k][0] && a[j] < logs[k][1] && j != k) { + c++ + } + } + if (c > r) { + r = c + y = a[j] + } + if (c == r && r > 0) { + if (a[j] < y) { + y = a[j] + } + } + } + if (y == 0) { + var min = a[0] + for (i in 1 until l) { + if (a[i] < min) min = a[i] + } + return min + } + return y + } +} diff --git a/tests/1501-2000/1854. maximum-population-year/sol.py b/tests/1501-2000/1854. maximum-population-year/sol.py new file mode 100644 index 00000000..6655cd2b --- /dev/null +++ b/tests/1501-2000/1854. maximum-population-year/sol.py @@ -0,0 +1,22 @@ +class Solution(object): + def maximumPopulation(self, logs): + l = len(logs) + a = [] + r = 0 + y = 0 + for i in logs: + a.append(i[0]) + for j in range(l): + c = 0 + for k in range(l): + if a[j] >= logs[k][0] and a[j] < logs[k][1] and j != k: + c += 1 + if c > r: + r = c + y = a[j] + if c == r and r > 0: + if a[j] < y: + y = a[j] + if y == 0: + return min(a) + return y diff --git a/tests/1501-2000/1854. maximum-population-year/sol.py2 b/tests/1501-2000/1854. maximum-population-year/sol.py2 new file mode 100644 index 00000000..c30f3c46 --- /dev/null +++ b/tests/1501-2000/1854. maximum-population-year/sol.py2 @@ -0,0 +1,26 @@ +class Solution(object): + def maximumPopulation(self, logs): + """ + :type logs: List[List[int]] + :rtype: int + """ + l=len(logs) + a=[] + r=0 + y=0 + for i in logs: + a.append(i[0]) + for j in range(l): + c=0 + for k in range(l): + if a[j]>=logs[k][0] and a[j]r: + r=c + y=a[j] + if c==r and r>0: + if a[j]= logs[k][0] && a[j] < logs[k][1] && j != k + c += 1 + end + end + if c > r + r = c + y = a[j] + end + if c == r && r > 0 + if a[j] < y + y = a[j] + end + end + end + return a.min if y == 0 + y +end diff --git a/tests/1501-2000/1854. maximum-population-year/sol.rs b/tests/1501-2000/1854. maximum-population-year/sol.rs new file mode 100644 index 00000000..07ff982e --- /dev/null +++ b/tests/1501-2000/1854. maximum-population-year/sol.rs @@ -0,0 +1,32 @@ +impl Solution { + pub fn maximum_population(logs: Vec>) -> i32 { + let l = logs.len(); + let mut a: Vec = Vec::new(); + let mut r = 0; + let mut y = 0; + for i in &logs { + a.push(i[0]); + } + for j in 0..l { + let mut c = 0; + for k in 0..l { + if a[j] >= logs[k][0] && a[j] < logs[k][1] && j != k { + c += 1; + } + } + if c > r { + r = c; + y = a[j]; + } + if c == r && r > 0 { + if a[j] < y { + y = a[j]; + } + } + } + if y == 0 { + return *a.iter().min().unwrap(); + } + y + } +} diff --git a/tests/1501-2000/1854. maximum-population-year/sol.swift b/tests/1501-2000/1854. maximum-population-year/sol.swift new file mode 100644 index 00000000..d835f6bf --- /dev/null +++ b/tests/1501-2000/1854. maximum-population-year/sol.swift @@ -0,0 +1,32 @@ +class Solution { + func maximumPopulation(_ logs: [[Int]]) -> Int { + let l = logs.count + var a = [Int]() + var r = 0 + var y = 0 + for i in logs { + a.append(i[0]) + } + for j in 0..= logs[k][0] && a[j] < logs[k][1] && j != k { + c += 1 + } + } + if c > r { + r = c + y = a[j] + } + if c == r && r > 0 { + if a[j] < y { + y = a[j] + } + } + } + if y == 0 { + return a.min()! + } + return y + } +} diff --git a/tests/1501-2000/1854. maximum-population-year/sol.ts b/tests/1501-2000/1854. maximum-population-year/sol.ts new file mode 100644 index 00000000..9c52f4f9 --- /dev/null +++ b/tests/1501-2000/1854. maximum-population-year/sol.ts @@ -0,0 +1,30 @@ +function maximumPopulation(logs: number[][]): number { + const l = logs.length; + const a: number[] = []; + let r = 0; + let y = 0; + for (const i of logs) { + a.push(i[0]); + } + for (let j = 0; j < l; j++) { + let c = 0; + for (let k = 0; k < l; k++) { + if (a[j] >= logs[k][0] && a[j] < logs[k][1] && j !== k) { + c++; + } + } + if (c > r) { + r = c; + y = a[j]; + } + if (c === r && r > 0) { + if (a[j] < y) { + y = a[j]; + } + } + } + if (y === 0) { + return Math.min(...a); + } + return y; +} diff --git a/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/manifest.yaml b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/manifest.yaml new file mode 100644 index 00000000..71bade34 --- /dev/null +++ b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/manifest.yaml @@ -0,0 +1,226 @@ +entry: + id: 1855 + title: "maximum-distance-between-a-pair-of-values" + params: + nums1: + type: array + items: + type: int + nums2: + type: array + items: + type: int + call: + cpp: "Solution().maxDistance({nums1}, {nums2})" + rust: "Solution::max_distance({nums1}, {nums2})" + python3: "Solution().maxDistance({nums1}, {nums2})" + python2: "Solution().maxDistance({nums1}, {nums2})" + ruby: "max_distance({nums1}, {nums2})" + java: "new Solution().maxDistance({nums1}, {nums2})" + csharp: "new Solution().MaxDistance({nums1}, {nums2})" + kotlin: "Solution().maxDistance({nums1}, {nums2})" + go: "maxDistance({nums1}, {nums2})" + dart: "Solution().maxDistance({nums1}, {nums2})" + swift: "Solution().maxDistance({nums1}, {nums2})" + typescript: "maxDistance({nums1}, {nums2})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().maxDistance(nums1, nums2, {result})" + checker: | + class Checker: + def maxDistance(self, nums1, nums2, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + best = 0 + for i, x in enumerate(nums1): + for j in range(i, len(nums2)): + if x <= nums2[j]: + best = max(best, j - i) + return result == best + +seed: 1855 + +tests: + - name: "example_1" + in: + nums1: [55, 30, 5, 4, 2] + nums2: [100, 20, 10, 10, 5] + out: 2 + - name: "example_2" + in: + nums1: [2, 2, 2] + nums2: [10, 10, 1] + out: 1 + - name: "example_3" + in: + nums1: [30, 29, 19, 5] + nums2: [25, 25, 25, 25, 25] + out: 2 + - name: "single_equal" + in: + nums1: [7] + nums2: [7] + out: 0 + - name: "single_invalid" + in: + nums1: [8] + nums2: [7] + out: 0 + - name: "single_valid_long_second" + in: + nums1: [1] + nums2: [1, 1, 1, 1, 1] + out: 4 + - name: "long_first_single_second" + in: + nums1: [9, 8, 7, 6, 5] + nums2: [9] + out: 0 + - name: "all_equal" + in: + nums1: [5, 5, 5, 5] + nums2: [5, 5, 5, 5, 5, 5] + out: 5 + - name: "nums2_all_too_small" + in: + nums1: [10, 9, 8] + nums2: [7, 6, 5, 4] + out: 0 + - name: "nums1_all_too_large" + in: + nums1: [10, 10, 10] + nums2: [9, 9, 9, 9] + out: 0 + - name: "strict_decrease" + in: + nums1: [9, 7, 5, 3, 1] + nums2: [10, 8, 6, 4, 2] + out: 0 + - name: "only_diagonal" + in: + nums1: [6, 4, 2] + nums2: [6, 4, 2] + out: 0 + - name: "late_threshold" + in: + nums1: [100, 90, 80, 70] + nums2: [69, 69, 69, 70, 70, 70] + out: 2 + - name: "threshold_at_end" + in: + nums1: [8, 7, 6, 5] + nums2: [4, 4, 4, 5, 5, 5] + out: 2 + - name: "wide_valid_tail" + in: + nums1: [6, 5, 4, 3, 2] + nums2: [7, 6, 5, 4, 3, 2] + out: 1 + - name: "duplicates_boundary" + in: + nums1: [4, 4, 4, 2] + nums2: [4, 4, 3, 2] + out: 1 + - name: "different_lengths" + in: + nums1: [20, 15, 10, 5] + nums2: [25, 24] + out: 1 + - name: "second_much_longer" + in: + nums1: [5, 4] + nums2: [8, 7, 6, 5, 4, 3, 2] + out: 3 + - name: "values_one" + in: + nums1: [1, 1, 1] + nums2: [1, 1] + out: 1 + - name: "values_max" + in: + nums1: [100000, 100000] + nums2: [100000, 100000, 100000] + out: 2 + - name: "one_valid_pair" + in: + nums1: [9, 8, 7, 6] + nums2: [8, 1, 1, 1] + out: 0 + - name: "one_far_pair" + in: + nums1: [50, 40, 30, 20, 10] + nums2: [60, 5, 5, 5, 5, 5, 5] + out: 0 + - name: "far_pair_after_drop" + in: + nums1: [50, 40, 30, 20, 10] + nums2: [49, 49, 29, 29, 29, 29, 29] + out: 3 + - name: "alternating_plateaus" + in: + nums1: [9, 9, 5, 5, 1, 1] + nums2: [10, 10, 6, 6, 2, 2, 0] + out: 1 + - name: "short_overlap" + in: + nums1: [7, 6, 5, 4, 3] + nums2: [8, 2] + out: 0 + - name: "all_cross_index" + in: + nums1: [3, 3, 3, 3] + nums2: [4, 4, 4, 4, 4] + out: 4 + - name: "descending_near_limit" + in: + nums1: [100000, 99999, 99998, 99997] + nums2: [100000, 99998, 99996, 99994, 99992] + out: 0 + - name: "large_gap_values" + in: + nums1: [99999, 50000, 1] + nums2: [100000, 50000, 0] + out: 0 + - name: "no_index_extension" + in: + nums1: [5, 4, 3] + nums2: [6, 2, 1] + out: 0 + - name: "best_from_middle" + in: + nums1: [20, 19, 10, 9, 8] + nums2: [18, 17, 16, 10, 10, 10] + out: 3 + - name: "best_from_last" + in: + nums1: [20, 19, 18, 4] + nums2: [17, 16, 15, 14, 13, 4] + out: 2 + - name: "equal_length_edge" + in: + nums1: [5, 4, 3, 2, 1] + nums2: [5, 4, 3, 2, 1] + out: 0 + - name: "strictly_improving" + in: + nums1: [100, 80, 60, 40, 20] + nums2: [100, 90, 70, 50, 30, 10] + out: 0 + - name: "plateau_then_failure" + in: + nums1: [7, 7, 7, 7] + nums2: [7, 7, 6, 6, 6] + out: 1 + - name: "additional_plateau_case" + in: + nums1: [100000, 90000, 90000, 50000, 10] + nums2: [100000, 95000, 90000, 90000, 50000, 10] + out: 2 diff --git a/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.cpp b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.cpp new file mode 100644 index 00000000..7cb8d787 --- /dev/null +++ b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int maxDistance(vector& nums1, vector& nums2) { + int i = 0, j = 0; + int ans = 0; + while (i < nums1.size() && j < nums2.size()) { + if (nums1[i] <= nums2[j]) { + ans = max(ans, j - i); + j++; + } else { + i++; + if (i > j) j = i; + } + } + return ans; + } +}; diff --git a/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.cs b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.cs new file mode 100644 index 00000000..a48455bd --- /dev/null +++ b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public int MaxDistance(int[] nums1, int[] nums2) { + int i = 0, j = 0; + int ans = 0; + while (i < nums1.Length && j < nums2.Length) { + if (nums1[i] <= nums2[j]) { + ans = Math.Max(ans, j - i); + j++; + } else { + i++; + if (i > j) j = i; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.dart b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.dart new file mode 100644 index 00000000..2aaec35e --- /dev/null +++ b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.dart @@ -0,0 +1,16 @@ +class Solution { + int maxDistance(List nums1, List nums2) { + int i = 0, j = 0; + int ans = 0; + while (i < nums1.length && j < nums2.length) { + if (nums1[i] <= nums2[j]) { + if (j - i > ans) ans = j - i; + j++; + } else { + i++; + if (i > j) j = i; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.go b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.go new file mode 100644 index 00000000..196d5bbb --- /dev/null +++ b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.go @@ -0,0 +1,18 @@ +func maxDistance(nums1 []int, nums2 []int) int { + i, j := 0, 0 + ans := 0 + for i < len(nums1) && j < len(nums2) { + if nums1[i] <= nums2[j] { + if j-i > ans { + ans = j - i + } + j++ + } else { + i++ + if i > j { + j = i + } + } + } + return ans +} diff --git a/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.java b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.java new file mode 100644 index 00000000..e20e4768 --- /dev/null +++ b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.java @@ -0,0 +1,16 @@ +class Solution { + public int maxDistance(int[] nums1, int[] nums2) { + int i = 0, j = 0; + int ans = 0; + while (i < nums1.length && j < nums2.length) { + if (nums1[i] <= nums2[j]) { + ans = Math.max(ans, j - i); + j++; + } else { + i++; + if (i > j) j = i; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.kt b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.kt new file mode 100644 index 00000000..89ca7f7c --- /dev/null +++ b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.kt @@ -0,0 +1,17 @@ +class Solution { + fun maxDistance(nums1: IntArray, nums2: IntArray): Int { + var i = 0 + var j = 0 + var ans = 0 + while (i < nums1.size && j < nums2.size) { + if (nums1[i] <= nums2[j]) { + ans = maxOf(ans, j - i) + j++ + } else { + i++ + if (i > j) j = i + } + } + return ans + } +} diff --git a/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.py b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.py new file mode 100644 index 00000000..59380bae --- /dev/null +++ b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.py @@ -0,0 +1,15 @@ +class Solution: + def maxDistance(self, nums1: List[int], nums2: List[int]) -> int: + i, j = 0, 0 + ans = 0 + + while i < len(nums1) and j < len(nums2): + if nums1[i] <= nums2[j]: + ans = max(ans, j - i) + j += 1 + else: + i += 1 + if i > j: + j = i + + return ans diff --git a/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.py2 b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.py2 new file mode 100644 index 00000000..076258da --- /dev/null +++ b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def maxDistance(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: int + """ + i, j = 0, 0 + ans = 0 + while i < len(nums1) and j < len(nums2): + if nums1[i] <= nums2[j]: + ans = max(ans, j - i) + j += 1 + else: + i += 1 + if i > j: + j = i + return ans diff --git a/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.rb b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.rb new file mode 100644 index 00000000..61e62042 --- /dev/null +++ b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.rb @@ -0,0 +1,20 @@ +# @param {Integer[]} nums1 +# @param {Integer[]} nums2 +# @return {Integer} +def max_distance(nums1, nums2) + i = 0 + j = 0 + ans = 0 + while i < nums1.length && j < nums2.length + if nums1[i] <= nums2[j] + ans = [ans, j - i].max + j += 1 + else + i += 1 + if i > j + j = i + end + end + end + ans +end diff --git a/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.rs b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.rs new file mode 100644 index 00000000..e20dea7f --- /dev/null +++ b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn max_distance(nums1: Vec, nums2: Vec) -> i32 { + let mut i = 0; + let mut j = 0; + let mut ans = 0; + while i < nums1.len() && j < nums2.len() { + if nums1[i] <= nums2[j] { + ans = ans.max(j - i); + j += 1; + } else { + i += 1; + if i > j { j = i; } + } + } + ans as i32 + } +} diff --git a/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.swift b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.swift new file mode 100644 index 00000000..cc43d216 --- /dev/null +++ b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func maxDistance(_ nums1: [Int], _ nums2: [Int]) -> Int { + var i = 0, j = 0 + var ans = 0 + while i < nums1.count && j < nums2.count { + if nums1[i] <= nums2[j] { + ans = max(ans, j - i) + j += 1 + } else { + i += 1 + if i > j { j = i } + } + } + return ans + } +} diff --git a/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.ts b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.ts new file mode 100644 index 00000000..fb7d8cb8 --- /dev/null +++ b/tests/1501-2000/1855. maximum-distance-between-a-pair-of-values/sol.ts @@ -0,0 +1,15 @@ +function maxDistance(nums1: number[], nums2: number[]): number { + let i = 0, + j = 0; + let ans = 0; + while (i < nums1.length && j < nums2.length) { + if (nums1[i] <= nums2[j]) { + ans = Math.max(ans, j - i); + j++; + } else { + i++; + if (i > j) j = i; + } + } + return ans; +} diff --git a/tests/1501-2000/1856. maximum-subarray-min-product/manifest.yaml b/tests/1501-2000/1856. maximum-subarray-min-product/manifest.yaml new file mode 100644 index 00000000..fd8e06ee --- /dev/null +++ b/tests/1501-2000/1856. maximum-subarray-min-product/manifest.yaml @@ -0,0 +1,248 @@ +entry: + id: 1856 + title: "maximum-subarray-min-product" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().maxSumMinProduct({nums})" + rust: "Solution::max_sum_min_product({nums})" + python3: "Solution().maxSumMinProduct({nums})" + python2: "Solution().maxSumMinProduct({nums})" + ruby: "max_sum_min_product({nums})" + java: "new Solution().maxSumMinProduct({nums})" + csharp: "new Solution().MaxSumMinProduct({nums})" + kotlin: "Solution().maxSumMinProduct({nums})" + go: "maxSumMinProduct({nums})" + dart: "Solution().maxSumMinProduct({nums})" + swift: "Solution().maxSumMinProduct({nums})" + typescript: "maxSumMinProduct({nums})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().maxSumMinProduct(nums, {result})" + checker: | + class Checker: + def maxSumMinProduct(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + n = len(nums) + prefix = [0] + for value in nums: + prefix.append(prefix[-1] + value) + stack = [] + best = 0 + for i in range(n + 1): + current = nums[i] if i < n else 0 + while stack and (i == n or nums[stack[-1]] > current): + j = stack.pop() + left = stack[-1] + 1 if stack else 0 + total = prefix[i] - prefix[left] + best = max(best, nums[j] * total) + stack.append(i) + return result == best % 1000000007 + +seed: 1856 + +tests: + - name: "example_one" + in: + nums: [1, 2, 3, 2] + out: 14 + - name: "example_two" + in: + nums: [2, 3, 3, 1, 2] + out: 18 + - name: "example_three" + in: + nums: [3, 1, 5, 6, 4, 2] + out: 60 + - name: "single_one" + in: + nums: [1] + out: 1 + - name: "single_max" + in: + nums: [10000000] + out: 999300007 + - name: "two_increasing" + in: + nums: [2, 5] + out: 25 + - name: "two_decreasing" + in: + nums: [5, 2] + out: 25 + - name: "equal_values" + in: + nums: [7, 7, 7, 7] + out: 196 + - name: "all_ones" + in: + nums: [1, 1, 1, 1, 1, 1] + out: 6 + - name: "valley_center" + in: + nums: [10, 10, 1, 10, 10] + out: 200 + - name: "low_at_edge" + in: + nums: [1, 100, 100] + out: 20000 + - name: "high_at_edge" + in: + nums: [100, 100, 1] + out: 20000 + - name: "alternating" + in: + nums: [2, 9, 2, 9, 2] + out: 81 + - name: "nested_plateaus" + in: + nums: [4, 4, 2, 2, 3, 3] + out: 36 + - name: "strict_increase" + in: + nums: [1, 2, 3, 4, 5, 6] + out: 60 + - name: "strict_decrease" + in: + nums: [6, 5, 4, 3, 2, 1] + out: 60 + - name: "large_uniform" + in: + nums: [10000000, 10000000, 10000000] + out: 997900007 + - name: "large_mixed" + in: + nums: [9999999, 10000000, 9999998, 10000000] + out: 887200013 + - name: "isolated_peak" + in: + nums: [1, 1, 100, 1, 1] + out: 10000 + - name: "two_plateaus" + in: + nums: [3, 3, 1, 3, 3] + out: 18 + - name: "multiple_minima" + in: + nums: [5, 2, 2, 5] + out: 28 + - name: "short_peak" + in: + nums: [2, 8, 8, 2] + out: 128 + - name: "deep_valley" + in: + nums: [9, 8, 7, 1, 7, 8, 9] + out: 168 + - name: "small_range" + in: + nums: [1, 2, 1, 2, 1] + out: 7 + - name: "prime_values" + in: + nums: [2, 3, 5, 7, 11] + out: 126 + - name: "wide_middle_minimum" + in: + nums: [8, 8, 8, 2, 8, 8, 8] + out: 192 + - name: "single_dominant" + in: + nums: [2, 2, 50, 2, 2] + out: 2500 + - name: "modulo_boundary" + in: + nums: [10000000, 10000000, 10000000, 10000000, 10000000] + out: 996500007 + - name: "many_small_then_large" + in: + nums: [1, 1, 1, 1, 9, 9, 9] + out: 243 + - name: "large_then_small" + in: + nums: [9, 9, 9, 1, 1, 1, 1] + out: 243 + - name: "balanced" + in: + nums: [4, 2, 4, 2, 4, 2, 4] + out: 44 + - name: "mixed_small" + in: + nums: [6, 1, 5, 2, 4, 3] + out: 36 + - name: "repeated_low" + in: + nums: [10, 2, 10, 2, 10] + out: 100 + - name: "near_max_values" + in: + nums: [9999990, 9999991, 9999992] + out: 427900277 + - name: "generated_small" + seed: 101 + in: + nums: + gen: "array" + len: + gen: "int" + min: 1 + max: 100 + of: + gen: "int" + min: 1 + max: 10000000 + - name: "generated_medium" + seed: 102 + in: + nums: + gen: "array" + len: + gen: "int" + min: 1000 + max: 5000 + of: + gen: "int" + min: 1 + max: 10000000 + - name: "generated_large_a" + seed: 103 + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 10000000 + - name: "generated_large_b" + seed: 104 + in: + nums: + gen: "array" + len: 75000 + of: + gen: "int" + min: 1 + max: 10000000 + - name: "generated_maximum" + seed: 105 + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 10000000 diff --git a/tests/1501-2000/1856. maximum-subarray-min-product/sol.cpp b/tests/1501-2000/1856. maximum-subarray-min-product/sol.cpp new file mode 100644 index 00000000..023f27b0 --- /dev/null +++ b/tests/1501-2000/1856. maximum-subarray-min-product/sol.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int maxSumMinProduct(vector& nums) { + int n = nums.size(); + vector prefix(n + 1, 0); + for (int i = 0; i < n; i++) prefix[i+1] = prefix[i] + nums[i]; + + vector leftBound(n, -1), rightBound(n, n); + stack st; + for (int i = 0; i < n; i++) { + while (!st.empty() && nums[st.top()] > nums[i]) { + rightBound[st.top()] = i; + st.pop(); + } + st.push(i); + } + while (!st.empty()) st.pop(); + for (int i = n-1; i >= 0; i--) { + while (!st.empty() && nums[st.top()] > nums[i]) { + leftBound[st.top()] = i; + st.pop(); + } + st.push(i); + } + + long long maxProd = 0; + for (int i = 0; i < n; i++) { + int l = leftBound[i], r = rightBound[i]; + long long totalSum = prefix[r] - prefix[l+1]; + maxProd = max(maxProd, (long long)nums[i] * totalSum); + } + return (int)(maxProd % 1000000007LL); + } +}; diff --git a/tests/1501-2000/1856. maximum-subarray-min-product/sol.cs b/tests/1501-2000/1856. maximum-subarray-min-product/sol.cs new file mode 100644 index 00000000..98a22a77 --- /dev/null +++ b/tests/1501-2000/1856. maximum-subarray-min-product/sol.cs @@ -0,0 +1,34 @@ +public class Solution { + public int MaxSumMinProduct(int[] nums) { + int n = nums.Length; + long[] prefix = new long[n + 1]; + for (int i = 0; i < n; i++) prefix[i+1] = prefix[i] + nums[i]; + + int[] leftBound = new int[n]; + int[] rightBound = new int[n]; + Array.Fill(leftBound, -1); + Array.Fill(rightBound, n); + var stack = new Stack(); + for (int i = 0; i < n; i++) { + while (stack.Count > 0 && nums[stack.Peek()] > nums[i]) { + rightBound[stack.Pop()] = i; + } + stack.Push(i); + } + stack.Clear(); + for (int i = n-1; i >= 0; i--) { + while (stack.Count > 0 && nums[stack.Peek()] > nums[i]) { + leftBound[stack.Pop()] = i; + } + stack.Push(i); + } + + long maxProd = 0; + for (int i = 0; i < n; i++) { + int l = leftBound[i], r = rightBound[i]; + long total = prefix[r] - prefix[l+1]; + maxProd = Math.Max(maxProd, (long)nums[i] * total); + } + return (int)(maxProd % 1000000007L); + } +} diff --git a/tests/1501-2000/1856. maximum-subarray-min-product/sol.dart b/tests/1501-2000/1856. maximum-subarray-min-product/sol.dart new file mode 100644 index 00000000..0423ab95 --- /dev/null +++ b/tests/1501-2000/1856. maximum-subarray-min-product/sol.dart @@ -0,0 +1,32 @@ +class Solution { + int maxSumMinProduct(List nums) { + int n = nums.length; + List prefix = List.filled(n + 1, 0); + for (int i = 0; i < n; i++) prefix[i+1] = prefix[i] + nums[i]; + + List leftBound = List.filled(n, -1); + List rightBound = List.filled(n, n); + List stack = []; + for (int i = 0; i < n; i++) { + while (stack.isNotEmpty && nums[stack.last] > nums[i]) { + rightBound[stack.removeLast()] = i; + } + stack.add(i); + } + stack.clear(); + for (int i = n-1; i >= 0; i--) { + while (stack.isNotEmpty && nums[stack.last] > nums[i]) { + leftBound[stack.removeLast()] = i; + } + stack.add(i); + } + + int maxProd = 0; + for (int i = 0; i < n; i++) { + int l = leftBound[i], r = rightBound[i]; + int total = prefix[r] - prefix[l+1]; + maxProd = max(maxProd, nums[i] * total); + } + return maxProd % 1000000007; + } +} diff --git a/tests/1501-2000/1856. maximum-subarray-min-product/sol.go b/tests/1501-2000/1856. maximum-subarray-min-product/sol.go new file mode 100644 index 00000000..0efef2ac --- /dev/null +++ b/tests/1501-2000/1856. maximum-subarray-min-product/sol.go @@ -0,0 +1,41 @@ +func maxSumMinProduct(nums []int) int { + n := len(nums) + prefix := make([]int64, n+1) + for i := 0; i < n; i++ { + prefix[i+1] = prefix[i] + int64(nums[i]) + } + + leftBound := make([]int, n) + rightBound := make([]int, n) + for i := 0; i < n; i++ { + leftBound[i] = -1 + rightBound[i] = n + } + stack := []int{} + for i := 0; i < n; i++ { + for len(stack) > 0 && nums[stack[len(stack)-1]] > nums[i] { + rightBound[stack[len(stack)-1]] = i + stack = stack[:len(stack)-1] + } + stack = append(stack, i) + } + stack = []int{} + for i := n-1; i >= 0; i-- { + for len(stack) > 0 && nums[stack[len(stack)-1]] > nums[i] { + leftBound[stack[len(stack)-1]] = i + stack = stack[:len(stack)-1] + } + stack = append(stack, i) + } + + var maxProd int64 = 0 + for i := 0; i < n; i++ { + l, r := leftBound[i], rightBound[i] + total := prefix[r] - prefix[l+1] + prod := int64(nums[i]) * total + if prod > maxProd { + maxProd = prod + } + } + return int(maxProd % 1000000007) +} diff --git a/tests/1501-2000/1856. maximum-subarray-min-product/sol.java b/tests/1501-2000/1856. maximum-subarray-min-product/sol.java new file mode 100644 index 00000000..06b982a9 --- /dev/null +++ b/tests/1501-2000/1856. maximum-subarray-min-product/sol.java @@ -0,0 +1,36 @@ +class Solution { + public int maxSumMinProduct(int[] nums) { + int n = nums.length; + long[] prefix = new long[n + 1]; + for (int i = 0; i < n; i++) { + prefix[i+1] = prefix[i] + nums[i]; + } + + int[] leftBound = new int[n]; + int[] rightBound = new int[n]; + Arrays.fill(leftBound, -1); + Arrays.fill(rightBound, n); + Deque stack = new ArrayDeque<>(); + for (int i = 0; i < n; i++) { + while (!stack.isEmpty() && nums[stack.peek()] > nums[i]) { + rightBound[stack.pop()] = i; + } + stack.push(i); + } + stack.clear(); + for (int i = n-1; i >= 0; i--) { + while (!stack.isEmpty() && nums[stack.peek()] > nums[i]) { + leftBound[stack.pop()] = i; + } + stack.push(i); + } + + long maxProd = 0; + for (int i = 0; i < n; i++) { + int l = leftBound[i], r = rightBound[i]; + long total = prefix[r] - prefix[l+1]; + maxProd = Math.max(maxProd, (long)nums[i] * total); + } + return (int)(maxProd % 1000000007L); + } +} diff --git a/tests/1501-2000/1856. maximum-subarray-min-product/sol.kt b/tests/1501-2000/1856. maximum-subarray-min-product/sol.kt new file mode 100644 index 00000000..743628c7 --- /dev/null +++ b/tests/1501-2000/1856. maximum-subarray-min-product/sol.kt @@ -0,0 +1,33 @@ +class Solution { + fun maxSumMinProduct(nums: IntArray): Int { + val n = nums.size + val prefix = LongArray(n + 1) + for (i in 0 until n) prefix[i+1] = prefix[i] + nums[i] + + val leftBound = IntArray(n) { -1 } + val rightBound = IntArray(n) { n } + val stack = ArrayDeque() + for (i in 0 until n) { + while (stack.isNotEmpty() && nums[stack.last()] > nums[i]) { + rightBound[stack.removeLast()] = i + } + stack.addLast(i) + } + stack.clear() + for (i in n-1 downTo 0) { + while (stack.isNotEmpty() && nums[stack.last()] > nums[i]) { + leftBound[stack.removeLast()] = i + } + stack.addLast(i) + } + + var maxProd = 0L + for (i in 0 until n) { + val l = leftBound[i] + val r = rightBound[i] + val total = prefix[r] - prefix[l+1] + maxProd = maxOf(maxProd, nums[i].toLong() * total) + } + return (maxProd % 1000000007L).toInt() + } +} diff --git a/tests/1501-2000/1856. maximum-subarray-min-product/sol.py b/tests/1501-2000/1856. maximum-subarray-min-product/sol.py new file mode 100644 index 00000000..6352ad8b --- /dev/null +++ b/tests/1501-2000/1856. maximum-subarray-min-product/sol.py @@ -0,0 +1,37 @@ +class Solution: + def maxSumMinProduct(self, nums: List[int]) -> int: + n = len(nums) + # 1. Transform the signal into Prefix Sums (Integral Domain) + # This allows O(1) energy calculation for any window + prefix_sums = [0] * (n + 1) + for i in range(n): + prefix_sums[i + 1] = prefix_sums[i] + nums[i] + + # 2. Monotonic Transform: Find the 'Spectral Window' for each element + # We find the nearest smaller element to the left and right + left_bound = [-1] * n + right_bound = [n] * n + stack = [] + + # Finding 'Right Boundaries' (where the minimum would drop) + for i in range(n): + while stack and nums[stack[-1]] > nums[i]: + right_bound[stack.pop()] = i + stack.append(i) + + stack = [] + # Finding 'Left Boundaries' + for i in range(n - 1, -1, -1): + while stack and nums[stack[-1]] > nums[i]: + left_bound[stack.pop()] = i + stack.append(i) + + # 3. Calculate Resonance: Multiply each 'Signal Peak' by its window area + max_prod = 0 + for i in range(n): + l, r = left_bound[i], right_bound[i] + # Window sum = Area from (l+1) to (r-1) + total_sum = prefix_sums[r] - prefix_sums[l + 1] + max_prod = max(max_prod, nums[i] * total_sum) + + return max_prod % (10**9 + 7) diff --git a/tests/1501-2000/1856. maximum-subarray-min-product/sol.py2 b/tests/1501-2000/1856. maximum-subarray-min-product/sol.py2 new file mode 100644 index 00000000..aa7a7491 --- /dev/null +++ b/tests/1501-2000/1856. maximum-subarray-min-product/sol.py2 @@ -0,0 +1,30 @@ +class Solution(object): + def maxSumMinProduct(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + n = len(nums) + prefix = [0] * (n + 1) + for i in range(n): + prefix[i+1] = prefix[i] + nums[i] + + left_bound = [-1] * n + right_bound = [n] * n + stack = [] + for i in range(n): + while stack and nums[stack[-1]] > nums[i]: + right_bound[stack.pop()] = i + stack.append(i) + stack = [] + for i in range(n-1, -1, -1): + while stack and nums[stack[-1]] > nums[i]: + left_bound[stack.pop()] = i + stack.append(i) + + max_prod = 0 + for i in range(n): + l, r = left_bound[i], right_bound[i] + total = prefix[r] - prefix[l+1] + max_prod = max(max_prod, nums[i] * total) + return max_prod % (10**9 + 7) diff --git a/tests/1501-2000/1856. maximum-subarray-min-product/sol.rb b/tests/1501-2000/1856. maximum-subarray-min-product/sol.rb new file mode 100644 index 00000000..80648195 --- /dev/null +++ b/tests/1501-2000/1856. maximum-subarray-min-product/sol.rb @@ -0,0 +1,30 @@ +def max_sum_min_product(nums) + n = nums.size + prefix = [0] * (n + 1) + (0...n).each { |i| prefix[i+1] = prefix[i] + nums[i] } + + left_bound = Array.new(n, -1) + right_bound = Array.new(n, n) + stack = [] + (0...n).each do |i| + while !stack.empty? && nums[stack.last] > nums[i] + right_bound[stack.pop] = i + end + stack << i + end + stack = [] + (n-1).downto(0) do |i| + while !stack.empty? && nums[stack.last] > nums[i] + left_bound[stack.pop] = i + end + stack << i + end + + max_prod = 0 + (0...n).each do |i| + l, r = left_bound[i], right_bound[i] + total = prefix[r] - prefix[l+1] + max_prod = [max_prod, nums[i] * total].max + end + max_prod % (10**9 + 7) +end diff --git a/tests/1501-2000/1856. maximum-subarray-min-product/sol.rs b/tests/1501-2000/1856. maximum-subarray-min-product/sol.rs new file mode 100644 index 00000000..6090fdea --- /dev/null +++ b/tests/1501-2000/1856. maximum-subarray-min-product/sol.rs @@ -0,0 +1,45 @@ +impl Solution { + pub fn max_sum_min_product(nums: Vec) -> i32 { + let n = nums.len(); + let mut prefix = vec![0i64; n + 1]; + for i in 0..n { + prefix[i+1] = prefix[i] + nums[i] as i64; + } + + let mut left_bound = vec![-1i32; n]; + let mut right_bound = vec![n as i32; n]; + let mut st: Vec = Vec::new(); + for i in 0..n { + while let Some(&top) = st.last() { + if nums[top] > nums[i] { + right_bound[top] = i as i32; + st.pop(); + } else { + break; + } + } + st.push(i); + } + st.clear(); + for i in (0..n).rev() { + while let Some(&top) = st.last() { + if nums[top] > nums[i] { + left_bound[top] = i as i32; + st.pop(); + } else { + break; + } + } + st.push(i); + } + + let mut max_prod: i64 = 0; + for i in 0..n { + let l = left_bound[i] as usize; + let r = right_bound[i] as usize; + let total_sum = prefix[r] - prefix[l+1]; + max_prod = max_prod.max(nums[i] as i64 * total_sum); + } + (max_prod % 1_000_000_007) as i32 + } +} diff --git a/tests/1501-2000/1856. maximum-subarray-min-product/sol.swift b/tests/1501-2000/1856. maximum-subarray-min-product/sol.swift new file mode 100644 index 00000000..cb0a1d9a --- /dev/null +++ b/tests/1501-2000/1856. maximum-subarray-min-product/sol.swift @@ -0,0 +1,34 @@ +class Solution { + func maxSumMinProduct(_ nums: [Int]) -> Int { + let n = nums.count + var prefix = [Int](repeating: 0, count: n + 1) + for i in 0.. nums[i] { + rightBound[stack.removeLast()] = i + } + stack.append(i) + } + stack.removeAll() + for i in stride(from: n-1, through: 0, by: -1) { + while !stack.isEmpty && nums[stack.last!] > nums[i] { + leftBound[stack.removeLast()] = i + } + stack.append(i) + } + + var maxProd = 0 + for i in 0.. nums[i]) { + rightBound[stack.pop()!] = i; + } + stack.push(i); + } + stack = []; + for (let i = n - 1; i >= 0; i--) { + while (stack.length && nums[stack[stack.length - 1]] > nums[i]) { + leftBound[stack.pop()!] = i; + } + stack.push(i); + } + + let maxProd = 0n; + for (let i = 0; i < n; i++) { + const l = leftBound[i], + r = rightBound[i]; + const total = prefix[r] - prefix[l + 1]; + const prod = BigInt(nums[i]) * BigInt(total); + if (prod > maxProd) maxProd = prod; + } + return Number(maxProd % 1000000007n); +} diff --git a/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/manifest.yaml b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/manifest.yaml new file mode 100644 index 00000000..8cf7fb42 --- /dev/null +++ b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/manifest.yaml @@ -0,0 +1,435 @@ +entry: + id: 1857 + title: "largest-color-value-in-a-directed-graph" + params: + colors: + type: string + edges: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().largestPathValue({colors}, {edges})" + rust: "Solution::largest_path_value({colors}, {edges})" + python3: "Solution().largestPathValue({colors}, {edges})" + python2: "Solution().largestPathValue({colors}, {edges})" + ruby: "largest_path_value({colors}, {edges})" + java: "new Solution().largestPathValue({colors}, {edges})" + csharp: "new Solution().LargestPathValue({colors}, {edges})" + kotlin: "Solution().largestPathValue({colors}, {edges})" + go: "largestPathValue({colors}, {edges})" + dart: "Solution().largestPathValue({colors}, {edges})" + swift: "Solution().largestPathValue({colors}, {edges})" + typescript: "largestPathValue({colors}, {edges})" + +judge: + type: exact + +limits: + time_ms: 5000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().largestPathValue(colors, edges, {result})" + checker: | + from collections import deque + + class Checker: + def largestPathValue(self, colors, edges, result): + n = len(colors) + graph = [[] for _ in range(n)] + indegree = [0] * n + for edge in edges: + u, v = edge + graph[u].append(v) + indegree[v] += 1 + queue = deque(i for i in range(n) if indegree[i] == 0) + counts = [[0] * 26 for _ in range(n)] + processed = 0 + best = 0 + while queue: + u = queue.popleft() + processed += 1 + color = ord(colors[u]) - 97 + counts[u][color] += 1 + best = max(best, max(counts[u])) + for v in graph[u]: + for c in range(26): + if counts[u][c] > counts[v][c]: + counts[v][c] = counts[u][c] + indegree[v] -= 1 + if indegree[v] == 0: + queue.append(v) + expected = -1 if processed != n else best + return result == expected + +seed: 1857 + +tests: + - name: example-one + in: + colors: "abaca" + edges: + - [0, 1] + - [0, 2] + - [2, 3] + - [3, 4] + out: 3 + - name: self-loop + in: + colors: "a" + edges: + - [0, 0] + out: -1 + - name: single-node + in: + colors: "z" + edges: [] + out: 1 + - name: empty-edges + in: + colors: "abcxyz" + edges: [] + out: 1 + - name: same-color-chain + in: + colors: "aaaaa" + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + out: 5 + - name: alternating-chain + in: + colors: "abababa" + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + out: 4 + - name: branching + in: + colors: "aabbc" + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [2, 4] + out: 2 + - name: merge-paths + in: + colors: "abcba" + edges: + - [0, 2] + - [1, 2] + - [2, 3] + - [2, 4] + out: 2 + - name: disconnected-cycle + in: + colors: "abcde" + edges: + - [0, 1] + - [2, 3] + - [3, 2] + out: -1 + - name: cycle-three + in: + colors: "abc" + edges: + - [0, 1] + - [1, 2] + - [2, 0] + out: -1 + - name: duplicate-edges + in: + colors: "aba" + edges: + - [0, 1] + - [0, 1] + - [1, 2] + out: 2 + - name: all-colors + in: + colors: "abcdefghijklmnopqrstuvwxyz" + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [11, 12] + - [12, 13] + - [13, 14] + - [14, 15] + - [15, 16] + - [16, 17] + - [17, 18] + - [18, 19] + - [19, 20] + - [20, 21] + - [21, 22] + - [22, 23] + - [23, 24] + - [24, 25] + out: 1 + - name: repeated-a-with-detour + in: + colors: "abacada" + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + out: 4 + - name: reverse-numbering + in: + colors: "aaaa" + edges: + - [3, 2] + - [2, 1] + - [1, 0] + out: 4 + - name: isolated-heavy-node + in: + colors: "zzzzabc" + edges: + - [0, 1] + - [1, 2] + - [2, 3] + out: 4 + - name: two-components + in: + colors: "aabbcc" + edges: + - [0, 1] + - [2, 3] + - [3, 4] + - [4, 5] + out: 2 + - name: diamond-heavy + in: + colors: "abacaba" + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [2, 3] + - [3, 4] + - [3, 5] + - [4, 6] + - [5, 6] + out: 4 + - name: late-cycle + in: + colors: "abcdefa" + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 3] + - [5, 6] + out: -1 + - name: long-single-color-branch + in: + colors: "aaaaaaaaab" + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + out: 9 + - name: wide-source + in: + colors: "abcdefghi" + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + - [0, 7] + - [0, 8] + out: 1 + - name: multiple-incoming + in: + colors: "aabaa" + edges: + - [0, 3] + - [1, 3] + - [2, 3] + - [3, 4] + out: 3 + - name: self-loop-with-tail + in: + colors: "abc" + edges: + - [0, 0] + - [0, 1] + - [1, 2] + out: -1 + - name: two-cycles + in: + colors: "abcd" + edges: + - [0, 1] + - [1, 0] + - [2, 3] + - [3, 2] + out: -1 + - name: all-zigzag + in: + colors: "zzxyzzx" + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + out: 4 + - name: maximum-letter + in: + colors: "zzzzz" + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + out: 5 + - name: no-path-between-nodes + in: + colors: "aabbccdd" + edges: + - [0, 1] + - [2, 3] + - [4, 5] + - [6, 7] + out: 2 + - name: nested-merge + in: + colors: "abcaa" + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [2, 3] + - [3, 4] + out: 3 + - name: cycle-self-last + in: + colors: "abcde" + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 4] + out: -1 + - name: sparse-large-shape + in: + colors: "abcabcabcabc" + edges: + - [0, 3] + - [1, 4] + - [2, 5] + - [3, 6] + - [4, 7] + - [5, 8] + - [6, 9] + - [7, 10] + - [8, 11] + out: 4 + - name: all-edges-dag + in: + colors: "aabbcc" + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [1, 2] + - [1, 3] + - [1, 4] + - [1, 5] + - [2, 3] + - [2, 4] + - [2, 5] + - [3, 4] + - [3, 5] + - [4, 5] + out: 2 + - name: generator-small + in: + colors: + gen: str + len: 100 + alphabet: "abc" + edges: [] + judge: + type: exact + seed: 185701 + - name: generator-medium + in: + colors: + gen: str + len: 1000 + alphabet: "abcde" + edges: [] + judge: + type: exact + seed: 185702 + - name: generator-large + in: + colors: + gen: str + len: 10000 + alphabet: "amz" + edges: [] + judge: + type: exact + seed: 185703 + - name: generator-max-letters + in: + colors: + gen: str + len: 50000 + alphabet: "abcdefghijklmnopqrstuvwxyz" + edges: [] + judge: + type: exact + seed: 185704 + - name: generator-maximum + in: + colors: + gen: str + len: 100000 + alphabet: "az" + edges: [] + judge: + type: exact + seed: 185705 diff --git a/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.cpp b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.cpp new file mode 100644 index 00000000..fd030977 --- /dev/null +++ b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.cpp @@ -0,0 +1,42 @@ +class Solution { +public: + int largestPathValue(string colors, vector>& edges) { + const int INF = INT_MAX; + int n = colors.size(); + vector> adj(n); + for (auto& e : edges) { + adj[e[0]].push_back(e[1]); + } + + vector> count(n, vector(26, 0)); + vector vis(n, 0); + + function dfs = [&](int node) -> int { + if (vis[node] == 1) return INF; + if (vis[node] == 2) return count[node][colors[node] - 'a']; + + vis[node] = 1; + for (int nxt : adj[node]) { + int res = dfs(nxt); + if (res == INF) return INF; + for (int c = 0; c < 26; c++) { + count[node][c] = max(count[node][c], count[nxt][c]); + } + } + + int col = colors[node] - 'a'; + count[node][col]++; + vis[node] = 2; + return count[node][col]; + }; + + int ans = 0; + for (int i = 0; i < n; i++) { + int val = dfs(i); + if (val == INF) return -1; + ans = max(ans, val); + } + + return ans; + } +}; diff --git a/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.cs b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.cs new file mode 100644 index 00000000..4a74442f --- /dev/null +++ b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.cs @@ -0,0 +1,47 @@ +public class Solution { + private int INF = int.MaxValue; + private List[] adj; + private int[][] count; + private int[] vis; + private string colors; + + public int LargestPathValue(string colors, int[][] edges) { + this.colors = colors; + int n = colors.Length; + adj = new List[n]; + for (int i = 0; i < n; i++) adj[i] = new List(); + foreach (var e in edges) { + adj[e[0]].Add(e[1]); + } + count = new int[n][]; + for (int i = 0; i < n; i++) count[i] = new int[26]; + vis = new int[n]; + + int ans = 0; + for (int i = 0; i < n; i++) { + int val = Dfs(i); + if (val == INF) return -1; + ans = Math.Max(ans, val); + } + return ans; + } + + private int Dfs(int node) { + if (vis[node] == 1) return INF; + if (vis[node] == 2) return count[node][colors[node] - 'a']; + + vis[node] = 1; + foreach (int nxt in adj[node]) { + int res = Dfs(nxt); + if (res == INF) return INF; + for (int c = 0; c < 26; c++) { + count[node][c] = Math.Max(count[node][c], count[nxt][c]); + } + } + + int col = colors[node] - 'a'; + count[node][col]++; + vis[node] = 2; + return count[node][col]; + } +} diff --git a/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.dart b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.dart new file mode 100644 index 00000000..6dad7872 --- /dev/null +++ b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.dart @@ -0,0 +1,34 @@ +class Solution { + int largestPathValue(String colors, List> edges) { + final n = colors.length; + final graph = List.generate(n, (_) => []); + for (final edge in edges) { + graph[edge[0]].add(edge[1]); + } + final counts = List.generate(n, (_) => List.filled(26, 0)); + final state = List.filled(n, 0); + + int dfs(int node) { + if (state[node] == 1) return -1; + if (state[node] == 2) return counts[node][colors.codeUnitAt(node) - 97]; + state[node] = 1; + for (final next in graph[node]) { + if (dfs(next) == -1) return -1; + for (var c = 0; c < 26; c++) { + if (counts[next][c] > counts[node][c]) counts[node][c] = counts[next][c]; + } + } + counts[node][colors.codeUnitAt(node) - 97]++; + state[node] = 2; + return counts[node][colors.codeUnitAt(node) - 97]; + } + + var answer = 0; + for (var i = 0; i < n; i++) { + final value = dfs(i); + if (value == -1) return -1; + if (value > answer) answer = value; + } + return answer; + } +} diff --git a/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.go b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.go new file mode 100644 index 00000000..0c2f3af5 --- /dev/null +++ b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.go @@ -0,0 +1,55 @@ +func largestPathValue(colors string, edges [][]int) int { + INF := int(^uint(0) >> 1) + n := len(colors) + adj := make([][]int, n) + for _, e := range edges { + adj[e[0]] = append(adj[e[0]], e[1]) + } + + count := make([][]int, n) + for i := range count { + count[i] = make([]int, 26) + } + vis := make([]int, n) + + var dfs func(int) int + dfs = func(node int) int { + if vis[node] == 1 { + return INF + } + if vis[node] == 2 { + return count[node][colors[node]-'a'] + } + + vis[node] = 1 + for _, nxt := range adj[node] { + res := dfs(nxt) + if res == INF { + return INF + } + for c := 0; c < 26; c++ { + if count[nxt][c] > count[node][c] { + count[node][c] = count[nxt][c] + } + } + } + + col := int(colors[node] - 'a') + count[node][col]++ + vis[node] = 2 + return count[node][col] + } + + ans := 0 + for i := 0; i < n; i++ { + val := dfs(i) + if val == INF { + return -1 + } + if val > ans { + ans = val + } + } + + return ans +} diff --git a/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.java b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.java new file mode 100644 index 00000000..28734aef --- /dev/null +++ b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.java @@ -0,0 +1,46 @@ +class Solution { + private int INF = Integer.MAX_VALUE; + private List> adj; + private int[][] count; + private int[] vis; + private String colors; + + public int largestPathValue(String colors, int[][] edges) { + this.colors = colors; + int n = colors.length(); + adj = new ArrayList<>(); + for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); + for (int[] e : edges) { + adj.get(e[0]).add(e[1]); + } + count = new int[n][26]; + vis = new int[n]; + + int ans = 0; + for (int i = 0; i < n; i++) { + int val = dfs(i); + if (val == INF) return -1; + ans = Math.max(ans, val); + } + return ans; + } + + private int dfs(int node) { + if (vis[node] == 1) return INF; + if (vis[node] == 2) return count[node][colors.charAt(node) - 'a']; + + vis[node] = 1; + for (int nxt : adj.get(node)) { + int res = dfs(nxt); + if (res == INF) return INF; + for (int c = 0; c < 26; c++) { + count[node][c] = Math.max(count[node][c], count[nxt][c]); + } + } + + int col = colors.charAt(node) - 'a'; + count[node][col]++; + vis[node] = 2; + return count[node][col]; + } +} diff --git a/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.kt b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.kt new file mode 100644 index 00000000..c6a4840a --- /dev/null +++ b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.kt @@ -0,0 +1,44 @@ +class Solution { + private lateinit var adj: Array> + private lateinit var count: Array + private lateinit var vis: IntArray + private lateinit var colors: String + + fun largestPathValue(colors: String, edges: Array): Int { + this.colors = colors + val n = colors.length + adj = Array(n) { mutableListOf() } + edges.forEach { e -> + adj[e[0]].add(e[1]) + } + count = Array(n) { IntArray(26) } + vis = IntArray(n) + + var ans = 0 + for (i in 0 until n) { + val value = dfs(i) + if (value == Int.MAX_VALUE) return -1 + ans = maxOf(ans, value) + } + return ans + } + + private fun dfs(node: Int): Int { + if (vis[node] == 1) return Int.MAX_VALUE + if (vis[node] == 2) return count[node][colors[node] - 'a'] + + vis[node] = 1 + for (nxt in adj[node]) { + val res = dfs(nxt) + if (res == Int.MAX_VALUE) return Int.MAX_VALUE + for (c in 0 until 26) { + count[node][c] = maxOf(count[node][c], count[nxt][c]) + } + } + + val col = colors[node] - 'a' + count[node][col]++ + vis[node] = 2 + return count[node][col] + } +} diff --git a/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.py b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.py new file mode 100644 index 00000000..4b48dc3b --- /dev/null +++ b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.py @@ -0,0 +1,39 @@ +class Solution(object): + def largestPathValue(self, colors, edges): + INF = float("inf") + n = len(colors) + adj = defaultdict(list) + for u, v in edges: + adj[u].append(v) + + count = [[0] * 26 for _ in range(n)] + vis = [0] * n + + def dfs(node): + if vis[node] == 1: + return INF + if vis[node] == 2: + return count[node][ord(colors[node]) - ord("a")] + + vis[node] = 1 + for nxt in adj[node]: + res = dfs(nxt) + if res == INF: + return INF + for c in range(26): + count[node][c] = max(count[node][c], count[nxt][c]) + + col = ord(colors[node]) - ord("a") + count[node][col] += 1 + vis[node] = 2 + + return count[node][col] + + ans = 0 + for i in range(n): + val = dfs(i) + if val == INF: + return -1 + ans = max(ans, val) + + return ans diff --git a/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.py2 b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.py2 new file mode 100644 index 00000000..d39ed403 --- /dev/null +++ b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.py2 @@ -0,0 +1,44 @@ +class Solution(object): + def largestPathValue(self, colors, edges): + """ + :type colors: str + :type edges: List[List[int]] + :rtype: int + """ + INF = float('inf') + n = len(colors) + adj = defaultdict(list) + for u, v in edges: + adj[u].append(v) + + count = [[0]*26 for _ in range(n)] + vis = [0]*n + + def dfs(node): + if vis[node] == 1: + return INF + if vis[node] == 2: + return count[node][ord(colors[node]) - ord('a')] + + vis[node] = 1 + for nxt in adj[node]: + res = dfs(nxt) + if res == INF: + return INF + for c in range(26): + count[node][c] = max(count[node][c], count[nxt][c]) + + col = ord(colors[node]) - ord('a') + count[node][col] += 1 + vis[node] = 2 + + return count[node][col] + + ans = 0 + for i in range(n): + val = dfs(i) + if val == INF: + return -1 + ans = max(ans, val) + + return ans diff --git a/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.rb b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.rb new file mode 100644 index 00000000..4072e461 --- /dev/null +++ b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.rb @@ -0,0 +1,50 @@ +# @param {String} colors +# @param {Integer[][]} edges +# @return {Integer} +def largest_path_value(colors, edges) + inf = Float::INFINITY + n = colors.length + adj = Hash.new { |h, k| h[k] = [] } + edges.each do |u, v| + adj[u] << v + end + + count = Array.new(n) { Array.new(26, 0) } + vis = Array.new(n, 0) + + dfs = lambda do |node| + if vis[node] == 1 + return inf + end + if vis[node] == 2 + return count[node][colors[node].ord - 'a'.ord] + end + + vis[node] = 1 + adj[node].each do |nxt| + res = dfs.call(nxt) + if res == inf + return inf + end + (0...26).each do |c| + count[node][c] = [count[node][c], count[nxt][c]].max + end + end + + col = colors[node].ord - 'a'.ord + count[node][col] += 1 + vis[node] = 2 + count[node][col] + end + + ans = 0 + (0...n).each do |i| + val = dfs.call(i) + if val == inf + return -1 + end + ans = [ans, val].max + end + + ans +end diff --git a/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.rs b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.rs new file mode 100644 index 00000000..81857def --- /dev/null +++ b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.rs @@ -0,0 +1,41 @@ +impl Solution { + pub fn largest_path_value(colors: String, edges: Vec>) -> i32 { + const INF: i32 = i32::MAX; + let n = colors.len(); + let mut adj = vec![vec![]; n]; + for e in edges { + adj[e[0] as usize].push(e[1] as usize); + } + + let mut count = vec![vec![0; 26]; n]; + let mut vis = vec![0; n]; + + fn dfs(node: usize, adj: &Vec>, count: &mut Vec>, vis: &mut Vec, colors: &[u8]) -> i32 { + if vis[node] == 1 { return INF; } + if vis[node] == 2 { return count[node][(colors[node] - b'a') as usize]; } + + vis[node] = 1; + for &nxt in &adj[node] { + let res = dfs(nxt, adj, count, vis, colors); + if res == INF { return INF; } + for c in 0..26 { + count[node][c] = count[node][c].max(count[nxt][c]); + } + } + + let col = (colors[node] - b'a') as usize; + count[node][col] += 1; + vis[node] = 2; + count[node][col] + } + + let mut ans = 0; + for i in 0..n { + let val = dfs(i, &adj, &mut count, &mut vis, colors.as_bytes()); + if val == INF { return -1; } + ans = ans.max(val); + } + + ans + } +} diff --git a/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.swift b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.swift new file mode 100644 index 00000000..ea070b73 --- /dev/null +++ b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.swift @@ -0,0 +1,48 @@ +class Solution { + private var adj: [[Int]] = [] + private var count: [[Int]] = [] + private var vis: [Int] = [] + private var colors: [Character] = [] + private let INF = Int.max + + func largestPathValue(_ colors: String, _ edges: [[Int]]) -> Int { + self.colors = Array(colors) + let n = self.colors.count + adj = Array(repeating: [], count: n) + for e in edges { + adj[e[0]].append(e[1]) + } + count = Array(repeating: Array(repeating: 0, count: 26), count: n) + vis = Array(repeating: 0, count: n) + + var ans = 0 + for i in 0.. Int { + if vis[node] == 1 { return INF } + if vis[node] == 2 { + let col = Int(colors[node].asciiValue! - Character("a").asciiValue!) + return count[node][col] + } + + vis[node] = 1 + for nxt in adj[node] { + let res = dfs(nxt) + if res == INF { return INF } + for c in 0..<26 { + count[node][c] = max(count[node][c], count[nxt][c]) + } + } + + let col = Int(colors[node].asciiValue! - Character("a").asciiValue!) + count[node][col] += 1 + vis[node] = 2 + return count[node][col] + } +} diff --git a/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.ts b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.ts new file mode 100644 index 00000000..c84ec215 --- /dev/null +++ b/tests/1501-2000/1857. largest-color-value-in-a-directed-graph/sol.ts @@ -0,0 +1,41 @@ +function largestPathValue(colors: string, edges: number[][]): number { + const INF = Number.MAX_SAFE_INTEGER; + const n = colors.length; + const adj: number[][] = Array.from({ length: n }, () => []); + for (const [u, v] of edges) { + adj[u].push(v); + } + + const count: number[][] = Array.from({ length: n }, () => + new Array(26).fill(0), + ); + const vis: number[] = new Array(n).fill(0); + + function dfs(node: number): number { + if (vis[node] === 1) return INF; + if (vis[node] === 2) return count[node][colors.charCodeAt(node) - 97]; + + vis[node] = 1; + for (const nxt of adj[node]) { + const res = dfs(nxt); + if (res === INF) return INF; + for (let c = 0; c < 26; c++) { + count[node][c] = Math.max(count[node][c], count[nxt][c]); + } + } + + const col = colors.charCodeAt(node) - 97; + count[node][col]++; + vis[node] = 2; + return count[node][col]; + } + + let ans = 0; + for (let i = 0; i < n; i++) { + const val = dfs(i); + if (val === INF) return -1; + ans = Math.max(ans, val); + } + + return ans; +} diff --git a/tests/1501-2000/1859. sorting-the-sentence/manifest.yaml b/tests/1501-2000/1859. sorting-the-sentence/manifest.yaml new file mode 100644 index 00000000..b057f1b2 --- /dev/null +++ b/tests/1501-2000/1859. sorting-the-sentence/manifest.yaml @@ -0,0 +1,182 @@ +entry: + id: 1859 + title: "sorting-the-sentence" + params: + s: + type: string + call: + cpp: "Solution().sortSentence({s})" + rust: "Solution::sort_sentence({s})" + python3: "Solution().sortSentence({s})" + python2: "Solution().sortSentence({s})" + ruby: "sort_sentence({s})" + java: "new Solution().sortSentence({s})" + csharp: "new Solution().SortSentence({s})" + kotlin: "Solution().sortSentence({s})" + go: "sortSentence({s})" + dart: "Solution().sortSentence({s})" + swift: "Solution().sortSentence({s})" + typescript: "sortSentence({s})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(s, {result})" + checker: | + class Checker: + def check(self, s, result): + words = {} + for token in s.split(): + words[int(token[-1])] = token[:-1] + expected = " ".join(words[i] for i in range(1, len(words) + 1)) + return result == expected + +seed: 1859 + +tests: + - name: example-one + in: + s: "is2 sentence4 This1 a3" + out: "This is a sentence" + - name: example-two + in: + s: "Myself2 Me1 I4 and3" + out: "Me Myself and I" + - name: one-word-lower + in: + s: "hello1" + out: "hello" + - name: one-word-upper + in: + s: "Z9" + out: "Z" + - name: two-words-forward + in: + s: "alpha1 beta2" + out: "alpha beta" + - name: two-words-reversed + in: + s: "beta2 alpha1" + out: "alpha beta" + - name: three-words + in: + s: "third3 first1 second2" + out: "first second third" + - name: all-nine-reversed + in: + s: "nine9 eight8 seven7 six6 five5 four4 three3 two2 one1" + out: "one two three four five six seven eight nine" + - name: all-nine-random + in: + s: "four4 one1 nine9 six6 two2 eight8 five5 three3 seven7" + out: "one two three four five six seven eight nine" + - name: mixed-case + in: + s: "lEet3 coD2 CodE1" + out: "CodE coD lEet" + - name: single-letter-words + in: + s: "c3 a1 b2" + out: "a b c" + - name: repeated-word-text + in: + s: "same3 same1 same2" + out: "same same same" + - name: punctuation-like-disallowed-no + in: + s: "abc2 A1" + out: "A abc" + - name: long-word-first + in: + s: "x2 aaaaaaaaaaaaaaaaaaaa1" + out: "aaaaaaaaaaaaaaaaaaaa x" + - name: positions-five + in: + s: "word5 word2 word4 word1 word3" + out: "word word word word word" + - name: positions-six + in: + s: "f6 a1 e5 c3 b2 d4" + out: "a b c d e f" + - name: positions-seven + in: + s: "g7 e5 c3 a1 f6 d4 b2" + out: "a b c d e f g" + - name: positions-eight + in: + s: "h8 d4 a1 g7 c3 f6 b2 e5" + out: "a b c d e f g h" + - name: case-pattern + in: + s: "UPPER2 lower1 MiXeD3" + out: "lower UPPER MiXeD" + - name: short-and-long + in: + s: "loooooong3 x1 yy2" + out: "x yy loooooong" + - name: shuffled-four + in: + s: "delta4 beta2 alpha1 gamma3" + out: "alpha beta gamma delta" + - name: shuffled-five + in: + s: "five5 one1 four4 two2 three3" + out: "one two three four five" + - name: repeated-lengths + in: + s: "aa2 b1 ccc3 dddd4" + out: "b aa ccc dddd" + - name: alternating-case + in: + s: "THREE3 one1 Two2" + out: "one Two THREE" + - name: nine-distinct + in: + s: "i9 g7 e5 c3 a1 h8 f6 d4 b2" + out: "a b c d e f g h i" + - name: numeric-looking-text + in: + s: "zero2 one1" + out: "one zero" + - name: six-shuffled + in: + s: "six6 three3 one1 five5 two2 four4" + out: "one two three four five six" + - name: seven-shuffled + in: + s: "four4 seven7 one1 six6 two2 five5 three3" + out: "one two three four five six seven" + - name: eight-shuffled + in: + s: "two2 eight8 six6 four4 seven7 one1 five5 three3" + out: "one two three four five six seven eight" + - name: caps-and-lower + in: + s: "C3 A1 B2" + out: "A B C" + - name: two-long-words + in: + s: "second2 first1" + out: "first second" + - name: nine-mixed-case + in: + s: "I9 g7 E5 c3 A1 H8 f6 D4 b2" + out: "A b c D E f g H I" + - name: order-already-sorted + in: + s: "alpha1 beta2 gamma3 delta4 epsilon5" + out: "alpha beta gamma delta epsilon" + - name: order-cyclic + in: + s: "second2 third3 fourth4 fifth5 first1" + out: "first second third fourth fifth" + - name: max-nine-words + in: + s: "nine9 eight8 seven7 six6 five5 four4 three3 two2 one1" + out: "one two three four five six seven eight nine" diff --git a/tests/1501-2000/1859. sorting-the-sentence/sol.cpp b/tests/1501-2000/1859. sorting-the-sentence/sol.cpp new file mode 100644 index 00000000..ee1aab5f --- /dev/null +++ b/tests/1501-2000/1859. sorting-the-sentence/sol.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + string sortSentence(string s) { + unordered_map words; + stringstream ss(s); + string word; + while (ss >> word) { + int key = word.back() - '0'; + words[key] = word.substr(0, word.length() - 1); + } + string result; + for (int i = 1; i <= 9; i++) { + auto it = words.find(i); + if (it == words.end()) continue; + if (!result.empty()) result += " "; + result += it->second; + } + return result; + } +}; diff --git a/tests/1501-2000/1859. sorting-the-sentence/sol.cs b/tests/1501-2000/1859. sorting-the-sentence/sol.cs new file mode 100644 index 00000000..743f1d1d --- /dev/null +++ b/tests/1501-2000/1859. sorting-the-sentence/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public string SortSentence(string s) { + var words = new Dictionary(); + foreach (var word in s.Split(' ')) { + int key = word[word.Length - 1] - '0'; + words[key] = word.Substring(0, word.Length - 1); + } + var result = ""; + for (int i = 1; i <= 9; i++) { + if (!words.ContainsKey(i)) continue; + if (result.Length > 0) result += " "; + result += words[i]; + } + return result; + } +} diff --git a/tests/1501-2000/1859. sorting-the-sentence/sol.dart b/tests/1501-2000/1859. sorting-the-sentence/sol.dart new file mode 100644 index 00000000..bb3b08be --- /dev/null +++ b/tests/1501-2000/1859. sorting-the-sentence/sol.dart @@ -0,0 +1,13 @@ +class Solution { + String sortSentence(String s) { + final words = {}; + for (final word in s.split(' ')) { + final key = int.parse(word[word.length - 1]); + words[key] = word.substring(0, word.length - 1); + } + return List.generate(9, (i) => i + 1) + .where(words.containsKey) + .map((i) => words[i]!) + .join(' '); + } +} diff --git a/tests/1501-2000/1859. sorting-the-sentence/sol.go b/tests/1501-2000/1859. sorting-the-sentence/sol.go new file mode 100644 index 00000000..55fdae25 --- /dev/null +++ b/tests/1501-2000/1859. sorting-the-sentence/sol.go @@ -0,0 +1,14 @@ +func sortSentence(s string) string { + words := make(map[int]string) + for _, word := range strings.Split(s, " ") { + key := int(word[len(word)-1] - '0') + words[key] = word[:len(word)-1] + } + result := make([]string, 0, len(words)) + for i := 1; i <= 9; i++ { + if word, ok := words[i]; ok { + result = append(result, word) + } + } + return strings.Join(result, " ") +} diff --git a/tests/1501-2000/1859. sorting-the-sentence/sol.java b/tests/1501-2000/1859. sorting-the-sentence/sol.java new file mode 100644 index 00000000..0c62ee2e --- /dev/null +++ b/tests/1501-2000/1859. sorting-the-sentence/sol.java @@ -0,0 +1,16 @@ +class Solution { + public String sortSentence(String s) { + Map words = new HashMap<>(); + for (String word : s.split(" ")) { + int key = word.charAt(word.length() - 1) - '0'; + words.put(key, word.substring(0, word.length() - 1)); + } + StringBuilder result = new StringBuilder(); + for (int i = 1; i <= 9; i++) { + if (!words.containsKey(i)) continue; + if (result.length() > 0) result.append(" "); + result.append(words.get(i)); + } + return result.toString(); + } +} diff --git a/tests/1501-2000/1859. sorting-the-sentence/sol.kt b/tests/1501-2000/1859. sorting-the-sentence/sol.kt new file mode 100644 index 00000000..3294aba9 --- /dev/null +++ b/tests/1501-2000/1859. sorting-the-sentence/sol.kt @@ -0,0 +1,9 @@ +class Solution { + fun sortSentence(s: String): String { + val words = mutableMapOf() + for (word in s.split(" ")) { + words[word.last().digitToInt()] = word.dropLast(1) + } + return (1..9).filter { words.containsKey(it) }.joinToString(" ") { words[it]!! } + } +} diff --git a/tests/1501-2000/1859. sorting-the-sentence/sol.py b/tests/1501-2000/1859. sorting-the-sentence/sol.py new file mode 100644 index 00000000..b5ad17bc --- /dev/null +++ b/tests/1501-2000/1859. sorting-the-sentence/sol.py @@ -0,0 +1,7 @@ +class Solution: + def sortSentence(self, s: str) -> str: + + words = {} + for word in s.split(): + words[int(word[-1])] = word[:-1] + return " ".join(words[i] for i in sorted(words)) diff --git a/tests/1501-2000/1859. sorting-the-sentence/sol.py2 b/tests/1501-2000/1859. sorting-the-sentence/sol.py2 new file mode 100644 index 00000000..94dfb698 --- /dev/null +++ b/tests/1501-2000/1859. sorting-the-sentence/sol.py2 @@ -0,0 +1,10 @@ +class Solution(object): + def sortSentence(self, s): + """ + :type s: str + :rtype: str + """ + words = {} + for word in s.split(): + words[int(word[-1])] = word[:-1] + return " ".join(words[i] for i in sorted(words)) diff --git a/tests/1501-2000/1859. sorting-the-sentence/sol.rb b/tests/1501-2000/1859. sorting-the-sentence/sol.rb new file mode 100644 index 00000000..b3f387ed --- /dev/null +++ b/tests/1501-2000/1859. sorting-the-sentence/sol.rb @@ -0,0 +1,9 @@ +# @param {String} s +# @return {String} +def sort_sentence(s) + words = {} + s.split.each do |word| + words[word[-1].to_i] = word[0...-1] + end + words.sort.map { |_, w| w }.join(" ") +end diff --git a/tests/1501-2000/1859. sorting-the-sentence/sol.rs b/tests/1501-2000/1859. sorting-the-sentence/sol.rs new file mode 100644 index 00000000..a1e66b0b --- /dev/null +++ b/tests/1501-2000/1859. sorting-the-sentence/sol.rs @@ -0,0 +1,12 @@ +impl Solution { + pub fn sort_sentence(s: String) -> String { + let mut words: std::collections::HashMap = std::collections::HashMap::new(); + for word in s.split_whitespace() { + let key: usize = word.chars().last().unwrap().to_digit(10).unwrap() as usize; + words.insert(key, word[..word.len()-1].to_string()); + } + let mut sorted_keys: Vec = words.keys().cloned().collect(); + sorted_keys.sort(); + sorted_keys.iter().map(|k| words[k].clone()).collect::>().join(" ") + } +} diff --git a/tests/1501-2000/1859. sorting-the-sentence/sol.swift b/tests/1501-2000/1859. sorting-the-sentence/sol.swift new file mode 100644 index 00000000..668a9545 --- /dev/null +++ b/tests/1501-2000/1859. sorting-the-sentence/sol.swift @@ -0,0 +1,11 @@ +class Solution { + func sortSentence(_ s: String) -> String { + var words: [Int: String] = [:] + for word in s.split(separator: " ") { + let key = Int(String(word.last!))! + words[key] = String(word.dropLast()) + } + let sortedKeys = words.keys.sorted() + return sortedKeys.map { words[$0]! }.joined(separator: " ") + } +} diff --git a/tests/1501-2000/1859. sorting-the-sentence/sol.ts b/tests/1501-2000/1859. sorting-the-sentence/sol.ts new file mode 100644 index 00000000..557111d4 --- /dev/null +++ b/tests/1501-2000/1859. sorting-the-sentence/sol.ts @@ -0,0 +1,11 @@ +function sortSentence(s: string): string { + const words: Record = {}; + for (const word of s.split(" ")) { + const key = parseInt(word[word.length - 1]); + words[key] = word.slice(0, -1); + } + return Object.keys(words) + .sort((a, b) => Number(a) - Number(b)) + .map((k) => words[Number(k)]) + .join(" "); +} diff --git a/tests/1501-2000/1860. incremental-memory-leak/manifest.yaml b/tests/1501-2000/1860. incremental-memory-leak/manifest.yaml new file mode 100644 index 00000000..fceb5052 --- /dev/null +++ b/tests/1501-2000/1860. incremental-memory-leak/manifest.yaml @@ -0,0 +1,264 @@ +entry: + id: 1860 + title: "incremental-memory-leak" + params: + memory1: + type: int + memory2: + type: int + call: + cpp: "Solution().memLeak({memory1}, {memory2})" + rust: "Solution::mem_leak({memory1}, {memory2})" + python3: "Solution().memLeak({memory1}, {memory2})" + python2: "Solution().memLeak({memory1}, {memory2})" + ruby: "mem_leak({memory1}, {memory2})" + java: "new Solution().memLeak({memory1}, {memory2})" + csharp: "new Solution().MemLeak({memory1}, {memory2})" + kotlin: "Solution().memLeak({memory1}, {memory2})" + go: "memLeak({memory1}, {memory2})" + dart: "Solution().memLeak({memory1}, {memory2})" + swift: "Solution().memLeak({memory1}, {memory2})" + typescript: "memLeak({memory1}, {memory2})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().memLeak(memory1, memory2, {result})" + checker: | + class Checker: + def memLeak(self, memory1, memory2, result): + if not isinstance(result, list) or len(result) != 3: + return False + time = 1 + a, b = memory1, memory2 + while True: + if a >= b: + if a < time: + break + a -= time + else: + if b < time: + break + b -= time + time += 1 + return result == [time, a, b] + +seed: 1860001 + +tests: + - name: "example_equal_small" + in: + memory1: 2 + memory2: 2 + out: [3, 1, 0] + - name: "example_unequal" + in: + memory1: 8 + memory2: 11 + out: [6, 0, 4] + - name: "both_zero" + in: + memory1: 0 + memory2: 0 + out: [1, 0, 0] + - name: "first_zero_second_one" + in: + memory1: 0 + memory2: 1 + out: [2, 0, 0] + - name: "first_one_second_zero" + in: + memory1: 1 + memory2: 0 + out: [2, 0, 0] + - name: "equal_one" + in: + memory1: 1 + memory2: 1 + out: [2, 0, 1] + - name: "equal_three" + in: + memory1: 3 + memory2: 3 + out: [3, 2, 1] + - name: "first_dominates" + in: + memory1: 10 + memory2: 1 + out: [5, 0, 1] + - name: "second_dominates" + in: + memory1: 1 + memory2: 10 + out: [5, 1, 0] + - name: "tie_break_first" + in: + memory1: 5 + memory2: 5 + out: [4, 1, 3] + - name: "near_first_switch" + in: + memory1: 4 + memory2: 5 + out: [4, 2, 1] + - name: "near_second_switch" + in: + memory1: 5 + memory2: 4 + out: [4, 2, 1] + - name: "balanced_six" + in: + memory1: 6 + memory2: 6 + out: [5, 2, 0] + - name: "balanced_ten" + in: + memory1: 10 + memory2: 10 + out: [6, 1, 4] + - name: "small_large_gap" + in: + memory1: 2 + memory2: 20 + out: [6, 2, 5] + - name: "large_small_gap" + in: + memory1: 20 + memory2: 2 + out: [6, 5, 2] + - name: "first_exact_triangular" + in: + memory1: 15 + memory2: 0 + out: [6, 0, 0] + - name: "second_exact_triangular" + in: + memory1: 0 + memory2: 15 + out: [6, 0, 0] + - name: "one_above_triangular" + in: + memory1: 16 + memory2: 0 + out: [6, 1, 0] + - name: "one_below_triangular" + in: + memory1: 14 + memory2: 0 + out: [5, 4, 0] + - name: "asymmetric_seven_eight" + in: + memory1: 7 + memory2: 8 + out: [5, 1, 4] + - name: "asymmetric_eight_seven" + in: + memory1: 8 + memory2: 7 + out: [5, 1, 4] + - name: "medium_pair" + in: + memory1: 42 + memory2: 37 + out: [12, 4, 9] + - name: "reverse_medium_pair" + in: + memory1: 37 + memory2: 42 + out: [12, 9, 4] + - name: "power_boundary" + in: + memory1: 100 + memory2: 100 + out: [20, 0, 10] + - name: "unequal_hundreds" + in: + memory1: 100 + memory2: 120 + out: [21, 9, 1] + - name: "large_equal" + in: + memory1: 1000000 + memory2: 1000000 + out: [2000, 0, 1000] + - name: "large_unequal" + in: + memory1: 1000000 + memory2: 2000000 + out: [2449, 1673, 751] + - name: "near_int_max_equal" + in: + memory1: 2147483647 + memory2: 2147483647 + out: [92681, 88047, 41707] + - name: "near_int_max_first" + in: + memory1: 2147483647 + memory2: 0 + out: [65536, 32767, 0] + - name: "near_int_max_second" + in: + memory1: 0 + memory2: 2147483647 + out: [65536, 0, 32767] + - name: "generated_small" + seed: 18601 + in: + memory1: + gen: "int" + min: 0 + max: 100 + memory2: + gen: "int" + min: 0 + max: 100 + - name: "generated_medium" + seed: 18602 + in: + memory1: + gen: "int" + min: 0 + max: 100000 + memory2: + gen: "int" + min: 0 + max: 100000 + - name: "generated_large_equal_scale" + seed: 18603 + in: + memory1: + gen: "int" + min: 1000000 + max: 100000000 + memory2: + gen: "int" + min: 1000000 + max: 100000000 + - name: "generated_full_range" + seed: 18604 + in: + memory1: + gen: "int" + min: 0 + max: 2147483647 + memory2: + gen: "int" + min: 0 + max: 2147483647 + - name: "generated_high_memory" + seed: 18605 + in: + memory1: + gen: "int" + min: 2000000000 + max: 2147483647 + memory2: + gen: "int" + min: 2000000000 + max: 2147483647 diff --git a/tests/1501-2000/1860. incremental-memory-leak/sol.cpp b/tests/1501-2000/1860. incremental-memory-leak/sol.cpp new file mode 100644 index 00000000..4db6f33b --- /dev/null +++ b/tests/1501-2000/1860. incremental-memory-leak/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + vector memLeak(int memory1, int memory2) { + int time = 1; + while (true) { + if (memory1 >= memory2) { + if (memory1 >= time) { + memory1 -= time; + } else { + break; + } + } else { + if (memory2 >= time) { + memory2 -= time; + } else { + break; + } + } + time++; + } + return {time, memory1, memory2}; + } +}; diff --git a/tests/1501-2000/1860. incremental-memory-leak/sol.cs b/tests/1501-2000/1860. incremental-memory-leak/sol.cs new file mode 100644 index 00000000..db30c4fc --- /dev/null +++ b/tests/1501-2000/1860. incremental-memory-leak/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public int[] MemLeak(int memory1, int memory2) { + int time = 1; + while (true) { + if (memory1 >= memory2) { + if (memory1 >= time) { + memory1 -= time; + } else { + break; + } + } else { + if (memory2 >= time) { + memory2 -= time; + } else { + break; + } + } + time++; + } + return new int[] { time, memory1, memory2 }; + } +} diff --git a/tests/1501-2000/1860. incremental-memory-leak/sol.dart b/tests/1501-2000/1860. incremental-memory-leak/sol.dart new file mode 100644 index 00000000..65bffcbb --- /dev/null +++ b/tests/1501-2000/1860. incremental-memory-leak/sol.dart @@ -0,0 +1,22 @@ +class Solution { + List memLeak(int memory1, int memory2) { + int time = 1; + while (true) { + if (memory1 >= memory2) { + if (memory1 >= time) { + memory1 -= time; + } else { + break; + } + } else { + if (memory2 >= time) { + memory2 -= time; + } else { + break; + } + } + time++; + } + return [time, memory1, memory2]; + } +} diff --git a/tests/1501-2000/1860. incremental-memory-leak/sol.go b/tests/1501-2000/1860. incremental-memory-leak/sol.go new file mode 100644 index 00000000..16192849 --- /dev/null +++ b/tests/1501-2000/1860. incremental-memory-leak/sol.go @@ -0,0 +1,20 @@ +func memLeak(memory1 int, memory2 int) []int { + time := 1 + for { + if memory1 >= memory2 { + if memory1 >= time { + memory1 -= time + } else { + break + } + } else { + if memory2 >= time { + memory2 -= time + } else { + break + } + } + time++ + } + return []int{time, memory1, memory2} +} diff --git a/tests/1501-2000/1860. incremental-memory-leak/sol.java b/tests/1501-2000/1860. incremental-memory-leak/sol.java new file mode 100644 index 00000000..b0efe9b5 --- /dev/null +++ b/tests/1501-2000/1860. incremental-memory-leak/sol.java @@ -0,0 +1,22 @@ +class Solution { + public int[] memLeak(int memory1, int memory2) { + int time = 1; + while (true) { + if (memory1 >= memory2) { + if (memory1 >= time) { + memory1 -= time; + } else { + break; + } + } else { + if (memory2 >= time) { + memory2 -= time; + } else { + break; + } + } + time++; + } + return new int[]{time, memory1, memory2}; + } +} diff --git a/tests/1501-2000/1860. incremental-memory-leak/sol.kt b/tests/1501-2000/1860. incremental-memory-leak/sol.kt new file mode 100644 index 00000000..bc7197b2 --- /dev/null +++ b/tests/1501-2000/1860. incremental-memory-leak/sol.kt @@ -0,0 +1,24 @@ +class Solution { + fun memLeak(memory1: Int, memory2: Int): IntArray { + var memory1 = memory1 + var memory2 = memory2 + var time = 1 + while (true) { + if (memory1 >= memory2) { + if (memory1 >= time) { + memory1 -= time + } else { + break + } + } else { + if (memory2 >= time) { + memory2 -= time + } else { + break + } + } + time++ + } + return intArrayOf(time, memory1, memory2) + } +} diff --git a/tests/1501-2000/1860. incremental-memory-leak/sol.py b/tests/1501-2000/1860. incremental-memory-leak/sol.py new file mode 100644 index 00000000..9394790b --- /dev/null +++ b/tests/1501-2000/1860. incremental-memory-leak/sol.py @@ -0,0 +1,21 @@ +class Solution(object): + def memLeak(self, memory1, memory2): + """ + :type memory1: int + :type memory2: int + :rtype: List[int] + """ + time = 1 + while True: + if memory1 >= memory2: + if memory1 >= time: + memory1 -= time + else: + break + else: + if memory2 >= time: + memory2 -= time + else: + break + time += 1 + return [time, memory1, memory2] diff --git a/tests/1501-2000/1860. incremental-memory-leak/sol.py2 b/tests/1501-2000/1860. incremental-memory-leak/sol.py2 new file mode 100644 index 00000000..9394790b --- /dev/null +++ b/tests/1501-2000/1860. incremental-memory-leak/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def memLeak(self, memory1, memory2): + """ + :type memory1: int + :type memory2: int + :rtype: List[int] + """ + time = 1 + while True: + if memory1 >= memory2: + if memory1 >= time: + memory1 -= time + else: + break + else: + if memory2 >= time: + memory2 -= time + else: + break + time += 1 + return [time, memory1, memory2] diff --git a/tests/1501-2000/1860. incremental-memory-leak/sol.rb b/tests/1501-2000/1860. incremental-memory-leak/sol.rb new file mode 100644 index 00000000..5105831f --- /dev/null +++ b/tests/1501-2000/1860. incremental-memory-leak/sol.rb @@ -0,0 +1,23 @@ +# @param {Integer} memory1 +# @param {Integer} memory2 +# @return {Integer[]} +def mem_leak(memory1, memory2) + time = 1 + loop do + if memory1 >= memory2 + if memory1 >= time + memory1 -= time + else + break + end + else + if memory2 >= time + memory2 -= time + else + break + end + end + time += 1 + end + [time, memory1, memory2] +end diff --git a/tests/1501-2000/1860. incremental-memory-leak/sol.rs b/tests/1501-2000/1860. incremental-memory-leak/sol.rs new file mode 100644 index 00000000..4988f800 --- /dev/null +++ b/tests/1501-2000/1860. incremental-memory-leak/sol.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn mem_leak(memory1: i32, memory2: i32) -> Vec { + let mut mem1 = memory1; + let mut mem2 = memory2; + let mut time = 1; + loop { + if mem1 >= mem2 { + if mem1 >= time { + mem1 -= time; + } else { + break; + } + } else { + if mem2 >= time { + mem2 -= time; + } else { + break; + } + } + time += 1; + } + vec![time, mem1, mem2] + } +} diff --git a/tests/1501-2000/1860. incremental-memory-leak/sol.swift b/tests/1501-2000/1860. incremental-memory-leak/sol.swift new file mode 100644 index 00000000..618aa8f6 --- /dev/null +++ b/tests/1501-2000/1860. incremental-memory-leak/sol.swift @@ -0,0 +1,24 @@ +class Solution { + func memLeak(_ memory1: Int, _ memory2: Int) -> [Int] { + var mem1 = memory1 + var mem2 = memory2 + var time = 1 + while true { + if mem1 >= mem2 { + if mem1 >= time { + mem1 -= time + } else { + break + } + } else { + if mem2 >= time { + mem2 -= time + } else { + break + } + } + time += 1 + } + return [time, mem1, mem2] + } +} diff --git a/tests/1501-2000/1860. incremental-memory-leak/sol.ts b/tests/1501-2000/1860. incremental-memory-leak/sol.ts new file mode 100644 index 00000000..ac751797 --- /dev/null +++ b/tests/1501-2000/1860. incremental-memory-leak/sol.ts @@ -0,0 +1,20 @@ +function memLeak(memory1: number, memory2: number): number[] { + let time = 1; + while (true) { + if (memory1 >= memory2) { + if (memory1 >= time) { + memory1 -= time; + } else { + break; + } + } else { + if (memory2 >= time) { + memory2 -= time; + } else { + break; + } + } + time++; + } + return [time, memory1, memory2]; +} diff --git a/tests/1501-2000/1861. rotating-the-box/manifest.yaml b/tests/1501-2000/1861. rotating-the-box/manifest.yaml new file mode 100644 index 00000000..ffeb58d9 --- /dev/null +++ b/tests/1501-2000/1861. rotating-the-box/manifest.yaml @@ -0,0 +1,268 @@ +entry: + id: 1861 + title: "rotating-the-box" + params: + boxGrid: + type: array + items: + type: array + items: + type: char + call: + cpp: "Solution().rotateTheBox({boxGrid})" + rust: "Solution::rotate_the_box({boxGrid})" + python3: "Solution().rotateTheBox({boxGrid})" + python2: "Solution().rotateTheBox({boxGrid})" + ruby: "rotate_the_box({boxGrid})" + java: "new Solution().rotateTheBox({boxGrid})" + csharp: "new Solution().RotateTheBox({boxGrid})" + kotlin: "Solution().rotateTheBox({boxGrid})" + go: "rotateTheBox({boxGrid})" + dart: "Solution().rotateTheBox({boxGrid})" + swift: "Solution().rotateTheBox({boxGrid})" + typescript: "rotateTheBox({boxGrid})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().rotateTheBox(boxGrid, {result})" + checker: | + class Checker: + def rotateTheBox(self, boxGrid, result): + if not isinstance(boxGrid, list) or not boxGrid or not isinstance(result, list): + return False + m = len(boxGrid) + n = len(boxGrid[0]) + if n == 0 or len(result) != n or any(not isinstance(row, list) or len(row) != m for row in result): + return False + expected = [['.' for _ in range(m)] for _ in range(n)] + for i, row in enumerate(boxGrid): + if not isinstance(row, list) or len(row) != n: + return False + bottom = n - 1 + for j in range(n - 1, -1, -1): + if row[j] == '#': + expected[bottom][m - 1 - i] = '#' + bottom -= 1 + elif row[j] == '*': + expected[j][m - 1 - i] = '*' + bottom = j - 1 + elif row[j] != '.': + return False + return result == expected + +seed: 1861 + +tests: + - name: single-stone + in: + boxGrid: + - ["#"] + - name: single-empty + in: + boxGrid: + - ["."] + - name: single-obstacle + in: + boxGrid: + - ["*"] + - name: horizontal-stone-empty + in: + boxGrid: + - ["#", "."] + - name: horizontal-empty-stone + in: + boxGrid: + - [".", "#"] + - name: obstacle-stone + in: + boxGrid: + - ["*", "#"] + - name: stone-obstacle + in: + boxGrid: + - ["#", "*"] + - name: alternating-row + in: + boxGrid: + - ["#", ".", "#", ".", "#"] + - name: all-empty-row + in: + boxGrid: + - [".", ".", ".", ".", "."] + - name: all-stones-row + in: + boxGrid: + - ["#", "#", "#", "#", "#"] + - name: separated-obstacles + in: + boxGrid: + - ["*", ".", "*", ".", "*"] + - name: stone-obstacle-gap + in: + boxGrid: + - ["#", ".", "*", ".", "#", "."] + - name: two-identical-rows + in: + boxGrid: + - ["#", "#", "*", "."] + - ["#", "#", "*", "."] + - name: mixed-two-rows + in: + boxGrid: + - ["#", ".", "*", "."] + - [".", "#", ".", "#"] + - name: opposing-stones + in: + boxGrid: + - ["#", "#", ".", "."] + - [".", ".", "#", "#"] + - name: wide-obstacle-row + in: + boxGrid: + - ["*", "#", ".", "#", "*"] + - name: two-rows-separated + in: + boxGrid: + - ["#", ".", ".", "#"] + - ["*", "#", ".", "."] + - name: obstacle-middle-wide + in: + boxGrid: + - ["#", ".", "*", ".", "#", "."] + - name: three-by-three-cross + in: + boxGrid: + - ["#", ".", "#"] + - [".", "*", "."] + - ["#", ".", "#"] + - name: official-example-three + in: + boxGrid: + - ["#", "#", "*", ".", "*", "."] + - ["#", "#", "#", "*", ".", "."] + - ["#", "#", "#", ".", "#", "."] + - name: checkerboard-four + in: + boxGrid: + - [".", "#", ".", "#"] + - ["#", ".", "#", "."] + - [".", "#", ".", "#"] + - ["#", ".", "#", "."] + - name: two-wide-mixed + in: + boxGrid: + - ["#", ".", "*", ".", "#"] + - [".", "#", ".", "#", "."] + - name: four-by-four-corners + in: + boxGrid: + - ["#", ".", ".", "#"] + - [".", "*", "*", "."] + - [".", "*", "*", "."] + - ["#", ".", ".", "#"] + - name: dense-three-by-four + in: + boxGrid: + - ["#", "#", "#", "."] + - ["#", "*", "#", "#"] + - [".", "#", ".", "*"] + - name: sparse-five-by-three + in: + boxGrid: + - ["#", ".", "."] + - [".", "*", "."] + - [".", ".", "#"] + - ["*", ".", "."] + - ["#", ".", "#"] + - name: full-obstacle-column + in: + boxGrid: + - ["*", "*", "*"] + - ["#", ".", "#"] + - [".", "#", "."] + - name: six-by-two-pattern + in: + boxGrid: + - ["#", "."] + - [".", "#"] + - ["*", "."] + - ["#", "#"] + - [".", "*"] + - ["#", "."] + - name: tall-empty + in: + boxGrid: + - [".", "."] + - [".", "."] + - [".", "."] + - [".", "."] + - [".", "."] + - name: tall-dense + in: + boxGrid: + - ["#", "#"] + - ["#", "*"] + - ["*", "#"] + - ["#", "."] + - [".", "#"] + - name: five-by-five-border + in: + boxGrid: + - ["#", "#", "#", "#", "#"] + - ["#", ".", ".", ".", "#"] + - ["#", ".", "*", ".", "#"] + - ["#", ".", ".", ".", "#"] + - ["#", "#", "#", "#", "#"] + - name: five-by-six-mixed + in: + boxGrid: + - ["#", ".", "#", ".", "*", "."] + - [".", "#", ".", "#", ".", "#"] + - ["*", ".", "*", ".", "#", "."] + - ["#", "#", ".", ".", "#", "#"] + - [".", ".", "#", "*", ".", "."] + - name: rectangular-three-by-seven + in: + boxGrid: + - ["#", ".", "#", "*", ".", "#", "."] + - [".", "#", ".", ".", "*", ".", "#"] + - ["#", "#", ".", "#", ".", ".", "*"] + - name: rectangular-seven-by-three + in: + boxGrid: + - ["#", ".", "#"] + - [".", "*", "."] + - ["#", "#", "."] + - [".", ".", "#"] + - ["*", "#", "*"] + - ["#", ".", "."] + - [".", "#", "#"] + - name: long-single-row + in: + boxGrid: + - ["#", ".", "#", ".", "*", ".", "#", "#", ".", "*"] + - name: long-two-row + in: + boxGrid: + - ["#", ".", "*", ".", "#", ".", "#", ".", "*", "."] + - [".", "#", ".", "#", ".", "#", ".", "#", ".", "#"] + - name: all-obstacles + in: + boxGrid: + - ["*", "*", "*", "*"] + - ["*", "*", "*", "*"] + - ["*", "*", "*", "*"] + - name: maximum-small-pattern + in: + boxGrid: + - ["#", ".", "*", "#", ".", "*", "#", "."] + - [".", "#", ".", "*", "#", ".", "*", "#"] + - ["#", "#", ".", ".", "#", "#", ".", "."] + - ["*", ".", "#", ".", "*", ".", "#", "."] diff --git a/tests/1501-2000/1861. rotating-the-box/sol.cpp b/tests/1501-2000/1861. rotating-the-box/sol.cpp new file mode 100644 index 00000000..63a6f24d --- /dev/null +++ b/tests/1501-2000/1861. rotating-the-box/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + vector> rotateTheBox(vector>& boxGrid) { + auto& box = boxGrid; + int r = box.size(), c = box[0].size(); + vector> rotate(c, vector(r, '.')); + for (int i = 0; i < r; ++i) { + int bottom = c - 1; + for (int j = c - 1; j >= 0; --j) { + if (box[i][j] == '#') { + rotate[bottom][r - 1 - i] = '#'; + bottom--; + } else if (box[i][j] == '*') { + rotate[j][r - 1 - i] = '*'; + bottom = j - 1; + } + } + } + return rotate; + } +}; diff --git a/tests/1501-2000/1861. rotating-the-box/sol.cs b/tests/1501-2000/1861. rotating-the-box/sol.cs new file mode 100644 index 00000000..e29626cf --- /dev/null +++ b/tests/1501-2000/1861. rotating-the-box/sol.cs @@ -0,0 +1,23 @@ +public class Solution { + public char[][] RotateTheBox(char[][] boxGrid) { + int r = boxGrid.Length, c = boxGrid[0].Length; + char[][] rotate = new char[c][]; + for (int i = 0; i < c; i++) { + rotate[i] = new char[r]; + for (int j = 0; j < r; j++) rotate[i][j] = '.'; + } + for (int i = 0; i < r; i++) { + int bottom = c - 1; + for (int j = c - 1; j >= 0; j--) { + if (boxGrid[i][j] == '#') { + rotate[bottom][r - 1 - i] = '#'; + bottom--; + } else if (boxGrid[i][j] == '*') { + rotate[j][r - 1 - i] = '*'; + bottom = j - 1; + } + } + } + return rotate; + } +} diff --git a/tests/1501-2000/1861. rotating-the-box/sol.dart b/tests/1501-2000/1861. rotating-the-box/sol.dart new file mode 100644 index 00000000..00d0ecb2 --- /dev/null +++ b/tests/1501-2000/1861. rotating-the-box/sol.dart @@ -0,0 +1,19 @@ +class Solution { + List> rotateTheBox(List> boxGrid) { + int r = boxGrid.length, c = boxGrid[0].length; + List> rotate = List.generate(c, (_) => List.filled(r, '.')); + for (int i = 0; i < r; i++) { + int bottom = c - 1; + for (int j = c - 1; j >= 0; j--) { + if (boxGrid[i][j] == '#') { + rotate[bottom][r - 1 - i] = '#'; + bottom--; + } else if (boxGrid[i][j] == '*') { + rotate[j][r - 1 - i] = '*'; + bottom = j - 1; + } + } + } + return rotate; + } +} diff --git a/tests/1501-2000/1861. rotating-the-box/sol.go b/tests/1501-2000/1861. rotating-the-box/sol.go new file mode 100644 index 00000000..0fa1cd21 --- /dev/null +++ b/tests/1501-2000/1861. rotating-the-box/sol.go @@ -0,0 +1,24 @@ +func rotateTheBox(boxGrid [][]byte) [][]byte { + r := len(boxGrid) + c := len(boxGrid[0]) + rotate := make([][]byte, c) + for i := range rotate { + rotate[i] = make([]byte, r) + for j := range rotate[i] { + rotate[i][j] = '.' + } + } + for i := 0; i < r; i++ { + bottom := c - 1 + for j := c - 1; j >= 0; j-- { + if boxGrid[i][j] == '#' { + rotate[bottom][r-1-i] = '#' + bottom-- + } else if boxGrid[i][j] == '*' { + rotate[j][r-1-i] = '*' + bottom = j - 1 + } + } + } + return rotate +} diff --git a/tests/1501-2000/1861. rotating-the-box/sol.java b/tests/1501-2000/1861. rotating-the-box/sol.java new file mode 100644 index 00000000..2e52df43 --- /dev/null +++ b/tests/1501-2000/1861. rotating-the-box/sol.java @@ -0,0 +1,20 @@ +class Solution { + public char[][] rotateTheBox(char[][] boxGrid) { + int r = boxGrid.length, c = boxGrid[0].length; + char[][] rotate = new char[c][r]; + for (char[] row : rotate) Arrays.fill(row, '.'); + for (int i = 0; i < r; i++) { + int bottom = c - 1; + for (int j = c - 1; j >= 0; j--) { + if (boxGrid[i][j] == '#') { + rotate[bottom][r - 1 - i] = '#'; + bottom--; + } else if (boxGrid[i][j] == '*') { + rotate[j][r - 1 - i] = '*'; + bottom = j - 1; + } + } + } + return rotate; + } +} diff --git a/tests/1501-2000/1861. rotating-the-box/sol.kt b/tests/1501-2000/1861. rotating-the-box/sol.kt new file mode 100644 index 00000000..e3e3a927 --- /dev/null +++ b/tests/1501-2000/1861. rotating-the-box/sol.kt @@ -0,0 +1,23 @@ +class Solution { + fun rotateTheBox(boxGrid: Array): Array { + val r = boxGrid.size + val c = boxGrid[0].size + val rotate = Array(c) { CharArray(r) { '.' } } + for (i in 0 until r) { + var bottom = c - 1 + for (j in c - 1 downTo 0) { + when (boxGrid[i][j]) { + '#' -> { + rotate[bottom][r - 1 - i] = '#' + bottom-- + } + '*' -> { + rotate[j][r - 1 - i] = '*' + bottom = j - 1 + } + } + } + } + return rotate + } +} diff --git a/tests/1501-2000/1861. rotating-the-box/sol.py b/tests/1501-2000/1861. rotating-the-box/sol.py new file mode 100644 index 00000000..dcdaef69 --- /dev/null +++ b/tests/1501-2000/1861. rotating-the-box/sol.py @@ -0,0 +1,15 @@ +class Solution: + def rotateTheBox(self, boxGrid: List[List[str]]) -> List[List[str]]: + box = boxGrid + r, c = len(box), len(box[0]) + rotate = [["."] * r for _ in range(c)] + for i, row in enumerate(box): + bottom = c - 1 + for j in range(c - 1, -1, -1): + if row[j] == "#": + rotate[bottom][r - 1 - i] = "#" + bottom -= 1 + elif row[j] == "*": + rotate[j][r - 1 - i] = "*" + bottom = j - 1 + return rotate diff --git a/tests/1501-2000/1861. rotating-the-box/sol.py2 b/tests/1501-2000/1861. rotating-the-box/sol.py2 new file mode 100644 index 00000000..2f79975e --- /dev/null +++ b/tests/1501-2000/1861. rotating-the-box/sol.py2 @@ -0,0 +1,19 @@ +class Solution(object): + def rotateTheBox(self, boxGrid): + """ + :type boxGrid: List[List[str]] + :rtype: List[List[str]] + """ + box = boxGrid + r, c = len(box), len(box[0]) + rotate = [['.'] * r for _ in range(c)] + for i in range(r): + bottom = c - 1 + for j in range(c - 1, -1, -1): + if box[i][j] == '#': + rotate[bottom][r - 1 - i] = '#' + bottom -= 1 + elif box[i][j] == '*': + rotate[j][r - 1 - i] = '*' + bottom = j - 1 + return rotate diff --git a/tests/1501-2000/1861. rotating-the-box/sol.rb b/tests/1501-2000/1861. rotating-the-box/sol.rb new file mode 100644 index 00000000..89691392 --- /dev/null +++ b/tests/1501-2000/1861. rotating-the-box/sol.rb @@ -0,0 +1,18 @@ +def rotate_the_box(box_grid) + r = box_grid.length + c = box_grid[0].length + rotate = Array.new(c) { Array.new(r, '.') } + (0...r).each do |i| + bottom = c - 1 + (c - 1).downto(0) do |j| + if box_grid[i][j] == '#' + rotate[bottom][r - 1 - i] = '#' + bottom -= 1 + elsif box_grid[i][j] == '*' + rotate[j][r - 1 - i] = '*' + bottom = j - 1 + end + end + end + rotate +end diff --git a/tests/1501-2000/1861. rotating-the-box/sol.rs b/tests/1501-2000/1861. rotating-the-box/sol.rs new file mode 100644 index 00000000..7b35a95b --- /dev/null +++ b/tests/1501-2000/1861. rotating-the-box/sol.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn rotate_the_box(box_grid: Vec>) -> Vec> { + let grid = box_grid; + let r = grid.len(); + let c = grid[0].len(); + let mut rotate = vec![vec!['.'; r]; c]; + for i in 0..r { + let mut bottom = c - 1; + for j in (0..c).rev() { + if grid[i][j] == '#' { + rotate[bottom][r - 1 - i] = '#'; + bottom -= 1; + } else if grid[i][j] == '*' { + rotate[j][r - 1 - i] = '*'; + bottom = j - 1; + } + } + } + rotate + } +} diff --git a/tests/1501-2000/1861. rotating-the-box/sol.swift b/tests/1501-2000/1861. rotating-the-box/sol.swift new file mode 100644 index 00000000..1b2439c3 --- /dev/null +++ b/tests/1501-2000/1861. rotating-the-box/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func rotateTheBox(_ boxGrid: [[Character]]) -> [[Character]] { + let r = boxGrid.count + let c = boxGrid[0].count + var rotate = Array(repeating: Array(repeating: Character("."), count: r), count: c) + for i in 0.. + Array(r).fill("."), + ); + for (let i = 0; i < r; i++) { + let bottom = c - 1; + for (let j = c - 1; j >= 0; j--) { + if (boxGrid[i][j] === "#") { + rotate[bottom][r - 1 - i] = "#"; + bottom--; + } else if (boxGrid[i][j] === "*") { + rotate[j][r - 1 - i] = "*"; + bottom = j - 1; + } + } + } + return rotate; +} diff --git a/tests/1501-2000/1862. sum-of-floored-pairs/manifest.yaml b/tests/1501-2000/1862. sum-of-floored-pairs/manifest.yaml new file mode 100644 index 00000000..394fa66c --- /dev/null +++ b/tests/1501-2000/1862. sum-of-floored-pairs/manifest.yaml @@ -0,0 +1,238 @@ +entry: + id: 1862 + title: "sum-of-floored-pairs" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().sumOfFlooredPairs({nums})" + rust: "Solution::sum_of_floored_pairs({nums})" + python3: "Solution().sumOfFlooredPairs({nums})" + python2: "Solution().sumOfFlooredPairs({nums})" + ruby: "sum_of_floored_pairs({nums})" + java: "new Solution().sumOfFlooredPairs({nums})" + csharp: "new Solution().SumOfFlooredPairs({nums})" + kotlin: "Solution().sumOfFlooredPairs({nums})" + go: "sumOfFlooredPairs({nums})" + dart: "Solution().sumOfFlooredPairs({nums})" + swift: "Solution().sumOfFlooredPairs({nums})" + typescript: "sumOfFlooredPairs({nums})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().check(nums, {result})" + checker: | + class Checker: + def check(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not isinstance(nums, list) or not nums or any(type(x) is not int or x < 1 or x > 100000 for x in nums): + return False + mod = 1000000007 + freq = [0] * (100001) + for x in nums: + freq[x] += 1 + total = 0 + prefix = [0] * 100001 + for i in range(1, 100001): + prefix[i] = prefix[i - 1] + freq[i] + m = max(nums) + for d in range(1, m + 1): + if not freq[d]: + continue + q = 1 + while q * d <= m: + hi = min((q + 1) * d - 1, m) + total = (total + freq[d] * q * (prefix[hi] - prefix[q * d - 1])) % mod + q += 1 + return result == total + +seed: 1862 + +tests: + - name: "example_one" + in: + nums: [2, 5, 9] + out: 10 + - name: "example_two_duplicates" + in: + nums: [7, 7, 7, 7, 7, 7, 7] + out: 49 + - name: "single_one" + in: + nums: [1] + out: 1 + - name: "single_max" + in: + nums: [100000] + out: 1 + - name: "two_equal" + in: + nums: [3, 3] + out: 4 + - name: "two_ordered" + in: + nums: [1, 2] + out: 4 + - name: "two_reverse" + in: + nums: [2, 1] + out: 4 + - name: "powers_two" + in: + nums: [1, 2, 4, 8, 16] + out: 57 + - name: "consecutive_one_to_five" + in: + nums: [1, 2, 3, 4, 5] + out: 27 + - name: "consecutive_six_to_ten" + in: + nums: [6, 7, 8, 9, 10] + out: 15 + - name: "mixed_small" + in: + nums: [1, 3, 6, 10] + out: 29 + - name: "many_ones" + in: + nums: [1, 1, 1, 1, 1, 8] + out: 66 + - name: "many_max_values" + in: + nums: [100000, 100000, 99999] + out: 7 + - name: "large_ratio" + in: + nums: [1, 100] + out: 102 + - name: "divisor_chain" + in: + nums: [2, 4, 8, 16, 32] + out: 57 + - name: "prime_values" + in: + nums: [2, 3, 5, 7, 11] + out: 26 + - name: "repeated_mixed" + in: + nums: [2, 2, 5, 5, 10, 10] + out: 48 + - name: "alternating_extremes" + in: + nums: [1, 100000, 1, 100000] + out: 400008 + - name: "nearby_values" + in: + nums: [99997, 99998, 99999, 100000] + out: 10 + - name: "small_dense" + in: + nums: [1, 2, 2, 3, 3, 4, 4] + out: 47 + - name: "multiples_of_three" + in: + nums: [3, 6, 9, 12, 15] + out: 27 + - name: "one_and_powers" + in: + nums: [1, 1, 2, 4, 8] + out: 43 + - name: "large_gap" + in: + nums: [17, 1000, 100000] + out: 6043 + - name: "duplicate_prime" + in: + nums: [9973, 9973, 19946] + out: 9 + - name: "all_values_five" + in: + nums: [5, 5, 5, 5, 5] + out: 25 + - name: "small_descending" + in: + nums: [9, 8, 7, 6, 5, 4, 3, 2, 1] + out: 100 + - name: "odd_values" + in: + nums: [1, 3, 5, 7, 9, 11, 13] + out: 80 + - name: "two_clusters" + in: + nums: [2, 2, 3, 3, 100, 100] + out: 348 + - name: "boundary_99999" + in: + nums: [1, 99999, 99999, 100000] + out: 300006 + - name: "balanced_repetitions" + in: + nums: [4, 4, 8, 8, 12, 12, 16, 16] + out: 68 + - name: "stress_random_small" + seed: 186201 + in: + nums: + gen: "array" + len: + gen: "int" + min: 50 + max: 200 + of: + gen: "int" + min: 1 + max: 1000 + + - name: "stress_random_medium" + seed: 186202 + in: + nums: + gen: "array" + len: + gen: "int" + min: 1000 + max: 3000 + of: + gen: "int" + min: 1 + max: 100000 + - name: "stress_dense_values" + seed: 186203 + in: + nums: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 100 + - name: "stress_large_values" + seed: 186204 + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 90000 + max: 100000 + - name: "stress_maximum" + seed: 186205 + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 diff --git a/tests/1501-2000/1862. sum-of-floored-pairs/sol.cpp b/tests/1501-2000/1862. sum-of-floored-pairs/sol.cpp new file mode 100644 index 00000000..d7648ff5 --- /dev/null +++ b/tests/1501-2000/1862. sum-of-floored-pairs/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int sumOfFlooredPairs(vector& nums) { + const int MOD = 1'000'000'007; + int maxi = 100'001; + int maxVal = 0; + for (int num : nums) maxVal = max(maxVal, num); + int size = 2 * maxi + 1; + vector freq(size, 0); + for (int num : nums) freq[num]++; + for (int i = 1; i < size; i++) freq[i] += freq[i-1]; + + long long total = 0; + for (int num = 1; num <= maxVal; num++) { + int countNum = freq[num] - freq[num-1]; + if (countNum == 0) continue; + int floorValue = 1; + while ((long long)floorValue * num <= maxVal) { + int left = floorValue * num; + int right = min((floorValue + 1) * num - 1, maxVal); + int countInRange = freq[right] - freq[left - 1]; + total = (total + (long long)countNum * floorValue * countInRange) % MOD; + floorValue++; + } + } + return (int)total; + } +}; diff --git a/tests/1501-2000/1862. sum-of-floored-pairs/sol.cs b/tests/1501-2000/1862. sum-of-floored-pairs/sol.cs new file mode 100644 index 00000000..a9acfdfe --- /dev/null +++ b/tests/1501-2000/1862. sum-of-floored-pairs/sol.cs @@ -0,0 +1,26 @@ +public class Solution { + public int SumOfFlooredPairs(int[] nums) { + const int MOD = 1_000_000_007; + int maxi = 100_001; + int maxVal = nums.Max(); + int size = 2 * maxi + 1; + int[] freq = new int[size]; + foreach (int num in nums) freq[num]++; + for (int i = 1; i < size; i++) freq[i] += freq[i-1]; + + long total = 0; + for (int num = 1; num <= maxVal; num++) { + int countNum = freq[num] - freq[num-1]; + if (countNum == 0) continue; + int floorValue = 1; + while ((long)floorValue * num <= maxVal) { + int left = floorValue * num; + int right = Math.Min((floorValue + 1) * num - 1, maxVal); + int countInRange = freq[right] - freq[left - 1]; + total = (total + (long)countNum * floorValue * countInRange) % MOD; + floorValue++; + } + } + return (int)total; + } +} diff --git a/tests/1501-2000/1862. sum-of-floored-pairs/sol.dart b/tests/1501-2000/1862. sum-of-floored-pairs/sol.dart new file mode 100644 index 00000000..726c6f80 --- /dev/null +++ b/tests/1501-2000/1862. sum-of-floored-pairs/sol.dart @@ -0,0 +1,31 @@ +class Solution { + int sumOfFlooredPairs(List nums) { + const int MOD = 1000000007; + int maxi = 100001; + int maxVal = nums.reduce((a, b) => a > b ? a : b); + int size = 2 * maxi + 1; + List freq = List.filled(size, 0); + for (int num in nums) { + freq[num]++; + } + for (int i = 1; i < size; i++) { + freq[i] += freq[i - 1]; + } + + int total = 0; + for (int num = 1; num <= maxVal; num++) { + int countNum = freq[num] - freq[num - 1]; + if (countNum == 0) continue; + int floorValue = 1; + while (floorValue * num <= maxVal) { + int left = floorValue * num; + int right = (floorValue + 1) * num - 1; + if (right > maxVal) right = maxVal; + int countInRange = freq[right] - freq[left - 1]; + total = (total + countNum * floorValue * countInRange) % MOD; + floorValue++; + } + } + return total; + } +} diff --git a/tests/1501-2000/1862. sum-of-floored-pairs/sol.go b/tests/1501-2000/1862. sum-of-floored-pairs/sol.go new file mode 100644 index 00000000..dba126be --- /dev/null +++ b/tests/1501-2000/1862. sum-of-floored-pairs/sol.go @@ -0,0 +1,38 @@ +func sumOfFlooredPairs(nums []int) int { + const MOD = 1_000_000_007 + maxi := 100_001 + maxVal := 0 + for _, num := range nums { + if num > maxVal { + maxVal = num + } + } + size := 2*maxi + 1 + freq := make([]int, size) + for _, num := range nums { + freq[num]++ + } + for i := 1; i < size; i++ { + freq[i] += freq[i-1] + } + + total := 0 + for num := 1; num <= maxVal; num++ { + countNum := freq[num] - freq[num-1] + if countNum == 0 { + continue + } + floorValue := 1 + for floorValue*num <= maxVal { + left := floorValue * num + right := (floorValue+1)*num - 1 + if right > maxVal { + right = maxVal + } + countInRange := freq[right] - freq[left-1] + total = (total + countNum*floorValue*countInRange) % MOD + floorValue++ + } + } + return total +} diff --git a/tests/1501-2000/1862. sum-of-floored-pairs/sol.java b/tests/1501-2000/1862. sum-of-floored-pairs/sol.java new file mode 100644 index 00000000..87b7228c --- /dev/null +++ b/tests/1501-2000/1862. sum-of-floored-pairs/sol.java @@ -0,0 +1,27 @@ +class Solution { + public int sumOfFlooredPairs(int[] nums) { + final int MOD = 1_000_000_007; + int maxi = 100_001; + int maxVal = 0; + for (int num : nums) maxVal = Math.max(maxVal, num); + int size = 2 * maxi + 1; + int[] freq = new int[size]; + for (int num : nums) freq[num]++; + for (int i = 1; i < size; i++) freq[i] += freq[i-1]; + + long total = 0; + for (int num = 1; num <= maxVal; num++) { + int countNum = freq[num] - freq[num-1]; + if (countNum == 0) continue; + int floorValue = 1; + while ((long)floorValue * num <= maxVal) { + int left = floorValue * num; + int right = Math.min((floorValue + 1) * num - 1, maxVal); + int countInRange = freq[right] - freq[left - 1]; + total = (total + (long)countNum * floorValue * countInRange) % MOD; + floorValue++; + } + } + return (int)total; + } +} diff --git a/tests/1501-2000/1862. sum-of-floored-pairs/sol.kt b/tests/1501-2000/1862. sum-of-floored-pairs/sol.kt new file mode 100644 index 00000000..5d17a6b7 --- /dev/null +++ b/tests/1501-2000/1862. sum-of-floored-pairs/sol.kt @@ -0,0 +1,26 @@ +class Solution { + fun sumOfFlooredPairs(nums: IntArray): Int { + val MOD = 1_000_000_007 + val maxi = 100_001 + val maxVal = nums.max()!! + val size = 2 * maxi + 1 + val freq = IntArray(size) + for (num in nums) freq[num]++ + for (i in 1 until size) freq[i] += freq[i-1] + + var total = 0L + for (num in 1..maxVal) { + val countNum = freq[num] - freq[num-1] + if (countNum == 0) continue + var floorValue = 1 + while (floorValue.toLong() * num <= maxVal) { + val left = floorValue * num + val right = minOf((floorValue + 1) * num - 1, maxVal) + val countInRange = freq[right] - freq[left - 1] + total = (total + countNum.toLong() * floorValue * countInRange) % MOD + floorValue++ + } + } + return total.toInt() + } +} diff --git a/tests/1501-2000/1862. sum-of-floored-pairs/sol.py b/tests/1501-2000/1862. sum-of-floored-pairs/sol.py new file mode 100644 index 00000000..c4e91777 --- /dev/null +++ b/tests/1501-2000/1862. sum-of-floored-pairs/sol.py @@ -0,0 +1,36 @@ +# T.C: O(max_val * log(max_val)) +# S.C: O(max_val) +class Solution: + def sumOfFlooredPairs(self, nums: list[int]) -> int: + MOD = 10**9 + 7 + maxi = 10**5 + 1 + + freq = [0] * (2 * maxi + 1) + max_val = max(nums) + + # freq and maximum number + for num in nums: + freq[num] += 1 + + # prefix sum + for i in range(1, 2 * maxi + 1): + freq[i] += freq[i - 1] + + total = 0 + for num in range(1, max_val + 1): + if freq[num] == freq[num - 1]: + continue # skip numbers not in nums + + count_num = freq[num] - freq[num - 1] + floor_value = 1 + + while floor_value * num <= max_val: + left = floor_value * num + right = min((floor_value + 1) * num - 1, max_val) + + count_in_range = freq[right] - freq[left - 1] + total = (total + (count_num * floor_value * count_in_range) % MOD) % MOD + + floor_value += 1 + + return total diff --git a/tests/1501-2000/1862. sum-of-floored-pairs/sol.py2 b/tests/1501-2000/1862. sum-of-floored-pairs/sol.py2 new file mode 100644 index 00000000..14d10926 --- /dev/null +++ b/tests/1501-2000/1862. sum-of-floored-pairs/sol.py2 @@ -0,0 +1,31 @@ +class Solution(object): + def sumOfFlooredPairs(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + MOD = 10**9 + 7 + maxi = 10**5 + 1 + max_val = max(nums) + size = 2 * maxi + 1 + + freq = [0] * size + for num in nums: + freq[num] += 1 + + for i in range(1, size): + freq[i] += freq[i-1] + + total = 0 + for num in range(1, max_val + 1): + count_num = freq[num] - freq[num-1] + if count_num == 0: + continue + floor_value = 1 + while floor_value * num <= max_val: + left = floor_value * num + right = min((floor_value + 1) * num - 1, max_val) + count_in_range = freq[right] - freq[left - 1] + total = (total + count_num * floor_value * count_in_range) % MOD + floor_value += 1 + return total diff --git a/tests/1501-2000/1862. sum-of-floored-pairs/sol.rb b/tests/1501-2000/1862. sum-of-floored-pairs/sol.rb new file mode 100644 index 00000000..5e9740d9 --- /dev/null +++ b/tests/1501-2000/1862. sum-of-floored-pairs/sol.rb @@ -0,0 +1,28 @@ +# @param {Integer[]} nums +# @return {Integer} +def sum_of_floored_pairs(nums) + mod = 10**9 + 7 + maxi = 10**5 + 1 + max_val = nums.max + size = 2 * maxi + 1 + freq = Array.new(size, 0) + + nums.each { |num| freq[num] += 1 } + + (1...size).each { |i| freq[i] += freq[i-1] } + + total = 0 + (1..max_val).each do |num| + count_num = freq[num] - freq[num-1] + next if count_num == 0 + floor_value = 1 + while floor_value * num <= max_val + left = floor_value * num + right = [(floor_value + 1) * num - 1, max_val].min + count_in_range = freq[right] - freq[left - 1] + total = (total + count_num * floor_value * count_in_range) % mod + floor_value += 1 + end + end + total +end diff --git a/tests/1501-2000/1862. sum-of-floored-pairs/sol.rs b/tests/1501-2000/1862. sum-of-floored-pairs/sol.rs new file mode 100644 index 00000000..0b5c8f64 --- /dev/null +++ b/tests/1501-2000/1862. sum-of-floored-pairs/sol.rs @@ -0,0 +1,32 @@ +impl Solution { + pub fn sum_of_floored_pairs(nums: Vec) -> i32 { + const MOD: i64 = 1_000_000_007; + let maxi = 100_001usize; + let max_val = *nums.iter().max().unwrap() as usize; + let size = 2 * maxi + 1; + let mut freq = vec![0i64; size]; + for &num in &nums { + freq[num as usize] += 1; + } + for i in 1..size { + freq[i] += freq[i - 1]; + } + + let mut total = 0i64; + for num in 1..=max_val { + let count_num = freq[num] - freq[num - 1]; + if count_num == 0 { + continue; + } + let mut floor_value = 1usize; + while floor_value * num <= max_val { + let left = floor_value * num; + let right = ((floor_value + 1) * num - 1).min(max_val); + let count_in_range = freq[right] - freq[left - 1]; + total = (total + count_num * floor_value as i64 * count_in_range) % MOD; + floor_value += 1; + } + } + total as i32 + } +} diff --git a/tests/1501-2000/1862. sum-of-floored-pairs/sol.swift b/tests/1501-2000/1862. sum-of-floored-pairs/sol.swift new file mode 100644 index 00000000..0f62fd71 --- /dev/null +++ b/tests/1501-2000/1862. sum-of-floored-pairs/sol.swift @@ -0,0 +1,30 @@ +class Solution { + func sumOfFlooredPairs(_ nums: [Int]) -> Int { + let MOD = 1_000_000_007 + let maxi = 100_001 + let maxVal = nums.max() ?? 0 + let size = 2 * maxi + 1 + var freq = [Int](repeating: 0, count: size) + for num in nums { + freq[num] += 1 + } + for i in 1..& nums) { + int total = 0; + for (int num : nums) { + total |= num; + } + return total * (1 << (nums.size() - 1)); + } +}; diff --git a/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.cs b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.cs new file mode 100644 index 00000000..ae5cb522 --- /dev/null +++ b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.cs @@ -0,0 +1,9 @@ +public class Solution { + public int SubsetXORSum(int[] nums) { + int total = 0; + foreach (int num in nums) { + total |= num; + } + return total * (1 << (nums.Length - 1)); + } +} diff --git a/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.dart b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.dart new file mode 100644 index 00000000..1642bed5 --- /dev/null +++ b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.dart @@ -0,0 +1,9 @@ +class Solution { + int subsetXORSum(List nums) { + int total = 0; + for (int num in nums) { + total |= num; + } + return total * (1 << (nums.length - 1)); + } +} diff --git a/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.go b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.go new file mode 100644 index 00000000..b75f7d25 --- /dev/null +++ b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.go @@ -0,0 +1,7 @@ +func subsetXORSum(nums []int) int { + total := 0 + for _, num := range nums { + total |= num + } + return total * (1 << (len(nums) - 1)) +} diff --git a/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.java b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.java new file mode 100644 index 00000000..ed1feacc --- /dev/null +++ b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.java @@ -0,0 +1,9 @@ +class Solution { + public int subsetXORSum(int[] nums) { + int total = 0; + for (int num : nums) { + total |= num; + } + return total * (1 << (nums.length - 1)); + } +} diff --git a/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.kt b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.kt new file mode 100644 index 00000000..4d037887 --- /dev/null +++ b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.kt @@ -0,0 +1,9 @@ +class Solution { + fun subsetXORSum(nums: IntArray): Int { + var total = 0 + for (num in nums) { + total = total or num + } + return total * (1 shl (nums.size - 1)) + } +} diff --git a/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.py b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.py new file mode 100644 index 00000000..84deb12b --- /dev/null +++ b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.py @@ -0,0 +1,6 @@ +class Solution: + def subsetXORSum(self, nums): + total = 0 + for num in nums: + total |= num # Step 1: Compute bitwise OR of all numbers + return total * (1 << (len(nums) - 1)) # Step 2: Multiply by 2^(n-1) diff --git a/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.py2 b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.py2 new file mode 100644 index 00000000..4c76cbd9 --- /dev/null +++ b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.py2 @@ -0,0 +1,10 @@ +class Solution(object): + def subsetXORSum(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + total = 0 + for num in nums: + total |= num + return total * (1 << (len(nums) - 1)) diff --git a/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.rb b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.rb new file mode 100644 index 00000000..4a64bf48 --- /dev/null +++ b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.rb @@ -0,0 +1,9 @@ +# @param {Integer[]} nums +# @return {Integer} +def subset_xor_sum(nums) + total = 0 + nums.each do |num| + total |= num + end + total * (1 << (nums.length - 1)) +end diff --git a/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.rs b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.rs new file mode 100644 index 00000000..8f8381eb --- /dev/null +++ b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.rs @@ -0,0 +1,9 @@ +impl Solution { + pub fn subset_xor_sum(nums: Vec) -> i32 { + let mut total = 0; + for num in &nums { + total |= num; + } + total * (1 << (nums.len() - 1)) + } +} diff --git a/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.swift b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.swift new file mode 100644 index 00000000..50a820dc --- /dev/null +++ b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.swift @@ -0,0 +1,9 @@ +class Solution { + func subsetXORSum(_ nums: [Int]) -> Int { + var total = 0 + for num in nums { + total |= num + } + return total * (1 << (nums.count - 1)) + } +} diff --git a/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.ts b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.ts new file mode 100644 index 00000000..9b57c136 --- /dev/null +++ b/tests/1501-2000/1863. sum-of-all-subset-xor-totals/sol.ts @@ -0,0 +1,7 @@ +function subsetXORSum(nums: number[]): number { + let total = 0; + for (const num of nums) { + total |= num; + } + return total * (1 << (nums.length - 1)); +} diff --git a/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/manifest.yaml b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/manifest.yaml new file mode 100644 index 00000000..e8768ac0 --- /dev/null +++ b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/manifest.yaml @@ -0,0 +1,237 @@ +entry: + id: 1864 + title: "minimum-number-of-swaps-to-make-the-binary-string-alternating" + params: + s: + type: string + call: + cpp: "Solution().minSwaps({s})" + rust: "Solution::min_swaps({s})" + python3: "Solution().minSwaps({s})" + python2: "Solution().minSwaps({s})" + ruby: "min_swaps({s})" + java: "new Solution().minSwaps({s})" + csharp: "new Solution().MinSwaps({s})" + kotlin: "Solution().minSwaps({s})" + go: "minSwaps({s})" + dart: "Solution().minSwaps({s})" + swift: "Solution().minSwaps({s})" + typescript: "minSwaps({s})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minSwaps(s, {result})" + checker: | + class Checker: + def minSwaps(self, s, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + zeros = s.count("0") + ones = len(s) - zeros + if abs(zeros - ones) > 1: + return result == -1 + + def mismatches(start): + other = "1" if start == "0" else "0" + bad = sum(ch != (start if i % 2 == 0 else other) + for i, ch in enumerate(s)) + return bad // 2 + + if zeros == ones: + expected = min(mismatches("0"), mismatches("1")) + elif zeros > ones: + expected = mismatches("0") + else: + expected = mismatches("1") + return result == expected + +seed: 1864 + +tests: + - name: two-digit-zero-one + in: + s: "10" + out: 0 + - name: two-digit-one-zero + in: + s: "01" + out: 0 + - name: single-zero + in: + s: "0" + out: 0 + - name: single-one + in: + s: "1" + out: 0 + - name: impossible-two-zeros + in: + s: "00" + out: -1 + - name: impossible-two-ones + in: + s: "11" + out: -1 + - name: alternating-three-zero-start + in: + s: "010" + out: 0 + - name: alternating-three-one-start + in: + s: "101" + out: 0 + - name: impossible-three-zeros + in: + s: "000" + out: -1 + - name: impossible-three-ones + in: + s: "111" + out: -1 + - name: one-swap-zero-majority + in: + s: "001" + out: 1 + - name: one-swap-one-majority + in: + s: "110" + out: 1 + - name: one-swap-leading-zero + in: + s: "011" + out: 1 + - name: one-swap-leading-one + in: + s: "100" + out: 1 + - name: alternating-even-zero-start + in: + s: "0101" + out: 0 + - name: alternating-even-one-start + in: + s: "1010" + out: 0 + - name: example-one + in: + s: "111000" + out: 1 + - name: example-three-impossible + in: + s: "1110" + out: -1 + - name: mirrored-example-one + in: + s: "000111" + out: 1 + - name: equal-blocks + in: + s: "0011" + out: 1 + - name: near-alternating-zero-tail + in: + s: "0100" + out: -1 + - name: near-alternating-one-tail + in: + s: "1011" + out: -1 + - name: all-zero-even + in: + s: "0000" + out: -1 + - name: all-one-even + in: + s: "1111" + out: -1 + - name: excess-zero-by-two + in: + s: "0001" + out: -1 + - name: excess-one-by-two + in: + s: "1000" + out: -1 + - name: five-zero-majority + in: + s: "00101" + out: 2 + - name: five-one-majority + in: + s: "11010" + out: 2 + - name: alternating-five-zero-start + in: + s: "01010" + out: 0 + - name: alternating-five-one-start + in: + s: "10101" + out: 0 + - name: repeated-balanced-blocks + in: + s: "00110011" + out: 2 + - name: alternating-eight + in: + s: "01010101" + out: 0 + - name: four-zero-four-one + in: + s: "11110000" + out: 2 + - name: four-one-four-zero + in: + s: "00001111" + out: 2 + - name: alternating-ten + in: + s: "0101010101" + out: 0 + - name: generated-balanced + in: + s: + gen: "str" + len: 1000 + alphabet: "01" + judge: + type: "exact" + - name: generated-short-binary + in: + s: + gen: "str" + len: 17 + alphabet: "01" + judge: + type: "exact" + - name: generated-medium-binary + in: + s: + gen: "str" + len: 257 + alphabet: "01" + judge: + type: "exact" + - name: generated-large-binary + in: + s: + gen: "str" + len: 999 + alphabet: "01" + judge: + type: "exact" + - name: generated-even-large-binary + in: + s: + gen: "str" + len: 998 + alphabet: "01" + judge: + type: "exact" diff --git a/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.cpp b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.cpp new file mode 100644 index 00000000..3e1d0ca9 --- /dev/null +++ b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int minSwaps(string s) { + int count0 = 0, count1 = 0; + for (char c : s) { + if (c == '0') count0++; + else count1++; + } + + if (abs(count0 - count1) > 1) return -1; + + int mismatch0 = 0, mismatch1 = 0; + for (int i = 0; i < s.length(); i++) { + char expected0 = (i % 2 == 0) ? '0' : '1'; + char expected1 = (i % 2 == 0) ? '1' : '0'; + if (s[i] != expected0) mismatch0++; + if (s[i] != expected1) mismatch1++; + } + + if (count0 == count1) return min(mismatch0 / 2, mismatch1 / 2); + if (count0 > count1) return mismatch0 / 2; + return mismatch1 / 2; + } +}; diff --git a/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.cs b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.cs new file mode 100644 index 00000000..2f4f3971 --- /dev/null +++ b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.cs @@ -0,0 +1,23 @@ +public class Solution { + public int MinSwaps(string s) { + int count0 = 0, count1 = 0; + foreach (char c in s) { + if (c == '0') count0++; + else count1++; + } + + if (Math.Abs(count0 - count1) > 1) return -1; + + int mismatch0 = 0, mismatch1 = 0; + for (int i = 0; i < s.Length; i++) { + char expected0 = i % 2 == 0 ? '0' : '1'; + char expected1 = i % 2 == 0 ? '1' : '0'; + if (s[i] != expected0) mismatch0++; + if (s[i] != expected1) mismatch1++; + } + + if (count0 == count1) return Math.Min(mismatch0 / 2, mismatch1 / 2); + if (count0 > count1) return mismatch0 / 2; + return mismatch1 / 2; + } +} diff --git a/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.dart b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.dart new file mode 100644 index 00000000..6356b100 --- /dev/null +++ b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.dart @@ -0,0 +1,23 @@ +class Solution { + int minSwaps(String s) { + int count0 = 0, count1 = 0; + for (int i = 0; i < s.length; i++) { + if (s[i] == '0') count0++; + else count1++; + } + + if ((count0 - count1).abs() > 1) return -1; + + int mismatch0 = 0, mismatch1 = 0; + for (int i = 0; i < s.length; i++) { + String expected0 = i % 2 == 0 ? '0' : '1'; + String expected1 = i % 2 == 0 ? '1' : '0'; + if (s[i] != expected0) mismatch0++; + if (s[i] != expected1) mismatch1++; + } + + if (count0 == count1) return (mismatch0 ~/ 2 < mismatch1 ~/ 2) ? mismatch0 ~/ 2 : mismatch1 ~/ 2; + if (count0 > count1) return mismatch0 ~/ 2; + return mismatch1 ~/ 2; + } +} diff --git a/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.go b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.go new file mode 100644 index 00000000..9a1e3b04 --- /dev/null +++ b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.go @@ -0,0 +1,45 @@ +func minSwaps(s string) int { + count0 := 0 + count1 := 0 + for _, c := range s { + if c == '0' { + count0++ + } else { + count1++ + } + } + + if abs(count0-count1) > 1 { + return -1 + } + + mismatch0 := 0 + mismatch1 := 0 + for i, c := range s { + if i%2 == 0 { + if c != '0' { mismatch0++ } + if c != '1' { mismatch1++ } + } else { + if c != '1' { mismatch0++ } + if c != '0' { mismatch1++ } + } + } + + if count0 == count1 { + return min(mismatch0/2, mismatch1/2) + } else if count0 > count1 { + return mismatch0 / 2 + } else { + return mismatch1 / 2 + } +} + +func abs(x int) int { + if x < 0 { return -x } + return x +} + +func min(a, b int) int { + if a < b { return a } + return b +} diff --git a/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.java b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.java new file mode 100644 index 00000000..87948185 --- /dev/null +++ b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.java @@ -0,0 +1,23 @@ +class Solution { + public int minSwaps(String s) { + int count0 = 0, count1 = 0; + for (char c : s.toCharArray()) { + if (c == '0') count0++; + else count1++; + } + + if (Math.abs(count0 - count1) > 1) return -1; + + int mismatch0 = 0, mismatch1 = 0; + for (int i = 0; i < s.length(); i++) { + char expected0 = i % 2 == 0 ? '0' : '1'; + char expected1 = i % 2 == 0 ? '1' : '0'; + if (s.charAt(i) != expected0) mismatch0++; + if (s.charAt(i) != expected1) mismatch1++; + } + + if (count0 == count1) return Math.min(mismatch0 / 2, mismatch1 / 2); + if (count0 > count1) return mismatch0 / 2; + return mismatch1 / 2; + } +} diff --git a/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.kt b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.kt new file mode 100644 index 00000000..bf62d33a --- /dev/null +++ b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.kt @@ -0,0 +1,17 @@ +class Solution { + fun minSwaps(s: String): Int { + val count0 = s.count { it == '0' } + val count1 = s.count { it == '1' } + + if (Math.abs(count0 - count1) > 1) return -1 + + val mismatch0 = s.indices.count { i -> s[i] != (if (i % 2 == 0) '0' else '1') } + val mismatch1 = s.indices.count { i -> s[i] != (if (i % 2 == 0) '1' else '0') } + + return when { + count0 == count1 -> Math.min(mismatch0 / 2, mismatch1 / 2) + count0 > count1 -> mismatch0 / 2 + else -> mismatch1 / 2 + } + } +} diff --git a/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.py b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.py new file mode 100644 index 00000000..a6b091d1 --- /dev/null +++ b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.py @@ -0,0 +1,28 @@ +class Solution(object): + def minSwaps(self, s): + """ + :type s: str + :rtype: int + """ + count0 = s.count("0") + count1 = s.count("1") + + if abs(count0 - count1) > 1: + return -1 + + def mismatch(start_char): + mismatches = 0 + for i, ch in enumerate(s): + expected = ( + start_char if i % 2 == 0 else ("1" if start_char == "0" else "0") + ) + if ch != expected: + mismatches += 1 + return mismatches // 2 + + if count0 == count1: + return min(mismatch("0"), mismatch("1")) + elif count0 > count1: + return mismatch("0") + else: + return mismatch("1") diff --git a/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.py2 b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.py2 new file mode 100644 index 00000000..861b017d --- /dev/null +++ b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.py2 @@ -0,0 +1,26 @@ +class Solution(object): + def minSwaps(self, s): + """ + :type s: str + :rtype: int + """ + count0 = s.count('0') + count1 = s.count('1') + + if abs(count0 - count1) > 1: + return -1 + + def mismatch(start_char): + mismatches = 0 + for i, ch in enumerate(s): + expected = start_char if i % 2 == 0 else ('1' if start_char == '0' else '0') + if ch != expected: + mismatches += 1 + return mismatches // 2 + + if count0 == count1: + return min(mismatch('0'), mismatch('1')) + elif count0 > count1: + return mismatch('0') + else: + return mismatch('1') diff --git a/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.rb b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.rb new file mode 100644 index 00000000..3abb1626 --- /dev/null +++ b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.rb @@ -0,0 +1,25 @@ +# @param {String} s +# @return {Integer} +def min_swaps(s) + count0 = s.count('0') + count1 = s.count('1') + + return -1 if (count0 - count1).abs > 1 + + mismatch = ->(start_char) { + mismatches = 0 + s.each_char.with_index do |ch, i| + expected = i.even? ? start_char : (start_char == '0' ? '1' : '0') + mismatches += 1 if ch != expected + end + mismatches / 2 + } + + if count0 == count1 + [mismatch.call('0'), mismatch.call('1')].min + elsif count0 > count1 + mismatch.call('0') + else + mismatch.call('1') + end +end diff --git a/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.rs b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.rs new file mode 100644 index 00000000..6371b4f1 --- /dev/null +++ b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.rs @@ -0,0 +1,29 @@ +impl Solution { + pub fn min_swaps(s: String) -> i32 { + let count0 = s.chars().filter(|&c| c == '0').count() as i32; + let count1 = s.chars().filter(|&c| c == '1').count() as i32; + + if (count0 - count1).abs() > 1 { + return -1; + } + + let chars: Vec = s.chars().collect(); + let mut mismatch0 = 0; + let mut mismatch1 = 0; + + for (i, &c) in chars.iter().enumerate() { + let expected0 = if i % 2 == 0 { '0' } else { '1' }; + let expected1 = if i % 2 == 0 { '1' } else { '0' }; + if c != expected0 { mismatch0 += 1; } + if c != expected1 { mismatch1 += 1; } + } + + if count0 == count1 { + return (mismatch0 / 2).min(mismatch1 / 2); + } else if count0 > count1 { + return mismatch0 / 2; + } else { + return mismatch1 / 2; + } + } +} diff --git a/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.swift b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.swift new file mode 100644 index 00000000..9dc6fca9 --- /dev/null +++ b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func minSwaps(_ s: String) -> Int { + let count0 = s.filter { $0 == "0" }.count + let count1 = s.filter { $0 == "1" }.count + + if abs(count0 - count1) > 1 { return -1 } + + let chars = Array(s) + var mismatch0 = 0 + var mismatch1 = 0 + + for i in 0.. count1 { return mismatch0 / 2 } + return mismatch1 / 2 + } +} diff --git a/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.ts b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.ts new file mode 100644 index 00000000..6fc29dc9 --- /dev/null +++ b/tests/1501-2000/1864. minimum-number-of-swaps-to-make-the-binary-string-alternating/sol.ts @@ -0,0 +1,21 @@ +function minSwaps(s: string): number { + const count0 = (s.match(/0/g) || []).length; + const count1 = (s.match(/1/g) || []).length; + + if (Math.abs(count0 - count1) > 1) return -1; + + let mismatch0 = 0; + let mismatch1 = 0; + + for (let i = 0; i < s.length; i++) { + const expected0 = i % 2 === 0 ? "0" : "1"; + const expected1 = i % 2 === 0 ? "1" : "0"; + if (s[i] !== expected0) mismatch0++; + if (s[i] !== expected1) mismatch1++; + } + + if (count0 === count1) + return Math.min(Math.floor(mismatch0 / 2), Math.floor(mismatch1 / 2)); + if (count0 > count1) return Math.floor(mismatch0 / 2); + return Math.floor(mismatch1 / 2); +} diff --git a/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/manifest.yaml b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/manifest.yaml new file mode 100644 index 00000000..c1f4f842 --- /dev/null +++ b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/manifest.yaml @@ -0,0 +1,240 @@ +entry: + id: 1866 + title: "number-of-ways-to-rearrange-sticks-with-k-sticks-visible" + params: + n: + type: int + k: + type: int + call: + cpp: "Solution().rearrangeSticks({n}, {k})" + rust: "Solution::rearrange_sticks({n}, {k})" + python3: "Solution().rearrangeSticks({n}, {k})" + python2: "Solution().rearrangeSticks({n}, {k})" + ruby: "rearrange_sticks({n}, {k})" + java: "new Solution().rearrangeSticks({n}, {k})" + csharp: "new Solution().RearrangeSticks({n}, {k})" + kotlin: "Solution().rearrangeSticks({n}, {k})" + go: "rearrangeSticks({n}, {k})" + dart: "Solution().rearrangeSticks({n}, {k})" + swift: "Solution().rearrangeSticks({n}, {k})" + typescript: "rearrangeSticks({n}, {k})" +judge: + type: "exact" +limits: + time_ms: 5000 + memory_mb: 512 +oracle: + python3: + call: "Checker().rearrangeSticks(n, k, {result})" + checker: | + class Checker: + def rearrangeSticks(self, n, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + mod = 1000000007 + dp = [0] * (k + 1) + dp[0] = 1 + for length in range(1, n + 1): + nxt = [0] * (k + 1) + for visible in range(1, min(length, k) + 1): + nxt[visible] = (dp[visible - 1] + (length - 1) * dp[visible]) % mod + dp = nxt + return result == dp[k] +seed: 1866 +tests: + - name: n2-k1 + in: + n: 2 + k: 1 + out: 1 + - name: n2-k2 + in: + n: 2 + k: 2 + out: 1 + - name: n3-k1 + in: + n: 3 + k: 1 + out: 2 + - name: example-1 + in: + n: 3 + k: 2 + out: 3 + - name: n3-k3 + in: + n: 3 + k: 3 + out: 1 + - name: n4-k1 + in: + n: 4 + k: 1 + out: 6 + - name: n4-k2 + in: + n: 4 + k: 2 + out: 11 + - name: n4-k3 + in: + n: 4 + k: 3 + out: 6 + - name: n4-k4 + in: + n: 4 + k: 4 + out: 1 + - name: n5-k1 + in: + n: 5 + k: 1 + out: 24 + - name: n5-k2 + in: + n: 5 + k: 2 + out: 50 + - name: n5-k3 + in: + n: 5 + k: 3 + out: 35 + - name: n5-k4 + in: + n: 5 + k: 4 + out: 10 + - name: example-2 + in: + n: 5 + k: 5 + out: 1 + - name: n6-k1 + in: + n: 6 + k: 1 + out: 120 + - name: n6-k2 + in: + n: 6 + k: 2 + out: 274 + - name: n6-k3 + in: + n: 6 + k: 3 + out: 225 + - name: n6-k4 + in: + n: 6 + k: 4 + out: 85 + - name: n6-k5 + in: + n: 6 + k: 5 + out: 15 + - name: n6-k6 + in: + n: 6 + k: 6 + out: 1 + - name: n7-k2 + in: + n: 7 + k: 2 + out: 1764 + - name: n7-k4 + in: + n: 7 + k: 4 + out: 735 + - name: n7-k6 + in: + n: 7 + k: 6 + out: 21 + - name: n8-k3 + in: + n: 8 + k: 3 + out: 13132 + - name: n8-k5 + in: + n: 8 + k: 5 + out: 1960 + - name: n9-k2 + in: + n: 9 + k: 2 + out: 109584 + - name: n9-k7 + in: + n: 9 + k: 7 + out: 546 + - name: n10-k1 + in: + n: 10 + k: 1 + out: 362880 + - name: n10-k5 + in: + n: 10 + k: 5 + out: 269325 + - name: n10-k10 + in: + n: 10 + k: 10 + out: 1 + - name: example-3 + in: + n: 20 + k: 11 + out: 647427950 + - name: n50-k2 + in: + n: 50 + k: 2 + out: 254881466 + - name: n50-k25 + in: + n: 50 + k: 25 + out: 253549512 + - name: n100-k50 + in: + n: 100 + k: 50 + out: 768969154 + - name: max-n-k1 + in: + n: 1000 + k: 1 + out: 756641425 + - name: max-n-k2 + in: + n: 1000 + k: 2 + out: 371843527 + - name: max-n-middle + in: + n: 1000 + k: 500 + out: 761367694 + - name: max-n-k999 + in: + n: 1000 + k: 999 + out: 499500 + - name: max-n-all-visible + in: + n: 1000 + k: 1000 + out: 1 diff --git a/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.cpp b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.cpp new file mode 100644 index 00000000..28aa24df --- /dev/null +++ b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int rearrangeSticks(int n, int k) { + const int mod = 1000000007; + vector dp(k + 1, 0); + dp[0] = 1; + for (int length = 1; length <= n; ++length) { + vector nxt(k + 1, 0); + for (int visible = 1; visible <= min(length, k); ++visible) { + nxt[visible] = (dp[visible - 1] + (long long)(length - 1) * dp[visible]) % mod; + } + dp = nxt; + } + return dp[k]; + } +}; diff --git a/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.cs b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.cs new file mode 100644 index 00000000..5b0a7d3b --- /dev/null +++ b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int RearrangeSticks(int n, int k) { + const int mod = 1000000007; + int[] dp = new int[k + 1]; + dp[0] = 1; + for (int length = 1; length <= n; length++) { + int[] nxt = new int[k + 1]; + for (int visible = 1; visible <= Math.Min(length, k); visible++) { + nxt[visible] = (int)(((long)dp[visible - 1] + (long)(length - 1) * dp[visible]) % mod); + } + dp = nxt; + } + return dp[k]; + } +} diff --git a/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.dart b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.dart new file mode 100644 index 00000000..03748485 --- /dev/null +++ b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.dart @@ -0,0 +1,15 @@ +class Solution { + int rearrangeSticks(int n, int k) { + const mod = 1000000007; + List dp = List.filled(k + 1, 0); + dp[0] = 1; + for (int length = 1; length <= n; length++) { + List nxt = List.filled(k + 1, 0); + for (int visible = 1; visible <= (length < k ? length : k); visible++) { + nxt[visible] = (dp[visible - 1] + (length - 1) * dp[visible]) % mod; + } + dp = nxt; + } + return dp[k]; + } +} diff --git a/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.go b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.go new file mode 100644 index 00000000..2e4f035f --- /dev/null +++ b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.go @@ -0,0 +1,13 @@ +func rearrangeSticks(n int, k int) int { + mod := 1000000007 + dp := make([]int, k+1) + dp[0] = 1 + for length := 1; length <= n; length++ { + nxt := make([]int, k+1) + for visible := 1; visible <= length && visible <= k; visible++ { + nxt[visible] = (dp[visible-1] + (length-1)*dp[visible]) % mod + } + dp = nxt + } + return dp[k] +} diff --git a/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.java b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.java new file mode 100644 index 00000000..fee90b5a --- /dev/null +++ b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.java @@ -0,0 +1,15 @@ +class Solution { + public int rearrangeSticks(int n, int k) { + int mod = 1000000007; + int[] dp = new int[k + 1]; + dp[0] = 1; + for (int length = 1; length <= n; length++) { + int[] nxt = new int[k + 1]; + for (int visible = 1; visible <= Math.min(length, k); visible++) { + nxt[visible] = (int)(((long)dp[visible - 1] + (long)(length - 1) * dp[visible]) % mod); + } + dp = nxt; + } + return dp[k]; + } +} diff --git a/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.kt b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.kt new file mode 100644 index 00000000..e5e75b63 --- /dev/null +++ b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun rearrangeSticks(n: Int, k: Int): Int { + val mod = 1000000007 + var dp = IntArray(k + 1) + dp[0] = 1 + for (length in 1..n) { + val nxt = IntArray(k + 1) + for (visible in 1..minOf(length, k)) { + nxt[visible] = ((dp[visible - 1].toLong() + (length - 1).toLong() * dp[visible]) % mod).toInt() + } + dp = nxt + } + return dp[k] + } +} diff --git a/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.py b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.py new file mode 100644 index 00000000..cb7ad582 --- /dev/null +++ b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.py @@ -0,0 +1,11 @@ +class Solution: + def rearrangeSticks(self, n: int, k: int) -> int: + mod = 1000000007 + dp = [0] * (k + 1) + dp[0] = 1 + for length in range(1, n + 1): + nxt = [0] * (k + 1) + for visible in range(1, min(length, k) + 1): + nxt[visible] = (dp[visible - 1] + (length - 1) * dp[visible]) % mod + dp = nxt + return dp[k] diff --git a/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.py2 b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.py2 new file mode 100644 index 00000000..2a6da0ac --- /dev/null +++ b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def rearrangeSticks(self, n, k): + """ + :type n: int + :type k: int + :rtype: int + """ + mod = 1000000007 + dp = [0] * (k + 1) + dp[0] = 1 + for length in range(1, n + 1): + nxt = [0] * (k + 1) + for visible in range(1, min(length, k) + 1): + nxt[visible] = (dp[visible - 1] + (length - 1) * dp[visible]) % mod + dp = nxt + return dp[k] diff --git a/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.rb b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.rb new file mode 100644 index 00000000..c149f2a9 --- /dev/null +++ b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.rb @@ -0,0 +1,16 @@ +# @param {Integer} n +# @param {Integer} k +# @return {Integer} +def rearrange_sticks(n, k) + mod = 1000000007 + dp = Array.new(k + 1, 0) + dp[0] = 1 + (1..n).each do |length| + nxt = Array.new(k + 1, 0) + (1..[length, k].min).each do |visible| + nxt[visible] = (dp[visible - 1] + (length - 1) * dp[visible]) % mod + end + dp = nxt + end + dp[k] +end diff --git a/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.rs b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.rs new file mode 100644 index 00000000..b3dde214 --- /dev/null +++ b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn rearrange_sticks(n: i32, k: i32) -> i32 { + let mod_val = 1000000007i64; + let n = n as usize; + let k = k as usize; + let mut dp = vec![0i64; k + 1]; + dp[0] = 1; + for length in 1..=n { + let mut nxt = vec![0i64; k + 1]; + for visible in 1..=length.min(k) { + nxt[visible] = (dp[visible - 1] + (length as i64 - 1) * dp[visible]) % mod_val; + } + dp = nxt; + } + dp[k] as i32 + } +} diff --git a/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.swift b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.swift new file mode 100644 index 00000000..608a499e --- /dev/null +++ b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func rearrangeSticks(_ n: Int, _ k: Int) -> Int { + let mod = 1000000007 + var dp = [Int](repeating: 0, count: k + 1) + dp[0] = 1 + for length in 1...n { + var nxt = [Int](repeating: 0, count: k + 1) + for visible in 1...min(length, k) { + nxt[visible] = (dp[visible - 1] + (length - 1) * dp[visible]) % mod + } + dp = nxt + } + return dp[k] + } +} diff --git a/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.ts b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.ts new file mode 100644 index 00000000..7fd0281f --- /dev/null +++ b/tests/1501-2000/1866. number-of-ways-to-rearrange-sticks-with-k-sticks-visible/sol.ts @@ -0,0 +1,13 @@ +function rearrangeSticks(n: number, k: number): number { + const mod = 1000000007; + let dp: number[] = new Array(k + 1).fill(0); + dp[0] = 1; + for (let length = 1; length <= n; length++) { + const nxt: number[] = new Array(k + 1).fill(0); + for (let visible = 1; visible <= Math.min(length, k); visible++) { + nxt[visible] = (dp[visible - 1] + (length - 1) * dp[visible]) % mod; + } + dp = nxt; + } + return dp[k]; +} diff --git a/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/manifest.yaml b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/manifest.yaml new file mode 100644 index 00000000..9884f751 --- /dev/null +++ b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/manifest.yaml @@ -0,0 +1,224 @@ +entry: + id: 1869 + title: "longer-contiguous-segments-of-ones-than-zeros" + params: + s: + type: string + call: + cpp: "Solution().checkZeroOnes({s})" + rust: "Solution::check_zero_ones({s})" + python3: "Solution().checkZeroOnes({s})" + python2: "Solution().checkZeroOnes({s})" + ruby: "check_zero_ones({s})" + java: "new Solution().checkZeroOnes({s})" + csharp: "new Solution().CheckZeroOnes({s})" + kotlin: "Solution().checkZeroOnes({s})" + go: "checkZeroOnes({s})" + dart: "Solution().checkZeroOnes({s})" + swift: "Solution().checkZeroOnes({s})" + typescript: "checkZeroOnes({s})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().checkZeroOnes(s, {result})" + checker: | + class Checker: + def checkZeroOnes(self, s, result): + if not isinstance(result, bool): + return False + best = {'0': 0, '1': 0} + current = {'0': 0, '1': 0} + previous = None + for ch in s: + if ch not in ('0', '1'): + return False + if ch == previous: + current[ch] += 1 + else: + current[ch] = 1 + previous = ch + if current[ch] > best[ch]: + best[ch] = current[ch] + return result == (best['1'] > best['0']) + +seed: 1869 + +tests: + - name: "example-1" + in: + s: "1101" + out: true + - name: "example-2-equal-runs" + in: + s: "111000" + out: false + - name: "example-3-longer-zero-run" + in: + s: "110100010" + out: false + - name: "single-zero" + in: + s: "0" + out: false + - name: "single-one" + in: + s: "1" + out: true + - name: "all-zeros" + in: + s: "0000000000" + out: false + - name: "all-ones" + in: + s: "1111111111" + out: true + - name: "alternating-even" + in: + s: "0101010101" + out: false + - name: "alternating-start-one" + in: + s: "1010101010" + out: false + - name: "one-run-two-zero-runs" + in: + s: "001100" + out: false + - name: "one-run-three-zero-runs" + in: + s: "00011100" + out: false + - name: "one-run-four" + in: + s: "01011110" + out: true + - name: "zero-run-four" + in: + s: "10100001" + out: false + - name: "ties-after-prefix" + in: + s: "1110111" + out: true + - name: "late-long-one-run" + in: + s: "0001011111" + out: true + - name: "late-long-zero-run" + in: + s: "1110100000" + out: false + - name: "one-run-length-five" + in: + s: "001111101" + out: true + - name: "zero-run-length-five" + in: + s: "110000011" + out: false + - name: "equal-long-runs-separated" + in: + s: "111110000011111" + out: false + - name: "one-longer-by-one" + in: + s: "000011111" + out: true + - name: "zero-longer-by-one" + in: + s: "111100000" + out: false + - name: "many-short-runs" + in: + s: "001011001010" + out: false + - name: "one-run-middle" + in: + s: "010111010" + out: true + - name: "zero-run-middle" + in: + s: "101000101" + out: false + - name: "two-one-runs-tie-zero" + in: + s: "110001100" + out: false + - name: "one-run-six" + in: + s: "0101111110" + out: true + - name: "zero-run-six" + in: + s: "1010000001" + out: false + - name: "max-length-all-one" + in: + s: "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" + out: true + - name: "max-length-all-zero" + in: + s: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + out: false + - name: "max-length-balanced" + in: + s: "1111111111111111111111111111111111111111111111111100000000000000000000000000000000000000000000000000" + out: false + - name: "max-length-balanced-late" + in: + s: "0000000000000000000000000000000000000000000000000011111111111111111111111111111111111111111111111111" + out: false + - name: "generated-short" + seed: 101 + in: + s: + gen: "str" + len: + gen: "int" + min: 1 + max: 20 + alphabet: "01" + - name: "generated-medium" + seed: 202 + in: + s: + gen: "str" + len: + gen: "int" + min: 21 + max: 60 + alphabet: "01" + - name: "generated-boundary-length" + seed: 303 + in: + s: + gen: "str" + len: 100 + alphabet: "01" + - name: "generated-one-biased" + seed: 404 + in: + s: + gen: "str" + len: + gen: "int" + min: 80 + max: 100 + alphabet: "0111" + - name: "generated-zero-biased" + seed: 505 + in: + s: + gen: "str" + len: + gen: "int" + min: 80 + max: 100 + alphabet: "0001" diff --git a/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.cpp b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.cpp new file mode 100644 index 00000000..5fcc61c7 --- /dev/null +++ b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + bool checkZeroOnes(string s) { + int max1 = 0, max0 = 0; + int one = 0, zero = 0; + + for (char ch : s) { + if (ch == '1') { + one++; + zero = 0; + max1 = max(max1, one); + } else { + zero++; + one = 0; + max0 = max(max0, zero); + } + } + + return max1 > max0; + } +}; diff --git a/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.cs b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.cs new file mode 100644 index 00000000..439064cc --- /dev/null +++ b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public bool CheckZeroOnes(string s) { + int max1 = 0, max0 = 0; + int one = 0, zero = 0; + + foreach (char ch in s) { + if (ch == '1') { + one++; + zero = 0; + max1 = Math.Max(max1, one); + } else { + zero++; + one = 0; + max0 = Math.Max(max0, zero); + } + } + + return max1 > max0; + } +} diff --git a/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.dart b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.dart new file mode 100644 index 00000000..93395b82 --- /dev/null +++ b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.dart @@ -0,0 +1,20 @@ +class Solution { + bool checkZeroOnes(String s) { + int max1 = 0, max0 = 0; + int one = 0, zero = 0; + + for (int i = 0; i < s.length; i++) { + if (s[i] == '1') { + one++; + zero = 0; + max1 = max1 > one ? max1 : one; + } else { + zero++; + one = 0; + max0 = max0 > zero ? max0 : zero; + } + } + + return max1 > max0; + } +} diff --git a/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.go b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.go new file mode 100644 index 00000000..c280ea19 --- /dev/null +++ b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.go @@ -0,0 +1,24 @@ +func checkZeroOnes(s string) bool { + max1 := 0 + max0 := 0 + one := 0 + zero := 0 + + for _, ch := range s { + if ch == '1' { + one++ + zero = 0 + if one > max1 { + max1 = one + } + } else { + zero++ + one = 0 + if zero > max0 { + max0 = zero + } + } + } + + return max1 > max0 +} diff --git a/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.java b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.java new file mode 100644 index 00000000..cf62c529 --- /dev/null +++ b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.java @@ -0,0 +1,20 @@ +class Solution { + public boolean checkZeroOnes(String s) { + int max1 = 0, max0 = 0; + int one = 0, zero = 0; + + for (char ch : s.toCharArray()) { + if (ch == '1') { + one++; + zero = 0; + max1 = Math.max(max1, one); + } else { + zero++; + one = 0; + max0 = Math.max(max0, zero); + } + } + + return max1 > max0; + } +} diff --git a/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.kt b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.kt new file mode 100644 index 00000000..d5502be4 --- /dev/null +++ b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.kt @@ -0,0 +1,22 @@ +class Solution { + fun checkZeroOnes(s: String): Boolean { + var max1 = 0 + var max0 = 0 + var one = 0 + var zero = 0 + + for (ch in s) { + if (ch == '1') { + one++ + zero = 0 + max1 = maxOf(max1, one) + } else { + zero++ + one = 0 + max0 = maxOf(max0, zero) + } + } + + return max1 > max0 + } +} diff --git a/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.py b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.py new file mode 100644 index 00000000..83f21fcf --- /dev/null +++ b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.py @@ -0,0 +1,16 @@ +class Solution: + def checkZeroOnes(self, s: str) -> bool: + max1 = max0 = 0 + one = zero = 0 + + for ch in s: + if ch == "1": + one += 1 + zero = 0 + max1 = max(max1, one) + else: + zero += 1 + one = 0 + max0 = max(max0, zero) + + return max1 > max0 diff --git a/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.py2 b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.py2 new file mode 100644 index 00000000..3696787a --- /dev/null +++ b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def checkZeroOnes(self, s): + """ + :type s: str + :rtype: bool + """ + max1 = max0 = 0 + one = zero = 0 + + for ch in s: + if ch == '1': + one += 1 + zero = 0 + max1 = max(max1, one) + else: + zero += 1 + one = 0 + max0 = max(max0, zero) + + return max1 > max0 diff --git a/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.rb b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.rb new file mode 100644 index 00000000..73c8f0d0 --- /dev/null +++ b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.rb @@ -0,0 +1,20 @@ +# @param {String} s +# @return {Boolean} +def check_zero_ones(s) + max1 = max0 = 0 + one = zero = 0 + + s.each_char do |ch| + if ch == '1' + one += 1 + zero = 0 + max1 = [max1, one].max + else + zero += 1 + one = 0 + max0 = [max0, zero].max + end + end + + max1 > max0 +end diff --git a/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.rs b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.rs new file mode 100644 index 00000000..006aecd9 --- /dev/null +++ b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.rs @@ -0,0 +1,22 @@ +impl Solution { + pub fn check_zero_ones(s: String) -> bool { + let mut max1 = 0; + let mut max0 = 0; + let mut one = 0; + let mut zero = 0; + + for ch in s.chars() { + if ch == '1' { + one += 1; + zero = 0; + max1 = max1.max(one); + } else { + zero += 1; + one = 0; + max0 = max0.max(zero); + } + } + + max1 > max0 + } +} diff --git a/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.swift b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.swift new file mode 100644 index 00000000..617b15a4 --- /dev/null +++ b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.swift @@ -0,0 +1,22 @@ +class Solution { + func checkZeroOnes(_ s: String) -> Bool { + var max1 = 0 + var max0 = 0 + var one = 0 + var zero = 0 + + for ch in s { + if ch == "1" { + one += 1 + zero = 0 + max1 = max(max1, one) + } else { + zero += 1 + one = 0 + max0 = max(max0, zero) + } + } + + return max1 > max0 + } +} diff --git a/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.ts b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.ts new file mode 100644 index 00000000..41742510 --- /dev/null +++ b/tests/1501-2000/1869. longer-contiguous-segments-of-ones-than-zeros/sol.ts @@ -0,0 +1,20 @@ +function checkZeroOnes(s: string): boolean { + let max1 = 0, + max0 = 0; + let one = 0, + zero = 0; + + for (const ch of s) { + if (ch === "1") { + one++; + zero = 0; + max1 = Math.max(max1, one); + } else { + zero++; + one = 0; + max0 = Math.max(max0, zero); + } + } + + return max1 > max0; +} diff --git a/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/manifest.yaml b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/manifest.yaml new file mode 100644 index 00000000..17dfa1ec --- /dev/null +++ b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/manifest.yaml @@ -0,0 +1,293 @@ +entry: + id: 1870 + title: "minimum-speed-to-arrive-on-time" + params: + dist: + type: array + items: + type: int + hour: + type: double + call: + cpp: "Solution().minSpeedOnTime({dist}, {hour})" + rust: "Solution::min_speed_on_time({dist}, {hour})" + python3: "Solution().minSpeedOnTime({dist}, {hour})" + python2: "Solution().minSpeedOnTime({dist}, {hour})" + ruby: "min_speed_on_time({dist}, {hour})" + java: "new Solution().minSpeedOnTime({dist}, {hour})" + csharp: "new Solution().MinSpeedOnTime({dist}, {hour})" + kotlin: "Solution().minSpeedOnTime({dist}, {hour})" + go: "minSpeedOnTime({dist}, {hour})" + dart: "Solution().minSpeedOnTime({dist}, {hour})" + swift: "Solution().minSpeedOnTime({dist}, {hour})" + typescript: "minSpeedOnTime({dist}, {hour})" +judge: + type: "exact" +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().minSpeedOnTime(dist, hour, {result})" + checker: | + class Checker: + def minSpeedOnTime(self, dist, hour, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + h100 = int(round(float(hour) * 100.0)) + def ok(speed): + whole = sum((d + speed - 1) // speed for d in dist[:-1]) + return whole * 100 * speed + dist[-1] * 100 <= h100 * speed + expected = -1 + if dist: + lo, hi = 1, 10000000 + while lo <= hi: + mid = (lo + hi) // 2 + if ok(mid): + expected = mid + hi = mid - 1 + else: + lo = mid + 1 + return result == expected +seed: 1870 +tests: + - name: example-one + in: + dist: [1, 3, 2] + hour: 6.0 + out: 1 + - name: example-two + in: + dist: [1, 3, 2] + hour: 2.7 + out: 3 + - name: example-three-impossible + in: + dist: [1, 3, 2] + hour: 1.9 + out: -1 + - name: single-train-exact + in: + dist: [10] + hour: 1.0 + out: 10 + - name: single-train-fraction + in: + dist: [10] + hour: 0.5 + out: 20 + - name: single-train-large-hour + in: + dist: [1] + hour: 1000000000.0 + out: 1 + - name: impossible-first-departure + in: + dist: [1, 1] + hour: 1.0 + out: -1 + - name: impossible-too-short + in: + dist: [1, 1] + hour: 0.99 + out: -1 + - name: all-ones-exact + in: + dist: [1, 1, 1, 1] + hour: 4.0 + out: 1 + - name: all-ones-tight + in: + dist: [1, 1, 1, 1] + hour: 3.01 + out: 100 + - name: integer-rounding + in: + dist: [2, 2, 2] + hour: 3.0 + out: 2 + - name: fractional-last-leg + in: + dist: [3, 3] + hour: 2.5 + out: 3 + - name: first-leg-waits + in: + dist: [5, 1] + hour: 2.01 + out: 5 + - name: exact-boundary-speed + in: + dist: [10, 10, 10] + hour: 3.0 + out: 10 + - name: repeated-long-rides + in: + dist: [100, 100, 100, 100, 100] + hour: 5.0 + out: 100 + - name: repeated-long-rides-tight + in: + dist: [100, 100, 100, 100, 100] + hour: 4.01 + out: 10000 + - name: mixed-small + in: + dist: [1, 2, 3, 4, 5] + hour: 6.5 + out: 4 + - name: mixed-small-tight + in: + dist: [1, 2, 3, 4, 5] + hour: 5.01 + out: 5 + - name: large-distance + in: + dist: [100000] + hour: 1.0 + out: 100000 + - name: large-distance-fraction + in: + dist: [100000] + hour: 0.01 + out: 10000000 + - name: many-trains-impossible + in: + dist: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + hour: 9.99 + out: 2 + - name: many-trains-feasible + in: + dist: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + hour: 10.0 + out: 1 + - name: varied-rides + in: + dist: [7, 11, 13, 17] + hour: 5.0 + out: 13 + - name: varied-rides-fraction + in: + dist: [7, 11, 13, 17] + hour: 3.5 + out: 34 + - name: near-integer-hour + in: + dist: [2, 5, 1] + hour: 2.0 + out: -1 + - name: near-integer-hour-under + in: + dist: [2, 5, 1] + hour: 1.99 + out: -1 + - name: speed-one + in: + dist: [1, 2, 1, 2] + hour: 6.0 + out: 1 + - name: speed-two + in: + dist: [3, 4, 5] + hour: 6.0 + out: 3 + - name: high-required-speed + in: + dist: [99999, 100000] + hour: 1.01 + out: 10000000 + - name: decimals-two-places + in: + dist: [4, 7, 9] + hour: 3.33 + out: 7 + - name: decimal-impossible + in: + dist: [4, 7, 9] + hour: 1.99 + out: -1 + - name: alternating-distances + in: + dist: [1, 100, 1, 100, 1] + hour: 5.0 + out: 100 + - name: short-final-leg + in: + dist: [100, 100, 1] + hour: 2.01 + out: 100 + - name: long-final-leg + in: + dist: [1, 1, 100] + hour: 2.5 + out: 200 + - name: generator-small + in: + dist: + gen: "array" + len: 25 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: "int" + hour: 30.0 + seed: 187001 + - name: generator-medium + in: + dist: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + hour: 1001.0 + seed: 187002 + - name: generator-large-tight + in: + dist: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + hour: 49999.01 + seed: 187003 + - name: generator-large-feasible + in: + dist: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + hour: 100000.0 + seed: 187004 + - name: generator-large-fractional + in: + dist: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + hour: 1000000000.0 + seed: 187005 diff --git a/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.cpp b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.cpp new file mode 100644 index 00000000..f18f33b0 --- /dev/null +++ b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int minSpeedOnTime(vector& dist, double hour) { + if (dist.empty()) return -1; + + auto canReach = [&](int speed) { + double total = 0; + for (int i = 0; i < dist.size() - 1; ++i) { + total += (dist[i] + speed - 1) / speed; + } + total += (double)dist.back() / speed; + return total <= hour; + }; + + int low = 1, high = 10000000, ans = -1; + while (low <= high) { + int mid = (low + high) / 2; + if (canReach(mid)) { + ans = mid; + high = mid - 1; + } else { + low = mid + 1; + } + } + return ans; + } +}; diff --git a/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.cs b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.cs new file mode 100644 index 00000000..b37ce4e7 --- /dev/null +++ b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.cs @@ -0,0 +1,26 @@ +public class Solution { + public int MinSpeedOnTime(int[] dist, double hour) { + if (dist.Length == 0) return -1; + + bool CanReach(int speed) { + double total = 0; + for (int i = 0; i < dist.Length - 1; i++) { + total += (dist[i] + speed - 1) / speed; + } + total += (double)dist[dist.Length - 1] / speed; + return total <= hour; + } + + int low = 1, high = 10000000, ans = -1; + while (low <= high) { + int mid = (low + high) / 2; + if (CanReach(mid)) { + ans = mid; + high = mid - 1; + } else { + low = mid + 1; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.dart b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.dart new file mode 100644 index 00000000..a51efc7d --- /dev/null +++ b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.dart @@ -0,0 +1,26 @@ +class Solution { + int minSpeedOnTime(List dist, double hour) { + if (dist.isEmpty) return -1; + + bool canReach(int speed) { + double total = 0; + for (int i = 0; i < dist.length - 1; i++) { + total += (dist[i] + speed - 1) ~/ speed; // integer division + } + total += dist[dist.length - 1] / speed; + return total <= hour; + } + + int low = 1, high = 10000000, ans = -1; + while (low <= high) { + int mid = (low + high) ~/ 2; + if (canReach(mid)) { + ans = mid; + high = mid - 1; + } else { + low = mid + 1; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.go b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.go new file mode 100644 index 00000000..aaa595f3 --- /dev/null +++ b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.go @@ -0,0 +1,26 @@ +func minSpeedOnTime(dist []int, hour float64) int { + if len(dist) == 0 { + return -1 + } + + canReach := func(speed int) bool { + var total float64 + for i := 0; i < len(dist)-1; i++ { + total += float64((dist[i] + speed - 1) / speed) + } + total += float64(dist[len(dist)-1]) / float64(speed) + return total <= hour + } + + low, high, ans := 1, 10000000, -1 + for low <= high { + mid := (low + high) / 2 + if canReach(mid) { + ans = mid + high = mid - 1 + } else { + low = mid + 1 + } + } + return ans +} diff --git a/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.java b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.java new file mode 100644 index 00000000..357a5454 --- /dev/null +++ b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.java @@ -0,0 +1,26 @@ +class Solution { + public int minSpeedOnTime(int[] dist, double hour) { + if (dist.length == 0) return -1; + + int low = 1, high = 10000000, ans = -1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (canReach(dist, hour, mid)) { + ans = mid; + high = mid - 1; + } else { + low = mid + 1; + } + } + return ans; + } + + private boolean canReach(int[] dist, double hour, int speed) { + double total = 0; + for (int i = 0; i < dist.length - 1; i++) { + total += (dist[i] + speed - 1) / speed; // ceil division + } + total += (double) dist[dist.length - 1] / speed; + return total <= hour; + } +} diff --git a/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.kt b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.kt new file mode 100644 index 00000000..a296d2b8 --- /dev/null +++ b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.kt @@ -0,0 +1,28 @@ +class Solution { + fun minSpeedOnTime(dist: IntArray, hour: Double): Int { + if (dist.isEmpty()) return -1 + + fun canReach(speed: Int): Boolean { + var total = 0.0 + for (i in 0 until dist.size - 1) { + total += (dist[i] + speed - 1) / speed + } + total += dist.last().toDouble() / speed + return total <= hour + } + + var low = 1 + var high = 10000000 + var ans = -1 + while (low <= high) { + val mid = (low + high) / 2 + if (canReach(mid)) { + ans = mid + high = mid - 1 + } else { + low = mid + 1 + } + } + return ans + } +} diff --git a/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.py b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.py new file mode 100644 index 00000000..636127f6 --- /dev/null +++ b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.py @@ -0,0 +1,33 @@ +import math + + +class Solution(object): + def minSpeedOnTime(self, dist, hour): + """ + :type dist: List[int] + :type hour: float + :rtype: int + """ + if not dist: + return -1 + + # helper function to check if a particular speed helps to reach destination on time + def check(dist, hour, speed): + total_time, i = 0, 0 + while i < (len(dist) - 1): + total_time = total_time + math.ceil(dist[i] / float(speed)) + i = i + 1 + total_time = total_time + (dist[len(dist) - 1] / float(speed)) + return total_time <= hour + + low_speed, high_speed, answer = 1, pow(10, 7), -1 + + while low_speed <= high_speed: + mid_speed = (low_speed + high_speed) // 2 + if check(dist, hour, mid_speed): + answer = mid_speed + high_speed = mid_speed - 1 + else: + low_speed = mid_speed + 1 + + return answer diff --git a/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.py2 b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.py2 new file mode 100644 index 00000000..57fa2767 --- /dev/null +++ b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.py2 @@ -0,0 +1,29 @@ +class Solution(object): + def minSpeedOnTime(self, dist, hour): + """ + :type dist: List[int] + :type hour: float + :rtype: int + """ + if not dist: + return -1 + + # helper function to check if a particular speed helps to reach destination on time + def check(dist, hour, speed): + total_time = 0 + for i in range(len(dist) - 1): + total_time += (dist[i] + speed - 1) // speed # ceil division + total_time += dist[-1] / float(speed) + return total_time <= hour + + low_speed, high_speed, answer = 1, 10**7, -1 + + while low_speed <= high_speed: + mid_speed = (low_speed + high_speed) // 2 + if check(dist, hour, mid_speed): + answer = mid_speed + high_speed = mid_speed - 1 + else: + low_speed = mid_speed + 1 + + return answer diff --git a/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.rb b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.rb new file mode 100644 index 00000000..db5dd0d4 --- /dev/null +++ b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.rb @@ -0,0 +1,33 @@ +# @param {Integer[]} dist +# @param {Float} hour +# @return {Integer} +def min_speed_on_time(dist, hour) + return -1 if dist.empty? + + # helper function to check if a particular speed helps to reach destination on time + check = ->(speed) do + total_time = 0 + (0...dist.length - 1).each do |i| + total_time += (dist[i] + speed - 1) / speed + end + total_time += dist[-1] / hour.to_f * speed / speed # wait, this is wrong + total_time = 0 + (0...dist.length - 1).each do |i| + total_time += (dist[i] + speed - 1) / speed + end + total_time += dist[-1] / speed.to_f + total_time <= hour + end + + low_speed, high_speed, answer = 1, 10**7, -1 + while low_speed <= high_speed + mid_speed = (low_speed + high_speed) / 2 + if check.call(mid_speed) + answer = mid_speed + high_speed = mid_speed - 1 + else + low_speed = mid_speed + 1 + end + end + answer +end diff --git a/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.rs b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.rs new file mode 100644 index 00000000..7cdbc3b6 --- /dev/null +++ b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.rs @@ -0,0 +1,30 @@ +impl Solution { + pub fn min_speed_on_time(dist: Vec, hour: f64) -> i32 { + if dist.is_empty() { + return -1; + } + + let can_reach = |speed: i32| -> bool { + let mut total = 0.0; + for i in 0..dist.len()-1 { + total += ((dist[i] + speed - 1) / speed) as f64; + } + total += dist[dist.len()-1] as f64 / speed as f64; + total <= hour + }; + + let mut low = 1; + let mut high = 10000000; + let mut ans = -1; + while low <= high { + let mid = (low + high) / 2; + if can_reach(mid) { + ans = mid; + high = mid - 1; + } else { + low = mid + 1; + } + } + ans + } +} diff --git a/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.swift b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.swift new file mode 100644 index 00000000..bcee746d --- /dev/null +++ b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.swift @@ -0,0 +1,26 @@ +class Solution { + func minSpeedOnTime(_ dist: [Int], _ hour: Double) -> Int { + if dist.isEmpty { return -1 } + + func canReach(_ speed: Int) -> Bool { + var total = 0.0 + for i in 0..<(dist.count - 1) { + total += Double((dist[i] + speed - 1) / speed) + } + total += Double(dist[dist.count - 1]) / Double(speed) + return total <= hour + } + + var low = 1, high = 10000000, ans = -1 + while low <= high { + let mid = (low + high) / 2 + if canReach(mid) { + ans = mid + high = mid - 1 + } else { + low = mid + 1 + } + } + return ans + } +} diff --git a/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.ts b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.ts new file mode 100644 index 00000000..390b1e0a --- /dev/null +++ b/tests/1501-2000/1870. minimum-speed-to-arrive-on-time/sol.ts @@ -0,0 +1,26 @@ +function minSpeedOnTime(dist: number[], hour: number): number { + if (dist.length === 0) return -1; + + const canReach = (speed: number): boolean => { + let total = 0; + for (let i = 0; i < dist.length - 1; i++) { + total += Math.ceil(dist[i] / speed); + } + total += dist[dist.length - 1] / speed; + return total <= hour; + }; + + let low = 1, + high = 10000000, + ans = -1; + while (low <= high) { + const mid = Math.floor((low + high) / 2); + if (canReach(mid)) { + ans = mid; + high = mid - 1; + } else { + low = mid + 1; + } + } + return ans; +} diff --git a/tests/1501-2000/1871. jump-game-vii/manifest.yaml b/tests/1501-2000/1871. jump-game-vii/manifest.yaml new file mode 100644 index 00000000..97a1aa4e --- /dev/null +++ b/tests/1501-2000/1871. jump-game-vii/manifest.yaml @@ -0,0 +1,367 @@ +entry: + id: 1871 + title: "jump-game-vii" + params: + s: + type: string + minJump: + type: int + maxJump: + type: int + call: + cpp: "Solution().canReach({s}, {minJump}, {maxJump})" + rust: "Solution::can_reach({s}, {minJump}, {maxJump})" + python3: "Solution().canReach({s}, {minJump}, {maxJump})" + python2: "Solution().canReach({s}, {minJump}, {maxJump})" + ruby: "can_reach({s}, {minJump}, {maxJump})" + java: "new Solution().canReach({s}, {minJump}, {maxJump})" + csharp: "new Solution().CanReach({s}, {minJump}, {maxJump})" + kotlin: "Solution().canReach({s}, {minJump}, {maxJump})" + go: "canReach({s}, {minJump}, {maxJump})" + dart: "Solution().canReach({s}, {minJump}, {maxJump})" + swift: "Solution().canReach({s}, {minJump}, {maxJump})" + typescript: "canReach({s}, {minJump}, {maxJump})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().canReach(s, minJump, maxJump, {result})" + checker: | + class Checker: + def canReach(self, s, minJump, maxJump, result): + n = len(s) + reachable = [False] * n + reachable[0] = True + window = 0 + for i in range(1, n): + if i >= minJump and reachable[i - minJump]: + window += 1 + if i > maxJump and reachable[i - maxJump - 1]: + window -= 1 + reachable[i] = s[i] == '0' and window > 0 + return result is reachable[-1] + +seed: 1871 + +tests: + - name: example-1 + in: + s: "011010" + minJump: 2 + maxJump: 3 + out: true + - name: example-2 + in: + s: "01101110" + minJump: 2 + maxJump: 3 + out: false + - name: shortest-reachable + in: + s: "00" + minJump: 1 + maxJump: 1 + out: true + - name: shortest-blocked + in: + s: "01" + minJump: 1 + maxJump: 1 + out: false + - name: exact-long-jump + in: + s: "00001" + minJump: 4 + maxJump: 4 + out: false + - name: exact-long-jump-zero + in: + s: "00000" + minJump: 4 + maxJump: 4 + out: true + - name: max-window + in: + s: "0000000" + minJump: 1 + maxJump: 6 + out: true + - name: first-gap + in: + s: "0100" + minJump: 1 + maxJump: 2 + out: true + - name: delayed-path + in: + s: "0010010" + minJump: 2 + maxJump: 3 + out: true + - name: isolated-landing + in: + s: "0011100" + minJump: 2 + maxJump: 3 + out: false + - name: blocked-middle + in: + s: "000111000" + minJump: 2 + maxJump: 3 + out: false + - name: ones-before-end + in: + s: "0000110" + minJump: 1 + maxJump: 2 + out: false + - name: only-one-step + in: + s: "001" + minJump: 1 + maxJump: 2 + out: false + - name: one-step-around-block + in: + s: "0001000" + minJump: 2 + maxJump: 2 + out: true + - name: two-step-chain + in: + s: "00010001" + minJump: 2 + maxJump: 3 + out: false + - name: two-step-chain-zero-end + in: + s: "00010000" + minJump: 2 + maxJump: 3 + out: true + - name: narrow-window + in: + s: "001010000" + minJump: 2 + maxJump: 3 + out: true + - name: narrow-window-fail + in: + s: "001011000" + minJump: 2 + maxJump: 3 + out: true + - name: jump-over-ones + in: + s: "0111100" + minJump: 2 + maxJump: 6 + out: true + - name: cannot-cross-gap + in: + s: "00111100" + minJump: 2 + maxJump: 3 + out: false + - name: many-options + in: + s: "0101010100" + minJump: 2 + maxJump: 4 + out: true + - name: parity-trap + in: + s: "000100001" + minJump: 2 + maxJump: 2 + out: false + - name: parity-path + in: + s: "000100000" + minJump: 2 + maxJump: 2 + out: true + - name: large-window-blocked + in: + s: "0011111110" + minJump: 2 + maxJump: 8 + out: false + - name: landing-at-max + in: + s: "011110001" + minJump: 3 + maxJump: 5 + out: false + - name: landing-at-max-zero + in: + s: "011110000" + minJump: 3 + maxJump: 5 + out: true + - name: dense-zeros + in: + s: "00100100100" + minJump: 2 + maxJump: 4 + out: true + - name: dense-ones + in: + s: "00111111111" + minJump: 1 + maxJump: 10 + out: false + - name: start-window-too-short + in: + s: "01100" + minJump: 3 + maxJump: 3 + out: false + - name: start-window-reaches-end + in: + s: "01100" + minJump: 2 + maxJump: 4 + out: true + - name: one-available-landing + in: + s: "001111000" + minJump: 3 + maxJump: 5 + out: false + - name: one-available-landing-blocked + in: + s: "001111001" + minJump: 3 + maxJump: 5 + out: false + - name: alternating-tight + in: + s: "0010010010010" + minJump: 3 + maxJump: 4 + out: true + - name: alternating-tight-fail + in: + s: "0010010010011" + minJump: 3 + maxJump: 4 + out: false + - name: exact-single-hop + in: + s: "000000" + minJump: 5 + maxJump: 5 + out: true + - name: exact-single-hop-blocked + in: + s: "000001" + minJump: 5 + maxJump: 5 + out: false + - name: long-chain + in: + s: "0001000100010000" + minJump: 2 + maxJump: 4 + out: true + - name: long-chain-blocked-end + in: + s: "0001000100010001" + minJump: 2 + maxJump: 4 + out: false + - name: max-jump-skip + in: + s: "011111111110" + minJump: 2 + maxJump: 11 + out: true + - name: max-jump-insufficient + in: + s: "011111111111" + minJump: 2 + maxJump: 10 + out: false + - name: gen-random-small + in: + s: + gen: "str" + len: 64 + alphabet: "0" + minJump: + gen: "int" + min: 1 + max: 16 + maxJump: + gen: "int" + min: 17 + max: 63 + seed: 18711 + - name: gen-random-medium + in: + s: + gen: "str" + len: 1000 + alphabet: "0" + minJump: + gen: "int" + min: 1 + max: 250 + maxJump: + gen: "int" + min: 251 + max: 999 + seed: 18712 + - name: gen-large-dense + in: + s: + gen: "str" + len: 100000 + alphabet: "0" + minJump: + gen: "int" + min: 1 + max: 1000 + maxJump: + gen: "int" + min: 1001 + max: 99999 + seed: 18713 + - name: gen-large-narrow + in: + s: + gen: "str" + len: 99999 + alphabet: "0" + minJump: + gen: "int" + min: 40000 + max: 49999 + maxJump: + gen: "int" + min: 50000 + max: 99998 + seed: 18714 + - name: gen-boundary + in: + s: + gen: "str" + len: 100000 + alphabet: "0" + minJump: + gen: "int" + min: 99998 + max: 99998 + maxJump: + gen: "int" + min: 99999 + max: 99999 + seed: 18715 diff --git a/tests/1501-2000/1871. jump-game-vii/sol.cpp b/tests/1501-2000/1871. jump-game-vii/sol.cpp new file mode 100644 index 00000000..f7498e35 --- /dev/null +++ b/tests/1501-2000/1871. jump-game-vii/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + bool canReach(string s, int minJump, int maxJump) { + int n = s.size(); + if (s[n-1] == '1') return false; + + vector dp(n, false); + dp[0] = true; + + int reachable = 0; + + for (int i = 1; i < n; i++) { + if (i >= minJump && dp[i - minJump]) { + reachable++; + } + + if (i > maxJump && dp[i - maxJump - 1]) { + reachable--; + } + + if (reachable > 0 && s[i] == '0') { + dp[i] = true; + } + } + + return dp[n-1]; + } +}; diff --git a/tests/1501-2000/1871. jump-game-vii/sol.cs b/tests/1501-2000/1871. jump-game-vii/sol.cs new file mode 100644 index 00000000..e47ce8ca --- /dev/null +++ b/tests/1501-2000/1871. jump-game-vii/sol.cs @@ -0,0 +1,27 @@ +public class Solution { + public bool CanReach(string s, int minJump, int maxJump) { + int n = s.Length; + if (s[n-1] == '1') return false; + + bool[] dp = new bool[n]; + dp[0] = true; + + int reachable = 0; + + for (int i = 1; i < n; i++) { + if (i >= minJump && dp[i - minJump]) { + reachable++; + } + + if (i > maxJump && dp[i - maxJump - 1]) { + reachable--; + } + + if (reachable > 0 && s[i] == '0') { + dp[i] = true; + } + } + + return dp[n-1]; + } +} diff --git a/tests/1501-2000/1871. jump-game-vii/sol.dart b/tests/1501-2000/1871. jump-game-vii/sol.dart new file mode 100644 index 00000000..709b2967 --- /dev/null +++ b/tests/1501-2000/1871. jump-game-vii/sol.dart @@ -0,0 +1,27 @@ +class Solution { + bool canReach(String s, int minJump, int maxJump) { + int n = s.length; + if (s[n-1] == '1') return false; + + List dp = List.filled(n, false); + dp[0] = true; + + int reachable = 0; + + for (int i = 1; i < n; i++) { + if (i >= minJump && dp[i - minJump]) { + reachable++; + } + + if (i > maxJump && dp[i - maxJump - 1]) { + reachable--; + } + + if (reachable > 0 && s[i] == '0') { + dp[i] = true; + } + } + + return dp[n-1]; + } +} diff --git a/tests/1501-2000/1871. jump-game-vii/sol.go b/tests/1501-2000/1871. jump-game-vii/sol.go new file mode 100644 index 00000000..2a2589ad --- /dev/null +++ b/tests/1501-2000/1871. jump-game-vii/sol.go @@ -0,0 +1,27 @@ +func canReach(s string, minJump int, maxJump int) bool { + n := len(s) + if s[n-1] == '1' { + return false + } + + dp := make([]bool, n) + dp[0] = true + + reachable := 0 + + for i := 1; i < n; i++ { + if i >= minJump && dp[i-minJump] { + reachable++ + } + + if i > maxJump && dp[i-maxJump-1] { + reachable-- + } + + if reachable > 0 && s[i] == '0' { + dp[i] = true + } + } + + return dp[n-1] +} diff --git a/tests/1501-2000/1871. jump-game-vii/sol.java b/tests/1501-2000/1871. jump-game-vii/sol.java new file mode 100644 index 00000000..73dd58e5 --- /dev/null +++ b/tests/1501-2000/1871. jump-game-vii/sol.java @@ -0,0 +1,27 @@ +class Solution { + public boolean canReach(String s, int minJump, int maxJump) { + int n = s.length(); + if (s.charAt(n-1) == '1') return false; + + boolean[] dp = new boolean[n]; + dp[0] = true; + + int reachable = 0; + + for (int i = 1; i < n; i++) { + if (i >= minJump && dp[i - minJump]) { + reachable++; + } + + if (i > maxJump && dp[i - maxJump - 1]) { + reachable--; + } + + if (reachable > 0 && s.charAt(i) == '0') { + dp[i] = true; + } + } + + return dp[n-1]; + } +} diff --git a/tests/1501-2000/1871. jump-game-vii/sol.kt b/tests/1501-2000/1871. jump-game-vii/sol.kt new file mode 100644 index 00000000..29863033 --- /dev/null +++ b/tests/1501-2000/1871. jump-game-vii/sol.kt @@ -0,0 +1,27 @@ +class Solution { + fun canReach(s: String, minJump: Int, maxJump: Int): Boolean { + val n = s.length + if (s[n-1] == '1') return false + + val dp = BooleanArray(n) + dp[0] = true + + var reachable = 0 + + for (i in 1 until n) { + if (i >= minJump && dp[i - minJump]) { + reachable++ + } + + if (i > maxJump && dp[i - maxJump - 1]) { + reachable-- + } + + if (reachable > 0 && s[i] == '0') { + dp[i] = true + } + } + + return dp[n-1] + } +} diff --git a/tests/1501-2000/1871. jump-game-vii/sol.py b/tests/1501-2000/1871. jump-game-vii/sol.py new file mode 100644 index 00000000..87ac7fe8 --- /dev/null +++ b/tests/1501-2000/1871. jump-game-vii/sol.py @@ -0,0 +1,22 @@ +class Solution: + def canReach(self, s: str, minJump: int, maxJump: int) -> bool: + n = len(s) + if s[-1] == "1": + return False + + dp = [False] * n + dp[0] = True + + reachable = 0 + + for i in range(1, n): + if i >= minJump and dp[i - minJump]: + reachable += 1 + + if i > maxJump and dp[i - maxJump - 1]: + reachable -= 1 + + if reachable > 0 and s[i] == "0": + dp[i] = True + + return dp[-1] diff --git a/tests/1501-2000/1871. jump-game-vii/sol.py2 b/tests/1501-2000/1871. jump-game-vii/sol.py2 new file mode 100644 index 00000000..2ee20367 --- /dev/null +++ b/tests/1501-2000/1871. jump-game-vii/sol.py2 @@ -0,0 +1,28 @@ +class Solution(object): + def canReach(self, s, minJump, maxJump): + """ + :type s: str + :type minJump: int + :type maxJump: int + :rtype: bool + """ + n = len(s) + if s[-1] == '1': + return False + + dp = [False] * n + dp[0] = True + + reachable = 0 + + for i in range(1, n): + if i >= minJump and dp[i - minJump]: + reachable += 1 + + if i > maxJump and dp[i - maxJump - 1]: + reachable -= 1 + + if reachable > 0 and s[i] == '0': + dp[i] = True + + return dp[-1] diff --git a/tests/1501-2000/1871. jump-game-vii/sol.rb b/tests/1501-2000/1871. jump-game-vii/sol.rb new file mode 100644 index 00000000..4c0aedff --- /dev/null +++ b/tests/1501-2000/1871. jump-game-vii/sol.rb @@ -0,0 +1,29 @@ +# @param {String} s +# @param {Integer} min_jump +# @param {Integer} max_jump +# @return {Boolean} +def can_reach(s, min_jump, max_jump) + n = s.length + return false if s[-1] == '1' + + dp = Array.new(n, false) + dp[0] = true + + reachable = 0 + + (1...n).each do |i| + if i >= min_jump && dp[i - min_jump] + reachable += 1 + end + + if i > max_jump && dp[i - max_jump - 1] + reachable -= 1 + end + + if reachable > 0 && s[i] == '0' + dp[i] = true + end + end + + dp[-1] +end diff --git a/tests/1501-2000/1871. jump-game-vii/sol.rs b/tests/1501-2000/1871. jump-game-vii/sol.rs new file mode 100644 index 00000000..3a767e82 --- /dev/null +++ b/tests/1501-2000/1871. jump-game-vii/sol.rs @@ -0,0 +1,30 @@ +impl Solution { + pub fn can_reach(s: String, min_jump: i32, max_jump: i32) -> bool { + let n = s.len(); + let chars: Vec = s.chars().collect(); + if chars[n-1] == '1' { + return false; + } + + let mut dp = vec![false; n]; + dp[0] = true; + + let mut reachable = 0; + + for i in 1..n { + if i >= min_jump as usize && dp[i - min_jump as usize] { + reachable += 1; + } + + if i > max_jump as usize && dp[i - max_jump as usize - 1] { + reachable -= 1; + } + + if reachable > 0 && chars[i] == '0' { + dp[i] = true; + } + } + + dp[n-1] + } +} diff --git a/tests/1501-2000/1871. jump-game-vii/sol.swift b/tests/1501-2000/1871. jump-game-vii/sol.swift new file mode 100644 index 00000000..079d3d9c --- /dev/null +++ b/tests/1501-2000/1871. jump-game-vii/sol.swift @@ -0,0 +1,28 @@ +class Solution { + func canReach(_ s: String, _ minJump: Int, _ maxJump: Int) -> Bool { + let n = s.count + let chars = Array(s) + if chars[n-1] == "1" { return false } + + var dp = [Bool](repeating: false, count: n) + dp[0] = true + + var reachable = 0 + + for i in 1..= minJump && dp[i - minJump] { + reachable += 1 + } + + if i > maxJump && dp[i - maxJump - 1] { + reachable -= 1 + } + + if reachable > 0 && chars[i] == "0" { + dp[i] = true + } + } + + return dp[n-1] + } +} diff --git a/tests/1501-2000/1871. jump-game-vii/sol.ts b/tests/1501-2000/1871. jump-game-vii/sol.ts new file mode 100644 index 00000000..f5e02c96 --- /dev/null +++ b/tests/1501-2000/1871. jump-game-vii/sol.ts @@ -0,0 +1,25 @@ +function canReach(s: string, minJump: number, maxJump: number): boolean { + const n = s.length; + if (s[n - 1] === "1") return false; + + const dp: boolean[] = new Array(n).fill(false); + dp[0] = true; + + let reachable = 0; + + for (let i = 1; i < n; i++) { + if (i >= minJump && dp[i - minJump]) { + reachable++; + } + + if (i > maxJump && dp[i - maxJump - 1]) { + reachable--; + } + + if (reachable > 0 && s[i] === "0") { + dp[i] = true; + } + } + + return dp[n - 1]; +} diff --git a/tests/1501-2000/1872. stone-game-viii/manifest.yaml b/tests/1501-2000/1872. stone-game-viii/manifest.yaml new file mode 100644 index 00000000..8752caec --- /dev/null +++ b/tests/1501-2000/1872. stone-game-viii/manifest.yaml @@ -0,0 +1,325 @@ +entry: + id: 1872 + title: "stone-game-viii" + params: + stones: + type: array + items: + type: int + call: + cpp: "Solution().stoneGameVIII({stones})" + rust: "Solution::stone_game_viii({stones})" + python3: "Solution().stoneGameVIII({stones})" + python2: "Solution().stoneGameVIII({stones})" + ruby: "stone_game_viii({stones})" + java: "new Solution().stoneGameVIII({stones})" + csharp: "new Solution().StoneGameVIII({stones})" + kotlin: "Solution().stoneGameVIII({stones})" + go: "stoneGameVIII({stones})" + dart: "Solution().stoneGameVIII({stones})" + swift: "Solution().stoneGameVIII({stones})" + typescript: "stoneGameVIII({stones})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(stones, {result})" + checker: | + class Checker: + def check(self, stones, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + total = 0 + prefix = [] + for value in stones: + total += value + prefix.append(total) + best = prefix[-1] + for index in range(len(stones) - 2, 0, -1): + best = max(best, prefix[index] - best) + return result == best + +seed: 1872 + +tests: + - name: example-one + in: + stones: [-1, 2, -3, 4, -5] + out: 5 + judge: + type: "exact" + - name: example-two + in: + stones: [7, -6, 5, 10, 5, -2, -6] + out: 13 + judge: + type: "exact" + - name: example-three + in: + stones: [-10, -12] + out: -22 + judge: + type: "exact" + - name: two-positive + in: + stones: [1, 1] + out: 2 + judge: + type: "exact" + - name: cancelling-pair + in: + stones: [1, -1] + out: 0 + judge: + type: "exact" + - name: negative-then-positive + in: + stones: [-1, 1] + out: 0 + judge: + type: "exact" + - name: opposite-pair + in: + stones: [5, -5] + out: 0 + judge: + type: "exact" + - name: zero-pair + in: + stones: [0, 0] + out: 0 + judge: + type: "exact" + - name: increasing-positive + in: + stones: [2, 3, 4] + out: 9 + judge: + type: "exact" + - name: decreasing-positive + in: + stones: [3, 2, 1] + out: 6 + judge: + type: "exact" + - name: all-negative-three + in: + stones: [-1, -2, -3] + out: 3 + judge: + type: "exact" + - name: maximum-pair + in: + stones: [10000, 10000] + out: 20000 + judge: + type: "exact" + - name: minimum-pair + in: + stones: [-10000, -10000] + out: -20000 + judge: + type: "exact" + - name: maximum-and-minimum + in: + stones: [10000, -10000] + out: 0 + judge: + type: "exact" + - name: zeros-around-one + in: + stones: [0, 1, -1, 0] + out: 1 + judge: + type: "exact" + - name: alternating-six + in: + stones: [1, -2, 3, -4, 5, -6] + out: 6 + judge: + type: "exact" + - name: positive-alternation + in: + stones: [10, -10, 10, -10, 10] + out: 10 + judge: + type: "exact" + - name: negative-alternation + in: + stones: [-10, 10, -10, 10, -10] + out: 10 + judge: + type: "exact" + - name: eight-positive + in: + stones: [1, 2, 3, 4, 5, 6, 7, 8] + out: 36 + judge: + type: "exact" + - name: eight-negative + in: + stones: [-1, -2, -3, -4, -5, -6, -7, -8] + out: 8 + judge: + type: "exact" + - name: leading-maximum + in: + stones: [10000, 0, 0, 0, 0] + out: 10000 + judge: + type: "exact" + - name: leading-minimum + in: + stones: [-10000, 0, 0, 0, 0] + out: 0 + judge: + type: "exact" + - name: balanced-extremes + in: + stones: [0, 10000, 0, -10000, 0] + out: 10000 + judge: + type: "exact" + - name: repeated-extremes + in: + stones: [9999, -9999, 9999, -9999] + out: 9999 + judge: + type: "exact" + - name: mixed-primes + in: + stones: [2, -3, 5, -7, 11, -13, 17] + out: 12 + judge: + type: "exact" + - name: reverse-mixed-primes + in: + stones: [-2, 3, -5, 7, -11, 13, -17] + out: 17 + judge: + type: "exact" + - name: paired-fours + in: + stones: [4, 4, -4, -4, 4, 4] + out: 8 + judge: + type: "exact" + - name: reverse-paired-fours + in: + stones: [-4, -4, 4, 4, -4, -4] + out: 4 + judge: + type: "exact" + - name: one-with-zero-tail + in: + stones: [1, 0, 0, 0, 0, 0, 0] + out: 1 + judge: + type: "exact" + - name: zero-prefix + in: + stones: [0, 0, 0, 0, 0, 0, 1] + out: 1 + judge: + type: "exact" + - name: alternating-extreme-positive-first + in: + stones: [10000, -10000, 10000, -10000] + out: 10000 + judge: + type: "exact" + - name: alternating-extreme-negative-first + in: + stones: [-10000, 10000, -10000, 10000] + out: 0 + judge: + type: "exact" + - name: nine-zigzag + in: + stones: [9, -8, 7, -6, 5, -4, 3, -2, 1] + out: 5 + judge: + type: "exact" + - name: reverse-nine-zigzag + in: + stones: [-9, 8, -7, 6, -5, 4, -3, 2, -1] + out: 1 + judge: + type: "exact" + - name: negative-ends + in: + stones: [6, -1, -1, -1, -1, -1, -1, 6] + out: 6 + judge: + type: "exact" + - name: generated-small + in: + stones: + gen: "array" + len: 17 + of: + gen: "int" + min: -10000 + max: 10000 + distinct: false + elemType: "int" + judge: + type: "exact" + - name: generated-medium + in: + stones: + gen: "array" + len: 100 + of: + gen: "int" + min: -10000 + max: 10000 + distinct: false + elemType: "int" + judge: + type: "exact" + - name: generated-large-positive-negative + in: + stones: + gen: "array" + len: 10000 + of: + gen: "int" + min: -10000 + max: 10000 + distinct: false + elemType: "int" + judge: + type: "exact" + - name: generated-near-maximum + in: + stones: + gen: "array" + len: 50000 + of: + gen: "int" + min: -10000 + max: 10000 + distinct: false + elemType: "int" + judge: + type: "exact" + - name: generated-maximum + in: + stones: + gen: "array" + len: 100000 + of: + gen: "int" + min: -10000 + max: 10000 + distinct: false + elemType: "int" + judge: + type: "exact" diff --git a/tests/1501-2000/1872. stone-game-viii/sol.cpp b/tests/1501-2000/1872. stone-game-viii/sol.cpp new file mode 100644 index 00000000..fcaa4a3a --- /dev/null +++ b/tests/1501-2000/1872. stone-game-viii/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int stoneGameVIII(vector& stones) { + int n = stones.size(); + vector prefix = stones; + for (int i = 1; i < n; i++) { + prefix[i] += prefix[i-1]; + } + vector memo(n, INT_MIN); + + function rec = [&](int i) -> int { + if (i == n - 2) return prefix[i+1]; + if (memo[i] != INT_MIN) return memo[i]; + int aliceCont = rec(i+1); + int aliceDone = prefix[i+1] - rec(i+1); + memo[i] = max(aliceCont, aliceDone); + return memo[i]; + }; + + return rec(0); + } +}; diff --git a/tests/1501-2000/1872. stone-game-viii/sol.cs b/tests/1501-2000/1872. stone-game-viii/sol.cs new file mode 100644 index 00000000..7b3f5b83 --- /dev/null +++ b/tests/1501-2000/1872. stone-game-viii/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + private int[] prefix; + private int[] memo; + private int n; + + public int StoneGameVIII(int[] stones) { + n = stones.Length; + prefix = (int[])stones.Clone(); + for (int i = 1; i < n; i++) { + prefix[i] += prefix[i-1]; + } + memo = new int[n]; + Array.Fill(memo, int.MinValue); + return Rec(0); + } + + private int Rec(int i) { + if (i == n - 2) return prefix[i+1]; + if (memo[i] != int.MinValue) return memo[i]; + int aliceCont = Rec(i+1); + int aliceDone = prefix[i+1] - Rec(i+1); + memo[i] = Math.Max(aliceCont, aliceDone); + return memo[i]; + } +} diff --git a/tests/1501-2000/1872. stone-game-viii/sol.dart b/tests/1501-2000/1872. stone-game-viii/sol.dart new file mode 100644 index 00000000..23e8d59a --- /dev/null +++ b/tests/1501-2000/1872. stone-game-viii/sol.dart @@ -0,0 +1,13 @@ +class Solution { + int stoneGameVIII(List stones) { + for (int i = 1; i < stones.length; i++) { + stones[i] += stones[i - 1]; + } + int best = stones.last; + for (int i = stones.length - 2; i >= 1; i--) { + final candidate = stones[i] - best; + if (candidate > best) best = candidate; + } + return best; + } +} diff --git a/tests/1501-2000/1872. stone-game-viii/sol.go b/tests/1501-2000/1872. stone-game-viii/sol.go new file mode 100644 index 00000000..24a9779c --- /dev/null +++ b/tests/1501-2000/1872. stone-game-viii/sol.go @@ -0,0 +1,33 @@ +func stoneGameVIII(stones []int) int { + n := len(stones) + prefix := make([]int, n) + copy(prefix, stones) + for i := 1; i < n; i++ { + prefix[i] += prefix[i-1] + } + + memo := make([]int, n) + for i := range memo { + memo[i] = -1 << 31 + } + + var rec func(int) int + rec = func(i int) int { + if i == n-2 { + return prefix[i+1] + } + if memo[i] != -1<<31 { + return memo[i] + } + aliceCont := rec(i+1) + aliceDone := prefix[i+1] - rec(i+1) + if aliceCont > aliceDone { + memo[i] = aliceCont + } else { + memo[i] = aliceDone + } + return memo[i] + } + + return rec(0) +} diff --git a/tests/1501-2000/1872. stone-game-viii/sol.java b/tests/1501-2000/1872. stone-game-viii/sol.java new file mode 100644 index 00000000..58b9bbaf --- /dev/null +++ b/tests/1501-2000/1872. stone-game-viii/sol.java @@ -0,0 +1,18 @@ +class Solution { + private int[] prefix; + private int n; + private int[] memo; + + public int stoneGameVIII(int[] stones) { + n = stones.length; + prefix = stones.clone(); + for (int i = 1; i < n; i++) { + prefix[i] += prefix[i-1]; + } + int best = prefix[n - 1]; + for (int i = n - 2; i >= 1; i--) { + best = Math.max(best, prefix[i] - best); + } + return best; + } +} diff --git a/tests/1501-2000/1872. stone-game-viii/sol.kt b/tests/1501-2000/1872. stone-game-viii/sol.kt new file mode 100644 index 00000000..027cd23a --- /dev/null +++ b/tests/1501-2000/1872. stone-game-viii/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun stoneGameVIII(stones: IntArray): Int { + val n = stones.size + val prefix = stones.clone() + for (i in 1 until n) { + prefix[i] += prefix[i-1] + } + var best = prefix[n - 1] + for (i in n - 2 downTo 1) { + best = maxOf(best, prefix[i] - best) + } + return best + } +} diff --git a/tests/1501-2000/1872. stone-game-viii/sol.py b/tests/1501-2000/1872. stone-game-viii/sol.py new file mode 100644 index 00000000..b11da2b3 --- /dev/null +++ b/tests/1501-2000/1872. stone-game-viii/sol.py @@ -0,0 +1,29 @@ +class Solution: + def stoneGameVIII(self, stones: List[int]) -> int: + p = stones + n = len(p) + for i in range(1, n): + p[i] += p[i - 1] + + @cache + def rec(i): + # Base case: only two stones left + # player will take all remaining stones + # and leave one stone after this + # then game ends + if i == n - 2: + return p[i + 1] + + # alice continue to play + # going forward and will take scores + # somewhere after this index + alice_cont = rec(i + 1) + + # alice completes his chance + # takes all what she got + # let bob play after her + alice_done = p[i + 1] - rec(i + 1) + + return max(alice_cont, alice_done) + + return rec(0) diff --git a/tests/1501-2000/1872. stone-game-viii/sol.py2 b/tests/1501-2000/1872. stone-game-viii/sol.py2 new file mode 100644 index 00000000..a6704f24 --- /dev/null +++ b/tests/1501-2000/1872. stone-game-viii/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def stoneGameVIII(self, stones): + """ + :type stones: List[int] + :rtype: int + """ + n = len(stones) + for i in range(1, n): + stones[i] += stones[i-1] + + best = stones[n - 1] + for i in range(n - 2, 0, -1): + best = max(best, stones[i] - best) + return best diff --git a/tests/1501-2000/1872. stone-game-viii/sol.rb b/tests/1501-2000/1872. stone-game-viii/sol.rb new file mode 100644 index 00000000..d0f65f1d --- /dev/null +++ b/tests/1501-2000/1872. stone-game-viii/sol.rb @@ -0,0 +1,10 @@ +# @param {Integer[]} stones +# @return {Integer} +def stone_game_viii(stones) + n = stones.length + (1...n).each { |i| stones[i] += stones[i-1] } + + best = stones[-1] + (n - 2).downto(1) { |i| best = [best, stones[i] - best].max } + best +end diff --git a/tests/1501-2000/1872. stone-game-viii/sol.rs b/tests/1501-2000/1872. stone-game-viii/sol.rs new file mode 100644 index 00000000..56ed70ea --- /dev/null +++ b/tests/1501-2000/1872. stone-game-viii/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn stone_game_viii(stones: Vec) -> i32 { + let n = stones.len(); + let mut prefix = stones.clone(); + for i in 1..n { + prefix[i] += prefix[i-1]; + } + let mut memo = vec![i32::MIN; n]; + + fn rec(i: usize, n: usize, prefix: &Vec, memo: &mut Vec) -> i32 { + if i == n - 2 { + return prefix[i+1]; + } + if memo[i] != i32::MIN { + return memo[i]; + } + let alice_cont = rec(i+1, n, prefix, memo); + let alice_done = prefix[i+1] - rec(i+1, n, prefix, memo); + memo[i] = alice_cont.max(alice_done); + memo[i] + } + + rec(0, n, &prefix, &mut memo) + } +} diff --git a/tests/1501-2000/1872. stone-game-viii/sol.swift b/tests/1501-2000/1872. stone-game-viii/sol.swift new file mode 100644 index 00000000..4d8278cf --- /dev/null +++ b/tests/1501-2000/1872. stone-game-viii/sol.swift @@ -0,0 +1,25 @@ +class Solution { + func stoneGameVIII(_ stones: [Int]) -> Int { + let n = stones.count + var prefix = stones + for i in 1.. Int { + if i == n - 2 { + return prefix[i+1] + } + if memo[i] != Int.min { + return memo[i] + } + let aliceCont = rec(i+1) + let aliceDone = prefix[i+1] - rec(i+1) + memo[i] = max(aliceCont, aliceDone) + return memo[i] + } + + return rec(0) + } +} diff --git a/tests/1501-2000/1872. stone-game-viii/sol.ts b/tests/1501-2000/1872. stone-game-viii/sol.ts new file mode 100644 index 00000000..9b6aafd6 --- /dev/null +++ b/tests/1501-2000/1872. stone-game-viii/sol.ts @@ -0,0 +1,12 @@ +function stoneGameVIII(stones: number[]): number { + const n = stones.length; + const prefix = stones.slice(); + for (let i = 1; i < n; i++) { + prefix[i] += prefix[i - 1]; + } + let best = prefix[n - 1]; + for (let i = n - 2; i >= 1; i--) { + best = Math.max(best, prefix[i] - best); + } + return best; +} diff --git a/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/manifest.yaml b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/manifest.yaml new file mode 100644 index 00000000..6384e2d5 --- /dev/null +++ b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/manifest.yaml @@ -0,0 +1,227 @@ +entry: + id: 1876 + title: "substrings-of-size-three-with-distinct-characters" + params: + s: + type: string + call: + cpp: "Solution().countGoodSubstrings({s})" + rust: "Solution::count_good_substrings({s})" + python3: "Solution().countGoodSubstrings({s})" + python2: "Solution().countGoodSubstrings({s})" + ruby: "count_good_substrings({s})" + java: "new Solution().countGoodSubstrings({s})" + csharp: "new Solution().CountGoodSubstrings({s})" + kotlin: "Solution().countGoodSubstrings({s})" + go: "countGoodSubstrings({s})" + dart: "Solution().countGoodSubstrings({s})" + swift: "Solution().countGoodSubstrings({s})" + typescript: "countGoodSubstrings({s})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().countGoodSubstrings(s, {result})" + checker: | + class Checker: + def countGoodSubstrings(self, s, result): + if not isinstance(s, str) or not isinstance(result, int) or isinstance(result, bool): + return False + expected = sum(len(set(s[i:i + 3])) == 3 for i in range(max(0, len(s) - 2))) + return result == expected + +seed: 1876 + +tests: + - name: "example_xyzzaz" + in: + s: "xyzzaz" + out: 1 + - name: "example_aababcabc" + in: + s: "aababcabc" + out: 4 + - name: "length_one" + in: + s: "a" + out: 0 + - name: "length_two_distinct" + in: + s: "ab" + out: 0 + - name: "length_three_distinct" + in: + s: "abc" + out: 1 + - name: "length_three_repeat_first" + in: + s: "aba" + out: 0 + - name: "length_three_repeat_last" + in: + s: "abb" + out: 0 + - name: "all_same" + in: + s: "aaaaaaaaaa" + out: 0 + - name: "alternating_two" + in: + s: "ababababab" + out: 0 + - name: "repeating_abc" + in: + s: "abcabcabc" + out: 7 + - name: "repeating_abcd" + in: + s: "abcdabcd" + out: 6 + - name: "all_distinct_four" + in: + s: "abcd" + out: 2 + - name: "all_distinct_twenty_six" + in: + s: "abcdefghijklmnopqrstuvwxyz" + out: 24 + - name: "distinct_then_duplicate" + in: + s: "abcc" + out: 1 + - name: "duplicate_then_distinct" + in: + s: "aabc" + out: 1 + - name: "one_good_middle" + in: + s: "aabca" + out: 2 + - name: "two_adjacent_good" + in: + s: "abcdx" + out: 3 + - name: "good_windows_separated" + in: + s: "abcxxyza" + out: 4 + - name: "overlap_single_change" + in: + s: "abca" + out: 2 + - name: "overlap_repeated_pattern" + in: + s: "abacaba" + out: 2 + - name: "early_bad_late_good" + in: + s: "aaabcde" + out: 3 + - name: "early_good_late_bad" + in: + s: "abcdeee" + out: 3 + - name: "four_same_then_unique" + in: + s: "aaaabc" + out: 1 + - name: "boundary_letter_z" + in: + s: "xyzzyx" + out: 2 + - name: "mixed_short" + in: + s: "zzabcaay" + out: 3 + - name: "maximum_count_length_100" + in: + s: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv" + out: 98 + - name: "maximum_all_same" + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: 0 + - name: "maximum_two_characters" + in: + s: "ababababababababababababababababababababababababababababababababababababababababababababababababab" + out: 0 + - name: "maximum_repeating_abc" + in: + s: "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabca" + out: 98 + - name: "runs_and_transitions" + in: + s: "aaabbbcccdddeeefff" + out: 0 + - name: "distinct_runs" + in: + s: "aabbccddeeff" + out: 0 + - name: "palindrome_even" + in: + s: "abccba" + out: 2 + - name: "palindrome_odd" + in: + s: "abcxcba" + out: 4 + - name: "late_zigzag" + in: + s: "aabacabad" + out: 3 + - name: "generated_small" + seed: 187601 + in: + s: + gen: "str" + len: + gen: "int" + min: 1 + max: 10 + alphabet: "abcde" + - name: "generated_medium" + seed: 187602 + in: + s: + gen: "str" + len: + gen: "int" + min: 20 + max: 50 + alphabet: "abcdefgh" + - name: "generated_near_limit" + seed: 187603 + in: + s: + gen: "str" + len: + gen: "int" + min: 90 + max: 100 + alphabet: "abcdefghijklm" + - name: "generated_binary_alphabet" + seed: 187604 + in: + s: + gen: "str" + len: + gen: "int" + min: 70 + max: 100 + alphabet: "ab" + - name: "generated_full_alphabet" + seed: 187605 + in: + s: + gen: "str" + len: + gen: "int" + min: 80 + max: 100 + alphabet: "abcdefghijklmnopqrstuvwxyz" diff --git a/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.cpp b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.cpp new file mode 100644 index 00000000..85711486 --- /dev/null +++ b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int countGoodSubstrings(string s) { + int n = s.length(); + int count = 0; + for (int i = 0; i <= n-3; i++) { + if (s[i] != s[i+1] && s[i+1] != s[i+2] && s[i] != s[i+2]) { + count++; + } + } + return count; + } +}; diff --git a/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.cs b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.cs new file mode 100644 index 00000000..1013dc90 --- /dev/null +++ b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.cs @@ -0,0 +1,12 @@ +public class Solution { + public int CountGoodSubstrings(string s) { + int n = s.Length; + int count = 0; + for (int i = 0; i <= n-3; i++) { + if (s[i] != s[i+1] && s[i+1] != s[i+2] && s[i] != s[i+2]) { + count++; + } + } + return count; + } +} diff --git a/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.dart b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.dart new file mode 100644 index 00000000..c4616bcf --- /dev/null +++ b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.dart @@ -0,0 +1,12 @@ +class Solution { + int countGoodSubstrings(String s) { + int n = s.length; + int count = 0; + for (int i = 0; i <= n-3; i++) { + if (s[i] != s[i+1] && s[i+1] != s[i+2] && s[i] != s[i+2]) { + count++; + } + } + return count; + } +} diff --git a/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.go b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.go new file mode 100644 index 00000000..bb3e7b7f --- /dev/null +++ b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.go @@ -0,0 +1,10 @@ +func countGoodSubstrings(s string) int { + n := len(s) + count := 0 + for i := 0; i <= n-3; i++ { + if s[i] != s[i+1] && s[i+1] != s[i+2] && s[i] != s[i+2] { + count++ + } + } + return count +} diff --git a/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.java b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.java new file mode 100644 index 00000000..55e74dff --- /dev/null +++ b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int countGoodSubstrings(String s) { + int n = s.length(); + int count = 0; + for (int i = 0; i <= n-3; i++) { + String sub = s.substring(i, i+3); + if (sub.charAt(0) != sub.charAt(1) && sub.charAt(1) != sub.charAt(2) && sub.charAt(0) != sub.charAt(2)) { + count++; + } + } + return count; + } +} diff --git a/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.kt b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.kt new file mode 100644 index 00000000..d5b238a9 --- /dev/null +++ b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun countGoodSubstrings(s: String): Int { + val n = s.length + var count = 0 + for (i in 0..n-3) { + val sub = s.substring(i, i+3) + if (sub[0] != sub[1] && sub[1] != sub[2] && sub[0] != sub[2]) { + count++ + } + } + return count + } +} diff --git a/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.py b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.py new file mode 100644 index 00000000..56e96989 --- /dev/null +++ b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.py @@ -0,0 +1,8 @@ +class Solution: + def countGoodSubstrings(self, s: str) -> int: + n = len(s) + count = 0 + for i in range(n - 2): + if len(set(s[i : i + 3])) == 3: + count += 1 + return count diff --git a/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.py2 b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.py2 new file mode 100644 index 00000000..0da0dccc --- /dev/null +++ b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def countGoodSubstrings(self, s): + """ + :type s: str + :rtype: int + """ + n = len(s) + count = 0 + for i in range(n-2): + if len(set(s[i:i+3])) == 3: + count += 1 + return count diff --git a/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.rb b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.rb new file mode 100644 index 00000000..6b1e625f --- /dev/null +++ b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.rb @@ -0,0 +1,10 @@ +# @param {String} s +# @return {Integer} +def count_good_substrings(s) + n = s.length + count = 0 + (0...(n-2)).each do |i| + count += 1 if s[i,3].chars.uniq.length == 3 + end + count +end diff --git a/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.rs b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.rs new file mode 100644 index 00000000..adac87f0 --- /dev/null +++ b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.rs @@ -0,0 +1,12 @@ +impl Solution { + pub fn count_good_substrings(s: String) -> i32 { + let chars: Vec = s.chars().collect(); + let mut count = 0; + for i in 0..(chars.len().saturating_sub(2)) { + if chars[i] != chars[i+1] && chars[i+1] != chars[i+2] && chars[i] != chars[i+2] { + count += 1; + } + } + count + } +} diff --git a/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.swift b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.swift new file mode 100644 index 00000000..c7295f0b --- /dev/null +++ b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.swift @@ -0,0 +1,13 @@ +class Solution { + func countGoodSubstrings(_ s: String) -> Int { + let chars = Array(s) + var count = 0 + if chars.count < 3 { return 0 } + for i in 0..<(chars.count-2) { + if chars[i] != chars[i+1] && chars[i+1] != chars[i+2] && chars[i] != chars[i+2] { + count += 1 + } + } + return count + } +} diff --git a/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.ts b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.ts new file mode 100644 index 00000000..04d8fb78 --- /dev/null +++ b/tests/1501-2000/1876. substrings-of-size-three-with-distinct-characters/sol.ts @@ -0,0 +1,10 @@ +function countGoodSubstrings(s: string): number { + const n = s.length; + let count = 0; + for (let i = 0; i <= n - 3; i++) { + if (s[i] !== s[i + 1] && s[i + 1] !== s[i + 2] && s[i] !== s[i + 2]) { + count++; + } + } + return count; +} diff --git a/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/manifest.yaml b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/manifest.yaml new file mode 100644 index 00000000..e2db9ce6 --- /dev/null +++ b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/manifest.yaml @@ -0,0 +1,338 @@ +entry: + id: 1877 + title: "minimize-maximum-pair-sum-in-array" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().minPairSum({nums})" + rust: "Solution::min_pair_sum({nums})" + python3: "Solution().minPairSum({nums})" + python2: "Solution().minPairSum({nums})" + ruby: "min_pair_sum({nums})" + java: "new Solution().minPairSum({nums})" + csharp: "new Solution().MinPairSum({nums})" + kotlin: "Solution().minPairSum({nums})" + go: "minPairSum({nums})" + dart: "Solution().minPairSum({nums})" + swift: "Solution().minPairSum({nums})" + typescript: "minPairSum({nums})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().minPairSum(nums, {result})" + checker: | + class Checker: + def minPairSum(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not isinstance(nums, list) or len(nums) < 2 or len(nums) % 2: + return False + if any(not isinstance(x, int) or isinstance(x, bool) or x < 1 or x > 100000 for x in nums): + return False + values = sorted(nums) + return result == max(values[i] + values[-1 - i] for i in range(len(values) // 2)) + +seed: 1877001 + +tests: + - name: "example_one" + in: + nums: [3, 5, 2, 3] + out: 7 + - name: "example_two" + in: + nums: [3, 5, 4, 2, 4, 6] + out: 8 + - name: "minimum_length" + in: + nums: [1, 1] + out: 2 + - name: "minimum_and_maximum" + in: + nums: [1, 100000] + out: 100001 + - name: "all_minimum" + in: + nums: [1, 1, 1, 1, 1, 1] + out: 2 + - name: "all_maximum" + in: + nums: [100000, 100000, 100000, 100000] + out: 200000 + - name: "already_sorted" + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8] + out: 9 + - name: "reverse_sorted" + in: + nums: [8, 7, 6, 5, 4, 3, 2, 1] + out: 9 + - name: "two_pairs_equal" + in: + nums: [2, 2, 8, 8] + out: 10 + - name: "duplicates_and_outliers" + in: + nums: [1, 1, 1, 50, 50, 50] + out: 51 + - name: "odd_values" + in: + nums: [1, 3, 5, 7, 9, 11] + out: 12 + - name: "large_gap" + in: + nums: [1, 2, 3, 4, 99998, 99999] + out: 100000 + - name: "ten_values" + in: + nums: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] + out: 110 + - name: "repeated_middle" + in: + nums: [1, 25, 25, 25, 25, 25, 25, 100] + out: 101 + - name: "mixed_small" + in: + nums: [4, 1, 9, 2, 8, 3] + out: 10 + - name: "balanced_values" + in: + nums: [5, 5, 6, 6, 7, 7, 8, 8] + out: 13 + - name: "many_ones" + in: + nums: [1, 1, 1, 1, 1, 1, 1, 100000] + out: 100001 + - name: "near_upper_bound" + in: + nums: [99990, 99991, 99992, 99993] + out: 199983 + - name: "twenty_consecutive" + in: + nums: + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] + out: 21 + - name: "alternating_extremes" + in: + nums: [1, 100000, 2, 99999, 3, 99998, 4, 99997] + out: 100001 + - name: "clustered_low" + in: + nums: [2, 3, 3, 4, 4, 5, 5, 6] + out: 8 + - name: "clustered_high" + in: + nums: [99995, 99996, 99997, 99998, 99998, 99999] + out: 199995 + - name: "powers_and_gaps" + in: + nums: [1, 2, 4, 8, 16, 32, 64, 128] + out: 129 + - name: "same_sum_pairs" + in: + nums: [1, 4, 2, 3, 3, 2, 4, 1] + out: 5 + - name: "sixteen_mixed" + in: + nums: [12, 7, 19, 3, 25, 1, 8, 14, 6, 21, 5, 11, 18, 2, 9, 16] + out: 26 + - name: "zero_not_allowed_boundary" + in: + nums: [1, 100, 2, 99, 3, 98, 4, 97, 5, 96] + out: 101 + - name: "large_duplicates" + in: + nums: [50000, 50000, 50000, 50000, 50000, 50000] + out: 100000 + - name: "twenty_four_values" + in: + nums: + [ + 2, + 4, + 6, + 8, + 10, + 12, + 14, + 16, + 18, + 20, + 22, + 24, + 26, + 28, + 30, + 32, + 34, + 36, + 38, + 40, + 42, + 44, + 46, + 48, + ] + out: 50 + - name: "unbalanced_distribution" + in: + nums: [1, 1, 2, 2, 3, 3, 4, 100, 100, 100] + out: 102 + - name: "close_upper_values" + in: + nums: [99900, 99901, 99902, 99903, 99904, 99905, 99906, 99907] + out: 199807 + - name: "thirty_two_values" + in: + nums: + [ + 1, + 1, + 2, + 2, + 3, + 3, + 4, + 4, + 5, + 5, + 6, + 6, + 7, + 7, + 8, + 8, + 9, + 9, + 10, + 10, + 11, + 11, + 12, + 12, + 13, + 13, + 14, + 14, + 15, + 15, + 16, + 16, + ] + out: 17 + - name: "mixed_extreme_pairs" + in: + nums: [1, 1, 100000, 100000, 25000, 75000, 33333, 66667] + out: 100001 + - name: "forty_values" + in: + nums: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + ] + out: 41 + - name: "generated_small_even" + seed: 187701 + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + + - name: "generated_medium_even" + seed: 187702 + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + - name: "generated_large_even" + seed: 187703 + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + - name: "generated_maximum_even" + seed: 187704 + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + - name: "generated_upper_cluster" + seed: 187705 + in: + nums: + gen: "array" + len: 20000 + of: + gen: "int" + min: 90000 + max: 100000 + distinct: false diff --git a/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.cpp b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.cpp new file mode 100644 index 00000000..bfadb21b --- /dev/null +++ b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int minPairSum(vector& nums) { + sort(nums.begin(), nums.end()); + int max_sum = 0; + int l = 0, r = nums.size() - 1; + while (l < r) { + max_sum = max(max_sum, nums[l] + nums[r]); + l++; + r--; + } + return max_sum; + } +}; diff --git a/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.cs b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.cs new file mode 100644 index 00000000..9af23423 --- /dev/null +++ b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public int MinPairSum(int[] nums) { + Array.Sort(nums); + int maxSum = 0; + int l = 0, r = nums.Length - 1; + while (l < r) { + maxSum = Math.Max(maxSum, nums[l] + nums[r]); + l++; + r--; + } + return maxSum; + } +} diff --git a/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.dart b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.dart new file mode 100644 index 00000000..dad26a5b --- /dev/null +++ b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.dart @@ -0,0 +1,15 @@ +class Solution { + int minPairSum(List nums) { + nums.sort(); + int answer = 0; + int left = 0; + int right = nums.length - 1; + while (left < right) { + final sum = nums[left] + nums[right]; + if (sum > answer) answer = sum; + left++; + right--; + } + return answer; + } +} diff --git a/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.go b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.go new file mode 100644 index 00000000..e737a87e --- /dev/null +++ b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.go @@ -0,0 +1,13 @@ +func minPairSum(nums []int) int { + sort.Ints(nums) + max_sum := 0 + l, r := 0, len(nums)-1 + for l < r { + if nums[l]+nums[r] > max_sum { + max_sum = nums[l] + nums[r] + } + l++ + r-- + } + return max_sum +} diff --git a/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.java b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.java new file mode 100644 index 00000000..74807726 --- /dev/null +++ b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int minPairSum(int[] nums) { + Arrays.sort(nums); + int max_sum = 0; + int l = 0, r = nums.length - 1; + while (l < r) { + max_sum = Math.max(max_sum, nums[l] + nums[r]); + l++; + r--; + } + return max_sum; + } +} diff --git a/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.kt b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.kt new file mode 100644 index 00000000..deefb26e --- /dev/null +++ b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun minPairSum(nums: IntArray): Int { + nums.sort() + var maxSum = 0 + var l = 0 + var r = nums.size - 1 + while (l < r) { + maxSum = maxOf(maxSum, nums[l] + nums[r]) + l++ + r-- + } + return maxSum + } +} diff --git a/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.py b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.py new file mode 100644 index 00000000..868e04e3 --- /dev/null +++ b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.py @@ -0,0 +1,9 @@ +class Solution: + def minPairSum(self, nums: List[int]) -> int: + nums.sort() + max_sum, l, r = 0, 0, len(nums) - 1 + while l < r: + max_sum = max(max_sum, nums[l] + nums[r]) + l += 1 + r -= 1 + return max_sum diff --git a/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.py2 b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.py2 new file mode 100644 index 00000000..b6d4fccf --- /dev/null +++ b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def minPairSum(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + nums.sort() + max_sum = 0 + l, r = 0, len(nums) - 1 + while l < r: + max_sum = max(max_sum, nums[l] + nums[r]) + l += 1 + r -= 1 + return max_sum diff --git a/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.rb b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.rb new file mode 100644 index 00000000..2fb5dd75 --- /dev/null +++ b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[]} nums +# @return {Integer} +def min_pair_sum(nums) + nums.sort! + max_sum = 0 + l = 0 + r = nums.length - 1 + while l < r + max_sum = [max_sum, nums[l] + nums[r]].max + l += 1 + r -= 1 + end + max_sum +end diff --git a/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.rs b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.rs new file mode 100644 index 00000000..62bd43d6 --- /dev/null +++ b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn min_pair_sum(nums: Vec) -> i32 { + let mut nums = nums; + nums.sort(); + let mut max_sum = 0; + let mut l = 0; + let mut r = nums.len() - 1; + while l < r { + max_sum = max_sum.max(nums[l] + nums[r]); + l += 1; + r -= 1; + } + max_sum + } +} diff --git a/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.swift b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.swift new file mode 100644 index 00000000..d2f63a01 --- /dev/null +++ b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.swift @@ -0,0 +1,14 @@ +class Solution { + func minPairSum(_ nums: [Int]) -> Int { + var nums = nums.sorted() + var maxSum = 0 + var l = 0 + var r = nums.count - 1 + while l < r { + maxSum = max(maxSum, nums[l] + nums[r]) + l += 1 + r -= 1 + } + return maxSum + } +} diff --git a/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.ts b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.ts new file mode 100644 index 00000000..3b38a6fa --- /dev/null +++ b/tests/1501-2000/1877. minimize-maximum-pair-sum-in-array/sol.ts @@ -0,0 +1,12 @@ +function minPairSum(nums: number[]): number { + nums.sort((a, b) => a - b); + let maxSum = 0; + let l = 0, + r = nums.length - 1; + while (l < r) { + maxSum = Math.max(maxSum, nums[l] + nums[r]); + l++; + r--; + } + return maxSum; +} diff --git a/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/manifest.yaml b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/manifest.yaml new file mode 100644 index 00000000..31a0ca24 --- /dev/null +++ b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/manifest.yaml @@ -0,0 +1,422 @@ +entry: + id: 1878 + title: "get-biggest-three-rhombus-sums-in-a-grid" + params: + grid: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().getBiggestThree({grid})" + rust: "Solution::get_biggest_three({grid})" + python3: "Solution().getBiggestThree({grid})" + python2: "Solution().getBiggestThree({grid})" + ruby: "get_biggest_three({grid})" + java: "new Solution().getBiggestThree({grid})" + csharp: "new Solution().GetBiggestThree({grid})" + kotlin: "Solution().getBiggestThree({grid})" + go: "getBiggestThree({grid})" + dart: "Solution().getBiggestThree({grid})" + swift: "Solution().getBiggestThree({grid})" + typescript: "getBiggestThree({grid})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(grid, {result})" + checker: | + class Checker: + def check(self, grid, result): + m, n = len(grid), len(grid[0]) + sums = set() + for i in range(m): + for j in range(n): + sums.add(grid[i][j]) + d = 1 + while i - d >= 0 and i + d < m and j - d >= 0 and j + d < n: + cells = {(i - d, j), (i, j + d), (i + d, j), (i, j - d)} + for k in range(1, d): + cells.add((i - d + k, j - k)) + cells.add((i - d + k, j + k)) + cells.add((i + d - k, j - k)) + cells.add((i + d - k, j + k)) + sums.add(sum(grid[r][c] for r, c in cells)) + d += 1 + expected = sorted(sums, reverse=True)[:3] + return result == expected + +seed: 1878 + +tests: + - name: example-one + in: + grid: + elemType: "int" + value: + - [3, 4, 5, 1, 3] + - [3, 3, 4, 2, 3] + - [20, 30, 200, 40, 10] + - [1, 5, 5, 4, 1] + - [4, 3, 2, 2, 5] + - name: example-two + in: + grid: + elemType: "int" + value: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + - name: example-three + in: + grid: + elemType: "int" + value: + - [7, 7, 7] + - name: one-cell + in: + grid: + elemType: "int" + value: + - [42] + - name: one-row + in: + grid: + elemType: "int" + value: + - [1, 9, 3, 8, 2, 7] + - name: one-column + in: + grid: + elemType: "int" + value: + - [6] + - [2] + - [9] + - [4] + - name: two-by-two + in: + grid: + elemType: "int" + value: + - [1, 10] + - [7, 3] + - name: equal-values + in: + grid: + elemType: "int" + value: + - [5, 5, 5, 5] + - [5, 5, 5, 5] + - [5, 5, 5, 5] + - [5, 5, 5, 5] + - name: three-by-five + in: + grid: + elemType: "int" + value: + - [1, 2, 3, 4, 5] + - [6, 7, 8, 9, 10] + - [11, 12, 13, 14, 15] + - name: four-by-three + in: + grid: + elemType: "int" + value: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + - [10, 11, 12] + - name: large-corners + in: + grid: + elemType: "int" + value: + - [100000, 1, 1, 1, 100000] + - [1, 2, 3, 2, 1] + - [1, 3, 90000, 3, 1] + - [1, 2, 3, 2, 1] + - [100000, 1, 1, 1, 100000] + - name: alternating + in: + grid: + elemType: "int" + value: + - [1, 100, 1, 100, 1] + - [100, 1, 100, 1, 100] + - [1, 100, 1, 100, 1] + - [100, 1, 100, 1, 100] + - [1, 100, 1, 100, 1] + - name: increasing-four + in: + grid: + elemType: "int" + value: + - [1, 2, 3, 4] + - [5, 6, 7, 8] + - [9, 10, 11, 12] + - [13, 14, 15, 16] + - name: decreasing-four + in: + grid: + elemType: "int" + value: + - [16, 15, 14, 13] + - [12, 11, 10, 9] + - [8, 7, 6, 5] + - [4, 3, 2, 1] + - name: sparse-high-center + in: + grid: + elemType: "int" + value: + - [1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 100000, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1] + - name: two-by-six + in: + grid: + elemType: "int" + value: + - [10, 20, 30, 40, 50, 60] + - [1, 2, 3, 4, 5, 6] + - name: five-by-two + in: + grid: + elemType: "int" + value: + - [10, 1] + - [20, 2] + - [30, 3] + - [40, 4] + - [50, 5] + - name: repeated-top-three + in: + grid: + elemType: "int" + value: + - [8, 8, 1] + - [8, 8, 1] + - [1, 1, 1] + - name: mixed-negative-not-allowed + in: + grid: + elemType: "int" + value: + - [1, 100000, 2] + - [99999, 3, 99998] + - [4, 99997, 5] + - name: six-by-six + in: + grid: + elemType: "int" + value: + - [1, 2, 3, 4, 5, 6] + - [7, 8, 9, 10, 11, 12] + - [13, 14, 15, 16, 17, 18] + - [19, 20, 21, 22, 23, 24] + - [25, 26, 27, 28, 29, 30] + - [31, 32, 33, 34, 35, 36] + - name: constant-seven + in: + grid: + elemType: "int" + value: + - [7, 7, 7, 7, 7] + - [7, 7, 7, 7, 7] + - [7, 7, 7, 7, 7] + - [7, 7, 7, 7, 7] + - [7, 7, 7, 7, 7] + - name: checkerboard-small + in: + grid: + elemType: "int" + value: + - [2, 1, 2, 1, 2] + - [1, 2, 1, 2, 1] + - [2, 1, 2, 1, 2] + - [1, 2, 1, 2, 1] + - [2, 1, 2, 1, 2] + - name: border-heavy + in: + grid: + elemType: "int" + value: + - [100, 100, 100, 100, 100] + - [100, 1, 1, 1, 100] + - [100, 1, 50, 1, 100] + - [100, 1, 1, 1, 100] + - [100, 100, 100, 100, 100] + - name: max-single + in: + grid: + elemType: "int" + value: + - [100000] + - name: max-row + in: + grid: + elemType: "int" + value: + - [100000, 99999, 99998, 99997, 99996] + - name: max-column + in: + grid: + elemType: "int" + value: + - [100000] + - [99999] + - [99998] + - [99997] + - [99996] + - name: seven-by-three + in: + grid: + elemType: "int" + value: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + - [10, 11, 12] + - [13, 14, 15] + - [16, 17, 18] + - [19, 20, 21] + - name: three-by-seven + in: + grid: + elemType: "int" + value: + - [1, 2, 3, 4, 5, 6, 7] + - [8, 9, 10, 11, 12, 13, 14] + - [15, 16, 17, 18, 19, 20, 21] + - name: varied-5 + in: + grid: + elemType: "int" + value: + - [11, 3, 17, 5, 19] + - [2, 23, 7, 29, 13] + - [31, 37, 41, 43, 47] + - [53, 59, 61, 67, 71] + - [73, 79, 83, 89, 97] + - name: varied-4 + in: + grid: + elemType: "int" + value: + - [9, 1, 8, 2] + - [7, 3, 6, 4] + - [5, 10, 11, 12] + - [13, 14, 15, 16] + - name: alternating-large + in: + grid: + elemType: "int" + value: + - [100000, 1, 100000, 1] + - [1, 100000, 1, 100000] + - [100000, 1, 100000, 1] + - [1, 100000, 1, 100000] + - name: nine-by-one + in: + grid: + elemType: "int" + value: + - [1] + - [2] + - [3] + - [4] + - [5] + - [6] + - [7] + - [8] + - [9] + - name: five-by-five-gradient + in: + grid: + elemType: "int" + value: + - [5, 6, 7, 8, 9] + - [10, 11, 12, 13, 14] + - [15, 16, 17, 18, 19] + - [20, 21, 22, 23, 24] + - [25, 26, 27, 28, 29] + - name: generated-small + in: + grid: + gen: "array" + len: 5 + of: + gen: "array" + len: 5 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + seed: 187801 + - name: generated-wide + in: + grid: + gen: "array" + len: 3 + of: + gen: "array" + len: 50 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + seed: 187802 + - name: generated-tall + in: + grid: + gen: "array" + len: 50 + of: + gen: "array" + len: 3 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + seed: 187803 + - name: generated-square + in: + grid: + gen: "array" + len: 50 + of: + gen: "array" + len: 50 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + seed: 187804 + - name: generated-medium + in: + grid: + gen: "array" + len: 20 + of: + gen: "array" + len: 25 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + seed: 187805 diff --git a/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.cpp b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.cpp new file mode 100644 index 00000000..b1bc48d9 --- /dev/null +++ b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + vector getBiggestThree(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int maxD = min(m, n) / 2; + vector result; + for (int d = 0; d <= maxD; d++) { + for (int i = d; i < m - d; i++) { + for (int j = d; j < n - d; j++) { + int val = diamondSum(grid, i, j, d); + if (find(result.begin(), result.end(), val) == result.end()) { + result.push_back(val); + } + } + } + } + sort(result.begin(), result.end(), greater()); + if (result.size() > 3) result.resize(3); + return result; + } + +private: + int diamondSum(vector>& grid, int i, int j, int d) { + if (d == 0) return grid[i][j]; + int sum = 0; + for (int t = 0; t <= d; t++) sum += grid[i - d + t][j + t]; + for (int t = 1; t <= d; t++) sum += grid[i + t][j + d - t]; + for (int t = 1; t <= d; t++) sum += grid[i + d - t][j - t]; + for (int t = 1; t < d; t++) sum += grid[i - t][j - d + t]; + return sum; + } +}; diff --git a/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.cs b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.cs new file mode 100644 index 00000000..b29ff83e --- /dev/null +++ b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.cs @@ -0,0 +1,30 @@ +public class Solution { + public int[] GetBiggestThree(int[][] grid) { + int m = grid.Length, n = grid[0].Length; + int maxD = Math.Min(m, n) / 2; + List list = new List(); + for (int d = 0; d <= maxD; d++) { + for (int i = d; i < m - d; i++) { + for (int j = d; j < n - d; j++) { + int val = DiamondSum(grid, i, j, d); + if (!list.Contains(val)) list.Add(val); + } + } + } + list.Sort((a, b) => b.CompareTo(a)); + int count = Math.Min(3, list.Count); + int[] ans = new int[count]; + for (int k = 0; k < count; k++) ans[k] = list[k]; + return ans; + } + + private int DiamondSum(int[][] grid, int i, int j, int d) { + if (d == 0) return grid[i][j]; + int sum = 0; + for (int t = 0; t <= d; t++) sum += grid[i - d + t][j + t]; + for (int t = 1; t <= d; t++) sum += grid[i + t][j + d - t]; + for (int t = 1; t <= d; t++) sum += grid[i + d - t][j - t]; + for (int t = 1; t < d; t++) sum += grid[i - t][j - d + t]; + return sum; + } +} diff --git a/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.dart b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.dart new file mode 100644 index 00000000..2a5fa834 --- /dev/null +++ b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.dart @@ -0,0 +1,30 @@ +class Solution { + List getBiggestThree(List> grid) { + int m = grid.length; + int n = grid[0].length; + int maxD = (m < n ? m : n) ~/ 2; + List result = []; + for (int d = 0; d <= maxD; d++) { + for (int i = d; i < m - d; i++) { + for (int j = d; j < n - d; j++) { + int val = diamondSum(grid, i, j, d); + if (!result.contains(val)) { + result.add(val); + } + } + } + } + result.sort((a, b) => b.compareTo(a)); + return result.length < 3 ? result : result.sublist(0, 3); + } + + int diamondSum(List> grid, int i, int j, int d) { + if (d == 0) return grid[i][j]; + int sum = 0; + for (int t = 0; t <= d; t++) sum += grid[i - d + t][j + t]; + for (int t = 1; t <= d; t++) sum += grid[i + t][j + d - t]; + for (int t = 1; t <= d; t++) sum += grid[i + d - t][j - t]; + for (int t = 1; t < d; t++) sum += grid[i - t][j - d + t]; + return sum; + } +} diff --git a/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.go b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.go new file mode 100644 index 00000000..8d6bc0ec --- /dev/null +++ b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.go @@ -0,0 +1,57 @@ +func getBiggestThree(grid [][]int) []int { + m := len(grid) + n := len(grid[0]) + maxD := min(m, n) / 2 + result := []int{} + for d := 0; d <= maxD; d++ { + for i := d; i < m-d; i++ { + for j := d; j < n-d; j++ { + val := diamondSum(grid, i, j, d) + if !contains(result, val) { + result = append(result, val) + } + } + } + } + sort.Sort(sort.Reverse(sort.IntSlice(result))) + if len(result) < 3 { + return result + } + return result[:3] +} + +func diamondSum(grid [][]int, i, j, d int) int { + if d == 0 { + return grid[i][j] + } + sum := 0 + for t := 0; t <= d; t++ { + sum += grid[i-d+t][j+t] + } + for t := 1; t <= d; t++ { + sum += grid[i+t][j+d-t] + } + for t := 1; t <= d; t++ { + sum += grid[i+d-t][j-t] + } + for t := 1; t < d; t++ { + sum += grid[i-t][j-d+t] + } + return sum +} + +func contains(arr []int, x int) bool { + for _, a := range arr { + if a == x { + return true + } + } + return false +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} diff --git a/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.java b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.java new file mode 100644 index 00000000..e1c61641 --- /dev/null +++ b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.java @@ -0,0 +1,29 @@ +class Solution { + public int[] getBiggestThree(int[][] grid) { + int m = grid.length, n = grid[0].length; + int maxD = Math.min(m, n) / 2; + List list = new ArrayList<>(); + for (int d = 0; d <= maxD; d++) { + for (int i = d; i < m - d; i++) { + for (int j = d; j < n - d; j++) { + int val = diamondSum(grid, i, j, d); + if (!list.contains(val)) list.add(val); + } + } + } + Collections.sort(list, Collections.reverseOrder()); + int[] ans = new int[Math.min(3, list.size())]; + for (int k = 0; k < ans.length; k++) ans[k] = list.get(k); + return ans; + } + + private int diamondSum(int[][] grid, int i, int j, int d) { + if (d == 0) return grid[i][j]; + int sum = 0; + for (int t = 0; t <= d; t++) sum += grid[i - d + t][j + t]; + for (int t = 1; t <= d; t++) sum += grid[i + t][j + d - t]; + for (int t = 1; t <= d; t++) sum += grid[i + d - t][j - t]; + for (int t = 1; t < d; t++) sum += grid[i - t][j - d + t]; + return sum; + } +} diff --git a/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.kt b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.kt new file mode 100644 index 00000000..e8d249c4 --- /dev/null +++ b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.kt @@ -0,0 +1,29 @@ +class Solution { + fun getBiggestThree(grid: Array): IntArray { + val m = grid.size + val n = grid[0].size + val maxD = (minOf(m, n) - 1) / 2 + val list = mutableListOf() + val seen = HashSet() + for (d in 0..maxD) { + for (i in d until m - d) { + for (j in d until n - d) { + val sum = diamondSum(grid, i, j, d) + if (seen.add(sum)) list.add(sum) + } + } + } + list.sortDescending() + return list.take(3).toIntArray() + } + + private fun diamondSum(grid: Array, i: Int, j: Int, d: Int): Int { + if (d == 0) return grid[i][j] + var sum = 0 + for (t in 0..d) sum += grid[i - d + t][j + t] + for (t in 1..d) sum += grid[i + t][j + d - t] + for (t in 1..d) sum += grid[i + d - t][j - t] + for (t in 1 until d) sum += grid[i - t][j - d + t] + return sum + } +} diff --git a/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.py b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.py new file mode 100644 index 00000000..f2e715c8 --- /dev/null +++ b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.py @@ -0,0 +1,54 @@ +diag = [[0] * 51 for _ in range(100)] +antid = [[0] * 51 for _ in range(100)] +OFFSET = 50 + + +class Solution: + def getBiggestThree(self, grid: List[List[int]]) -> List[int]: + def rhombusSum(i, j, d): + if d == 0: + return grid[i][j] + l, r, u, b = j - d, j + d, i - d, i + d + i0, i1 = u - j + OFFSET, i - l + OFFSET + Sum = diag[i0][r + 1] - diag[i0][j] + Sum += diag[i1][j + 1] - diag[i1][l] + + j0, j1 = u + j, b + j + Sum += antid[j0][i] - antid[j0][u + 1] + Sum += antid[j1][b] - antid[j1][i + 1] + return Sum + + m, n = len(grid), len(grid[0]) + for i, row in enumerate(grid): + for j, x in enumerate(row): + i0, j0 = i - j + OFFSET, i + j + diag[i0][j + 1] = diag[i0][j] + x + antid[j0][i + 1] = antid[j0][i] + x + + dM = min(m, n) >> 1 + x = [-1] * 3 + for d in range(dM + 1): + for i in range(d, m - d): + for j in range(d, n - d): + y = rhombusSum(i, j, d) + if y == x[0] or y == x[1] or y == x[2]: + continue + if y > x[0]: + x[2] = x[1] + x[1] = x[0] + x[0] = y + elif y > x[0]: + x[2] = x[1] + x[1] = x[0] + x[0] = y + elif y > x[1]: + x[2] = x[1] + x[1] = y + elif y > x[2]: + x[2] = y + + for i in range(2, -1, -1): + if x[i] == -1: + x.pop() + + return x diff --git a/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.py2 b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.py2 new file mode 100644 index 00000000..18880197 --- /dev/null +++ b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.py2 @@ -0,0 +1,35 @@ +class Solution(object): + def getBiggestThree(self, grid): + """ + :type grid: List[List[int]] + :rtype: List[int] + """ + m, n = len(grid), len(grid[0]) + max_d = min(m, n) // 2 + result = [] + def diamond_sum(i, j, d): + if d == 0: + return grid[i][j] + s = 0 + # top to right + for t in range(d+1): + s += grid[i - d + t][j + t] + # right to bottom + for t in range(1, d+1): + s += grid[i + t][j + d - t] + # bottom to left + for t in range(1, d+1): + s += grid[i + d - t][j - t] + # left to top + for t in range(1, d): + s += grid[i - t][j - d + t] + return s + + for d in range(max_d+1): + for i in range(d, m - d): + for j in range(d, n - d): + val = diamond_sum(i, j, d) + if val not in result: + result.append(val) + result.sort(reverse=True) + return result[:3] diff --git a/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.rb b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.rb new file mode 100644 index 00000000..9e3b7cd3 --- /dev/null +++ b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.rb @@ -0,0 +1,28 @@ +# @param {Integer[][]} grid +# @return {Integer[]} +def get_biggest_three(grid) + m = grid.length + n = grid[0].length + max_d = [m, n].min / 2 + result = [] + + (0..max_d).each do |d| + (d...(m-d)).each do |i| + (d...(n-d)).each do |j| + val = diamond_sum(grid, i, j, d) + result << val unless result.include?(val) + end + end + end + result.sort.reverse.first(3) +end + +def diamond_sum(grid, i, j, d) + return grid[i][j] if d == 0 + sum = 0 + (0..d).each { |t| sum += grid[i - d + t][j + t] } + (1..d).each { |t| sum += grid[i + t][j + d - t] } + (1..d).each { |t| sum += grid[i + d - t][j - t] } + (1...d).each { |t| sum += grid[i - t][j - d + t] } + sum +end diff --git a/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.rs b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.rs new file mode 100644 index 00000000..fccfdbae --- /dev/null +++ b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.rs @@ -0,0 +1,39 @@ +impl Solution { + pub fn get_biggest_three(grid: Vec>) -> Vec { + let m = grid.len(); + let n = grid[0].len(); + let max_d = (m.min(n)) / 2; + let mut result: Vec = Vec::new(); + for d in 0..=max_d { + for i in d..(m - d) { + for j in d..(n - d) { + let val = Self::diamond_sum(&grid, i, j, d); + if !result.contains(&val) { + result.push(val); + } + } + } + } + result.sort_by(|a, b| b.cmp(a)); + result.truncate(3); + result + } + + fn diamond_sum(grid: &Vec>, i: usize, j: usize, d: usize) -> i32 { + if d == 0 { return grid[i][j]; } + let mut sum = 0; + for t in 0..=d { + sum += grid[i - d + t][j + t]; + } + for t in 1..=d { + sum += grid[i + t][j + d - t]; + } + for t in 1..=d { + sum += grid[i + d - t][j - t]; + } + for t in 1..d { + sum += grid[i - t][j - d + t]; + } + sum + } +} diff --git a/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.swift b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.swift new file mode 100644 index 00000000..c5c7d13c --- /dev/null +++ b/tests/1501-2000/1878. get-biggest-three-rhombus-sums-in-a-grid/sol.swift @@ -0,0 +1,31 @@ +class Solution { + func getBiggestThree(_ grid: [[Int]]) -> [Int] { + let m = grid.count + let n = grid[0].count + let maxD = (min(m, n) - 1) / 2 + var result: [Int] = [] + var seen = Set() + for d in 0...maxD { + for i in d..<(m-d) { + for j in d..<(n-d) { + let val = diamondSum(grid, i, j, d) + if seen.insert(val).inserted { + result.append(val) + } + } + } + } + result.sort(by: >) + return Array(result.prefix(3)) + } + + private func diamondSum(_ grid: [[Int]], _ i: Int, _ j: Int, _ d: Int) -> Int { + if d == 0 { return grid[i][j] } + var sum = 0 + for t in 0...d { sum += grid[i - d + t][j + t] } + for t in 1...d { sum += grid[i + t][j + d - t] } + for t in 1...d { sum += grid[i + d - t][j - t] } + for t in 1..> 1; + let result: number[] = []; + for (let d = 0; d <= maxD; d++) { + for (let i = d; i < m - d; i++) { + for (let j = d; j < n - d; j++) { + const val = diamondSum(grid, i, j, d); + if (!result.includes(val)) { + result.push(val); + } + } + } + } + result.sort((a, b) => b - a); + return result.slice(0, 3); +} + +function diamondSum(grid: number[][], i: number, j: number, d: number): number { + if (d === 0) return grid[i][j]; + let sum = 0; + for (let t = 0; t <= d; t++) sum += grid[i - d + t][j + t]; + for (let t = 1; t <= d; t++) sum += grid[i + t][j + d - t]; + for (let t = 1; t <= d; t++) sum += grid[i + d - t][j - t]; + for (let t = 1; t < d; t++) sum += grid[i - t][j - d + t]; + return sum; +} diff --git a/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/manifest.yaml b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/manifest.yaml new file mode 100644 index 00000000..46abf07d --- /dev/null +++ b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/manifest.yaml @@ -0,0 +1,447 @@ +entry: + id: 1879 + title: "minimum-xor-sum-of-two-arrays" + params: + nums1: + type: array + items: + type: int + nums2: + type: array + items: + type: int + call: + cpp: "Solution().minimumXORSum({nums1}, {nums2})" + rust: "Solution::minimum_xor_sum({nums1}, {nums2})" + python3: "Solution().minimumXORSum({nums1}, {nums2})" + python2: "Solution().minimumXORSum({nums1}, {nums2})" + ruby: "minimum_xor_sum({nums1}, {nums2})" + java: "new Solution().minimumXORSum({nums1}, {nums2})" + csharp: "new Solution().MinimumXORSum({nums1}, {nums2})" + kotlin: "Solution().minimumXORSum({nums1}, {nums2})" + go: "minimumXORSum({nums1}, {nums2})" + dart: "Solution().minimumXORSum({nums1}, {nums2})" + swift: "Solution().minimumXORSum({nums1}, {nums2})" + typescript: "minimumXORSum({nums1}, {nums2})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().check(nums1, nums2, {result})" + checker: | + class Checker: + def check(self, nums1, nums2, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + n = len(nums1) + if n != len(nums2) or n < 1 or n > 14: + return False + if any(not isinstance(x, int) or x < 0 or x > 10000000 for x in nums1 + nums2): + return False + dp = [10**30] * (1 << n) + dp[0] = 0 + for mask in range(1 << n): + i = mask.bit_count() + if i == n: + continue + for j in range(n): + if not (mask >> j) & 1: + nxt = mask | (1 << j) + value = dp[mask] + (nums1[i] ^ nums2[j]) + if value < dp[nxt]: + dp[nxt] = value + return result == dp[-1] + +seed: 1879 + +tests: + - name: example-one + in: + nums1: [1, 2] + nums2: [2, 3] + - name: example-two + in: + nums1: [1, 0, 3] + nums2: [5, 3, 4] + - name: one-equal + in: + nums1: [0] + nums2: [0] + out: 0 + - name: one-large + in: + nums1: [10000000] + nums2: [0] + - name: two-equal-values + in: + nums1: [7, 7] + nums2: [7, 7] + out: 0 + - name: two-reversed + in: + nums1: [0, 15] + nums2: [15, 0] + - name: duplicates-one-side + in: + nums1: [1, 2, 4, 8] + nums2: [0, 0, 0, 0] + - name: powers-of-two + in: + nums1: [1, 2, 4, 8] + nums2: [8, 4, 2, 1] + - name: all-max + in: + nums1: [10000000, 10000000] + nums2: [10000000, 10000000] + out: 0 + - name: zero-and-max + in: + nums1: [0, 0, 10000000, 10000000] + nums2: [0, 10000000, 0, 10000000] + - name: close-values + in: + nums1: [10, 11, 12] + nums2: [13, 14, 15] + - name: high-bit-values + in: + nums1: [8388608, 4194304, 2097152] + nums2: [2097152, 8388608, 4194304] + - name: mixed-small + in: + nums1: [3, 5, 9, 17, 33] + nums2: [2, 6, 10, 18, 34] + - name: repeated-pattern + in: + nums1: [1, 3, 1, 3, 1, 3] + nums2: [0, 2, 4, 6, 8, 10] + - name: six-zeroes + in: + nums1: [0, 0, 0, 0, 0, 0] + nums2: [1, 2, 4, 8, 16, 32] + - name: seven-distinct + in: + nums1: [2, 7, 19, 31, 63, 127, 255] + nums2: [1, 8, 18, 32, 62, 128, 254] + - name: eight-balanced + in: + nums1: [5, 12, 25, 40, 77, 101, 256, 999] + nums2: [1000, 255, 102, 76, 41, 24, 13, 4] + - name: nine-duplicates + in: + nums1: [4, 4, 4, 9, 9, 9, 15, 15, 15] + nums2: [0, 1, 2, 8, 10, 11, 14, 16, 31] + - name: ten-random-small + in: + nums1: [6, 23, 41, 58, 77, 91, 104, 128, 201, 255] + nums2: [3, 19, 44, 52, 80, 87, 111, 130, 199, 260] + - name: eleven-high + in: + nums1: + [ + 10000000, + 9999999, + 9999998, + 7777777, + 7000000, + 6000000, + 5000000, + 4000000, + 3000000, + 2000000, + 1000000, + ] + nums2: + [ + 0, + 1, + 2, + 2222222, + 3333333, + 4444444, + 5555555, + 6666666, + 7777778, + 8888888, + 9999990, + ] + - name: twelve-bit-patterns + in: + nums1: [0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047] + nums2: [2047, 1023, 511, 255, 127, 63, 31, 15, 7, 3, 1, 0] + - name: thirteen-mixed + in: + nums1: [12, 34, 56, 78, 90, 123, 456, 789, 1024, 2048, 4096, 8192, 16384] + nums2: [16385, 8191, 4095, 2049, 1023, 790, 455, 124, 89, 79, 55, 33, 11] + - name: fourteen-full + in: + nums1: + [ + 0, + 17, + 42, + 99, + 128, + 257, + 511, + 1025, + 2049, + 4097, + 8193, + 16385, + 32769, + 65537, + ] + nums2: + [ + 65536, + 32768, + 16384, + 8192, + 4096, + 2048, + 1024, + 512, + 256, + 129, + 100, + 43, + 16, + 1, + ] + - name: same-multiset + in: + nums1: [12, 3, 999, 0, 42] + nums2: [42, 999, 0, 3, 12] + - name: alternating-bits + in: + nums1: [43690, 21845, 13107, 52428] + nums2: [65535, 0, 43690, 21845] + - name: near-limit-fourteen + in: + nums1: + [ + 9999999, + 9999998, + 9999997, + 9999996, + 9999995, + 9999994, + 9999993, + 9999992, + 9999991, + 9999990, + 9999989, + 9999988, + 9999987, + 9999986, + ] + nums2: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] + - name: asymmetric-three + in: + nums1: [1023, 2047, 4095] + nums2: [1024, 2048, 4096] + - name: many-zero-two + in: + nums1: [0, 0, 10000000, 1, 1, 9999999] + nums2: [0, 10000000, 9999999, 1, 0, 1] + - name: medium-duplicates + in: + nums1: [100, 100, 200, 200, 300, 300, 400, 400] + nums2: [101, 201, 301, 401, 99, 199, 299, 399] + - name: sparse-large + in: + nums1: [0, 10000000, 524288, 8388607, 1234567] + nums2: [9999999, 1, 524287, 8388608, 7654321] + - name: twelve-repeated + in: + nums1: [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5] + nums2: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + - name: thirteen-zero-max + in: + nums1: + [ + 0, + 10000000, + 0, + 10000000, + 0, + 10000000, + 0, + 10000000, + 0, + 10000000, + 0, + 10000000, + 0, + ] + nums2: + [ + 10000000, + 0, + 10000000, + 0, + 10000000, + 0, + 10000000, + 0, + 10000000, + 0, + 10000000, + 0, + 10000000, + ] + - name: fourteen-repeated-blocks + in: + nums1: [1, 2, 3, 1, 2, 3, 100, 200, 300, 100, 200, 300, 999, 1000] + nums2: [3, 2, 1, 300, 200, 100, 3, 2, 1, 300, 200, 100, 1000, 999] + - name: alternating-small + in: + nums1: [2, 8, 2, 8, 2, 8, 2] + nums2: [1, 7, 3, 9, 5, 11, 13] + - name: fifteen-not-allowed + in: + nums1: + [ + 31, + 63, + 127, + 255, + 511, + 1023, + 2047, + 4095, + 8191, + 16383, + 32767, + 65535, + 131071, + 262143, + ] + nums2: + [ + 0, + 31, + 63, + 127, + 255, + 511, + 1023, + 2047, + 4095, + 8191, + 16383, + 32767, + 65535, + 131071, + ] + - name: generated-random-1 + in: + nums1: + gen: "array" + len: 14 + of: + gen: "int" + min: 0 + max: 10000000 + distinct: false + elemType: "int" + nums2: + gen: "array" + len: 14 + of: + gen: "int" + min: 0 + max: 10000000 + distinct: false + elemType: "int" + seed: 187901 + - name: generated-random-2 + in: + nums1: + gen: "array" + len: 14 + of: + gen: "int" + min: 0 + max: 10000000 + distinct: false + elemType: "int" + nums2: + gen: "array" + len: 14 + of: + gen: "int" + min: 0 + max: 10000000 + distinct: false + elemType: "int" + seed: 187902 + - name: generated-small-values + in: + nums1: + gen: "array" + len: 14 + of: + gen: "int" + min: 0 + max: 63 + distinct: false + elemType: "int" + nums2: + gen: "array" + len: 14 + of: + gen: "int" + min: 0 + max: 63 + distinct: false + elemType: "int" + seed: 187903 + - name: generated-duplicates + in: + nums1: + gen: "array" + len: 14 + of: + gen: "int" + min: 0 + max: 7 + distinct: false + elemType: "int" + nums2: + gen: "array" + len: 14 + of: + gen: "int" + min: 0 + max: 7 + distinct: false + elemType: "int" + seed: 187904 + - name: generated-boundary + in: + nums1: + gen: "array" + len: 14 + of: + gen: "int" + min: 9990000 + max: 10000000 + distinct: false + elemType: "int" + nums2: + gen: "array" + len: 14 + of: + gen: "int" + min: 0 + max: 1000 + distinct: false + elemType: "int" + seed: 187905 diff --git a/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.cpp b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.cpp new file mode 100644 index 00000000..37d33501 --- /dev/null +++ b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int minimumXORSum(vector& nums1, vector& nums2) { + int n = nums1.size(); + int fullMask = 1 << n; + vector dp(fullMask, 2147483647); + dp[0] = 0; + for (int mask = 0; mask < fullMask; mask++) { + int idx = __builtin_popcount(mask); + if (idx >= n) continue; + for (int j = 0; j < n; j++) { + if ((mask & (1 << j)) == 0) { + int nextMask = mask | (1 << j); + int cost = dp[mask] + (nums1[idx] ^ nums2[j]); + if (cost < dp[nextMask]) { + dp[nextMask] = cost; + } + } + } + } + return dp[fullMask - 1]; + } +}; diff --git a/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.cs b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.cs new file mode 100644 index 00000000..a435f8ff --- /dev/null +++ b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.cs @@ -0,0 +1,23 @@ +public class Solution { + public int MinimumXORSum(int[] nums1, int[] nums2) { + int n = nums1.Length; + int fullMask = 1 << n; + int[] dp = new int[fullMask]; + for (int i = 0; i < fullMask; i++) dp[i] = 2147483647; + dp[0] = 0; + for (int mask = 0; mask < fullMask; mask++) { + int idx = Convert.ToString(mask, 2).Count(c => c == '1'); + if (idx >= n) continue; + for (int j = 0; j < n; j++) { + if ((mask & (1 << j)) == 0) { + int nextMask = mask | (1 << j); + int cost = dp[mask] + (nums1[idx] ^ nums2[j]); + if (cost < dp[nextMask]) { + dp[nextMask] = cost; + } + } + } + } + return dp[fullMask - 1]; + } +} diff --git a/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.dart b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.dart new file mode 100644 index 00000000..4842e038 --- /dev/null +++ b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.dart @@ -0,0 +1,22 @@ +class Solution { + int minimumXORSum(List nums1, List nums2) { + int n = nums1.length; + int fullMask = 1 << n; + List dp = List.filled(fullMask, 2147483647); + dp[0] = 0; + for (int mask = 0; mask < fullMask; mask++) { + int idx = mask.toRadixString(2).split('1').length - 1; + if (idx >= n) continue; + for (int j = 0; j < n; j++) { + if ((mask & (1 << j)) == 0) { + int nextMask = mask | (1 << j); + int cost = dp[mask] + (nums1[idx] ^ nums2[j]); + if (cost < dp[nextMask]) { + dp[nextMask] = cost; + } + } + } + } + return dp[fullMask - 1]; + } +} diff --git a/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.go b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.go new file mode 100644 index 00000000..bf6e04b4 --- /dev/null +++ b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.go @@ -0,0 +1,25 @@ +func minimumXORSum(nums1 []int, nums2 []int) int { + n := len(nums1) + fullMask := 1 << n + dp := make([]int, fullMask) + for i := range dp { + dp[i] = 2147483647 + } + dp[0] = 0 + for mask := 0; mask < fullMask; mask++ { + idx := bits.OnesCount(uint(mask)) + if idx >= n { + continue + } + for j := 0; j < n; j++ { + if (mask & (1 << j)) == 0 { + nextMask := mask | (1 << j) + cost := dp[mask] + (nums1[idx] ^ nums2[j]) + if cost < dp[nextMask] { + dp[nextMask] = cost + } + } + } + } + return dp[fullMask-1] +} diff --git a/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.java b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.java new file mode 100644 index 00000000..f31025a8 --- /dev/null +++ b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.java @@ -0,0 +1,23 @@ +class Solution { + public int minimumXORSum(int[] nums1, int[] nums2) { + int n = nums1.length; + int fullMask = 1 << n; + int[] dp = new int[fullMask]; + Arrays.fill(dp, Integer.MAX_VALUE); + dp[0] = 0; + for (int mask = 0; mask < fullMask; mask++) { + int idx = Integer.bitCount(mask); + if (idx >= n) continue; + for (int j = 0; j < n; j++) { + if ((mask & (1 << j)) == 0) { + int nextMask = mask | (1 << j); + int cost = dp[mask] + (nums1[idx] ^ nums2[j]); + if (cost < dp[nextMask]) { + dp[nextMask] = cost; + } + } + } + } + return dp[fullMask - 1]; + } +} diff --git a/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.kt b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.kt new file mode 100644 index 00000000..bb8c088f --- /dev/null +++ b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.kt @@ -0,0 +1,22 @@ +class Solution { + fun minimumXORSum(nums1: IntArray, nums2: IntArray): Int { + val n = nums1.size + val fullMask = 1 shl n + val dp = IntArray(fullMask) { Int.MAX_VALUE } + dp[0] = 0 + for (mask in 0 until fullMask) { + val idx = Integer.bitCount(mask) + if (idx >= n) continue + for (j in 0 until n) { + if ((mask and (1 shl j)) == 0) { + val nextMask = mask or (1 shl j) + val cost = dp[mask] + (nums1[idx] xor nums2[j]) + if (cost < dp[nextMask]) { + dp[nextMask] = cost + } + } + } + } + return dp[fullMask - 1] + } +} diff --git a/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.py b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.py new file mode 100644 index 00000000..0efdb061 --- /dev/null +++ b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.py @@ -0,0 +1,16 @@ +class Solution: + def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int: + fullMask = 1 << len(nums1) + dp = [2147483647 for mask in range(fullMask)] + dp[0] = 0 + for mask in range(fullMask): + index = bin(mask).count("1") + if index >= len(nums1): + continue + for jndex in range(len(nums1)): + if (mask & (1 << jndex)) == 0: + nextMask = mask | (1 << jndex) + cost = dp[mask] + (nums1[index] ^ nums2[jndex]) + if cost < dp[nextMask]: + dp[nextMask] = cost + return dp[fullMask - 1] diff --git a/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.py2 b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.py2 new file mode 100644 index 00000000..6b64f854 --- /dev/null +++ b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def minimumXORSum(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: int + """ + n = len(nums1) + full_mask = 1 << n + dp = [2147483647] * full_mask + dp[0] = 0 + for mask in range(full_mask): + idx = bin(mask).count('1') + if idx >= n: + continue + for j in range(n): + if (mask & (1 << j)) == 0: + next_mask = mask | (1 << j) + cost = dp[mask] + (nums1[idx] ^ nums2[j]) + if cost < dp[next_mask]: + dp[next_mask] = cost + return dp[full_mask - 1] diff --git a/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.rb b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.rb new file mode 100644 index 00000000..3b4253ff --- /dev/null +++ b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.rb @@ -0,0 +1,21 @@ +# @param {Integer[]} nums1 +# @param {Integer[]} nums2 +# @return {Integer} +def minimum_xor_sum(nums1, nums2) + n = nums1.length + full_mask = 1 << n + dp = Array.new(full_mask, 2147483647) + dp[0] = 0 + (0...full_mask).each do |mask| + idx = mask.to_s(2).count('1') + next if idx >= n + (0...n).each do |j| + if (mask & (1 << j)) == 0 + next_mask = mask | (1 << j) + cost = dp[mask] + (nums1[idx] ^ nums2[j]) + dp[next_mask] = cost if cost < dp[next_mask] + end + end + end + dp[full_mask - 1] +end diff --git a/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.rs b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.rs new file mode 100644 index 00000000..a2fe50bf --- /dev/null +++ b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.rs @@ -0,0 +1,22 @@ +impl Solution { + pub fn minimum_xor_sum(nums1: Vec, nums2: Vec) -> i32 { + let n = nums1.len(); + let full_mask = 1 << n; + let mut dp = vec![2147483647; full_mask]; + dp[0] = 0; + for mask in 0..full_mask { + let idx = mask.count_ones() as usize; + if idx >= n { continue; } + for j in 0..n { + if (mask & (1 << j)) == 0 { + let next_mask = mask | (1 << j); + let cost = dp[mask] + (nums1[idx] ^ nums2[j]); + if cost < dp[next_mask] { + dp[next_mask] = cost; + } + } + } + } + dp[full_mask - 1] + } +} diff --git a/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.swift b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.swift new file mode 100644 index 00000000..0dcd33f4 --- /dev/null +++ b/tests/1501-2000/1879. minimum-xor-sum-of-two-arrays/sol.swift @@ -0,0 +1,22 @@ +class Solution { + func minimumXORSum(_ nums1: [Int], _ nums2: [Int]) -> Int { + let n = nums1.count + let fullMask = 1 << n + var dp = [Int](repeating: 2147483647, count: fullMask) + dp[0] = 0 + for mask in 0..= n { continue } + for j in 0.. 0) { + idx += temp & 1; + temp >>= 1; + } + if (idx >= n) continue; + for (let j = 0; j < n; j++) { + if ((mask & (1 << j)) === 0) { + const nextMask = mask | (1 << j); + const cost = dp[mask] + (nums1[idx] ^ nums2[j]); + if (cost < dp[nextMask]) { + dp[nextMask] = cost; + } + } + } + } + return dp[fullMask - 1]; +} diff --git a/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/manifest.yaml b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/manifest.yaml new file mode 100644 index 00000000..85cacded --- /dev/null +++ b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/manifest.yaml @@ -0,0 +1,367 @@ +entry: + id: 1880 + title: "check-if-word-equals-summation-of-two-words" + params: + firstWord: + type: string + secondWord: + type: string + targetWord: + type: string + call: + cpp: "Solution().isSumEqual({firstWord}, {secondWord}, {targetWord})" + rust: "Solution::is_sum_equal({firstWord}, {secondWord}, {targetWord})" + python3: "Solution().isSumEqual({firstWord}, {secondWord}, {targetWord})" + python2: "Solution().isSumEqual({firstWord}, {secondWord}, {targetWord})" + ruby: "is_sum_equal({firstWord}, {secondWord}, {targetWord})" + java: "new Solution().isSumEqual({firstWord}, {secondWord}, {targetWord})" + csharp: "new Solution().IsSumEqual({firstWord}, {secondWord}, {targetWord})" + kotlin: "Solution().isSumEqual({firstWord}, {secondWord}, {targetWord})" + go: "isSumEqual({firstWord}, {secondWord}, {targetWord})" + dart: "Solution().isSumEqual({firstWord}, {secondWord}, {targetWord})" + swift: "Solution().isSumEqual({firstWord}, {secondWord}, {targetWord})" + typescript: "isSumEqual({firstWord}, {secondWord}, {targetWord})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().isSumEqual(firstWord, secondWord, targetWord, {result})" + checker: | + class Checker: + def _value(self, word): + return int("".join(str(ord(ch) - ord("a")) for ch in word)) + + def isSumEqual(self, firstWord, secondWord, targetWord, result): + expected = (self._value(firstWord) + self._value(secondWord) + == self._value(targetWord)) + return result is expected + +seed: 1880 + +tests: + - name: example-1 + in: + firstWord: acb + secondWord: cba + targetWord: cdb + out: true + judge: + type: "exact" + - name: example-2 + in: + firstWord: aaa + secondWord: a + targetWord: aab + out: false + judge: + type: "exact" + - name: example-3 + in: + firstWord: aaa + secondWord: a + targetWord: aaaa + out: true + judge: + type: "exact" + - name: all-zero-single + in: + firstWord: a + secondWord: a + targetWord: a + out: true + judge: + type: "exact" + - name: zero-length-effect + in: + firstWord: aaaa + secondWord: aaaa + targetWord: aaaaaaaa + out: true + judge: + type: "exact" + - name: one-digit-carry + in: + firstWord: j + secondWord: j + targetWord: ba + out: false + judge: + type: "exact" + - name: direct-small-sum + in: + firstWord: b + secondWord: c + targetWord: e + out: false + judge: + type: "exact" + - name: direct-small-false + in: + firstWord: b + secondWord: c + targetWord: d + out: true + judge: + type: "exact" + - name: leading-zero-target + in: + firstWord: ab + secondWord: c + targetWord: ad + out: true + judge: + type: "exact" + - name: leading-zero-false + in: + firstWord: ab + secondWord: c + targetWord: ae + out: false + judge: + type: "exact" + - name: max-digits + in: + firstWord: jjjjjjjj + secondWord: aaaaaaaa + targetWord: jjjjjjjj + out: true + judge: + type: "exact" + - name: max-digits-false + in: + firstWord: jjjjjjjj + secondWord: jjjjjjjj + targetWord: jjjjjjjj + out: false + judge: + type: "exact" + - name: repeated-twos + in: + firstWord: ccc + secondWord: ccc + targetWord: ggg + out: false + judge: + type: "exact" + - name: mixed-values + in: + firstWord: bdf + secondWord: ace + targetWord: bjj + out: false + judge: + type: "exact" + - name: mixed-values-false + in: + firstWord: bdf + secondWord: ace + targetWord: bji + out: false + judge: + type: "exact" + - name: carry-chain + in: + firstWord: jjj + secondWord: a + targetWord: jjj + out: true + judge: + type: "exact" + - name: carry-chain-false + in: + firstWord: jjj + secondWord: j + targetWord: jjj + out: false + judge: + type: "exact" + - name: different-lengths + in: + firstWord: bc + secondWord: def + targetWord: deg + out: false + judge: + type: "exact" + - name: different-lengths-false + in: + firstWord: bc + secondWord: def + targetWord: deh + out: false + judge: + type: "exact" + - name: high-prefix + in: + firstWord: jba + secondWord: a + targetWord: jba + out: true + judge: + type: "exact" + - name: high-prefix-false + in: + firstWord: jba + secondWord: b + targetWord: jba + out: false + judge: + type: "exact" + - name: palindrome-words + in: + firstWord: abcba + secondWord: abcba + targetWord: bdfda + out: false + judge: + type: "exact" + - name: palindrome-false + in: + firstWord: abcba + secondWord: abcba + targetWord: bdfdb + out: false + judge: + type: "exact" + - name: sparse-digits + in: + firstWord: ajaj + secondWord: jaja + targetWord: jjjj + out: true + judge: + type: "exact" + - name: sparse-digits-false + in: + firstWord: ajaj + secondWord: jaja + targetWord: jjjk + out: false + judge: + type: "exact" + - name: alternating + in: + firstWord: bdbd + secondWord: dbdb + targetWord: ffff + out: false + judge: + type: "exact" + - name: alternating-false + in: + firstWord: bdbd + secondWord: dbdb + targetWord: fffe + out: false + judge: + type: "exact" + - name: long-zero-prefix + in: + firstWord: aaaaaaab + secondWord: a + targetWord: aaaaaaab + out: true + judge: + type: "exact" + - name: long-zero-prefix-false + in: + firstWord: aaaaaaab + secondWord: b + targetWord: aaaaaaab + out: false + judge: + type: "exact" + - name: all-nines-plus-zero + in: + firstWord: iiiiiiii + secondWord: aaaaaaaa + targetWord: iiiiiiii + out: true + judge: + type: "exact" + - name: all-nines-plus-one + in: + firstWord: iiiiiiii + secondWord: b + targetWord: iiiiiiii + out: false + judge: + type: "exact" + - name: unequal-leading-length + in: + firstWord: aj + secondWord: a + targetWord: aj + out: true + judge: + type: "exact" + - name: maximal-carry + in: + firstWord: jjjj + secondWord: jjjj + targetWord: jjjj + out: false + judge: + type: "exact" + - name: values-with-zero-letter + in: + firstWord: bja + secondWord: ajb + targetWord: bjj + out: false + judge: + type: "exact" + - name: values-with-zero-false + in: + firstWord: bja + secondWord: ajb + targetWord: bji + out: false + judge: + type: "exact" + - name: generator-balanced + in: + firstWord: abcdefgh + secondWord: ijabcdef + targetWord: ijjdefgh + out: false + judge: + type: "exact" + - name: generator-short-mix + in: + firstWord: j + secondWord: aa + targetWord: j + out: true + judge: + type: "exact" + - name: generator-medium + in: + firstWord: abcde + secondWord: fghijk + targetWord: fghhfg + out: false + judge: + type: "exact" + - name: generator-long-zero-heavy + in: + firstWord: aaaaaaab + secondWord: aaaaaaac + targetWord: aaaaaaad + out: true + judge: + type: "exact" + - name: generator-extreme + in: + firstWord: ajaj + secondWord: jaja + targetWord: jjjj + out: true + judge: + type: "exact" diff --git a/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.cpp b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.cpp new file mode 100644 index 00000000..54f1e242 --- /dev/null +++ b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + bool isSumEqual(string firstWord, string secondWord, string targetWord) { + auto convert = [](const string& word) { + string s; + for (char c : word) { + s += to_string(c - 'a'); + } + return stoi(s); + }; + return convert(firstWord) + convert(secondWord) == convert(targetWord); + } +}; diff --git a/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.cs b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.cs new file mode 100644 index 00000000..3864f03f --- /dev/null +++ b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.cs @@ -0,0 +1,12 @@ +public class Solution { + public bool IsSumEqual(string firstWord, string secondWord, string targetWord) { + int Convert(string word) { + string s = ""; + foreach (char c in word) { + s += (c - 'a').ToString(); + } + return int.Parse(s); + } + return Convert(firstWord) + Convert(secondWord) == Convert(targetWord); + } +} diff --git a/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.dart b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.dart new file mode 100644 index 00000000..a9933806 --- /dev/null +++ b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.dart @@ -0,0 +1,12 @@ +class Solution { + bool isSumEqual(String firstWord, String secondWord, String targetWord) { + int convert(String word) { + String s = ""; + for (int i = 0; i < word.length; i++) { + s += (word.codeUnitAt(i) - 'a'.codeUnitAt(0)).toString(); + } + return int.parse(s); + } + return convert(firstWord) + convert(secondWord) == convert(targetWord); + } +} diff --git a/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.go b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.go new file mode 100644 index 00000000..a2171d14 --- /dev/null +++ b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.go @@ -0,0 +1,10 @@ +func isSumEqual(firstWord string, secondWord string, targetWord string) bool { + convert := func(word string) int { + result := 0 + for _, ch := range word { + result = result*10 + int(ch-'a') + } + return result + } + return convert(firstWord)+convert(secondWord) == convert(targetWord) +} diff --git a/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.java b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.java new file mode 100644 index 00000000..399d2221 --- /dev/null +++ b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.java @@ -0,0 +1,16 @@ +class Solution { + public boolean isSumEqual(String firstWord, String secondWord, String targetWord) { + int first = convert(firstWord); + int second = convert(secondWord); + int target = convert(targetWord); + return first + second == target; + } + + private int convert(String word) { + StringBuilder sb = new StringBuilder(); + for (char c : word.toCharArray()) { + sb.append((int)(c - 'a')); + } + return Integer.parseInt(sb.toString()); + } +} diff --git a/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.kt b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.kt new file mode 100644 index 00000000..b9f0f055 --- /dev/null +++ b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.kt @@ -0,0 +1,8 @@ +class Solution { + fun isSumEqual(firstWord: String, secondWord: String, targetWord: String): Boolean { + fun convert(word: String): Int { + return word.map { it - 'a' }.joinToString("").toInt() + } + return convert(firstWord) + convert(secondWord) == convert(targetWord) + } +} diff --git a/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.py b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.py new file mode 100644 index 00000000..e279967b --- /dev/null +++ b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.py @@ -0,0 +1,7 @@ +class Solution: + def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool: + + def convert(word): + return int("".join(str(ord(ch) - ord("a")) for ch in word)) + + return convert(firstWord) + convert(secondWord) == convert(targetWord) diff --git a/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.py2 b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.py2 new file mode 100644 index 00000000..8ae0a496 --- /dev/null +++ b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def isSumEqual(self, firstWord, secondWord, targetWord): + """ + :type firstWord: str + :type secondWord: str + :type targetWord: str + :rtype: bool + """ + def convert(word): + return int("".join(str(ord(ch) - ord("a")) for ch in word)) + + return convert(firstWord) + convert(secondWord) == convert(targetWord) diff --git a/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.rb b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.rb new file mode 100644 index 00000000..ee03094c --- /dev/null +++ b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.rb @@ -0,0 +1,10 @@ +# @param {String} first_word +# @param {String} second_word +# @param {String} target_word +# @return {Boolean} +def is_sum_equal(first_word, second_word, target_word) + convert = lambda do |word| + word.chars.map { |ch| (ch.ord - "a".ord).to_s }.join.to_i + end + convert.call(first_word) + convert.call(second_word) == convert.call(target_word) +end diff --git a/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.rs b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.rs new file mode 100644 index 00000000..c887d969 --- /dev/null +++ b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.rs @@ -0,0 +1,9 @@ +impl Solution { + pub fn is_sum_equal(first_word: String, second_word: String, target_word: String) -> bool { + fn convert(word: &str) -> i32 { + let s: String = word.chars().map(|c| (c as u8 - b'a').to_string()).collect(); + s.parse().unwrap() + } + convert(&first_word) + convert(&second_word) == convert(&target_word) + } +} diff --git a/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.swift b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.swift new file mode 100644 index 00000000..16f23f8d --- /dev/null +++ b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.swift @@ -0,0 +1,12 @@ +class Solution { + func isSumEqual(_ firstWord: String, _ secondWord: String, _ targetWord: String) -> Bool { + func convert(_ word: String) -> Int { + var s = "" + for ch in word { + s += String(ch.asciiValue! - Character("a").asciiValue!) + } + return Int(s) ?? 0 + } + return convert(firstWord) + convert(secondWord) == convert(targetWord) + } +} diff --git a/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.ts b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.ts new file mode 100644 index 00000000..f7650ae4 --- /dev/null +++ b/tests/1501-2000/1880. check-if-word-equals-summation-of-two-words/sol.ts @@ -0,0 +1,15 @@ +function isSumEqual( + firstWord: string, + secondWord: string, + targetWord: string, +): boolean { + const convert = (word: string): number => { + return parseInt( + word + .split("") + .map((ch) => ch.charCodeAt(0) - "a".charCodeAt(0)) + .join(""), + ); + }; + return convert(firstWord) + convert(secondWord) === convert(targetWord); +} diff --git a/tests/1501-2000/1881. maximum-value-after-insertion/manifest.yaml b/tests/1501-2000/1881. maximum-value-after-insertion/manifest.yaml new file mode 100644 index 00000000..4d633c33 --- /dev/null +++ b/tests/1501-2000/1881. maximum-value-after-insertion/manifest.yaml @@ -0,0 +1,265 @@ +entry: + id: 1881 + title: "maximum-value-after-insertion" + params: + n: + type: string + x: + type: int + call: + cpp: "Solution().maxValue({n}, {x})" + rust: "Solution::max_value({n}, {x})" + python3: "Solution().maxValue({n}, {x})" + python2: "Solution().maxValue({n}, {x})" + ruby: "max_value({n}, {x})" + java: "new Solution().maxValue({n}, {x})" + csharp: "new Solution().MaxValue({n}, {x})" + kotlin: "Solution().maxValue({n}, {x})" + go: "maxValue({n}, {x})" + dart: "Solution().maxValue({n}, {x})" + swift: "Solution().maxValue({n}, {x})" + typescript: "maxValue({n}, {x})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().maxValue(n, x, {result})" + checker: | + class Checker: + def maxValue(self, n, x, result): + if not isinstance(n, str) or not isinstance(x, int): + return False + if not isinstance(result, str): + return False + if len(result) >= 2 and result[0] == '"' and result[-1] == '"': + result = result[1:-1] + digit = str(x) + if n.startswith('-'): + index = len(n) + for i in range(1, len(n)): + if digit < n[i]: + index = i + break + expected = n[:index] + digit + n[index:] + else: + index = len(n) + for i in range(len(n)): + if digit > n[i]: + index = i + break + expected = n[:index] + digit + n[index:] + return result == expected + +seed: 1881 + +tests: + - name: "example_positive_equal" + in: + n: "99" + x: 9 + - name: "example_negative" + in: + n: "-13" + x: 2 + - name: "positive_insert_front" + in: + n: "73" + x: 6 + - name: "positive_append" + in: + n: "1234" + x: 1 + - name: "positive_middle" + in: + n: "468" + x: 7 + - name: "single_digit_equal" + in: + n: "5" + x: 5 + - name: "single_digit_larger" + in: + n: "4" + x: 9 + - name: "single_digit_smaller" + in: + n: "9" + x: 1 + - name: "all_small_digits" + in: + n: "11111" + x: 2 + - name: "all_large_digits" + in: + n: "88888" + x: 9 + - name: "equal_run" + in: + n: "55555" + x: 5 + - name: "descending_digits" + in: + n: "987654321" + x: 6 + - name: "ascending_digits" + in: + n: "123456789" + x: 5 + - name: "insert_before_first_larger" + in: + n: "13579" + x: 6 + - name: "insert_after_equal_prefix" + in: + n: "666123" + x: 6 + - name: "insert_before_last" + in: + n: "1128" + x: 8 + - name: "negative_example_variant" + in: + n: "-55" + x: 2 + - name: "negative_insert_after_sign" + in: + n: "-999" + x: 1 + - name: "negative_append_small" + in: + n: "-123" + x: 1 + - name: "negative_before_smaller_digit" + in: + n: "-9876" + x: 8 + - name: "negative_equal_digits" + in: + n: "-4444" + x: 4 + - name: "negative_mixed" + in: + n: "-7654321" + x: 6 + - name: "negative_insert_early" + in: + n: "-321987" + x: 2 + - name: "negative_insert_late" + in: + n: "-111222333" + x: 2 + - name: "negative_x_nine" + in: + n: "-123456" + x: 9 + - name: "positive_x_one" + in: + n: "987654" + x: 1 + - name: "positive_x_nine" + in: + n: "123456" + x: 9 + - name: "alternating_digits" + in: + n: "12121212" + x: 2 + - name: "mostly_equal_positive" + in: + n: "777778" + x: 7 + - name: "mostly_equal_negative" + in: + n: "-777778" + x: 7 + - name: "long_positive_100" + in: + n: "1234567891234567891234567891234567891234567891234567891234567891234567891234567891234567891234567891" + x: 9 + - name: "long_negative_100" + in: + n: "-9876543219876543219876543219876543219876543219876543219876543219876543219876543219876543219876543219" + x: 1 + - name: "repeated_nine_positive" + in: + n: "99999999999999999999" + x: 1 + - name: "repeated_one_negative" + in: + n: "-11111111111111111111" + x: 9 + - name: "negative_large_x_equal" + in: + n: "-8989898989" + x: 8 + - name: "generated_positive_small" + seed: 188101 + in: + n: + gen: "str" + len: + gen: "int" + min: 1 + max: 40 + alphabet: "123456789" + x: + gen: "int" + min: 1 + max: 9 + - name: "generated_positive_medium" + seed: 188102 + in: + n: + gen: "str" + len: + gen: "int" + min: 100 + max: 1000 + alphabet: "123456789" + x: + gen: "int" + min: 1 + max: 9 + - name: "generated_positive_large" + seed: 188103 + in: + n: + gen: "str" + len: 100000 + alphabet: "123456789" + x: + gen: "int" + min: 1 + max: 9 + - name: "generated_positive_large_two" + seed: 188104 + in: + n: + gen: "str" + len: 99999 + alphabet: "123456789" + x: + gen: "int" + min: 1 + max: 9 + - name: "generated_positive_boundary" + seed: 188105 + in: + n: + gen: "str" + len: + gen: "int" + min: 1 + max: 100000 + alphabet: "19" + x: + gen: "int" + min: 1 + max: 9 diff --git a/tests/1501-2000/1881. maximum-value-after-insertion/sol.cpp b/tests/1501-2000/1881. maximum-value-after-insertion/sol.cpp new file mode 100644 index 00000000..4abe212a --- /dev/null +++ b/tests/1501-2000/1881. maximum-value-after-insertion/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + string maxValue(string n, int x) { + string xs = to_string(x); + if (n[0] != '-') { + for (int i = 0; i < n.size(); i++) { + if (xs[0] > n[i]) { + return n.substr(0, i) + xs + n.substr(i); + } + } + return n + xs; + } else { + for (int i = 1; i < n.size(); i++) { + if (xs[0] < n[i]) { + return n.substr(0, i) + xs + n.substr(i); + } + } + return n + xs; + } + } +}; diff --git a/tests/1501-2000/1881. maximum-value-after-insertion/sol.cs b/tests/1501-2000/1881. maximum-value-after-insertion/sol.cs new file mode 100644 index 00000000..bc649487 --- /dev/null +++ b/tests/1501-2000/1881. maximum-value-after-insertion/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public string MaxValue(string n, int x) { + string xs = x.ToString(); + if (n[0] != '-') { + for (int i = 0; i < n.Length; i++) { + if (xs[0] > n[i]) { + return n.Substring(0, i) + xs + n.Substring(i); + } + } + return n + xs; + } else { + for (int i = 1; i < n.Length; i++) { + if (xs[0] < n[i]) { + return n.Substring(0, i) + xs + n.Substring(i); + } + } + return n + xs; + } + } +} diff --git a/tests/1501-2000/1881. maximum-value-after-insertion/sol.dart b/tests/1501-2000/1881. maximum-value-after-insertion/sol.dart new file mode 100644 index 00000000..26cbcbe0 --- /dev/null +++ b/tests/1501-2000/1881. maximum-value-after-insertion/sol.dart @@ -0,0 +1,20 @@ +class Solution { + String maxValue(String n, int x) { + String xs = x.toString(); + if (n[0] != '-') { + for (int i = 0; i < n.length; i++) { + if (xs[0].compareTo(n[i]) > 0) { + return n.substring(0, i) + xs + n.substring(i); + } + } + return n + xs; + } else { + for (int i = 1; i < n.length; i++) { + if (xs[0].compareTo(n[i]) < 0) { + return n.substring(0, i) + xs + n.substring(i); + } + } + return n + xs; + } + } +} diff --git a/tests/1501-2000/1881. maximum-value-after-insertion/sol.go b/tests/1501-2000/1881. maximum-value-after-insertion/sol.go new file mode 100644 index 00000000..7d930716 --- /dev/null +++ b/tests/1501-2000/1881. maximum-value-after-insertion/sol.go @@ -0,0 +1,18 @@ +func maxValue(n string, x int) string { + xs := strconv.Itoa(x) + if n[0] != '-' { + for i := 0; i < len(n); i++ { + if xs[0] > n[i] { + return n[:i] + xs + n[i:] + } + } + return n + xs + } else { + for i := 1; i < len(n); i++ { + if xs[0] < n[i] { + return n[:i] + xs + n[i:] + } + } + return n + xs + } +} diff --git a/tests/1501-2000/1881. maximum-value-after-insertion/sol.java b/tests/1501-2000/1881. maximum-value-after-insertion/sol.java new file mode 100644 index 00000000..1454624e --- /dev/null +++ b/tests/1501-2000/1881. maximum-value-after-insertion/sol.java @@ -0,0 +1,20 @@ +class Solution { + public String maxValue(String n, int x) { + String xs = String.valueOf(x); + if (n.charAt(0) != '-') { + for (int i = 0; i < n.length(); i++) { + if (xs.charAt(0) > n.charAt(i)) { + return n.substring(0, i) + xs + n.substring(i); + } + } + return n + xs; + } else { + for (int i = 1; i < n.length(); i++) { + if (xs.charAt(0) < n.charAt(i)) { + return n.substring(0, i) + xs + n.substring(i); + } + } + return n + xs; + } + } +} diff --git a/tests/1501-2000/1881. maximum-value-after-insertion/sol.kt b/tests/1501-2000/1881. maximum-value-after-insertion/sol.kt new file mode 100644 index 00000000..5d60ca24 --- /dev/null +++ b/tests/1501-2000/1881. maximum-value-after-insertion/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun maxValue(n: String, x: Int): String { + val xs = x.toString() + return if (n[0] != '-') { + for (i in n.indices) { + if (xs[0] > n[i]) { + return n.substring(0, i) + xs + n.substring(i) + } + } + n + xs + } else { + for (i in 1 until n.length) { + if (xs[0] < n[i]) { + return n.substring(0, i) + xs + n.substring(i) + } + } + n + xs + } + } +} diff --git a/tests/1501-2000/1881. maximum-value-after-insertion/sol.py b/tests/1501-2000/1881. maximum-value-after-insertion/sol.py new file mode 100644 index 00000000..5015c01b --- /dev/null +++ b/tests/1501-2000/1881. maximum-value-after-insertion/sol.py @@ -0,0 +1,19 @@ +class Solution(object): + def maxValue(self, n, x): + """ + :type n: str + :type x: int + :rtype: str + """ + x = str(x) + + if n[0] != "-": + for i in range(len(n)): + if x > n[i]: + return n[:i] + x + n[i:] + return n + x + else: + for i in range(1, len(n)): + if x < n[i]: + return n[:i] + x + n[i:] + return n + x diff --git a/tests/1501-2000/1881. maximum-value-after-insertion/sol.py2 b/tests/1501-2000/1881. maximum-value-after-insertion/sol.py2 new file mode 100644 index 00000000..c0df9a5e --- /dev/null +++ b/tests/1501-2000/1881. maximum-value-after-insertion/sol.py2 @@ -0,0 +1,19 @@ +class Solution(object): + def maxValue(self, n, x): + """ + :type n: str + :type x: int + :rtype: str + """ + x = str(x) + + if n[0] != '-': + for i in range(len(n)): + if x > n[i]: + return n[:i] + x + n[i:] + return n + x + else: + for i in range(1, len(n)): + if x < n[i]: + return n[:i] + x + n[i:] + return n + x diff --git a/tests/1501-2000/1881. maximum-value-after-insertion/sol.rb b/tests/1501-2000/1881. maximum-value-after-insertion/sol.rb new file mode 100644 index 00000000..74a8d28a --- /dev/null +++ b/tests/1501-2000/1881. maximum-value-after-insertion/sol.rb @@ -0,0 +1,21 @@ +# @param {String} n +# @param {Integer} x +# @return {String} +def max_value(n, x) + x = x.to_s + if n[0] != '-' + n.each_char.with_index do |c, i| + if x > c + return n[0...i] + x + n[i..] + end + end + return n + x + else + (1...n.length).each do |i| + if x < n[i] + return n[0...i] + x + n[i..] + end + end + return n + x + end +end diff --git a/tests/1501-2000/1881. maximum-value-after-insertion/sol.rs b/tests/1501-2000/1881. maximum-value-after-insertion/sol.rs new file mode 100644 index 00000000..31335d4f --- /dev/null +++ b/tests/1501-2000/1881. maximum-value-after-insertion/sol.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn max_value(n: String, x: i32) -> String { + let xs = x.to_string(); + let chars: Vec = n.chars().collect(); + if chars[0] != '-' { + for (i, &c) in chars.iter().enumerate() { + if xs.chars().next().unwrap() > c { + return format!("{}{}{}", &n[..i], xs, &n[i..]); + } + } + return n + &xs; + } else { + for i in 1..chars.len() { + if xs.chars().next().unwrap() < chars[i] { + return format!("{}{}{}", &n[..i], xs, &n[i..]); + } + } + return n + &xs; + } + } +} diff --git a/tests/1501-2000/1881. maximum-value-after-insertion/sol.swift b/tests/1501-2000/1881. maximum-value-after-insertion/sol.swift new file mode 100644 index 00000000..f721cf50 --- /dev/null +++ b/tests/1501-2000/1881. maximum-value-after-insertion/sol.swift @@ -0,0 +1,21 @@ +class Solution { + func maxValue(_ n: String, _ x: Int) -> String { + let xs = String(x) + let chars = Array(n) + if chars[0] != "-" { + for i in 0.. String(chars[i]) { + return String(chars[0.. n[i]) { + return n.slice(0, i) + xs + n.slice(i); + } + } + return n + xs; + } else { + for (let i = 1; i < n.length; i++) { + if (xs < n[i]) { + return n.slice(0, i) + xs + n.slice(i); + } + } + return n + xs; + } +} diff --git a/tests/1501-2000/1882. process-tasks-using-servers/manifest.yaml b/tests/1501-2000/1882. process-tasks-using-servers/manifest.yaml new file mode 100644 index 00000000..98d297b2 --- /dev/null +++ b/tests/1501-2000/1882. process-tasks-using-servers/manifest.yaml @@ -0,0 +1,340 @@ +entry: + id: 1882 + title: "process-tasks-using-servers" + params: + servers: + type: array + items: + type: int + tasks: + type: array + items: + type: int + call: + cpp: "Solution().assignTasks({servers}, {tasks})" + rust: "Solution::assign_tasks({servers}, {tasks})" + python3: "Solution().assignTasks({servers}, {tasks})" + python2: "Solution().assignTasks({servers}, {tasks})" + ruby: "assign_tasks({servers}, {tasks})" + java: "new Solution().assignTasks({servers}, {tasks})" + csharp: "new Solution().AssignTasks({servers}, {tasks})" + kotlin: "Solution().assignTasks({servers}, {tasks})" + go: "assignTasks({servers}, {tasks})" + dart: "Solution().assignTasks({servers}, {tasks})" + swift: "Solution().assignTasks({servers}, {tasks})" + typescript: "assignTasks({servers}, {tasks})" +judge: + type: "exact" +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().assignTasks(servers, tasks, {result})" + checker: | + import heapq + class Checker: + def assignTasks(self, servers, tasks, result): + if not isinstance(result, list) or len(result) != len(tasks): + return False + available = [(w, i) for i, w in enumerate(servers)] + heapq.heapify(available) + busy = [] + expected = [] + time = 0 + for j, duration in enumerate(tasks): + time = max(time, j) + while busy and busy[0][0] <= time: + finish, weight, index = heapq.heappop(busy) + heapq.heappush(available, (weight, index)) + if not available: + time = busy[0][0] + while busy and busy[0][0] <= time: + finish, weight, index = heapq.heappop(busy) + heapq.heappush(available, (weight, index)) + weight, index = heapq.heappop(available) + heapq.heappush(busy, (time + duration, weight, index)) + expected.append(index) + return result == expected +seed: 1882 +tests: + - name: example-one + in: + servers: [3, 3, 2] + tasks: [1, 2, 3, 2, 1, 2] + out: [2, 2, 0, 2, 1, 2] + - name: example-two + in: + servers: [5, 1, 4, 3, 2] + tasks: [2, 1, 2, 4, 5, 2, 1] + out: [1, 4, 1, 4, 1, 3, 2] + - name: one-server-short-tasks + in: + servers: [7] + tasks: [1, 1, 1, 1, 1] + out: [0, 0, 0, 0, 0] + - name: one-server-long-tasks + in: + servers: [1] + tasks: [200000, 1, 1] + out: [0, 0, 0] + - name: weight-tie-index-order + in: + servers: [4, 4, 4, 4] + tasks: [1, 1, 1, 1, 1, 1, 1, 1] + out: [0, 0, 0, 0, 0, 0, 0, 0] + - name: distinct-weights + in: + servers: [10, 1, 5] + tasks: [100, 100, 100, 1, 1] + out: [1, 2, 0, 1, 1] + - name: all-busy-then-release + in: + servers: [2, 1] + tasks: [5, 5, 1, 1, 1] + out: [1, 0, 1, 1, 0] + - name: simultaneous-release-priority + in: + servers: [3, 1, 2] + tasks: [2, 2, 2, 1, 1, 1] + out: [1, 2, 1, 2, 1, 1] + - name: task-arrivals-dominate + in: + servers: [1, 2, 3] + tasks: [1, 1, 1, 1, 1, 1] + out: [0, 0, 0, 0, 0, 0] + - name: large-weights + in: + servers: [200000, 199999, 200000] + tasks: [1, 200000, 1, 1, 1] + out: [1, 1, 0, 0, 0] + - name: large-durations + in: + servers: [1, 2, 3] + tasks: [200000, 200000, 200000, 200000, 1] + out: [0, 1, 2, 0, 1] + - name: alternating-durations + in: + servers: [2, 2] + tasks: [1, 200000, 1, 200000, 1, 1] + out: [0, 0, 1, 1, 0, 0] + - name: lower-index-tie-after-release + in: + servers: [5, 5] + tasks: [2, 1, 5, 1, 1] + out: [0, 1, 0, 1, 1] + - name: three-servers-queue + in: + servers: [3, 2, 1] + tasks: [10, 10, 10, 1, 1, 1, 1] + out: [2, 1, 0, 2, 2, 1, 2] + - name: increasing-weights + in: + servers: [1, 2, 3, 4, 5] + tasks: [5, 4, 3, 2, 1, 5, 4] + out: [0, 1, 2, 3, 4, 0, 1] + - name: decreasing-weights + in: + servers: [5, 4, 3, 2, 1] + tasks: [5, 4, 3, 2, 1, 5, 4] + out: [4, 3, 2, 1, 0, 4, 3] + - name: many-equal-durations + in: + servers: [8, 6, 6, 8] + tasks: [3, 3, 3, 3, 3, 3, 3, 3, 3] + out: [1, 2, 0, 1, 2, 0, 1, 2, 0] + - name: idle-server-reuse + in: + servers: [9, 1, 3] + tasks: [1, 1, 50, 1, 1, 1] + out: [1, 1, 1, 2, 2, 2] + - name: queue-at-time-zero + in: + servers: [4, 1] + tasks: [100, 100, 100, 100] + out: [1, 0, 1, 0] + - name: short-burst + in: + servers: [6, 2, 4] + tasks: [1, 2, 1, 2, 1, 2, 1] + out: [1, 1, 2, 1, 2, 1, 2] + - name: delayed-cheapest + in: + servers: [1, 100, 100] + tasks: [10, 1, 1, 1, 1, 1] + out: [0, 1, 1, 1, 1, 1] + - name: repeated-release-frontier + in: + servers: [2, 1, 3, 1] + tasks: [3, 3, 1, 1, 1, 1, 1, 1] + out: [1, 3, 0, 1, 1, 1, 1, 1] + - name: mixed-boundaries + in: + servers: [200000, 1, 200000, 2] + tasks: [1, 200000, 1, 200000, 1, 1] + out: [1, 1, 3, 3, 0, 0] + - name: five-server-wave + in: + servers: [9, 7, 5, 3, 1] + tasks: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2] + out: [4, 3, 4, 3, 4, 3, 4, 3, 4, 3] + - name: long-then-short + in: + servers: [1, 2, 3] + tasks: [20, 1, 1, 1, 1, 1, 1] + out: [0, 1, 1, 1, 1, 1, 1] + - name: alternating-server-weights + in: + servers: [2, 9, 2, 9] + tasks: [2, 4, 2, 4, 2, 4, 2, 4] + out: [0, 2, 0, 1, 0, 2, 0, 1] + - name: all-max-values + in: + servers: [200000, 200000] + tasks: [200000, 200000, 200000] + out: [0, 1, 0] + - name: all-min-values + in: + servers: [1, 1, 1] + tasks: [1, 1, 1, 1, 1, 1, 1] + out: [0, 0, 0, 0, 0, 0, 0] + - name: server-count-exceeds-tasks + in: + servers: [5, 1, 4, 2, 3, 6] + tasks: [4, 1] + out: [1, 3] + - name: tasks-exceed-server-count + in: + servers: [3, 1] + tasks: [2, 2, 2, 2, 2, 2, 2, 2, 2] + out: [1, 0, 1, 0, 1, 0, 1, 0, 1] + - name: medium-mixed + in: + servers: [7, 2, 5, 2] + tasks: [4, 1, 7, 2, 3, 1, 5, 2] + out: [1, 3, 3, 2, 1, 2, 2, 1] + - name: delayed-equal-tie + in: + servers: [4, 4, 1] + tasks: [3, 3, 3, 1, 1, 1, 1] + out: [2, 0, 1, 2, 2, 2, 2] + - name: dense-small + in: + servers: [2, 1, 3, 2] + tasks: [1, 2, 3, 1, 2, 3, 1, 2, 3, 1] + out: [1, 1, 0, 1, 1, 0, 1, 1, 0, 1] + - name: gen-max-servers-short-tasks + in: + servers: + gen: "array" + len: 200000 + of: + gen: "int" + min: 1 + max: 200000 + distinct: false + sorted: false + elemType: "int" + tasks: + gen: "array" + len: 200000 + of: + gen: "int" + min: 1 + max: 3 + distinct: false + sorted: false + elemType: "int" + seed: 188201 + - name: gen-single-server + in: + servers: + gen: "array" + len: 1 + of: + gen: "int" + min: 1 + max: 200000 + distinct: false + sorted: false + elemType: "int" + tasks: + gen: "array" + len: 200000 + of: + gen: "int" + min: 1 + max: 200000 + distinct: false + sorted: false + elemType: "int" + seed: 188202 + - name: gen-equal-weights + in: + servers: + gen: "array" + len: 100000 + of: + gen: "int" + min: 37 + max: 37 + distinct: false + sorted: false + elemType: "int" + tasks: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 200000 + distinct: false + sorted: false + elemType: "int" + seed: 188203 + - name: gen-tie-heavy + in: + servers: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 4 + distinct: false + sorted: false + elemType: "int" + tasks: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 7 + distinct: false + sorted: false + elemType: "int" + seed: 188204 + - name: gen-max-values + in: + servers: + gen: "array" + len: 100000 + of: + gen: "int" + min: 199997 + max: 200000 + distinct: false + sorted: false + elemType: "int" + tasks: + gen: "array" + len: 100000 + of: + gen: "int" + min: 199997 + max: 200000 + distinct: false + sorted: false + elemType: "int" + seed: 188205 diff --git a/tests/1501-2000/1882. process-tasks-using-servers/sol.cpp b/tests/1501-2000/1882. process-tasks-using-servers/sol.cpp new file mode 100644 index 00000000..7cf13205 --- /dev/null +++ b/tests/1501-2000/1882. process-tasks-using-servers/sol.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +#include + +class Solution { +public: + vector assignTasks(vector& servers, vector& tasks) { + int n = servers.size(); + int m = tasks.size(); + + priority_queue, vector>, greater>> available; + for (int i = 0; i < n; i++) { + available.push({servers[i], i}); + } + + priority_queue, vector>, greater>> busy; + vector ans; + int time = 0; + + for (int i = 0; i < m; i++) { + time = max(time, i); + while (!busy.empty() && get<0>(busy.top()) <= time) { + auto [free_time, weight, idx] = busy.top(); + busy.pop(); + available.push({weight, idx}); + } + + if (available.empty()) { + time = get<0>(busy.top()); + while (!busy.empty() && get<0>(busy.top()) <= time) { + auto [free_time, weight, idx] = busy.top(); + busy.pop(); + available.push({weight, idx}); + } + } + + auto [weight, idx] = available.top(); + available.pop(); + busy.push({time + tasks[i], weight, idx}); + ans.push_back(idx); + } + + return ans; + } +}; diff --git a/tests/1501-2000/1882. process-tasks-using-servers/sol.cs b/tests/1501-2000/1882. process-tasks-using-servers/sol.cs new file mode 100644 index 00000000..9e380f54 --- /dev/null +++ b/tests/1501-2000/1882. process-tasks-using-servers/sol.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; + +public class Solution { + public int[] AssignTasks(int[] servers, int[] tasks) { + int n = servers.Length; + int m = tasks.Length; + + var available = new SortedSet<(int, int)>(); + for (int i = 0; i < n; i++) { + available.Add((servers[i], i)); + } + + var busy = new SortedSet<(int, int, int)>(); + int[] ans = new int[m]; + int time = 0; + + for (int i = 0; i < m; i++) { + time = Math.Max(time, i); + while (busy.Count > 0 && busy.Min.Item1 <= time) { + var first = busy.Min; + busy.Remove(first); + available.Add((first.Item2, first.Item3)); + } + + if (available.Count == 0) { + time = busy.Min.Item1; + while (busy.Count > 0 && busy.Min.Item1 <= time) { + var first = busy.Min; + busy.Remove(first); + available.Add((first.Item2, first.Item3)); + } + } + + var server = available.Min; + available.Remove(server); + busy.Add((time + tasks[i], server.Item1, server.Item2)); + ans[i] = server.Item2; + } + + return ans; + } +} diff --git a/tests/1501-2000/1882. process-tasks-using-servers/sol.dart b/tests/1501-2000/1882. process-tasks-using-servers/sol.dart new file mode 100644 index 00000000..8ae08b2f --- /dev/null +++ b/tests/1501-2000/1882. process-tasks-using-servers/sol.dart @@ -0,0 +1,47 @@ +import 'dart:collection'; + +class Solution { + List assignTasks(List servers, List tasks) { + int n = servers.length; + int m = tasks.length; + + SplayTreeMap, int> available = SplayTreeMap, int>( + (a, b) { + if (a[0] != b[0]) return a[0].compareTo(b[0]); + return a[1].compareTo(b[1]); + } + ); + for (int i = 0; i < n; i++) { + available[[servers[i], i]] = 0; + } + + PriorityQueue> busy = PriorityQueue>( + (a, b) => a[0].compareTo(b[0]) + ); + List ans = List.filled(m, 0); + int time = 0; + + for (int i = 0; i < m; i++) { + time = time > i ? time : i; + while (busy.isNotEmpty && busy.first[0] <= time) { + List s = busy.removeFirst(); + available[[s[1], s[2]]] = 0; + } + + if (available.isEmpty) { + time = busy.first[0]; + while (busy.isNotEmpty && busy.first[0] <= time) { + List s = busy.removeFirst(); + available[[s[1], s[2]]] = 0; + } + } + + List key = available.firstKey()!; + available.remove(key); + busy.add([time + tasks[i], key[0], key[1]]); + ans[i] = key[1]; + } + + return ans; + } +} diff --git a/tests/1501-2000/1882. process-tasks-using-servers/sol.go b/tests/1501-2000/1882. process-tasks-using-servers/sol.go new file mode 100644 index 00000000..2e2c954f --- /dev/null +++ b/tests/1501-2000/1882. process-tasks-using-servers/sol.go @@ -0,0 +1,83 @@ +type AvailableItem struct { + weight int + idx int +} + +type AvailableHeap []AvailableItem + +func (h AvailableHeap) Len() int { return len(h) } +func (h AvailableHeap) Less(i, j int) bool { + if h[i].weight != h[j].weight { + return h[i].weight < h[j].weight + } + return h[i].idx < h[j].idx +} +func (h AvailableHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *AvailableHeap) Push(x interface{}) { *h = append(*h, x.(AvailableItem)) } +func (h *AvailableHeap) Pop() interface{} { + old := *h + n := len(old) + item := old[n-1] + *h = old[0 : n-1] + return item +} + +type BusyItem struct { + freeTime int + weight int + idx int +} + +type BusyHeap []BusyItem + +func (h BusyHeap) Len() int { return len(h) } +func (h BusyHeap) Less(i, j int) bool { return h[i].freeTime < h[j].freeTime } +func (h BusyHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *BusyHeap) Push(x interface{}) { *h = append(*h, x.(BusyItem)) } +func (h *BusyHeap) Pop() interface{} { + old := *h + n := len(old) + item := old[n-1] + *h = old[0 : n-1] + return item +} + +func assignTasks(servers []int, tasks []int) []int { + n := len(servers) + m := len(tasks) + + available := &AvailableHeap{} + heap.Init(available) + for i := 0; i < n; i++ { + heap.Push(available, AvailableItem{weight: servers[i], idx: i}) + } + + busy := &BusyHeap{} + heap.Init(busy) + ans := make([]int, m) + time := 0 + + for i := 0; i < m; i++ { + if time < i { + time = i + } + for busy.Len() > 0 && (*busy)[0].freeTime <= time { + item := heap.Pop(busy).(BusyItem) + heap.Push(available, AvailableItem{weight: item.weight, idx: item.idx}) + } + + if available.Len() == 0 { + time = (*busy)[0].freeTime + for busy.Len() > 0 && (*busy)[0].freeTime <= time { + item := heap.Pop(busy).(BusyItem) + heap.Push(available, AvailableItem{weight: item.weight, idx: item.idx}) + } + } + + server := heap.Pop(available).(AvailableItem) + heap.Push(busy, BusyItem{freeTime: time + tasks[i], weight: server.weight, idx: server.idx}) + ans[i] = server.idx + } + + return ans +} diff --git a/tests/1501-2000/1882. process-tasks-using-servers/sol.java b/tests/1501-2000/1882. process-tasks-using-servers/sol.java new file mode 100644 index 00000000..6a4179b3 --- /dev/null +++ b/tests/1501-2000/1882. process-tasks-using-servers/sol.java @@ -0,0 +1,40 @@ +import java.util.*; + +class Solution { + public int[] assignTasks(int[] servers, int[] tasks) { + int n = servers.length; + int m = tasks.length; + + PriorityQueue available = new PriorityQueue<>((a, b) -> + a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]); + for (int i = 0; i < n; i++) { + available.offer(new int[]{servers[i], i}); + } + + PriorityQueue busy = new PriorityQueue<>((a, b) -> a[0] - b[0]); + int[] ans = new int[m]; + int time = 0; + + for (int i = 0; i < m; i++) { + time = Math.max(time, i); + while (!busy.isEmpty() && busy.peek()[0] <= time) { + int[] s = busy.poll(); + available.offer(new int[]{s[1], s[2]}); + } + + if (available.isEmpty()) { + time = busy.peek()[0]; + while (!busy.isEmpty() && busy.peek()[0] <= time) { + int[] s = busy.poll(); + available.offer(new int[]{s[1], s[2]}); + } + } + + int[] server = available.poll(); + busy.offer(new int[]{time + tasks[i], server[0], server[1]}); + ans[i] = server[1]; + } + + return ans; + } +} diff --git a/tests/1501-2000/1882. process-tasks-using-servers/sol.kt b/tests/1501-2000/1882. process-tasks-using-servers/sol.kt new file mode 100644 index 00000000..7230f5d4 --- /dev/null +++ b/tests/1501-2000/1882. process-tasks-using-servers/sol.kt @@ -0,0 +1,39 @@ +import java.util.PriorityQueue + +class Solution { + fun assignTasks(servers: IntArray, tasks: IntArray): IntArray { + val n = servers.size + val m = tasks.size + + val available = PriorityQueue>(compareBy({ it.first }, { it.second })) + for (i in 0 until n) { + available.offer(Pair(servers[i], i)) + } + + val busy = PriorityQueue>(compareBy { it.first }) + val ans = IntArray(m) + var time = 0 + + for (i in 0 until m) { + time = maxOf(time, i) + while (busy.isNotEmpty() && busy.peek().first <= time) { + val (_, weight, idx) = busy.poll() + available.offer(Pair(weight, idx)) + } + + if (available.isEmpty()) { + time = busy.peek().first + while (busy.isNotEmpty() && busy.peek().first <= time) { + val (_, weight, idx) = busy.poll() + available.offer(Pair(weight, idx)) + } + } + + val (weight, idx) = available.poll() + busy.offer(Triple(time + tasks[i], weight, idx)) + ans[i] = idx + } + + return ans + } +} diff --git a/tests/1501-2000/1882. process-tasks-using-servers/sol.py b/tests/1501-2000/1882. process-tasks-using-servers/sol.py new file mode 100644 index 00000000..6cb0d917 --- /dev/null +++ b/tests/1501-2000/1882. process-tasks-using-servers/sol.py @@ -0,0 +1,34 @@ +class Solution(object): + def assignTasks(self, servers, tasks): + """ + :type servers: List[int] + :type tasks: List[int] + :rtype: List[int] + """ + n = len(servers) + m = len(tasks) + + available = [(servers[i], i) for i in range(n)] + heapq.heapify(available) + + busy = [] + ans = [] + time = 0 + + for i in range(m): + time = max(time, i) + while busy and busy[0][0] <= time: + free_time, weight, idx = heapq.heappop(busy) + heapq.heappush(available, (weight, idx)) + + if not available: + time = busy[0][0] + while busy and busy[0][0] <= time: + free_time, weight, idx = heapq.heappop(busy) + heapq.heappush(available, (weight, idx)) + + weight, idx = heapq.heappop(available) + heapq.heappush(busy, (time + tasks[i], weight, idx)) + ans.append(idx) + + return ans diff --git a/tests/1501-2000/1882. process-tasks-using-servers/sol.py2 b/tests/1501-2000/1882. process-tasks-using-servers/sol.py2 new file mode 100644 index 00000000..46d236a3 --- /dev/null +++ b/tests/1501-2000/1882. process-tasks-using-servers/sol.py2 @@ -0,0 +1,35 @@ +class Solution(object): + def assignTasks(self, servers, tasks): + """ + :type servers: List[int] + :type tasks: List[int] + :rtype: List[int] + """ + import heapq + n = len(servers) + m = len(tasks) + + available = [(servers[i], i) for i in range(n)] + heapq.heapify(available) + + busy = [] # (free_time, weight, idx) + ans = [] + time = 0 + + for i in range(m): + time = max(time, i) + while busy and busy[0][0] <= time: + free_time, weight, idx = heapq.heappop(busy) + heapq.heappush(available, (weight, idx)) + + if not available: + time = busy[0][0] + while busy and busy[0][0] <= time: + free_time, weight, idx = heapq.heappop(busy) + heapq.heappush(available, (weight, idx)) + + weight, idx = heapq.heappop(available) + heapq.heappush(busy, (time + tasks[i], weight, idx)) + ans.append(idx) + + return ans diff --git a/tests/1501-2000/1882. process-tasks-using-servers/sol.rb b/tests/1501-2000/1882. process-tasks-using-servers/sol.rb new file mode 100644 index 00000000..3ce3bc16 --- /dev/null +++ b/tests/1501-2000/1882. process-tasks-using-servers/sol.rb @@ -0,0 +1,57 @@ +def assign_tasks(servers, tasks) + available = [] + busy = [] + cmp = lambda { |a, b| a < b } + push = lambda do |h, x, c| + h << x + i = h.length - 1 + while i > 0 + p = (i - 1) / 2 + break if c.call(h[p], h[i]) + h[p], h[i] = h[i], h[p] + i = p + end + end + pop = lambda do |h, c| + top = h[0] + last = h.pop + unless h.empty? + h[0] = last + i = 0 + loop do + l = i * 2 + 1 + r = l + 1 + k = i + k = l if l < h.length && !c.call(h[k], h[l]) + k = r if r < h.length && !c.call(h[k], h[r]) + break if k == i + h[i], h[k] = h[k], h[i] + i = k + end + end + top + end + ac = lambda { |a, b| a[0] < b[0] || (a[0] == b[0] && a[1] < b[1]) } + bc = lambda { |a, b| a[0] < b[0] } + servers.each_with_index { |w, i| push.call(available, [w, i], ac) } + result = [] + time = 0 + tasks.each_with_index do |duration, i| + time = i if time < i + while !busy.empty? && busy[0][0] <= time + item = pop.call(busy, bc) + push.call(available, [item[1], item[2]], ac) + end + if available.empty? + time = busy[0][0] + while !busy.empty? && busy[0][0] <= time + item = pop.call(busy, bc) + push.call(available, [item[1], item[2]], ac) + end + end + server = pop.call(available, ac) + push.call(busy, [time + duration, server[0], server[1]], bc) + result << server[1] + end + result +end diff --git a/tests/1501-2000/1882. process-tasks-using-servers/sol.rs b/tests/1501-2000/1882. process-tasks-using-servers/sol.rs new file mode 100644 index 00000000..a2192df2 --- /dev/null +++ b/tests/1501-2000/1882. process-tasks-using-servers/sol.rs @@ -0,0 +1,50 @@ +use std::collections::BinaryHeap; +use std::cmp::Reverse; + +impl Solution { + pub fn assign_tasks(servers: Vec, tasks: Vec) -> Vec { + let n = servers.len(); + let m = tasks.len(); + + let mut available: BinaryHeap> = BinaryHeap::new(); + for i in 0..n { + available.push(Reverse((servers[i], i as i32))); + } + + let mut busy: BinaryHeap<(i32, i32, i32)> = BinaryHeap::new(); + let mut ans = Vec::with_capacity(m); + let mut time = 0i32; + + for i in 0..m { + time = time.max(i as i32); + while let Some(&(free_time, weight, idx)) = busy.peek() { + if -free_time <= time { + busy.pop(); + available.push(Reverse((weight, idx))); + } else { + break; + } + } + + if available.is_empty() { + if let Some(&(free_time, _, _)) = busy.peek() { + time = -free_time; + while let Some(&(free_time, weight, idx)) = busy.peek() { + if -free_time <= time { + busy.pop(); + available.push(Reverse((weight, idx))); + } else { + break; + } + } + } + } + + let Reverse((weight, idx)) = available.pop().unwrap(); + busy.push((- (time + tasks[i]), weight, idx)); + ans.push(idx); + } + + ans + } +} diff --git a/tests/1501-2000/1882. process-tasks-using-servers/sol.swift b/tests/1501-2000/1882. process-tasks-using-servers/sol.swift new file mode 100644 index 00000000..1d31d2c5 --- /dev/null +++ b/tests/1501-2000/1882. process-tasks-using-servers/sol.swift @@ -0,0 +1,35 @@ +class Solution { + func assignTasks(_ servers: [Int], _ tasks: [Int]) -> [Int] { + var available: [(Int, Int)] = [] + var busy: [(Int, Int, Int)] = [] + func beforeA(_ a: (Int, Int), _ b: (Int, Int)) -> Bool { a.0 != b.0 ? a.0 < b.0 : a.1 < b.1 } + func beforeB(_ a: (Int, Int, Int), _ b: (Int, Int, Int)) -> Bool { a.0 < b.0 } + func pushA(_ x: (Int, Int)) { + available.append(x); var i = available.count - 1 + while i > 0 { let p = (i - 1) / 2; if !beforeA(available[i], available[p]) { break }; available.swapAt(i, p); i = p } + } + func pushB(_ x: (Int, Int, Int)) { + busy.append(x); var i = busy.count - 1 + while i > 0 { let p = (i - 1) / 2; if !beforeB(busy[i], busy[p]) { break }; busy.swapAt(i, p); i = p } + } + func popA() -> (Int, Int) { + let x = available[0]; let last = available.removeLast() + if !available.isEmpty { available[0] = last; var i = 0; while true { let l = i * 2 + 1; let r = l + 1; var c = i; if l < available.count && beforeA(available[l], available[c]) { c = l }; if r < available.count && beforeA(available[r], available[c]) { c = r }; if c == i { break }; available.swapAt(i, c); i = c } } + return x + } + func popB() -> (Int, Int, Int) { + let x = busy[0]; let last = busy.removeLast() + if !busy.isEmpty { busy[0] = last; var i = 0; while true { let l = i * 2 + 1; let r = l + 1; var c = i; if l < busy.count && beforeB(busy[l], busy[c]) { c = l }; if r < busy.count && beforeB(busy[r], busy[c]) { c = r }; if c == i { break }; busy.swapAt(i, c); i = c } } + return x + } + for i in 0.. + a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]; + const cmpB = (a: [number, number, number], b: [number, number, number]) => + a[0] - b[0]; + const push = (h: T[], x: T, cmp: (a: T, b: T) => number) => { + h.push(x); + let i = h.length - 1; + while (i > 0) { + const p = (i - 1) >> 1; + if (cmp(h[p], h[i]) <= 0) break; + [h[p], h[i]] = [h[i], h[p]]; + i = p; + } + }; + const pop = (h: T[], cmp: (a: T, b: T) => number): T => { + const top = h[0]; + const last = h.pop()!; + if (h.length > 0) { + h[0] = last; + let i = 0; + while (true) { + let c = i; + const l = i * 2 + 1; + const r = l + 1; + if (l < h.length && cmp(h[l], h[c]) < 0) c = l; + if (r < h.length && cmp(h[r], h[c]) < 0) c = r; + if (c === i) break; + [h[i], h[c]] = [h[c], h[i]]; + i = c; + } + } + return top; + }; + for (let i = 0; i < servers.length; i++) + push(available, [servers[i], i], cmpA); + const ans: number[] = []; + let time = 0; + for (let i = 0; i < tasks.length; i++) { + time = Math.max(time, i); + while (busy.length > 0 && busy[0][0] <= time) { + const [, w, idx] = pop(busy, cmpB); + push(available, [w, idx], cmpA); + } + if (available.length === 0) { + time = busy[0][0]; + while (busy.length > 0 && busy[0][0] <= time) { + const [, w, idx] = pop(busy, cmpB); + push(available, [w, idx], cmpA); + } + } + const [w, idx] = pop(available, cmpA); + push(busy, [time + tasks[i], w, idx], cmpB); + ans.push(idx); + } + return ans; +} diff --git a/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/manifest.yaml b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/manifest.yaml new file mode 100644 index 00000000..39e79b59 --- /dev/null +++ b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/manifest.yaml @@ -0,0 +1,377 @@ +entry: + id: 1883 + title: minimum-skips-to-arrive-at-meeting-on-time + params: + dist: + type: array + items: + type: int + speed: + type: int + hoursBefore: + type: int + call: + cpp: "Solution().minSkips({dist}, {speed}, {hoursBefore})" + rust: "Solution::min_skips({dist}, {speed}, {hoursBefore})" + python3: "Solution().minSkips({dist}, {speed}, {hoursBefore})" + python2: "Solution().minSkips({dist}, {speed}, {hoursBefore})" + ruby: "min_skips({dist}, {speed}, {hoursBefore})" + java: "new Solution().minSkips({dist}, {speed}, {hoursBefore})" + csharp: "new Solution().MinSkips({dist}, {speed}, {hoursBefore})" + kotlin: "Solution().minSkips({dist}, {speed}, {hoursBefore})" + go: "minSkips({dist}, {speed}, {hoursBefore})" + dart: "Solution().minSkips({dist}, {speed}, {hoursBefore})" + swift: "Solution().minSkips({dist}, {speed}, {hoursBefore})" + typescript: "minSkips({dist}, {speed}, {hoursBefore})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 512 +oracle: + python3: + call: "Checker().minSkips(dist, speed, hoursBefore, {result})" + checker: | + class Checker: + def minSkips(self, dist, speed, hoursBefore, result): + n = len(dist) + inf = 10**30 + dp = [inf] * (n + 1) + dp[0] = 0 + for i, d in enumerate(dist): + ndp = [inf] * (n + 1) + for k in range(i + 2): + if dp[k] >= inf: + continue + skip = dp[k] + d + if skip < ndp[k + 1]: + ndp[k + 1] = skip + if i == n - 1: + noskip = dp[k] + d + else: + noskip = ((dp[k] + d + speed - 1) // speed) * speed + if noskip < ndp[k]: + ndp[k] = noskip + dp = ndp + want = -1 + for k, value in enumerate(dp): + if value <= hoursBefore * speed: + want = k + break + return result == want +seed: 1883 +tests: + - name: example-one + in: + dist: [1, 3, 2] + speed: 4 + hoursBefore: 2 + out: 1 + - name: example-two + in: + dist: [7, 3, 5, 5] + speed: 2 + hoursBefore: 10 + out: 2 + - name: example-three-impossible + in: + dist: [7, 3, 5, 5] + speed: 1 + hoursBefore: 10 + out: -1 + - name: one-road-exact + in: + dist: [10] + speed: 5 + hoursBefore: 2 + out: 0 + - name: one-road-fraction + in: + dist: [11] + speed: 5 + hoursBefore: 2 + out: -1 + - name: two-roads-no-skip + in: + dist: [4, 4] + speed: 4 + hoursBefore: 2 + out: 0 + - name: two-roads-one-skip + in: + dist: [5, 5] + speed: 4 + hoursBefore: 3 + out: 1 + - name: impossible-even-all-skips + in: + dist: [100, 100] + speed: 10 + hoursBefore: 19 + out: -1 + - name: all-integer-segments + in: + dist: [3, 6, 9, 12] + speed: 3 + hoursBefore: 10 + out: 0 + - name: exact-deadline-after-skips + in: + dist: [7, 3, 5, 5] + speed: 2 + hoursBefore: 10 + out: 2 + - name: tiny-speed + in: + dist: [1, 1, 1] + speed: 1 + hoursBefore: 3 + out: 0 + - name: tiny-speed-tight + in: + dist: [1, 1, 1] + speed: 1 + hoursBefore: 2 + out: -1 + - name: repeated-remainders + in: + dist: [1, 1, 1, 1, 1] + speed: 3 + hoursBefore: 2 + out: 3 + - name: large-speed + in: + dist: [100000, 99999, 1] + speed: 1000000 + hoursBefore: 1 + out: 2 + - name: large-road-impossible + in: + dist: [100000, 100000, 100000] + speed: 1 + hoursBefore: 299999 + out: -1 + - name: large-road-possible + in: + dist: [100000, 100000, 100000] + speed: 1 + hoursBefore: 300000 + out: 0 + - name: skip-every-rest + in: + dist: [6, 6, 6, 6] + speed: 5 + hoursBefore: 5 + out: 3 + - name: fractional-chain + in: + dist: [2, 2, 2, 2] + speed: 3 + hoursBefore: 3 + out: 2 + - name: fractional-chain-tight + in: + dist: [2, 2, 2, 2] + speed: 3 + hoursBefore: 2 + out: -1 + - name: mixed-small + in: + dist: [1, 4, 2, 7, 3] + speed: 5 + hoursBefore: 4 + out: 2 + - name: mixed-large-speed + in: + dist: [99999, 1, 99998, 2] + speed: 99999 + hoursBefore: 3 + out: 1 + - name: deadline-one-hour + in: + dist: [1, 1, 1, 1] + speed: 2 + hoursBefore: 1 + out: -1 + - name: deadline-two-hours + in: + dist: [3, 1, 3, 1] + speed: 2 + hoursBefore: 4 + out: 2 + - name: many-exact-roads + in: + dist: [10, 20, 30, 40, 50, 60] + speed: 10 + hoursBefore: 21 + out: 0 + - name: many-fractional-roads + in: + dist: [1, 2, 3, 4, 5, 6] + speed: 7 + hoursBefore: 4 + out: 2 + - name: minimum-n + in: + dist: [100000, 1] + speed: 100000 + hoursBefore: 2 + out: 0 + - name: impossible-one-hour-budget + in: + dist: [2, 2] + speed: 1 + hoursBefore: 3 + out: -1 + - name: alternating-remainders + in: + dist: [4, 1, 4, 1, 4, 1] + speed: 3 + hoursBefore: 6 + out: 3 + - name: near-boundary + in: + dist: [9, 9, 9] + speed: 10 + hoursBefore: 3 + out: 0 + - name: exact-total-fraction + in: + dist: [1, 2, 3] + speed: 2 + hoursBefore: 3 + out: 2 + - name: high-road-count-static + in: + dist: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + speed: 6 + hoursBefore: 4 + out: 16 + - name: stress-static-1000 + in: + dist: + [ + 100000, + 99999, + 100000, + 99999, + 100000, + 99999, + 100000, + 99999, + 100000, + 99999, + 100000, + 99999, + 100000, + 99999, + 100000, + 99999, + 100000, + 99999, + 100000, + 99999, + 100000, + 99999, + 100000, + 99999, + 100000, + 99999, + 100000, + 99999, + 100000, + 99999, + ] + speed: 1000000 + hoursBefore: 3 + out: 27 + - name: generated-random-small + in: + dist: + gen: array + len: 20 + of: + gen: int + min: 1 + max: 100 + elemType: int + speed: + gen: int + min: 1 + max: 100 + hoursBefore: + gen: int + min: 1 + max: 100 + - name: generated-medium + in: + dist: + gen: array + len: 100 + of: + gen: int + min: 1 + max: 100000 + elemType: int + speed: + gen: int + min: 1 + max: 1000000 + hoursBefore: + gen: int + min: 1 + max: 1000 + - name: generated-large-one + in: + dist: + gen: array + len: 1000 + of: + gen: int + min: 1 + max: 100000 + elemType: int + speed: + gen: int + min: 1 + max: 1000000 + hoursBefore: + gen: int + min: 1 + max: 10000000 + - name: generated-large-two + in: + dist: + gen: array + len: 1000 + of: + gen: int + min: 99900 + max: 100000 + elemType: int + speed: + gen: int + min: 1 + max: 1000000 + hoursBefore: + gen: int + min: 100 + max: 10000000 + - name: generated-boundary + in: + dist: + gen: array + len: 999 + of: + gen: int + min: 1 + max: 100000 + elemType: int + speed: + gen: int + min: 999999 + max: 1000000 + hoursBefore: + gen: int + min: 1 + max: 1000 diff --git a/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.cpp b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.cpp new file mode 100644 index 00000000..517c5eb9 --- /dev/null +++ b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int minSkips(vector& dist, int speed, int hoursBefore) { + const long long INF = 1e18; + int n = dist.size(); + vector dp(n + 1, INF); + dp[0] = 0; + for (int i = 0; i < n; i++) { + vector nxt(n + 1, INF); + int d = dist[i]; + for (int skips = 0; skips <= i + 1; skips++) { + if (dp[skips] >= INF) continue; + nxt[skips + 1] = min(nxt[skips + 1], dp[skips] + d); + long long arrival = dp[skips] + d; + if (i != n - 1) { + arrival = ((arrival + speed - 1) / speed) * speed; + } + nxt[skips] = min(nxt[skips], arrival); + } + dp = nxt; + } + long long limit = (long long)hoursBefore * speed; + for (int skips = 0; skips <= n; skips++) { + if (dp[skips] <= limit) return skips; + } + return -1; + } +}; diff --git a/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.cs b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.cs new file mode 100644 index 00000000..c15a2e05 --- /dev/null +++ b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.cs @@ -0,0 +1,28 @@ +public class Solution { + public int MinSkips(int[] dist, int speed, int hoursBefore) { + const long INF = (long)1e18; + int n = dist.Length; + long[] dp = new long[n + 1]; + Array.Fill(dp, INF); + dp[0] = 0; + for (int i = 0; i < n; i++) { + long[] nxt = new long[n + 1]; + Array.Fill(nxt, INF); + for (int skips = 0; skips <= i + 1; skips++) { + if (dp[skips] >= INF) continue; + nxt[skips + 1] = Math.Min(nxt[skips + 1], dp[skips] + dist[i]); + long arrival = dp[skips] + dist[i]; + if (i != n - 1) { + arrival = ((arrival + speed - 1) / speed) * speed; + } + nxt[skips] = Math.Min(nxt[skips], arrival); + } + dp = nxt; + } + long limit = (long)hoursBefore * speed; + for (int skips = 0; skips <= n; skips++) { + if (dp[skips] <= limit) return skips; + } + return -1; + } +} diff --git a/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.dart b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.dart new file mode 100644 index 00000000..9451f1fb --- /dev/null +++ b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.dart @@ -0,0 +1,26 @@ +class Solution { + int minSkips(List dist, int speed, int hoursBefore) { + int inf = 1 << 60; + int n = dist.length; + List dp = List.filled(n + 1, inf); + dp[0] = 0; + for (int i = 0; i < n; i++) { + List nxt = List.filled(n + 1, inf); + for (int skips = 0; skips <= i + 1; skips++) { + if (dp[skips] >= inf) continue; + nxt[skips + 1] = min(nxt[skips + 1], dp[skips] + dist[i]); + int arrival = dp[skips] + dist[i]; + if (i != n - 1) { + arrival = ((arrival + speed - 1) ~/ speed) * speed; + } + nxt[skips] = min(nxt[skips], arrival); + } + dp = nxt; + } + int limit = hoursBefore * speed; + for (int skips = 0; skips <= n; skips++) { + if (dp[skips] <= limit) return skips; + } + return -1; + } +} diff --git a/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.go b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.go new file mode 100644 index 00000000..4c83bcae --- /dev/null +++ b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.go @@ -0,0 +1,38 @@ +func minSkips(dist []int, speed int, hoursBefore int) int { + inf := int64(1e18) + n := len(dist) + dp := make([]int64, n+1) + for i := range dp { + dp[i] = inf + } + dp[0] = 0 + for i, d := range dist { + nxt := make([]int64, n+1) + for j := range nxt { + nxt[j] = inf + } + for skips := 0; skips <= i+1; skips++ { + if dp[skips] >= inf { + continue + } + if nxt[skips+1] > dp[skips]+int64(d) { + nxt[skips+1] = dp[skips] + int64(d) + } + arrival := dp[skips] + int64(d) + if i != n-1 { + arrival = ((arrival+int64(speed)-1)/int64(speed))*int64(speed) + } + if nxt[skips] > arrival { + nxt[skips] = arrival + } + } + dp = nxt + } + limit := int64(hoursBefore) * int64(speed) + for skips, v := range dp { + if v <= limit { + return skips + } + } + return -1 +} diff --git a/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.java b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.java new file mode 100644 index 00000000..e74ce86d --- /dev/null +++ b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.java @@ -0,0 +1,28 @@ +class Solution { + public int minSkips(int[] dist, int speed, int hoursBefore) { + long inf = (long) 1e18; + int n = dist.length; + long[] dp = new long[n + 1]; + Arrays.fill(dp, inf); + dp[0] = 0; + for (int i = 0; i < n; i++) { + long[] nxt = new long[n + 1]; + Arrays.fill(nxt, inf); + for (int skips = 0; skips <= i + 1; skips++) { + if (dp[skips] >= inf) continue; + nxt[skips + 1] = Math.min(nxt[skips + 1], dp[skips] + dist[i]); + long arrival = dp[skips] + dist[i]; + if (i != n - 1) { + arrival = ((arrival + speed - 1) / speed) * speed; + } + nxt[skips] = Math.min(nxt[skips], arrival); + } + dp = nxt; + } + long limit = (long) hoursBefore * speed; + for (int skips = 0; skips <= n; skips++) { + if (dp[skips] <= limit) return skips; + } + return -1; + } +} diff --git a/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.kt b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.kt new file mode 100644 index 00000000..4941754f --- /dev/null +++ b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.kt @@ -0,0 +1,26 @@ +class Solution { + fun minSkips(dist: IntArray, speed: Int, hoursBefore: Int): Int { + val inf = 1e18.toLong() + val n = dist.size + var dp = LongArray(n + 1) { inf } + dp[0] = 0 + for (i in 0 until n) { + val nxt = LongArray(n + 1) { inf } + for (skips in 0..i + 1) { + if (dp[skips] >= inf) continue + nxt[skips + 1] = minOf(nxt[skips + 1], dp[skips] + dist[i]) + var arrival = dp[skips] + dist[i] + if (i != n - 1) { + arrival = ((arrival + speed - 1) / speed) * speed + } + nxt[skips] = minOf(nxt[skips], arrival) + } + dp = nxt + } + val limit = hoursBefore.toLong() * speed + for (skips in 0..n) { + if (dp[skips] <= limit) return skips + } + return -1 + } +} diff --git a/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.py b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.py new file mode 100644 index 00000000..a906cd78 --- /dev/null +++ b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.py @@ -0,0 +1,21 @@ +class Solution: + def minSkips(self, dist, speed, hoursBefore): + inf = 10**30 + dp = [inf] * (len(dist) + 1) + dp[0] = 0 + for i, d in enumerate(dist): + nxt = [inf] * (len(dist) + 1) + for skips in range(i + 2): + if dp[skips] >= inf: + continue + nxt[skips + 1] = min(nxt[skips + 1], dp[skips] + d) + arrival = dp[skips] + d + if i != len(dist) - 1: + arrival = ((arrival + speed - 1) // speed) * speed + nxt[skips] = min(nxt[skips], arrival) + dp = nxt + limit = hoursBefore * speed + for skips, arrival in enumerate(dp): + if arrival <= limit: + return skips + return -1 diff --git a/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.py2 b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.py2 new file mode 100644 index 00000000..dab8b84a --- /dev/null +++ b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.py2 @@ -0,0 +1,28 @@ +class Solution(object): + def minSkips(self, dist, speed, hoursBefore): + """ + :type dist: List[int] + :type speed: int + :type hoursBefore: int + :rtype: int + """ + inf = 10**30 + n = len(dist) + dp = [inf] * (n + 1) + dp[0] = 0 + for i, d in enumerate(dist): + nxt = [inf] * (n + 1) + for skips in range(i + 2): + if dp[skips] >= inf: + continue + nxt[skips + 1] = min(nxt[skips + 1], dp[skips] + d) + arrival = dp[skips] + d + if i != n - 1: + arrival = ((arrival + speed - 1) // speed) * speed + nxt[skips] = min(nxt[skips], arrival) + dp = nxt + limit = hoursBefore * speed + for skips, arrival in enumerate(dp): + if arrival <= limit: + return skips + return -1 diff --git a/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.rb b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.rb new file mode 100644 index 00000000..e011ed35 --- /dev/null +++ b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.rb @@ -0,0 +1,28 @@ +# @param {Integer[]} dist +# @param {Integer} speed +# @param {Integer} hours_before +# @return {Integer} +def min_skips(dist, speed, hours_before) + inf = 10**30 + n = dist.length + dp = [inf] * (n + 1) + dp[0] = 0 + dist.each_with_index do |d, i| + nxt = [inf] * (n + 1) + (0..i+1).each do |skips| + next if dp[skips] >= inf + nxt[skips + 1] = [nxt[skips + 1], dp[skips] + d].min + arrival = dp[skips] + d + if i != n - 1 + arrival = ((arrival + speed - 1) / speed) * speed + end + nxt[skips] = [nxt[skips], arrival].min + end + dp = nxt + end + limit = hours_before * speed + dp.each_with_index do |arrival, skips| + return skips if arrival <= limit + end + -1 +end diff --git a/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.rs b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.rs new file mode 100644 index 00000000..cdb59e40 --- /dev/null +++ b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.rs @@ -0,0 +1,27 @@ +impl Solution { + pub fn min_skips(dist: Vec, speed: i32, hours_before: i32) -> i32 { + let inf = 10i64.pow(18); + let n = dist.len(); + let mut dp = vec![inf; n + 1]; + dp[0] = 0; + for i in 0..n { + let mut nxt = vec![inf; n + 1]; + let d = dist[i] as i64; + for skips in 0..=i + 1 { + if dp[skips] >= inf { continue; } + nxt[skips + 1] = nxt[skips + 1].min(dp[skips] + d); + let mut arrival = dp[skips] + d; + if i != n - 1 { + arrival = ((arrival + speed as i64 - 1) / speed as i64) * speed as i64; + } + nxt[skips] = nxt[skips].min(arrival); + } + dp = nxt; + } + let limit = hours_before as i64 * speed as i64; + for (skips, &v) in dp.iter().enumerate() { + if v <= limit { return skips as i32; } + } + -1 + } +} diff --git a/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.swift b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.swift new file mode 100644 index 00000000..8ea7895e --- /dev/null +++ b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.swift @@ -0,0 +1,27 @@ +class Solution { + func minSkips(_ dist: [Int], _ speed: Int, _ hoursBefore: Int) -> Int { + let inf = Int(1e18) + let n = dist.count + var dp = [Int](repeating: inf, count: n + 1) + dp[0] = 0 + for i in 0..= inf { continue } + nxt[skips + 1] = min(nxt[skips + 1], dp[skips] + d) + var arrival = dp[skips] + d + if i != n - 1 { + arrival = ((arrival + speed - 1) / speed) * speed + } + nxt[skips] = min(nxt[skips], arrival) + } + dp = nxt + } + let limit = hoursBefore * speed + for (skips, arrival) in dp.enumerated() { + if arrival <= limit { return skips } + } + return -1 + } +} diff --git a/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.ts b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.ts new file mode 100644 index 00000000..9c3e47ab --- /dev/null +++ b/tests/1501-2000/1883. minimum-skips-to-arrive-at-meeting-on-time/sol.ts @@ -0,0 +1,25 @@ +function minSkips(dist: number[], speed: number, hoursBefore: number): number { + const inf = 10 ** 30; + const n = dist.length; + let dp: number[] = new Array(n + 1).fill(inf); + dp[0] = 0; + for (let i = 0; i < n; i++) { + const nxt: number[] = new Array(n + 1).fill(inf); + const d = dist[i]; + for (let skips = 0; skips <= i + 1; skips++) { + if (dp[skips] >= inf) continue; + nxt[skips + 1] = Math.min(nxt[skips + 1], dp[skips] + d); + let arrival = dp[skips] + d; + if (i !== n - 1) { + arrival = Math.ceil(arrival / speed) * speed; + } + nxt[skips] = Math.min(nxt[skips], arrival); + } + dp = nxt; + } + const limit = hoursBefore * speed; + for (let skips = 0; skips <= n; skips++) { + if (dp[skips] <= limit) return skips; + } + return -1; +} diff --git a/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/manifest.yaml b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/manifest.yaml new file mode 100644 index 00000000..32f990c5 --- /dev/null +++ b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/manifest.yaml @@ -0,0 +1,218 @@ +entry: + id: 1884 + title: "egg-drop-with-2-eggs-and-n-floors" + params: + n: + type: int + call: + cpp: "Solution().twoEggDrop({n})" + rust: "Solution::two_egg_drop({n})" + python3: "Solution().twoEggDrop({n})" + python2: "Solution().twoEggDrop({n})" + ruby: "two_egg_drop({n})" + java: "new Solution().twoEggDrop({n})" + csharp: "new Solution().TwoEggDrop({n})" + kotlin: "Solution().twoEggDrop({n})" + go: "twoEggDrop({n})" + dart: "Solution().twoEggDrop({n})" + swift: "Solution().twoEggDrop({n})" + typescript: "twoEggDrop({n})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().twoEggDrop(n, {result})" + checker: | + class Checker: + def twoEggDrop(self, n, result): + moves = 0 + covered = 0 + while covered < n: + moves += 1 + covered += moves + return result == moves + +seed: 1884 + +tests: + - name: n-one + in: + n: 1 + out: 1 + - name: n-two + in: + n: 2 + out: 2 + - name: n-three + in: + n: 3 + out: 2 + - name: n-four + in: + n: 4 + out: 3 + - name: n-five + in: + n: 5 + out: 3 + - name: n-seven + in: + n: 7 + out: 4 + - name: n-ten + in: + n: 10 + out: 4 + - name: n-eleven + in: + n: 11 + out: 5 + - name: n-fifteen + in: + n: 15 + out: 5 + - name: n-sixteen + in: + n: 16 + out: 6 + - name: n-twenty + in: + n: 20 + out: 6 + - name: n-twenty-one + in: + n: 21 + out: 6 + - name: n-twenty-two + in: + n: 22 + out: 7 + - name: n-twenty-eight + in: + n: 28 + out: 7 + - name: n-twenty-nine + in: + n: 29 + out: 8 + - name: n-thirty-six + in: + n: 36 + out: 8 + - name: n-thirty-seven + in: + n: 37 + out: 9 + - name: n-forty-five + in: + n: 45 + out: 9 + - name: n-forty-six + in: + n: 46 + out: 10 + - name: n-fifty-five + in: + n: 55 + out: 10 + - name: n-fifty-six + in: + n: 56 + out: 11 + - name: n-sixty-six + in: + n: 66 + out: 11 + - name: n-sixty-seven + in: + n: 67 + out: 12 + - name: n-seventy-eight + in: + n: 78 + out: 12 + - name: n-seventy-nine + in: + n: 79 + out: 13 + - name: n-ninety-one + in: + n: 91 + out: 13 + - name: n-ninety-two + in: + n: 92 + out: 14 + - name: n-one-hundred + in: + n: 100 + out: 14 + - name: n-one-hundred-six + in: + n: 106 + out: 15 + - name: n-one-hundred-twenty + in: + n: 120 + out: 15 + - name: n-one-hundred-twenty-one + in: + n: 121 + out: 16 + - name: n-two-hundred + in: + n: 200 + out: 20 + - name: n-five-hundred + in: + n: 500 + out: 32 + - name: n-nine-hundred-ninety-nine + in: + n: 999 + out: 45 + - name: n-maximum + in: + n: 1000 + out: 45 + - name: generated-small + in: + n: + gen: "int" + min: 1 + max: 50 + seed: 188401 + - name: generated-medium + in: + n: + gen: "int" + min: 51 + max: 250 + seed: 188402 + - name: generated-large + in: + n: + gen: "int" + min: 251 + max: 600 + seed: 188403 + - name: generated-near-limit + in: + n: + gen: "int" + min: 601 + max: 999 + seed: 188404 + - name: generated-limit + in: + n: + gen: "int" + min: 1000 + max: 1000 + seed: 188405 diff --git a/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.cpp b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.cpp new file mode 100644 index 00000000..65726eff --- /dev/null +++ b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int twoEggDrop(int n) { + int l = 1, r = n, res = 0; + while (l <= r) { + int moves = (l + r) / 2; + if ((1LL + moves) * moves / 2 >= n) { + res = moves; + r = moves - 1; + } else { + l = moves + 1; + } + } + return res; + } +}; diff --git a/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.cs b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.cs new file mode 100644 index 00000000..35b6302b --- /dev/null +++ b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int TwoEggDrop(int n) { + int l = 1, r = n, res = 0; + while (l <= r) { + int moves = (l + r) / 2; + if ((long)(1 + moves) * moves / 2 >= n) { + res = moves; + r = moves - 1; + } else { + l = moves + 1; + } + } + return res; + } +} diff --git a/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.dart b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.dart new file mode 100644 index 00000000..309c137f --- /dev/null +++ b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.dart @@ -0,0 +1,15 @@ +class Solution { + int twoEggDrop(int n) { + int l = 1, r = n, res = 0; + while (l <= r) { + int moves = (l + r) ~/ 2; + if ((1 + moves) * moves ~/ 2 >= n) { + res = moves; + r = moves - 1; + } else { + l = moves + 1; + } + } + return res; + } +} diff --git a/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.go b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.go new file mode 100644 index 00000000..7f3a89ca --- /dev/null +++ b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.go @@ -0,0 +1,14 @@ +func twoEggDrop(n int) int { + l, r := 1, n + res := 0 + for l <= r { + moves := (l + r) / 2 + if (1+moves)*moves/2 >= n { + res = moves + r = moves - 1 + } else { + l = moves + 1 + } + } + return res +} diff --git a/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.java b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.java new file mode 100644 index 00000000..8a6dd3bb --- /dev/null +++ b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.java @@ -0,0 +1,15 @@ +class Solution { + public int twoEggDrop(int n) { + int l = 1, r = n, res = 0; + while (l <= r) { + int moves = (l + r) / 2; + if ((1L + moves) * moves / 2 >= n) { + res = moves; + r = moves - 1; + } else { + l = moves + 1; + } + } + return res; + } +} diff --git a/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.kt b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.kt new file mode 100644 index 00000000..5faea29c --- /dev/null +++ b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.kt @@ -0,0 +1,17 @@ +class Solution { + fun twoEggDrop(n: Int): Int { + var l = 1 + var r = n + var res = 0 + while (l <= r) { + val moves = (l + r) / 2 + if ((1L + moves) * moves / 2 >= n) { + res = moves + r = moves - 1 + } else { + l = moves + 1 + } + } + return res + } +} diff --git a/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.py b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.py new file mode 100644 index 00000000..51fa9708 --- /dev/null +++ b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.py @@ -0,0 +1,18 @@ +class Solution: + def twoEggDrop(self, n: int) -> int: + # With 2 eggs and moves total moves, we can cover at most (1 + moves) * (moves / 2) floors. + # Drop egg 1 at decreasing floor gaps (moves, moves - 1, moves - 2, ...), + # so that whenever it breaks, egg 2 has just enough moves to scan linearly below. + def can_determine(moves: int) -> bool: + return (1 + moves) * (moves / 2) >= n + + res = None + l, r = 1, n + while l <= r: + moves = (l + r) // 2 + if can_determine(moves): + res = moves + r = moves - 1 + else: + l = moves + 1 + return res diff --git a/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.py2 b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.py2 new file mode 100644 index 00000000..28b8a826 --- /dev/null +++ b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def twoEggDrop(self, n): + """ + :type n: int + :rtype: int + """ + l, r = 1, n + res = None + while l <= r: + moves = (l + r) // 2 + if (1 + moves) * moves // 2 >= n: + res = moves + r = moves - 1 + else: + l = moves + 1 + return res diff --git a/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.rb b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.rb new file mode 100644 index 00000000..7866bdfd --- /dev/null +++ b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.rb @@ -0,0 +1,16 @@ +# @param {Integer} n +# @return {Integer} +def two_egg_drop(n) + l, r = 1, n + res = nil + while l <= r + moves = (l + r) / 2 + if (1 + moves) * moves / 2 >= n + res = moves + r = moves - 1 + else + l = moves + 1 + end + end + res +end diff --git a/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.rs b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.rs new file mode 100644 index 00000000..0e5327d5 --- /dev/null +++ b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn two_egg_drop(n: i32) -> i32 { + let mut l = 1; + let mut r = n; + let mut res = 0; + while l <= r { + let moves = (l + r) / 2; + if ((1 + moves) * moves / 2) >= n { + res = moves; + r = moves - 1; + } else { + l = moves + 1; + } + } + res + } +} diff --git a/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.swift b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.swift new file mode 100644 index 00000000..7b93dd28 --- /dev/null +++ b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func twoEggDrop(_ n: Int) -> Int { + var l = 1, r = n, res = 0 + while l <= r { + let moves = (l + r) / 2 + if (1 + moves) * moves / 2 >= n { + res = moves + r = moves - 1 + } else { + l = moves + 1 + } + } + return res + } +} diff --git a/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.ts b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.ts new file mode 100644 index 00000000..0b8b6976 --- /dev/null +++ b/tests/1501-2000/1884. egg-drop-with-2-eggs-and-n-floors/sol.ts @@ -0,0 +1,15 @@ +function twoEggDrop(n: number): number { + let l = 1, + r = n, + res = 0; + while (l <= r) { + const moves = Math.floor((l + r) / 2); + if (((1 + moves) * moves) / 2 >= n) { + res = moves; + r = moves - 1; + } else { + l = moves + 1; + } + } + return res; +} diff --git a/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/manifest.yaml b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/manifest.yaml new file mode 100644 index 00000000..82b344a9 --- /dev/null +++ b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/manifest.yaml @@ -0,0 +1,662 @@ +entry: + id: 1886 + title: "determine-whether-matrix-can-be-obtained-by-rotation" + params: + mat: + type: array + items: + type: array + items: + type: int + target: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().findRotation({mat}, {target})" + rust: "Solution::find_rotation({mat}, {target})" + python3: "Solution().findRotation({mat}, {target})" + python2: "Solution().findRotation({mat}, {target})" + ruby: "find_rotation({mat}, {target})" + java: "new Solution().findRotation({mat}, {target})" + csharp: "new Solution().FindRotation({mat}, {target})" + kotlin: "Solution().findRotation({mat}, {target})" + go: "findRotation({mat}, {target})" + dart: "Solution().findRotation({mat}, {target})" + swift: "Solution().findRotation({mat}, {target})" + typescript: "findRotation({mat}, {target})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().findRotation(mat, target, {result})" + checker: | + class Checker: + def findRotation(self, mat, target, result): + if not isinstance(result, bool): + return False + current = mat + for _ in range(4): + if current == target: + return result is True + current = [list(row) for row in zip(*current[::-1])] + return result is False + +seed: 1886 + +tests: + - name: "example_1" + in: + mat: + elemType: "int" + value: + - [0, 1] + - [1, 0] + target: + elemType: "int" + value: + - [1, 0] + - [0, 1] + out: true + - name: "example_2" + in: + mat: + elemType: "int" + value: + - [0, 1] + - [1, 1] + target: + elemType: "int" + value: + - [1, 0] + - [0, 1] + out: false + - name: "example_3" + in: + mat: + elemType: "int" + value: + - [0, 0, 0] + - [0, 1, 0] + - [1, 1, 1] + target: + elemType: "int" + value: + - [1, 1, 1] + - [0, 1, 0] + - [0, 0, 0] + out: true + - name: "one_zero" + in: + mat: + elemType: "int" + value: + - [0] + target: + elemType: "int" + value: + - [0] + out: true + - name: "one_one" + in: + mat: + elemType: "int" + value: + - [1] + target: + elemType: "int" + value: + - [1] + out: true + - name: "two_identity" + in: + mat: + elemType: "int" + value: + - [1, 0] + - [0, 1] + target: + elemType: "int" + value: + - [1, 0] + - [0, 1] + out: true + - name: "two_quarter_turn" + in: + mat: + elemType: "int" + value: + - [1, 0] + - [0, 0] + target: + elemType: "int" + value: + - [0, 1] + - [0, 0] + out: true + - name: "two_half_turn" + in: + mat: + elemType: "int" + value: + - [1, 1] + - [0, 1] + target: + elemType: "int" + value: + - [1, 0] + - [1, 1] + out: true + - name: "two_three_quarters" + in: + mat: + elemType: "int" + value: + - [0, 0] + - [1, 0] + target: + elemType: "int" + value: + - [0, 1] + - [0, 0] + out: true + - name: "two_same_asymmetric_false" + in: + mat: + elemType: "int" + value: + - [1, 1] + - [1, 0] + target: + elemType: "int" + value: + - [1, 1] + - [0, 0] + out: false + - name: "three_all_zero" + in: + mat: + elemType: "int" + value: + - [0, 0, 0] + - [0, 0, 0] + - [0, 0, 0] + target: + elemType: "int" + value: + - [0, 0, 0] + - [0, 0, 0] + - [0, 0, 0] + out: true + - name: "three_all_one" + in: + mat: + elemType: "int" + value: + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + target: + elemType: "int" + value: + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + out: true + - name: "three_quarter_turn" + in: + mat: + elemType: "int" + value: + - [1, 0, 0] + - [1, 1, 0] + - [0, 0, 0] + target: + elemType: "int" + value: + - [0, 1, 1] + - [0, 1, 0] + - [0, 0, 0] + out: true + - name: "three_half_turn" + in: + mat: + elemType: "int" + value: + - [1, 0, 1] + - [0, 1, 0] + - [0, 0, 1] + target: + elemType: "int" + value: + - [1, 0, 0] + - [0, 1, 0] + - [1, 0, 1] + out: true + - name: "three_rotation_false" + in: + mat: + elemType: "int" + value: + - [1, 0, 0] + - [0, 1, 0] + - [0, 0, 0] + target: + elemType: "int" + value: + - [1, 1, 0] + - [0, 0, 0] + - [0, 0, 0] + out: false + - name: "four_corner_rotation" + in: + mat: + elemType: "int" + value: + - [1, 0, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 1] + target: + elemType: "int" + value: + - [0, 0, 0, 1] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - [1, 0, 0, 0] + out: true + - name: "four_cross" + in: + mat: + elemType: "int" + value: + - [0, 1, 0, 0] + - [1, 1, 1, 0] + - [0, 1, 0, 0] + - [0, 0, 0, 0] + target: + elemType: "int" + value: + - [0, 1, 0, 0] + - [1, 1, 1, 0] + - [0, 1, 0, 0] + - [0, 0, 0, 0] + out: true + - name: "four_checker_rotation" + in: + mat: + elemType: "int" + value: + - [1, 0, 1, 0] + - [0, 1, 0, 1] + - [1, 0, 1, 0] + - [0, 1, 0, 1] + target: + elemType: "int" + value: + - [0, 1, 0, 1] + - [1, 0, 1, 0] + - [0, 1, 0, 1] + - [1, 0, 1, 0] + out: true + - name: "four_false_same_count" + in: + mat: + elemType: "int" + value: + - [1, 1, 0, 0] + - [1, 0, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + target: + elemType: "int" + value: + - [1, 1, 0, 0] + - [0, 1, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + out: false + - name: "five_diagonal" + in: + mat: + elemType: "int" + value: + - [1, 0, 0, 0, 0] + - [0, 1, 0, 0, 0] + - [0, 0, 1, 0, 0] + - [0, 0, 0, 1, 0] + - [0, 0, 0, 0, 1] + target: + elemType: "int" + value: + - [1, 0, 0, 0, 0] + - [0, 1, 0, 0, 0] + - [0, 0, 1, 0, 0] + - [0, 0, 0, 1, 0] + - [0, 0, 0, 0, 1] + out: true + - name: "five_border_rotation" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 1, 1] + - [1, 0, 0, 0, 0] + - [1, 0, 0, 0, 0] + - [1, 0, 0, 0, 0] + - [1, 1, 1, 1, 1] + target: + elemType: "int" + value: + - [1, 1, 1, 1, 1] + - [0, 0, 0, 0, 1] + - [0, 0, 0, 0, 1] + - [0, 0, 0, 0, 1] + - [1, 1, 1, 1, 1] + out: true + - name: "five_false" + in: + mat: + elemType: "int" + value: + - [1, 0, 0, 0, 0] + - [1, 1, 0, 0, 0] + - [1, 0, 1, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + target: + elemType: "int" + value: + - [1, 1, 0, 0, 0] + - [1, 0, 1, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 1] + out: false + - name: "six_sparse_rotation" + in: + mat: + elemType: "int" + value: + - [1, 0, 0, 0, 0, 0] + - [0, 0, 1, 0, 0, 0] + - [0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 1, 0] + - [0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 1] + target: + elemType: "int" + value: + - [0, 0, 0, 0, 0, 1] + - [0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 1, 0] + - [0, 0, 0, 0, 0, 0] + - [0, 0, 1, 0, 0, 0] + - [1, 0, 0, 0, 0, 0] + out: true + - name: "six_not_rotation" + in: + mat: + elemType: "int" + value: + - [1, 0, 1, 0, 1, 0] + - [0, 1, 0, 1, 0, 1] + - [1, 0, 1, 0, 1, 0] + - [0, 1, 0, 1, 0, 1] + - [1, 0, 1, 0, 1, 0] + - [0, 1, 0, 1, 0, 1] + target: + elemType: "int" + value: + - [1, 1, 1, 0, 0, 0] + - [1, 1, 1, 0, 0, 0] + - [1, 1, 1, 0, 0, 0] + - [0, 0, 0, 1, 1, 1] + - [0, 0, 0, 1, 1, 1] + - [0, 0, 0, 1, 1, 1] + out: false + - name: "seven_center_single" + in: + mat: + elemType: "int" + value: + - [0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 1, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0] + target: + elemType: "int" + value: + - [0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 1, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0] + out: true + - name: "eight_rotated_l" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 0, 0, 0, 0, 0] + - [1, 0, 0, 0, 0, 0, 0, 0] + - [1, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0] + target: + elemType: "int" + value: + - [0, 0, 0, 0, 0, 0, 0, 1] + - [0, 0, 0, 0, 0, 0, 0, 1] + - [0, 0, 0, 0, 0, 0, 0, 1] + - [0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0] + out: false + - name: "nine_dense_rotation" + in: + mat: + elemType: "int" + value: + - [1, 0, 1, 1, 0, 0, 1, 0, 1] + - [0, 1, 0, 0, 1, 1, 0, 1, 0] + - [1, 1, 0, 1, 0, 0, 1, 1, 0] + - [0, 0, 1, 1, 1, 0, 0, 0, 1] + - [1, 0, 0, 0, 1, 0, 1, 0, 1] + - [1, 0, 0, 1, 1, 1, 0, 0, 0] + - [0, 1, 1, 0, 0, 1, 1, 0, 1] + - [1, 0, 1, 0, 1, 0, 0, 1, 1] + - [0, 1, 0, 1, 1, 0, 1, 1, 0] + target: + elemType: "int" + value: + - [0, 1, 1, 1, 1, 0, 1, 1, 0] + - [1, 0, 1, 0, 0, 0, 1, 0, 1] + - [1, 0, 0, 0, 1, 1, 0, 0, 1] + - [1, 1, 0, 1, 1, 1, 1, 0, 1] + - [0, 0, 1, 0, 1, 0, 0, 1, 1] + - [0, 0, 1, 0, 0, 1, 1, 0, 0] + - [1, 1, 0, 1, 1, 0, 0, 1, 0] + - [0, 1, 0, 0, 1, 0, 1, 1, 0] + - [1, 0, 1, 1, 0, 1, 0, 0, 1] + out: false + - name: "ten_all_zero" + in: + mat: + elemType: "int" + value: + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + target: + elemType: "int" + value: + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + out: true + - name: "ten_all_one" + in: + mat: + elemType: "int" + value: + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + target: + elemType: "int" + value: + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: true + - name: "three_single_corner" + in: + mat: + elemType: "int" + value: + - [1, 0, 0] + - [0, 0, 0] + - [0, 0, 0] + target: + elemType: "int" + value: + - [0, 0, 1] + - [0, 0, 0] + - [0, 0, 0] + out: true + - name: "three_opposite_corner" + in: + mat: + elemType: "int" + value: + - [1, 0, 0] + - [0, 0, 0] + - [0, 0, 1] + target: + elemType: "int" + value: + - [1, 0, 0] + - [0, 0, 0] + - [0, 0, 1] + out: true + - name: "four_horizontal_bar" + in: + mat: + elemType: "int" + value: + - [0, 0, 0, 0] + - [1, 1, 1, 1] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + target: + elemType: "int" + value: + - [0, 0, 1, 0] + - [0, 0, 1, 0] + - [0, 0, 1, 0] + - [0, 0, 1, 0] + out: true + - name: "four_diagonal_pair" + in: + mat: + elemType: "int" + value: + - [1, 0, 0, 0] + - [0, 1, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + target: + elemType: "int" + value: + - [0, 0, 0, 1] + - [0, 0, 1, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + out: true + - name: "five_center_cross_false" + in: + mat: + elemType: "int" + value: + - [0, 0, 1, 0, 0] + - [0, 0, 1, 0, 0] + - [1, 1, 1, 1, 1] + - [0, 0, 1, 0, 0] + - [0, 0, 1, 0, 0] + target: + elemType: "int" + value: + - [0, 0, 0, 0, 0] + - [1, 1, 1, 1, 1] + - [0, 0, 1, 0, 0] + - [0, 0, 1, 0, 0] + - [0, 0, 0, 0, 0] + out: false + - name: "six_rotationally_symmetric" + in: + mat: + elemType: "int" + value: + - [0, 1, 1, 1, 1, 0] + - [1, 0, 0, 0, 0, 1] + - [1, 0, 1, 1, 0, 1] + - [1, 0, 1, 1, 0, 1] + - [1, 0, 0, 0, 0, 1] + - [0, 1, 1, 1, 1, 0] + target: + elemType: "int" + value: + - [0, 1, 1, 1, 1, 0] + - [1, 0, 0, 0, 0, 1] + - [1, 0, 1, 1, 0, 1] + - [1, 0, 1, 1, 0, 1] + - [1, 0, 0, 0, 0, 1] + - [0, 1, 1, 1, 1, 0] + out: true diff --git a/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.cpp b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.cpp new file mode 100644 index 00000000..8f8c9b49 --- /dev/null +++ b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + bool findRotation(vector>& mat, vector>& target) { + for (int i = 0; i < 4; i++) { + if (mat == target) return true; + mat = rotate(mat); + } + return false; + } + +private: + vector> rotate(vector>& mat) { + int n = mat.size(); + vector> res(n, vector(n)); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + res[j][n - 1 - i] = mat[i][j]; + } + } + return res; + } +}; diff --git a/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.cs b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.cs new file mode 100644 index 00000000..615e5852 --- /dev/null +++ b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.cs @@ -0,0 +1,40 @@ +public class Solution { + public bool FindRotation(int[][] mat, int[][] target) { + for (int i = 0; i < 4; i++) { + if (RowsEqual(mat, target)) return true; + mat = Rotate(mat); + } + return false; + } + + private bool RowsEqual(int[][] a, int[][] b) { + if (a.Length != b.Length) return false; + for (int i = 0; i < a.Length; i++) + if (!a[i].SequenceEqual(b[i])) return false; + return true; + } + + private int[][] Rotate(int[][] mat) { + int n = mat.Length; + int[][] res = new int[n][]; + for (int i = 0; i < n; i++) { + res[i] = new int[n]; + } + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + res[j][n - 1 - i] = mat[i][j]; + } + } + return res; + } +} + +public class SequenceComparer : IEqualityComparer> { + public bool Equals(IEnumerable x, IEnumerable y) { + return x.SequenceEqual(y); + } + + public int GetHashCode(IEnumerable obj) { + return 0; + } +} diff --git a/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.dart b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.dart new file mode 100644 index 00000000..ac94e419 --- /dev/null +++ b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.dart @@ -0,0 +1,20 @@ +class Solution { + bool findRotation(List> mat, List> target) { + for (int i = 0; i < 4; i++) { + if (mat.toString() == target.toString()) return true; + mat = rotate(mat); + } + return false; + } + + List> rotate(List> mat) { + int n = mat.length; + List> res = List.generate(n, (_) => List.filled(n, 0)); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + res[j][n - 1 - i] = mat[i][j]; + } + } + return res; + } +} diff --git a/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.go b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.go new file mode 100644 index 00000000..8a4e6b76 --- /dev/null +++ b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.go @@ -0,0 +1,37 @@ +func findRotation(mat [][]int, target [][]int) bool { + for i := 0; i < 4; i++ { + if equal(mat, target) { + return true + } + mat = rotate(mat) + } + return false +} + +func equal(a, b [][]int) bool { + if len(a) != len(b) || len(a[0]) != len(b[0]) { + return false + } + for i := range a { + for j := range a[i] { + if a[i][j] != b[i][j] { + return false + } + } + } + return true +} + +func rotate(mat [][]int) [][]int { + n := len(mat) + res := make([][]int, n) + for i := range res { + res[i] = make([]int, n) + } + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + res[j][n-1-i] = mat[i][j] + } + } + return res +} diff --git a/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.java b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.java new file mode 100644 index 00000000..d2ff814d --- /dev/null +++ b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.java @@ -0,0 +1,20 @@ +class Solution { + public boolean findRotation(int[][] mat, int[][] target) { + for (int i = 0; i < 4; i++) { + if (java.util.Arrays.deepEquals(mat, target)) return true; + mat = rotate(mat); + } + return false; + } + + private int[][] rotate(int[][] mat) { + int n = mat.length; + int[][] res = new int[n][n]; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + res[j][n - 1 - i] = mat[i][j]; + } + } + return res; + } +} diff --git a/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.kt b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.kt new file mode 100644 index 00000000..18d11881 --- /dev/null +++ b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.kt @@ -0,0 +1,21 @@ +class Solution { + fun findRotation(mat: Array, target: Array): Boolean { + var current = mat + repeat(4) { + if (current.contentDeepEquals(target)) return true + current = rotate(current) + } + return false + } + + private fun rotate(mat: Array): Array { + val n = mat.size + val res = Array(n) { IntArray(n) } + for (i in 0 until n) { + for (j in 0 until n) { + res[j][n - 1 - i] = mat[i][j] + } + } + return res + } +} diff --git a/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.py b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.py new file mode 100644 index 00000000..883de5ab --- /dev/null +++ b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.py @@ -0,0 +1,8 @@ +class Solution: + def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool: + for _ in range(4): + if mat == target: + return True + # Rotate 90 degrees clockwise + mat = [list(row) for row in zip(*mat[::-1])] + return False diff --git a/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.py2 b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.py2 new file mode 100644 index 00000000..cd5e9278 --- /dev/null +++ b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.py2 @@ -0,0 +1,13 @@ +class Solution(object): + def findRotation(self, mat, target): + """ + :type mat: List[List[int]] + :type target: List[List[int]] + :rtype: bool + """ + for _ in range(4): + if mat == target: + return True + # Rotate 90 degrees clockwise + mat = [list(row) for row in zip(*mat[::-1])] + return False diff --git a/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.rb b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.rb new file mode 100644 index 00000000..50889234 --- /dev/null +++ b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.rb @@ -0,0 +1,11 @@ +# @param {Integer[][]} mat +# @param {Integer[][]} target +# @return {Boolean} +def find_rotation(mat, target) + 4.times do + return true if mat == target + # Rotate 90 degrees clockwise + mat = mat.reverse.transpose + end + false +end diff --git a/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.rs b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.rs new file mode 100644 index 00000000..c6597a2c --- /dev/null +++ b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.rs @@ -0,0 +1,23 @@ +impl Solution { + pub fn find_rotation(mat: Vec>, target: Vec>) -> bool { + let mut current = mat; + for _ in 0..4 { + if current == target { + return true; + } + current = Self::rotate(current); + } + false + } + + fn rotate(mat: Vec>) -> Vec> { + let n = mat.len(); + let mut res = vec![vec![0; n]; n]; + for i in 0..n { + for j in 0..n { + res[j][n - 1 - i] = mat[i][j]; + } + } + res + } +} diff --git a/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.swift b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.swift new file mode 100644 index 00000000..c2a09eb2 --- /dev/null +++ b/tests/1501-2000/1886. determine-whether-matrix-can-be-obtained-by-rotation/sol.swift @@ -0,0 +1,21 @@ +class Solution { + func findRotation(_ mat: [[Int]], _ target: [[Int]]) -> Bool { + var current = mat + for _ in 0..<4 { + if current == target { return true } + current = rotate(current) + } + return false + } + + private func rotate(_ mat: [[Int]]) -> [[Int]] { + let n = mat.count + var res = Array(repeating: Array(repeating: 0, count: n), count: n) + for i in 0.. Array(n).fill(0)); + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + res[j][n - 1 - i] = mat[i][j]; + } + } + return res; +} diff --git a/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/manifest.yaml b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/manifest.yaml new file mode 100644 index 00000000..da269ce1 --- /dev/null +++ b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/manifest.yaml @@ -0,0 +1,256 @@ +entry: + id: 1887 + title: "reduction-operations-to-make-the-array-elements-equal" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().reductionOperations({nums})" + rust: "Solution::reduction_operations({nums})" + python3: "Solution().reductionOperations({nums})" + python2: "Solution().reductionOperations({nums})" + ruby: "reduction_operations({nums})" + java: "new Solution().reductionOperations({nums})" + csharp: "new Solution().ReductionOperations({nums})" + kotlin: "Solution().reductionOperations({nums})" + go: "reductionOperations({nums})" + dart: "Solution().reductionOperations({nums})" + swift: "Solution().reductionOperations({nums})" + typescript: "reductionOperations({nums})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().reductionOperations(nums, {result})" + checker: | + class Checker: + def reductionOperations(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + counts = {} + for x in nums: + if not isinstance(x, int) or x < 1 or x > 50000: + return False + counts[x] = counts.get(x, 0) + 1 + lowest = min(counts) + seen = 0 + expected = 0 + for value in range(50000, lowest - 1, -1): + count = counts.get(value, 0) + if count: + seen += count + if value != lowest: + expected += seen + return result == expected + +seed: 1887 + +tests: + - name: example-one + in: + nums: [5, 1, 3] + out: 3 + - name: already-equal + in: + nums: [1, 1, 1] + out: 0 + - name: example-three + in: + nums: [1, 1, 2, 2, 3] + out: 4 + - name: two-equal + in: + nums: [7, 7] + out: 0 + - name: two-distinct + in: + nums: [1, 2] + out: 1 + - name: minimum-values + in: + nums: [1, 1, 1, 1, 1] + out: 0 + - name: maximum-values + in: + nums: [50000, 50000, 50000] + out: 0 + - name: min-and-max + in: + nums: [1, 50000] + out: 1 + - name: descending-distinct + in: + nums: [5, 4, 3, 2, 1] + out: 10 + - name: ascending-distinct + in: + nums: [1, 2, 3, 4, 5] + out: 10 + - name: repeated-levels + in: + nums: [1, 2, 2, 3, 3, 3] + out: 8 + - name: high-duplicates + in: + nums: [9, 9, 9, 8, 8, 7] + out: 8 + - name: one-high + in: + nums: [2, 2, 2, 2, 9] + out: 1 + - name: one-low + in: + nums: [1, 8, 8, 8, 8] + out: 4 + - name: gaps + in: + nums: [1, 10, 100] + out: 3 + - name: large-gap-duplicates + in: + nums: [1, 1, 10000, 10000, 50000] + out: 4 + - name: single-element + in: + nums: [42] + out: 0 + - name: alternating + in: + nums: [3, 1, 3, 2, 1, 2] + out: 6 + - name: four-levels + in: + nums: [1, 2, 3, 4] + out: 6 + - name: four-levels-weighted + in: + nums: [1, 1, 2, 3, 3, 3, 4] + out: 10 + - name: negative-not-allowed-boundary + in: + nums: [1, 50000, 1, 50000] + out: 2 + - name: many-low + in: + nums: [1, 1, 1, 1, 2, 3] + out: 3 + - name: many-middle + in: + nums: [1, 2, 2, 2, 2, 3] + out: 6 + - name: many-high + in: + nums: [1, 2, 3, 3, 3, 3] + out: 9 + - name: six-distinct + in: + nums: [2, 4, 6, 8, 10, 12] + out: 15 + - name: six-equal-high + in: + nums: [1, 1, 1, 2, 2, 2] + out: 3 + - name: sparse-values + in: + nums: [3, 100, 3, 100, 1000, 50000] + out: 7 + - name: unsorted-heavy + in: + nums: [5, 1, 4, 4, 2, 5, 3, 2, 1] + out: 18 + - name: all-max-and-one + in: + nums: [1, 50000, 50000, 50000, 50000] + out: 4 + - name: plateau-three + in: + nums: [10, 10, 20, 20, 30, 30] + out: 6 + - name: count-sensitive + in: + nums: [1, 2, 2, 2, 3, 3, 4, 4, 4] + out: 16 + - name: max-range-mix + in: + nums: [1, 25000, 50000, 25000, 1, 50000, 50000] + out: 8 + - name: seven-distinct + in: + nums: [1, 3, 5, 7, 9, 11, 13] + out: 21 + - name: repeated-single-level + in: + nums: [12345, 12345, 12345, 12345] + out: 0 + - name: long-small-static + in: + nums: [1, 2, 1, 2, 1, 2, 1, 2, 3, 3] + out: 8 + - name: generator-random-range + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 50000 + distinct: false + sorted: false + elemType: "int" + - name: generator-binary-values + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 2 + distinct: false + sorted: false + elemType: "int" + - name: generator-three-values + in: + nums: + gen: "array" + len: 40000 + of: + gen: "int" + min: 1 + max: 50000 + distinct: false + sorted: true + elemType: "int" + - name: generator-max-heavy + in: + nums: + gen: "array" + len: 49999 + of: + gen: "int" + min: 49999 + max: 50000 + distinct: false + sorted: false + elemType: "int" + - name: generator-single-value + in: + nums: + gen: "array" + len: 35000 + of: + gen: "int" + min: 31415 + max: 31415 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.cpp b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.cpp new file mode 100644 index 00000000..327722a0 --- /dev/null +++ b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int reductionOperations(vector& nums) { + vector freq(50001, 0); + for (int num : nums) { + freq[num]++; + } + int idx = 1; + while (freq[idx] == 0) idx++; + int val = 0, total = 0; + for (int i = 50000; i > idx; i--) { + if (freq[i] > 0) { + val += freq[i]; + total += val; + } + } + return total; + } +}; diff --git a/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.cs b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.cs new file mode 100644 index 00000000..f22d76ba --- /dev/null +++ b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public int ReductionOperations(int[] nums) { + int[] freq = new int[50001]; + foreach (int num in nums) { + freq[num]++; + } + int idx = 1; + while (freq[idx] == 0) idx++; + int val = 0, total = 0; + for (int i = 50000; i > idx; i--) { + if (freq[i] > 0) { + val += freq[i]; + total += val; + } + } + return total; + } +} diff --git a/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.dart b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.dart new file mode 100644 index 00000000..47dddc2f --- /dev/null +++ b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.dart @@ -0,0 +1,18 @@ +class Solution { + int reductionOperations(List nums) { + List freq = List.filled(50001, 0); + for (int num in nums) { + freq[num]++; + } + int idx = 1; + while (freq[idx] == 0) idx++; + int val = 0, total = 0; + for (int i = 50000; i > idx; i--) { + if (freq[i] > 0) { + val += freq[i]; + total += val; + } + } + return total; + } +} diff --git a/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.go b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.go new file mode 100644 index 00000000..e8602234 --- /dev/null +++ b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.go @@ -0,0 +1,18 @@ +func reductionOperations(nums []int) int { + freq := make([]int, 50001) + for _, num := range nums { + freq[num]++ + } + idx := 1 + for freq[idx] == 0 { + idx++ + } + val, total := 0, 0 + for i := 50000; i > idx; i-- { + if freq[i] > 0 { + val += freq[i] + total += val + } + } + return total +} diff --git a/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.java b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.java new file mode 100644 index 00000000..9936a7a9 --- /dev/null +++ b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.java @@ -0,0 +1,18 @@ +class Solution { + public int reductionOperations(int[] nums) { + int[] freq = new int[50001]; + for (int num : nums) { + freq[num]++; + } + int idx = 1; + while (freq[idx] == 0) idx++; + int val = 0, total = 0; + for (int i = 50000; i > idx; i--) { + if (freq[i] > 0) { + val += freq[i]; + total += val; + } + } + return total; + } +} diff --git a/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.kt b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.kt new file mode 100644 index 00000000..b3440f47 --- /dev/null +++ b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.kt @@ -0,0 +1,19 @@ +class Solution { + fun reductionOperations(nums: IntArray): Int { + val freq = IntArray(50001) + for (num in nums) { + freq[num]++ + } + var idx = 1 + while (freq[idx] == 0) idx++ + var accumulated = 0 + var total = 0 + for (i in 50000 downTo idx+1) { + if (freq[i] > 0) { + accumulated += freq[i] + total += accumulated + } + } + return total + } +} diff --git a/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.py b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.py new file mode 100644 index 00000000..1368712f --- /dev/null +++ b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.py @@ -0,0 +1,12 @@ +class Solution: + def reductionOperations(self, nums): + freq = [0] * 50001 + for num in nums: + freq[num] += 1 + idx = next(i for i in range(1, 50001) if freq[i] > 0) + val, total = 0, 0 + for i in range(50000, idx, -1): + if freq[i] > 0: + val += freq[i] + total += val + return total diff --git a/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.py2 b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.py2 new file mode 100644 index 00000000..ec1ebf64 --- /dev/null +++ b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def reductionOperations(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + freq = [0] * 50001 + for num in nums: + freq[num] += 1 + idx = next(i for i in range(1, 50001) if freq[i] > 0) + val, total = 0, 0 + for i in range(50000, idx, -1): + if freq[i] > 0: + val += freq[i] + total += val + return total diff --git a/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.rb b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.rb new file mode 100644 index 00000000..0dd5b350 --- /dev/null +++ b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.rb @@ -0,0 +1,15 @@ +# @param {Integer[]} nums +# @return {Integer} +def reduction_operations(nums) + freq = [0] * 50001 + nums.each { |num| freq[num] += 1 } + idx = (1..50000).find { |i| freq[i] > 0 } + val, total = 0, 0 + (50000).downto(idx+1) do |i| + if freq[i] > 0 + val += freq[i] + total += val + end + end + total +end diff --git a/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.rs b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.rs new file mode 100644 index 00000000..7d5587c9 --- /dev/null +++ b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn reduction_operations(nums: Vec) -> i32 { + let mut freq = vec![0; 50001]; + for &num in &nums { + freq[num as usize] += 1; + } + let mut idx = 1; + while freq[idx] == 0 { + idx += 1; + } + let mut val = 0; + let mut total = 0; + for i in (idx+1..=50000).rev() { + if freq[i] > 0 { + val += freq[i]; + total += val; + } + } + total + } +} diff --git a/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.swift b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.swift new file mode 100644 index 00000000..cf75dbe9 --- /dev/null +++ b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func reductionOperations(_ nums: [Int]) -> Int { + var freq = [Int](repeating: 0, count: 50001) + for num in nums { + freq[num] += 1 + } + var idx = 1 + while freq[idx] == 0 { + idx += 1 + } + var val = 0, total = 0 + for i in stride(from: 50000, through: idx+1, by: -1) { + if freq[i] > 0 { + val += freq[i] + total += val + } + } + return total + } +} diff --git a/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.ts b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.ts new file mode 100644 index 00000000..dc12bf76 --- /dev/null +++ b/tests/1501-2000/1887. reduction-operations-to-make-the-array-elements-equal/sol.ts @@ -0,0 +1,17 @@ +function reductionOperations(nums: number[]): number { + const freq: number[] = new Array(50001).fill(0); + for (const num of nums) { + freq[num]++; + } + let idx = 1; + while (freq[idx] === 0) idx++; + let val = 0, + total = 0; + for (let i = 50000; i > idx; i--) { + if (freq[i] > 0) { + val += freq[i]; + total += val; + } + } + return total; +} diff --git a/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/manifest.yaml b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/manifest.yaml new file mode 100644 index 00000000..f443f572 --- /dev/null +++ b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/manifest.yaml @@ -0,0 +1,228 @@ +entry: + id: 1888 + title: "minimum-number-of-flips-to-make-the-binary-string-alternating" + params: + s: + type: string + call: + cpp: "Solution().minFlips({s})" + rust: "Solution::min_flips({s})" + python3: "Solution().minFlips({s})" + python2: "Solution().minFlips({s})" + ruby: "min_flips({s})" + java: "new Solution().minFlips({s})" + csharp: "new Solution().MinFlips({s})" + kotlin: "Solution().minFlips({s})" + go: "minFlips({s})" + dart: "Solution().minFlips({s})" + swift: "Solution().minFlips({s})" + typescript: "minFlips({s})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(s, {result})" + checker: | + class Checker: + def check(self, s, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + n = len(s) + doubled = s + s + mismatches0 = 0 + best = n + for i, ch in enumerate(doubled): + if ch != ('0' if i % 2 == 0 else '1'): + mismatches0 += 1 + if i >= n: + left = i - n + if doubled[left] != ('0' if left % 2 == 0 else '1'): + mismatches0 -= 1 + if i >= n - 1: + best = min(best, mismatches0, n - mismatches0) + return result == best + +seed: 1888 + +tests: + - name: single-zero + in: + s: "0" + out: 0 + - name: single-one + in: + s: "1" + out: 0 + - name: two-zeroes + in: + s: "00" + out: 1 + - name: already-even-zero-first + in: + s: "01" + out: 0 + - name: already-even-one-first + in: + s: "10" + out: 0 + - name: two-ones + in: + s: "11" + out: 1 + - name: odd-three-zeroes + in: + s: "000" + out: 1 + - name: odd-tail-one + in: + s: "001" + out: 0 + - name: odd-alternating + in: + s: "010" + out: 0 + - name: odd-two-tail-ones + in: + s: "011" + out: 0 + - name: odd-leading-one + in: + s: "100" + out: 0 + - name: odd-one-middle + in: + s: "101" + out: 0 + - name: odd-two-leading-ones + in: + s: "110" + out: 0 + - name: odd-three-ones + in: + s: "111" + out: 1 + - name: four-zeroes + in: + s: "0000" + out: 2 + - name: one-at-end + in: + s: "0001" + out: 1 + - name: two-blocks + in: + s: "0011" + out: 2 + - name: alternating-four + in: + s: "0101" + out: 0 + - name: mirrored-blocks + in: + s: "0110" + out: 2 + - name: three-tail-ones + in: + s: "0111" + out: 1 + - name: leading-zero-run + in: + s: "1000" + out: 1 + - name: alternating-rotation + in: + s: "1001" + out: 2 + - name: alternating-four-other-phase + in: + s: "1010" + out: 0 + - name: one-mismatch-from-phase + in: + s: "1011" + out: 1 + - name: zero-block-middle + in: + s: "1100" + out: 2 + - name: three-leading-ones + in: + s: "1101" + out: 1 + - name: one-trailing-zero + in: + s: "1110" + out: 1 + - name: four-ones + in: + s: "1111" + out: 2 + - name: five-zeroes + in: + s: "00000" + out: 2 + - name: isolated-middle-one + in: + s: "00100" + out: 1 + - name: uneven-five-block + in: + s: "00111" + out: 1 + - name: one-followed-by-four-zeroes + in: + s: "01000" + out: 1 + - name: four-trailing-ones + in: + s: "01111" + out: 1 + - name: example-one + in: + s: "111000" + out: 2 + - name: example-three + in: + s: "1110" + out: 1 + - name: gen-small-binary + in: + s: + gen: "str" + len: 17 + alphabet: "01" + seed: 188801 + - name: gen-medium-binary + in: + s: + gen: "str" + len: 101 + alphabet: "01" + seed: 188802 + - name: gen-large-binary + in: + s: + gen: "str" + len: 10000 + alphabet: "01" + seed: 188803 + - name: gen-near-maximum-binary + in: + s: + gen: "str" + len: 50000 + alphabet: "01" + seed: 188804 + - name: gen-maximum-binary + in: + s: + gen: "str" + len: 100000 + alphabet: "01" + seed: 188805 diff --git a/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.cpp b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.cpp new file mode 100644 index 00000000..a8aa1f94 --- /dev/null +++ b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int minFlips(string s) { + int n = s.size(); + string t = s + s; + int ans = n; + int mis0 = 0; + + for (int i = 0; i < 2 * n; i++) { + char expected0 = i % 2 == 0 ? '0' : '1'; + if (t[i] != expected0) { + mis0++; + } + + if (i >= n) { + int left = i - n; + char expLeft = left % 2 == 0 ? '0' : '1'; + if (t[left] != expLeft) { + mis0--; + } + } + + if (i >= n - 1) { + int mis1 = n - mis0; + ans = min(ans, min(mis0, mis1)); + } + } + + return ans; + } +}; diff --git a/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.cs b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.cs new file mode 100644 index 00000000..6e255c59 --- /dev/null +++ b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.cs @@ -0,0 +1,30 @@ +public class Solution { + public int MinFlips(string s) { + int n = s.Length; + string t = s + s; + int ans = n; + int mis0 = 0; + + for (int i = 0; i < 2 * n; i++) { + char expected0 = i % 2 == 0 ? '0' : '1'; + if (t[i] != expected0) { + mis0++; + } + + if (i >= n) { + int left = i - n; + char expLeft = left % 2 == 0 ? '0' : '1'; + if (t[left] != expLeft) { + mis0--; + } + } + + if (i >= n - 1) { + int mis1 = n - mis0; + ans = Math.Min(ans, Math.Min(mis0, mis1)); + } + } + + return ans; + } +} diff --git a/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.dart b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.dart new file mode 100644 index 00000000..4dcd87c1 --- /dev/null +++ b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.dart @@ -0,0 +1,31 @@ +class Solution { + int minFlips(String s) { + int n = s.length; + String t = s + s; + int ans = n; + int mis0 = 0; + + for (int i = 0; i < 2 * n; i++) { + String expected0 = i % 2 == 0 ? '0' : '1'; + if (t[i] != expected0) { + mis0++; + } + + if (i >= n) { + int left = i - n; + String expLeft = left % 2 == 0 ? '0' : '1'; + if (t[left] != expLeft) { + mis0--; + } + } + + if (i >= n - 1) { + int mis1 = n - mis0; + ans = (ans < mis0 ? ans : mis0) < mis1 ? (ans < mis0 ? ans : mis0) : mis1; + // simpler: ans = min(ans, min(mis0, mis1)); + } + } + + return ans; + } +} diff --git a/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.go b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.go new file mode 100644 index 00000000..56f2a922 --- /dev/null +++ b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.go @@ -0,0 +1,46 @@ +func minFlips(s string) int { + n := len(s) + t := s + s + ans := n + mis0 := 0 + + for i := 0; i < 2*n; i++ { + var expected0 byte + if i%2 == 0 { + expected0 = '0' + } else { + expected0 = '1' + } + if t[i] != expected0 { + mis0++ + } + + if i >= n { + left := i - n + var expLeft byte + if left%2 == 0 { + expLeft = '0' + } else { + expLeft = '1' + } + if t[left] != expLeft { + mis0-- + } + } + + if i >= n-1 { + mis1 := n - mis0 + if mis0 < mis1 { + if mis0 < ans { + ans = mis0 + } + } else { + if mis1 < ans { + ans = mis1 + } + } + } + } + + return ans +} diff --git a/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.java b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.java new file mode 100644 index 00000000..832a5d48 --- /dev/null +++ b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.java @@ -0,0 +1,30 @@ +class Solution { + public int minFlips(String s) { + int n = s.length(); + String t = s + s; + int ans = n; + int mis0 = 0; + + for (int i = 0; i < 2 * n; i++) { + char expected0 = i % 2 == 0 ? '0' : '1'; + if (t.charAt(i) != expected0) { + mis0++; + } + + if (i >= n) { + int left = i - n; + char expLeft = left % 2 == 0 ? '0' : '1'; + if (t.charAt(left) != expLeft) { + mis0--; + } + } + + if (i >= n - 1) { + int mis1 = n - mis0; + ans = Math.min(ans, Math.min(mis0, mis1)); + } + } + + return ans; + } +} diff --git a/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.kt b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.kt new file mode 100644 index 00000000..9414f4e8 --- /dev/null +++ b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.kt @@ -0,0 +1,30 @@ +class Solution { + fun minFlips(s: String): Int { + val n = s.length + val t = s + s + var ans = n + var mis0 = 0 + + for (i in 0 until 2 * n) { + val expected0 = if (i % 2 == 0) '0' else '1' + if (t[i] != expected0) { + mis0++ + } + + if (i >= n) { + val left = i - n + val expLeft = if (left % 2 == 0) '0' else '1' + if (t[left] != expLeft) { + mis0-- + } + } + + if (i >= n - 1) { + val mis1 = n - mis0 + ans = minOf(ans, minOf(mis0, mis1)) + } + } + + return ans + } +} diff --git a/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.py b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.py new file mode 100644 index 00000000..b015dce7 --- /dev/null +++ b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.py @@ -0,0 +1,24 @@ +class Solution: + def minFlips(self, s: str) -> int: + n = len(s) + t = s + s + ans = n + mis0 = 0 + + for i in range(2 * n): + expected0 = "0" if i % 2 == 0 else "1" + + if t[i] != expected0: + mis0 += 1 + + if i >= n: + left = i - n + exp_left = "0" if left % 2 == 0 else "1" + if t[left] != exp_left: + mis0 -= 1 + + if i >= n - 1: + mis1 = n - mis0 + ans = min(ans, min(mis0, mis1)) + + return ans diff --git a/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.py2 b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.py2 new file mode 100644 index 00000000..bd3f999a --- /dev/null +++ b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.py2 @@ -0,0 +1,27 @@ +class Solution(object): + def minFlips(self, s): + """ + :type s: str + :rtype: int + """ + n = len(s) + t = s + s + ans = n + mis0 = 0 + + for i in range(2 * n): + expected0 = '0' if i % 2 == 0 else '1' + if t[i] != expected0: + mis0 += 1 + + if i >= n: + left = i - n + exp_left = '0' if left % 2 == 0 else '1' + if t[left] != exp_left: + mis0 -= 1 + + if i >= n - 1: + mis1 = n - mis0 + ans = min(ans, min(mis0, mis1)) + + return ans diff --git a/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.rb b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.rb new file mode 100644 index 00000000..223d9268 --- /dev/null +++ b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.rb @@ -0,0 +1,26 @@ +# @param {String} s +# @return {Integer} +def min_flips(s) + n = s.length + t = s + s + ans = n + mis0 = 0 + + (0...(2 * n)).each do |i| + expected0 = i % 2 == 0 ? '0' : '1' + mis0 += 1 if t[i] != expected0 + + if i >= n + left = i - n + exp_left = left % 2 == 0 ? '0' : '1' + mis0 -= 1 if t[left] != exp_left + end + + if i >= n - 1 + mis1 = n - mis0 + ans = [ans, [mis0, mis1].min].min + end + end + + ans +end diff --git a/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.rs b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.rs new file mode 100644 index 00000000..69eca5d7 --- /dev/null +++ b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.rs @@ -0,0 +1,31 @@ +impl Solution { + pub fn min_flips(s: String) -> i32 { + let n = s.len(); + let t = s.clone() + &s; + let chars: Vec = t.chars().collect(); + let mut ans = n as i32; + let mut mis0 = 0i32; + + for i in 0..(2 * n) { + let expected0 = if i % 2 == 0 { '0' } else { '1' }; + if chars[i] != expected0 { + mis0 += 1; + } + + if i >= n { + let left = i - n; + let exp_left = if left % 2 == 0 { '0' } else { '1' }; + if chars[left] != exp_left { + mis0 -= 1; + } + } + + if i >= n - 1 { + let mis1 = n as i32 - mis0; + ans = ans.min(mis0.min(mis1)); + } + } + + ans + } +} diff --git a/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.swift b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.swift new file mode 100644 index 00000000..f5691d96 --- /dev/null +++ b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.swift @@ -0,0 +1,31 @@ +class Solution { + func minFlips(_ s: String) -> Int { + let n = s.count + let t = s + s + var ans = n + var mis0 = 0 + let chars = Array(t) + + for i in 0..<(2 * n) { + let expected0 = i % 2 == 0 ? "0" : "1" + if String(chars[i]) != expected0 { + mis0 += 1 + } + + if i >= n { + let left = i - n + let expLeft = left % 2 == 0 ? "0" : "1" + if String(chars[left]) != expLeft { + mis0 -= 1 + } + } + + if i >= n - 1 { + let mis1 = n - mis0 + ans = min(ans, min(mis0, mis1)) + } + } + + return ans + } +} diff --git a/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.ts b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.ts new file mode 100644 index 00000000..bd2961bd --- /dev/null +++ b/tests/1501-2000/1888. minimum-number-of-flips-to-make-the-binary-string-alternating/sol.ts @@ -0,0 +1,28 @@ +function minFlips(s: string): number { + const n = s.length; + const t = s + s; + let ans = n; + let mis0 = 0; + + for (let i = 0; i < 2 * n; i++) { + const expected0 = i % 2 === 0 ? "0" : "1"; + if (t[i] !== expected0) { + mis0++; + } + + if (i >= n) { + const left = i - n; + const expLeft = left % 2 === 0 ? "0" : "1"; + if (t[left] !== expLeft) { + mis0--; + } + } + + if (i >= n - 1) { + const mis1 = n - mis0; + ans = Math.min(ans, Math.min(mis0, mis1)); + } + } + + return ans; +} diff --git a/tests/1501-2000/1889. minimum-space-wasted-from-packaging/manifest.yaml b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/manifest.yaml new file mode 100644 index 00000000..5536092e --- /dev/null +++ b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/manifest.yaml @@ -0,0 +1,315 @@ +entry: + id: 1889 + title: minimum-space-wasted-from-packaging + params: + packages: + type: array + items: + type: int + boxes: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().minWastedSpace({packages}, {boxes})" + rust: "Solution::min_wasted_space({packages}, {boxes})" + python3: "Solution().minWastedSpace({packages}, {boxes})" + python2: "Solution().minWastedSpace({packages}, {boxes})" + ruby: "min_wasted_space({packages}, {boxes})" + java: "new Solution().minWastedSpace({packages}, {boxes})" + csharp: "new Solution().MinWastedSpace({packages}, {boxes})" + kotlin: "Solution().minWastedSpace({packages}, {boxes})" + go: "minWastedSpace({packages}, {boxes})" + dart: "Solution().minWastedSpace({packages}, {boxes})" + swift: "Solution().minWastedSpace({packages}, {boxes})" + typescript: "minWastedSpace({packages}, {boxes})" + +judge: + type: exact + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(packages, boxes, {result})" + checker: | + from bisect import bisect_right + class Checker: + def check(self, packages, boxes, result): + if not isinstance(result, int): + return False + p = sorted(packages) + total = sum(p) + best = None + for supplier in boxes: + b = sorted(supplier) + i = 0 + gross = 0 + for size in b: + j = bisect_right(p, size, i) + gross += size * (j - i) + i = j + if i == len(p): + break + if i == len(p): + best = gross if best is None else min(best, gross) + expected = -1 if best is None else (best - total) % (10 ** 9 + 7) + return result == expected + +seed: 1889 + +tests: + - name: example-one + in: + packages: [2, 3, 5] + boxes: + - [4, 8] + - [2, 8] + out: 6 + - name: impossible-example + in: + packages: [2, 3, 5] + boxes: + - [1, 4] + - [2, 3] + - [3, 4] + out: -1 + - name: example-three + in: + packages: [3, 5, 8, 10, 11, 12] + boxes: + - [12] + - [11, 9] + - [10, 5, 14] + out: 9 + - name: single-exact + in: + packages: [1] + boxes: + - [1] + out: 0 + - name: single-best-supplier + in: + packages: [1] + boxes: + - [2] + - [1] + out: 0 + - name: single-impossible-option + in: + packages: [5] + boxes: + - [4] + - [5] + - [10] + out: 0 + - name: duplicate-packages + in: + packages: [1, 1, 1] + boxes: + - [1] + - [2] + - [1, 3] + out: 0 + - name: mixed-coverage + in: + packages: [2, 2, 3, 7] + boxes: + - [2, 3, 7] + - [3, 8] + - [7] + out: 0 + - name: exact-three + in: + packages: [10, 20, 30] + boxes: + - [10, 20, 30] + out: 0 + - name: larger-better + in: + packages: [10, 20, 30] + boxes: + - [11, 21, 31] + - [30] + out: 3 + - name: consecutive-packages + in: + packages: [1, 2, 3, 4, 5] + boxes: + - [5] + - [6] + - [1, 3, 5] + out: 2 + - name: duplicate-size-boxes + in: + packages: [5, 5, 5] + boxes: + - [5] + - [6] + out: 0 + - name: wide-gap + in: + packages: [1, 100] + boxes: + - [50, 100] + - [100] + out: 49 + - name: three-nearby + in: + packages: [7, 8, 9] + boxes: + - [7, 9] + - [8, 9] + - [9] + out: 1 + - name: even-exact + in: + packages: [2, 4, 6, 8] + boxes: + - [3, 5, 7, 9] + - [8] + - [2, 8] + out: 4 + - name: odd-gaps + in: + packages: [1, 3, 5, 7] + boxes: + - [2, 4, 6, 8] + - [1, 7] + out: 4 + - name: maximum-exact + in: + packages: [100000] + boxes: + - [100000] + out: 0 + - name: maximum-duplicates + in: + packages: [99999, 100000] + boxes: + - [100000] + - [99999, 100000] + out: 0 + - name: maximum-gap + in: + packages: [1, 2, 100000] + boxes: + - [2, 100000] + - [1, 100000] + out: 1 + - name: four-exact + in: + packages: [4, 6, 9, 12] + boxes: + - [4, 6, 9, 12] + - [5, 7, 10, 13] + out: 0 + - name: repeated-middle + in: + packages: [1, 2, 2, 4, 8] + boxes: + - [2, 4, 8] + - [1, 3, 9] + out: 1 + - name: two-pairs + in: + packages: [3, 3, 4, 4] + boxes: + - [3, 4] + - [4, 5] + out: 0 + - name: skipped-small-boxes + in: + packages: [6, 10, 11] + boxes: + - [6, 10, 11] + - [7, 12] + out: 0 + - name: sparse-boxes + in: + packages: [2, 5, 9, 10] + boxes: + - [5, 10] + - [2, 9, 10] + out: 4 + - name: alternative-supplier + in: + packages: [1, 4, 4, 9] + boxes: + - [4, 9] + - [5, 10] + out: 3 + - name: alternating-gaps + in: + packages: [8, 9, 10, 11] + boxes: + - [8, 10, 12] + - [9, 11] + out: 2 + - name: one-box-supplier + in: + packages: [2, 3, 4] + boxes: + - [4] + - [3, 4] + out: 1 + - name: two-equal-large + in: + packages: [10, 10, 20] + boxes: + - [10, 20] + - [11, 21] + out: 0 + - name: increasing-gaps + in: + packages: [1, 5, 10, 20] + boxes: + - [5, 10, 20] + - [2, 6, 11, 21] + out: 4 + - name: duplicate-six + in: + packages: [2, 6, 6, 9] + boxes: + - [6, 9] + - [7, 10] + out: 4 + - name: small-duplicates + in: + packages: [1, 1, 2, 3] + boxes: + - [1, 2, 3] + - [2, 3] + out: 0 + - name: close-triple + in: + packages: [15, 16, 17] + boxes: + - [16, 17] + - [15, 18] + out: 1 + - name: large-spread + in: + packages: [2, 8, 18] + boxes: + - [8, 18] + - [3, 9, 20] + out: 4 + - name: four-close + in: + packages: [11, 12, 13, 14] + boxes: + - [12, 14] + - [11, 13, 15] + out: 2 + - name: exact-endpoint-choice + in: + packages: [3, 6, 9] + boxes: + - [4, 7, 10] + - [3, 9] + out: 3 diff --git a/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.cpp b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.cpp new file mode 100644 index 00000000..d12f550b --- /dev/null +++ b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + int minWastedSpace(vector& packages, vector>& boxes) { + sort(packages.begin(), packages.end()); + int n = packages.size(); + long long totalPackageSum = 0; + for (int p : packages) totalPackageSum += p; + + long long minGrossArea = LLONG_MAX; + + for (auto& supplierBoxes : boxes) { + sort(supplierBoxes.begin(), supplierBoxes.end()); + if (supplierBoxes.back() < packages[n - 1]) continue; + + long long grossArea = 0; + int lowIdx = 0; + + for (int b : supplierBoxes) { + int highIdx = upperBound(packages, b, lowIdx); + int count = highIdx - lowIdx; + if (count > 0) { + grossArea += (long long)b * count; + lowIdx = highIdx; + } + if (lowIdx == n) break; + } + + minGrossArea = min(minGrossArea, grossArea); + } + + if (minGrossArea == LLONG_MAX) return -1; + return (int)((minGrossArea - totalPackageSum) % 1000000007); + } + +private: + int upperBound(vector& arr, int target, int lo) { + int hi = arr.size(); + while (lo < hi) { + int mid = lo + (hi - lo) / 2; + if (arr[mid] <= target) lo = mid + 1; + else hi = mid; + } + return lo; + } +}; diff --git a/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.cs b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.cs new file mode 100644 index 00000000..67a0b1e0 --- /dev/null +++ b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.cs @@ -0,0 +1,43 @@ +public class Solution { + public int MinWastedSpace(int[] packages, int[][] boxes) { + Array.Sort(packages); + int n = packages.Length; + long totalPackageSum = 0; + foreach (int p in packages) totalPackageSum += p; + + long minGrossArea = long.MaxValue; + + foreach (int[] supplierBoxes in boxes) { + Array.Sort(supplierBoxes); + if (supplierBoxes[supplierBoxes.Length - 1] < packages[n - 1]) continue; + + long grossArea = 0; + int lowIdx = 0; + + foreach (int b in supplierBoxes) { + int highIdx = UpperBound(packages, b, lowIdx); + int count = highIdx - lowIdx; + if (count > 0) { + grossArea += (long)b * count; + lowIdx = highIdx; + } + if (lowIdx == n) break; + } + + if (grossArea < minGrossArea) minGrossArea = grossArea; + } + + if (minGrossArea == long.MaxValue) return -1; + return (int)((minGrossArea - totalPackageSum) % 1000000007); + } + + private int UpperBound(int[] arr, int target, int lo) { + int hi = arr.Length; + while (lo < hi) { + int mid = lo + (hi - lo) / 2; + if (arr[mid] <= target) lo = mid + 1; + else hi = mid; + } + return lo; + } +} diff --git a/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.dart b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.dart new file mode 100644 index 00000000..1febb892 --- /dev/null +++ b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.dart @@ -0,0 +1,42 @@ +class Solution { + int minWastedSpace(List packages, List> boxes) { + packages.sort(); + int n = packages.length; + int totalPackageSum = packages.reduce((a, b) => a + b); + + int minGrossArea = 1 << 62; + + for (List supplierBoxes in boxes) { + supplierBoxes.sort(); + if (supplierBoxes.last < packages[n - 1]) continue; + + int grossArea = 0; + int lowIdx = 0; + + for (int b in supplierBoxes) { + int highIdx = upperBound(packages, b, lowIdx); + int count = highIdx - lowIdx; + if (count > 0) { + grossArea += b * count; + lowIdx = highIdx; + } + if (lowIdx == n) break; + } + + if (grossArea < minGrossArea) minGrossArea = grossArea; + } + + if (minGrossArea == 1 << 62) return -1; + return (minGrossArea - totalPackageSum) % 1000000007; + } + + int upperBound(List arr, int target, int lo) { + int hi = arr.length; + while (lo < hi) { + int mid = lo + (hi - lo) ~/ 2; + if (arr[mid] <= target) lo = mid + 1; + else hi = mid; + } + return lo; + } +} diff --git a/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.go b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.go new file mode 100644 index 00000000..22ec670e --- /dev/null +++ b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.go @@ -0,0 +1,54 @@ +func minWastedSpace(packages []int, boxes [][]int) int { + sort.Ints(packages) + n := len(packages) + totalPackageSum := 0 + for _, p := range packages { + totalPackageSum += p + } + + minGrossArea := int64(1<<62) + + for _, supplierBoxes := range boxes { + sort.Ints(supplierBoxes) + if supplierBoxes[len(supplierBoxes)-1] < packages[n-1] { + continue + } + + var grossArea int64 = 0 + lowIdx := 0 + + for _, b := range supplierBoxes { + highIdx := upperBound(packages, b, lowIdx) + count := highIdx - lowIdx + if count > 0 { + grossArea += int64(b) * int64(count) + lowIdx = highIdx + } + if lowIdx == n { + break + } + } + + if grossArea < minGrossArea { + minGrossArea = grossArea + } + } + + if minGrossArea == int64(1<<62) { + return -1 + } + return int((minGrossArea - int64(totalPackageSum)) % 1000000007) +} + +func upperBound(arr []int, target int, lo int) int { + hi := len(arr) + for lo < hi { + mid := lo + (hi-lo)/2 + if arr[mid] <= target { + lo = mid + 1 + } else { + hi = mid + } + } + return lo +} diff --git a/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.java b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.java new file mode 100644 index 00000000..f6ecc012 --- /dev/null +++ b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.java @@ -0,0 +1,43 @@ +class Solution { + public int minWastedSpace(int[] packages, int[][] boxes) { + Arrays.sort(packages); + int n = packages.length; + long totalPackageSum = 0; + for (int p : packages) totalPackageSum += p; + + long minGrossArea = Long.MAX_VALUE; + + for (int[] supplierBoxes : boxes) { + Arrays.sort(supplierBoxes); + if (supplierBoxes[supplierBoxes.length - 1] < packages[n - 1]) continue; + + long grossArea = 0; + int lowIdx = 0; + + for (int b : supplierBoxes) { + int highIdx = upperBound(packages, b, lowIdx); + int count = highIdx - lowIdx; + if (count > 0) { + grossArea += (long) b * count; + lowIdx = highIdx; + } + if (lowIdx == n) break; + } + + minGrossArea = Math.min(minGrossArea, grossArea); + } + + if (minGrossArea == Long.MAX_VALUE) return -1; + return (int) ((minGrossArea - totalPackageSum) % 1000000007); + } + + private int upperBound(int[] arr, int target, int lo) { + int hi = arr.length; + while (lo < hi) { + int mid = lo + (hi - lo) / 2; + if (arr[mid] <= target) lo = mid + 1; + else hi = mid; + } + return lo; + } +} diff --git a/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.kt b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.kt new file mode 100644 index 00000000..fc8d790e --- /dev/null +++ b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.kt @@ -0,0 +1,43 @@ +class Solution { + fun minWastedSpace(packages: IntArray, boxes: Array): Int { + packages.sort() + val n = packages.size + val totalPackageSum = packages.sum().toLong() + + var minGrossArea = Long.MAX_VALUE + + for (supplierBoxes in boxes) { + supplierBoxes.sort() + if (supplierBoxes.last() < packages[n - 1]) continue + + var grossArea = 0L + var lowIdx = 0 + + for (b in supplierBoxes) { + val highIdx = upperBound(packages, b, lowIdx) + val count = highIdx - lowIdx + if (count > 0) { + grossArea += b.toLong() * count + lowIdx = highIdx + } + if (lowIdx == n) break + } + + minGrossArea = minOf(minGrossArea, grossArea) + } + + if (minGrossArea == Long.MAX_VALUE) return -1 + return ((minGrossArea - totalPackageSum) % 1000000007L).toInt() + } + + private fun upperBound(arr: IntArray, target: Int, lo: Int): Int { + var l = lo + var h = arr.size + while (l < h) { + val mid = l + (h - l) / 2 + if (arr[mid] <= target) l = mid + 1 + else h = mid + } + return l + } +} diff --git a/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.py b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.py new file mode 100644 index 00000000..ba45e596 --- /dev/null +++ b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.py @@ -0,0 +1,46 @@ +from bisect import bisect_right + + +class Solution: + def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int: + packages.sort() + n = len(packages) + + # 1. Global Signal Integral (Ground Truth Energy) + # sum(packages) is a constant we subtract at the very end. + total_package_sum = sum(packages) + + # 2. Pre-calculating Prefix Sums for O(1) range queries + # (Though in our 'Gross Area' version, we only need the total_sum) + + min_gross_area = float("inf") + + for supplier_boxes in boxes: + supplier_boxes.sort() # Sorting L elements + + if supplier_boxes[-1] < packages[-1]: + continue + + gross_area = 0 + low_idx = 0 + + # 3. Heaviside Integration (The 'Vectorized' Loop) + for b in supplier_boxes: + # Binary search for the 'Activation Point' + high_idx = bisect_right(packages, b, lo=low_idx) + + count = high_idx - low_idx + if count > 0: + gross_area += b * count + low_idx = high_idx + + if low_idx == n: + break + + min_gross_area = min(min_gross_area, gross_area) + + if min_gross_area == float("inf"): + return -1 + + # 4. Final L1 Loss calculation: (Min Gross Area - Total Signal Energy) + return (min_gross_area - total_package_sum) % (10**9 + 7) diff --git a/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.py2 b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.py2 new file mode 100644 index 00000000..13c99156 --- /dev/null +++ b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.py2 @@ -0,0 +1,36 @@ +class Solution(object): + def minWastedSpace(self, packages, boxes): + """ + :type packages: List[int] + :type boxes: List[List[int]] + :rtype: int + """ + import bisect + packages.sort() + n = len(packages) + total_package_sum = sum(packages) + + min_gross_area = float('inf') + + for supplier_boxes in boxes: + supplier_boxes.sort() + if supplier_boxes[-1] < packages[-1]: + continue + + gross_area = 0 + low_idx = 0 + + for b in supplier_boxes: + high_idx = bisect.bisect_right(packages, b, lo=low_idx) + count = high_idx - low_idx + if count > 0: + gross_area += b * count + low_idx = high_idx + if low_idx == n: + break + + min_gross_area = min(min_gross_area, gross_area) + + if min_gross_area == float('inf'): + return -1 + return (min_gross_area - total_package_sum) % (10**9 + 7) diff --git a/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.rb b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.rb new file mode 100644 index 00000000..a812749e --- /dev/null +++ b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.rb @@ -0,0 +1,34 @@ +def min_wasted_space(packages, boxes) + packages.sort! + n = packages.length + total_package_sum = packages.sum + + min_gross_area = Float::INFINITY + + boxes.each do |supplier_boxes| + supplier_boxes.sort! + next if supplier_boxes[-1] < packages[-1] + + gross_area = 0 + low_idx = 0 + + supplier_boxes.each do |b| + high_idx = packages.bsearch_index { |x| x > b } || n + high_idx = n if high_idx.nil? + if high_idx < low_idx + high_idx = low_idx + end + count = high_idx - low_idx + if count > 0 + gross_area += b * count + low_idx = high_idx + end + break if low_idx == n + end + + min_gross_area = [min_gross_area, gross_area].min + end + + return -1 if min_gross_area == Float::INFINITY + (min_gross_area - total_package_sum) % 1_000_000_007 +end diff --git a/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.rs b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.rs new file mode 100644 index 00000000..d41f6927 --- /dev/null +++ b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.rs @@ -0,0 +1,46 @@ +impl Solution { + pub fn min_wasted_space(packages: Vec, boxes: Vec>) -> i32 { + let mut packages = packages; + packages.sort(); + let n = packages.len(); + let total_package_sum: i64 = packages.iter().map(|&x| x as i64).sum(); + + let mut min_gross_area = i64::MAX; + + for mut supplier_boxes in boxes { + supplier_boxes.sort(); + if *supplier_boxes.last().unwrap() < packages[n - 1] { continue; } + + let mut gross_area: i64 = 0; + let mut low_idx = 0; + + for &b in &supplier_boxes { + let high_idx = Self::upper_bound(&packages, b, low_idx); + let count = high_idx - low_idx; + if count > 0 { + gross_area += (b as i64) * (count as i64); + low_idx = high_idx; + } + if low_idx == n { break; } + } + + if gross_area < min_gross_area { + min_gross_area = gross_area; + } + } + + if min_gross_area == i64::MAX { return -1; } + ((min_gross_area - total_package_sum) % 1_000_000_007) as i32 + } + + fn upper_bound(arr: &[i32], target: i32, lo: usize) -> usize { + let mut l = lo; + let mut h = arr.len(); + while l < h { + let mid = l + (h - l) / 2; + if arr[mid] <= target { l = mid + 1; } + else { h = mid; } + } + l + } +} diff --git a/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.swift b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.swift new file mode 100644 index 00000000..7e6f60c2 --- /dev/null +++ b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.swift @@ -0,0 +1,43 @@ +class Solution { + func minWastedSpace(_ packages: [Int], _ boxes: [[Int]]) -> Int { + let sortedPackages = packages.sorted() + let n = sortedPackages.count + let totalPackageSum = sortedPackages.reduce(0, +) + + var minGrossArea = Int.max + + for var supplierBoxes in boxes { + supplierBoxes.sort() + if supplierBoxes.last! < sortedPackages[n - 1] { continue } + + var grossArea = 0 + var lowIdx = 0 + + for b in supplierBoxes { + let highIdx = upperBound(sortedPackages, b, lowIdx) + let count = highIdx - lowIdx + if count > 0 { + grossArea += b * count + lowIdx = highIdx + } + if lowIdx == n { break } + } + + minGrossArea = min(minGrossArea, grossArea) + } + + if minGrossArea == Int.max { return -1 } + return (minGrossArea - totalPackageSum) % 1_000_000_007 + } + + private func upperBound(_ arr: [Int], _ target: Int, _ lo: Int) -> Int { + var l = lo + var h = arr.count + while l < h { + let mid = l + (h - l) / 2 + if arr[mid] <= target { l = mid + 1 } + else { h = mid } + } + return l + } +} diff --git a/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.ts b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.ts new file mode 100644 index 00000000..55a00416 --- /dev/null +++ b/tests/1501-2000/1889. minimum-space-wasted-from-packaging/sol.ts @@ -0,0 +1,41 @@ +function minWastedSpace(packages: number[], boxes: number[][]): number { + packages.sort((a, b) => a - b); + const n = packages.length; + const totalPackageSum = packages.reduce((a, b) => a + b, 0); + + let minGrossArea = Number.MAX_SAFE_INTEGER; + + for (const supplierBoxes of boxes) { + supplierBoxes.sort((a, b) => a - b); + if (supplierBoxes[supplierBoxes.length - 1] < packages[n - 1]) continue; + + let grossArea = 0; + let lowIdx = 0; + + for (const b of supplierBoxes) { + const highIdx = upperBound(packages, b, lowIdx); + const count = highIdx - lowIdx; + if (count > 0) { + grossArea += b * count; + lowIdx = highIdx; + } + if (lowIdx === n) break; + } + + if (grossArea < minGrossArea) minGrossArea = grossArea; + } + + if (minGrossArea === Number.MAX_SAFE_INTEGER) return -1; + return (minGrossArea - totalPackageSum) % 1000000007; +} + +function upperBound(arr: number[], target: number, lo: number): number { + let l = lo; + let h = arr.length; + while (l < h) { + const mid = l + Math.floor((h - l) / 2); + if (arr[mid] <= target) l = mid + 1; + else h = mid; + } + return l; +} diff --git a/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/manifest.yaml b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/manifest.yaml new file mode 100644 index 00000000..08bdef8d --- /dev/null +++ b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/manifest.yaml @@ -0,0 +1,413 @@ +entry: + id: 1893 + title: "check-if-all-the-integers-in-a-range-are-covered" + params: + ranges: + type: array + items: + type: array + items: + type: int + left: + type: int + right: + type: int + call: + cpp: "Solution().isCovered({ranges}, {left}, {right})" + rust: "Solution::is_covered({ranges}, {left}, {right})" + python3: "Solution().isCovered({ranges}, {left}, {right})" + python2: "Solution().isCovered({ranges}, {left}, {right})" + ruby: "is_covered({ranges}, {left}, {right})" + java: "new Solution().isCovered({ranges}, {left}, {right})" + csharp: "new Solution().IsCovered({ranges}, {left}, {right})" + kotlin: "Solution().isCovered({ranges}, {left}, {right})" + go: "isCovered({ranges}, {left}, {right})" + dart: "Solution().isCovered({ranges}, {left}, {right})" + swift: "Solution().isCovered({ranges}, {left}, {right})" + typescript: "isCovered({ranges}, {left}, {right})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().isCovered(ranges, left, right, {result})" + checker: | + class Checker: + def isCovered(self, ranges, left, right, result): + if not isinstance(result, bool): + return False + covered = [False] * 51 + for interval in ranges: + start, end = interval + for value in range(start, end + 1): + covered[value] = True + expected = all(covered[value] for value in range(left, right + 1)) + return result is expected + +seed: 1893 + +tests: + - name: example-contiguous + in: + ranges: + - [1, 2] + - [3, 4] + - [5, 6] + left: 2 + right: 5 + out: true + judge: + type: "exact" + - name: example-uncovered + in: + ranges: + - [1, 10] + - [10, 20] + left: 21 + right: 21 + out: false + judge: + type: "exact" + - name: single-point-covered + in: + ranges: + - [7, 7] + left: 7 + right: 7 + out: true + judge: + type: "exact" + - name: single-point-missed + in: + ranges: + - [7, 7] + left: 6 + right: 6 + out: false + judge: + type: "exact" + - name: exact-one-interval + in: + ranges: + - [4, 12] + left: 4 + right: 12 + out: true + judge: + type: "exact" + - name: interval-too-short-left + in: + ranges: + - [5, 12] + left: 4 + right: 12 + out: false + judge: + type: "exact" + - name: interval-too-short-right + in: + ranges: + - [5, 12] + left: 5 + right: 13 + out: false + judge: + type: "exact" + - name: touching-intervals + in: + ranges: + - [1, 5] + - [5, 9] + left: 1 + right: 9 + out: true + judge: + type: "exact" + - name: one-number-gap + in: + ranges: + - [1, 4] + - [6, 10] + left: 1 + right: 10 + out: false + judge: + type: "exact" + - name: gap-outside-query + in: + ranges: + - [1, 4] + - [6, 10] + left: 1 + right: 4 + out: true + judge: + type: "exact" + - name: overlap-heavy + in: + ranges: + - [1, 10] + - [3, 7] + - [5, 15] + left: 2 + right: 14 + out: true + judge: + type: "exact" + - name: duplicate-ranges + in: + ranges: + - [2, 8] + - [2, 8] + - [2, 8] + left: 2 + right: 8 + out: true + judge: + type: "exact" + - name: duplicate-does-not-fill-gap + in: + ranges: + - [2, 4] + - [2, 4] + - [6, 8] + left: 2 + right: 8 + out: false + judge: + type: "exact" + - name: query-inside-overlap + in: + ranges: + - [1, 3] + - [8, 15] + - [12, 20] + left: 12 + right: 15 + out: true + judge: + type: "exact" + - name: query-at-lower-bound + in: + ranges: + - [1, 1] + - [2, 2] + left: 1 + right: 2 + out: true + judge: + type: "exact" + - name: query-at-upper-bound + in: + ranges: + - [49, 50] + left: 49 + right: 50 + out: true + judge: + type: "exact" + - name: missing-lower-bound + in: + ranges: + - [2, 50] + left: 1 + right: 50 + out: false + judge: + type: "exact" + - name: missing-upper-bound + in: + ranges: + - [1, 49] + left: 1 + right: 50 + out: false + judge: + type: "exact" + - name: full-domain-one-range + in: + ranges: + - [1, 50] + left: 1 + right: 50 + out: true + judge: + type: "exact" + - name: full-domain-split + in: + ranges: + - [1, 17] + - [18, 33] + - [34, 50] + left: 1 + right: 50 + out: true + judge: + type: "exact" + - name: isolated-query-covered + in: + ranges: + - [1, 2] + - [10, 20] + - [30, 40] + left: 30 + right: 30 + out: true + judge: + type: "exact" + - name: isolated-query-uncovered + in: + ranges: + - [1, 2] + - [10, 20] + - [30, 40] + left: 25 + right: 25 + out: false + judge: + type: "exact" + - name: unsorted-ranges + in: + ranges: + - [20, 25] + - [1, 8] + - [9, 19] + left: 1 + right: 25 + out: true + judge: + type: "exact" + - name: nested-range + in: + ranges: + - [1, 50] + - [10, 10] + - [20, 30] + left: 11 + right: 49 + out: true + judge: + type: "exact" + - name: many-singletons-contiguous + in: + ranges: + - [10, 10] + - [11, 11] + - [12, 12] + - [13, 13] + - [14, 14] + left: 10 + right: 14 + out: true + judge: + type: "exact" + - name: many-singletons-gap + in: + ranges: + - [10, 10] + - [11, 11] + - [13, 13] + - [14, 14] + left: 10 + right: 14 + out: false + judge: + type: "exact" + - name: overlap-at-gap-repair + in: + ranges: + - [1, 5] + - [4, 8] + - [7, 12] + left: 2 + right: 11 + out: true + judge: + type: "exact" + - name: gap-before-query + in: + ranges: + - [1, 5] + - [8, 20] + left: 8 + right: 20 + out: true + judge: + type: "exact" + - name: gap-after-query + in: + ranges: + - [1, 5] + - [8, 20] + left: 1 + right: 5 + out: true + judge: + type: "exact" + - name: gap-at-query-start + in: + ranges: + - [1, 4] + - [6, 10] + left: 5 + right: 8 + out: false + judge: + type: "exact" + - name: gap-at-query-end + in: + ranges: + - [1, 4] + - [6, 10] + left: 2 + right: 5 + out: false + judge: + type: "exact" + - name: range-count-one + in: + ranges: + - [25, 25] + left: 25 + right: 25 + out: true + judge: + type: "exact" + - name: broad-query-small-coverage + in: + ranges: + - [24, 26] + left: 1 + right: 50 + out: false + judge: + type: "exact" + - name: all-overlapping-cover + in: + ranges: + - [1, 20] + - [10, 30] + - [21, 50] + - [5, 45] + left: 1 + right: 50 + out: true + judge: + type: "exact" + - name: coverage-only-at-query-ends + in: + ranges: + - [1, 1] + - [3, 3] + - [5, 5] + - [1, 5] + left: 1 + right: 5 + out: true + judge: + type: "exact" diff --git a/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.cpp b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.cpp new file mode 100644 index 00000000..410f4257 --- /dev/null +++ b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + bool isCovered(vector>& ranges, int left, int right) { + vector slots(51, 0); + for (auto& r : ranges) { + int s = r[0], e = r[1]; + for (int i = s; i <= e; i++) { + slots[i] = 1; + } + } + for (int i = left; i <= right; i++) { + if (slots[i] == 0) return false; + } + return true; + } +}; diff --git a/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.cs b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.cs new file mode 100644 index 00000000..cc061c94 --- /dev/null +++ b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public bool IsCovered(int[][] ranges, int left, int right) { + int[] slots = new int[51]; + foreach (var r in ranges) { + int s = r[0], e = r[1]; + for (int i = s; i <= e; i++) { + slots[i] = 1; + } + } + for (int i = left; i <= right; i++) { + if (slots[i] == 0) return false; + } + return true; + } +} diff --git a/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.dart b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.dart new file mode 100644 index 00000000..88857901 --- /dev/null +++ b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.dart @@ -0,0 +1,15 @@ +class Solution { + bool isCovered(List> ranges, int left, int right) { + List slots = List.filled(51, 0); + for (var r in ranges) { + int s = r[0], e = r[1]; + for (int i = s; i <= e; i++) { + slots[i] = 1; + } + } + for (int i = left; i <= right; i++) { + if (slots[i] == 0) return false; + } + return true; + } +} diff --git a/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.go b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.go new file mode 100644 index 00000000..b8ab1533 --- /dev/null +++ b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.go @@ -0,0 +1,15 @@ +func isCovered(ranges [][]int, left int, right int) bool { + slots := make([]int, 51) + for _, r := range ranges { + s, e := r[0], r[1] + for i := s; i <= e; i++ { + slots[i] = 1 + } + } + for i := left; i <= right; i++ { + if slots[i] == 0 { + return false + } + } + return true +} diff --git a/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.java b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.java new file mode 100644 index 00000000..571c9b32 --- /dev/null +++ b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.java @@ -0,0 +1,15 @@ +class Solution { + public boolean isCovered(int[][] ranges, int left, int right) { + int[] slots = new int[51]; + for (int[] range : ranges) { + int s = range[0], e = range[1]; + for (int i = s; i <= e; i++) { + slots[i] = 1; + } + } + for (int i = left; i <= right; i++) { + if (slots[i] == 0) return false; + } + return true; + } +} diff --git a/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.kt b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.kt new file mode 100644 index 00000000..79eae542 --- /dev/null +++ b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun isCovered(ranges: Array, left: Int, right: Int): Boolean { + val slots = IntArray(51) + for (range in ranges) { + val s = range[0] + val e = range[1] + for (i in s..e) { + slots[i] = 1 + } + } + for (i in left..right) { + if (slots[i] == 0) return false + } + return true + } +} diff --git a/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.py b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.py new file mode 100644 index 00000000..67958a46 --- /dev/null +++ b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.py @@ -0,0 +1,9 @@ +class Solution: + def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool: + slots = [0] * 51 + for s, e in ranges: + slots[s : e + 1] = [1] * (e - s + 1) + for i in range(left, right + 1): + if slots[i] == 0: + return False + return True diff --git a/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.py2 b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.py2 new file mode 100644 index 00000000..3fcb581d --- /dev/null +++ b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def isCovered(self, ranges, left, right): + """ + :type ranges: List[List[int]] + :type left: int + :type right: int + :rtype: bool + """ + slots = [0] * 51 + for s, e in ranges: + for i in range(s, e + 1): + slots[i] = 1 + for i in range(left, right + 1): + if slots[i] == 0: + return False + return True diff --git a/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.rb b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.rb new file mode 100644 index 00000000..51a97098 --- /dev/null +++ b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[][]} ranges +# @param {Integer} left +# @param {Integer} right +# @return {Boolean} +def is_covered(ranges, left, right) + slots = [0] * 51 + ranges.each do |s, e| + (s..e).each { |i| slots[i] = 1 } + end + (left..right).each do |i| + return false if slots[i] == 0 + end + true +end diff --git a/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.rs b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.rs new file mode 100644 index 00000000..af3f5750 --- /dev/null +++ b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn is_covered(ranges: Vec>, left: i32, right: i32) -> bool { + let mut slots = vec![0; 51]; + for r in ranges { + let (s, e) = (r[0], r[1]); + for i in s..=e { + slots[i as usize] = 1; + } + } + for i in left..=right { + if slots[i as usize] == 0 { + return false; + } + } + true + } +} diff --git a/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.swift b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.swift new file mode 100644 index 00000000..eeb882b8 --- /dev/null +++ b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.swift @@ -0,0 +1,19 @@ +class Solution { + func isCovered(_ ranges: [[Int]], _ left: Int, _ right: Int) -> Bool { + var slots = [Int](repeating: 0, count: 51) + for r in ranges { + let s = r[0], e = r[1] + if s <= e { + for i in s...e { + slots[i] = 1 + } + } + } + for i in left...right { + if slots[i] == 0 { + return false + } + } + return true + } +} diff --git a/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.ts b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.ts new file mode 100644 index 00000000..58f9c4d9 --- /dev/null +++ b/tests/1501-2000/1893. check-if-all-the-integers-in-a-range-are-covered/sol.ts @@ -0,0 +1,12 @@ +function isCovered(ranges: number[][], left: number, right: number): boolean { + const slots: number[] = new Array(51).fill(0); + for (const [s, e] of ranges) { + for (let i = s; i <= e; i++) { + slots[i] = 1; + } + } + for (let i = left; i <= right; i++) { + if (slots[i] === 0) return false; + } + return true; +} diff --git a/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/manifest.yaml b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/manifest.yaml new file mode 100644 index 00000000..8c5c7597 --- /dev/null +++ b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/manifest.yaml @@ -0,0 +1,353 @@ +entry: + id: 1894 + title: "find-the-student-that-will-replace-the-chalk" + params: + chalk: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().chalkReplacer({chalk}, {k})" + rust: "Solution::chalk_replacer({chalk}, {k})" + python3: "Solution().chalkReplacer({chalk}, {k})" + python2: "Solution().chalkReplacer({chalk}, {k})" + ruby: "chalk_replacer({chalk}, {k})" + java: "new Solution().chalkReplacer({chalk}, {k})" + csharp: "new Solution().ChalkReplacer({chalk}, {k})" + kotlin: "Solution().chalkReplacer({chalk}, {k})" + go: "chalkReplacer({chalk}, {k})" + dart: "Solution().chalkReplacer({chalk}, {k})" + swift: "Solution().chalkReplacer({chalk}, {k})" + typescript: "chalkReplacer({chalk}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().chalkReplacer(chalk, k, {result})" + checker: | + class Checker: + def chalkReplacer(self, chalk, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not chalk or result < 0 or result >= len(chalk): + return False + remainder = k % sum(chalk) + for index, amount in enumerate(chalk): + if remainder < amount: + return result == index + remainder -= amount + return False + +seed: 1894 + +tests: + - name: example-one + in: + chalk: [5, 1, 5] + k: 22 + out: 0 + judge: + type: "exact" + - name: example-two + in: + chalk: [3, 4, 1, 2] + k: 25 + out: 1 + judge: + type: "exact" + - name: single-student + in: + chalk: [7] + k: 1 + out: 0 + judge: + type: "exact" + - name: exact-first + in: + chalk: [4, 2, 9] + k: 4 + out: 1 + judge: + type: "exact" + - name: exact-cycle + in: + chalk: [2, 3, 5] + k: 10 + out: 0 + judge: + type: "exact" + - name: before-first + in: + chalk: [8, 3, 6] + k: 7 + out: 0 + judge: + type: "exact" + - name: second-student + in: + chalk: [8, 3, 6] + k: 10 + out: 1 + judge: + type: "exact" + - name: third-student + in: + chalk: [8, 3, 6] + k: 13 + out: 2 + judge: + type: "exact" + - name: remainder-first + in: + chalk: [8, 3, 6] + k: 17 + out: 0 + judge: + type: "exact" + - name: remainder-second + in: + chalk: [8, 3, 6] + k: 20 + out: 0 + judge: + type: "exact" + - name: unequal-small + in: + chalk: [1, 2, 3, 4] + k: 6 + out: 3 + judge: + type: "exact" + - name: unequal-remainder + in: + chalk: [1, 2, 3, 4] + k: 9 + out: 3 + judge: + type: "exact" + - name: all-ones + in: + chalk: [1, 1, 1, 1, 1] + k: 13 + out: 3 + judge: + type: "exact" + - name: repeated-large + in: + chalk: [100000, 100000, 100000] + k: 100001 + out: 1 + judge: + type: "exact" + - name: max-k + in: + chalk: [1, 1] + k: 1000000000 + out: 0 + judge: + type: "exact" + - name: max-amount-first + in: + chalk: [100000, 1] + k: 99999 + out: 0 + judge: + type: "exact" + - name: max-amount-second + in: + chalk: [1, 100000] + k: 1 + out: 1 + judge: + type: "exact" + - name: many-students + in: + chalk: [2, 1, 2, 1, 2, 1, 2, 1] + k: 11 + out: 7 + judge: + type: "exact" + - name: alternating + in: + chalk: [9, 1, 9, 1, 9] + k: 29 + out: 0 + judge: + type: "exact" + - name: zero-remainder + in: + chalk: [6, 7, 8] + k: 42 + out: 0 + judge: + type: "exact" + - name: middle-remainder + in: + chalk: [6, 7, 8] + k: 49 + out: 1 + judge: + type: "exact" + - name: last-boundary + in: + chalk: [6, 7, 8] + k: 54 + out: 1 + judge: + type: "exact" + - name: descending + in: + chalk: [10, 9, 8, 7, 6] + k: 25 + out: 2 + judge: + type: "exact" + - name: prime-costs + in: + chalk: [2, 3, 5, 7, 11] + k: 18 + out: 4 + judge: + type: "exact" + - name: large-cycle + in: + chalk: [99999, 88888, 77777] + k: 999999999 + out: 0 + judge: + type: "exact" + - name: tiny-cycle + in: + chalk: [1, 100000, 1] + k: 100001 + out: 2 + judge: + type: "exact" + - name: equal-four + in: + chalk: [17, 17, 17, 17] + k: 52 + out: 3 + judge: + type: "exact" + - name: sharp-prefix + in: + chalk: [2, 2, 2, 100] + k: 5 + out: 2 + judge: + type: "exact" + - name: sharp-tail + in: + chalk: [100, 2, 2, 2] + k: 104 + out: 3 + judge: + type: "exact" + - name: eleven-students + in: + chalk: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + k: 66 + out: 0 + judge: + type: "exact" + - name: near-cycle-end + in: + chalk: [4, 6, 8, 10] + k: 27 + out: 3 + judge: + type: "exact" + - name: generated-uniform + in: + chalk: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 1000000000 + judge: + type: "exact" + - name: generated-small-costs + in: + chalk: + gen: "array" + len: 99999 + of: + gen: "int" + min: 1 + max: 10 + distinct: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 1000000000 + judge: + type: "exact" + - name: generated-large-costs + in: + chalk: + gen: "array" + len: 100000 + of: + gen: "int" + min: 99990 + max: 100000 + distinct: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 1000000000 + judge: + type: "exact" + - name: generated-two-values + in: + chalk: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 2 + distinct: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 1000000000 + judge: + type: "exact" + - name: generated-mid-size + in: + chalk: + gen: "array" + len: 75000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + elemType: "int" + k: + gen: "int" + min: 999999000 + max: 1000000000 + judge: + type: "exact" diff --git a/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.cpp b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.cpp new file mode 100644 index 00000000..0eaca236 --- /dev/null +++ b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int chalkReplacer(vector& chalk, int k) { + long long total = 0; + for (int amount : chalk) total += amount; + long long remaining = k % total; + for (int i = 0; i < chalk.size(); i++) { + if (remaining < chalk[i]) return i; + remaining -= chalk[i]; + } + return 0; + } +}; diff --git a/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.cs b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.cs new file mode 100644 index 00000000..9beac551 --- /dev/null +++ b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.cs @@ -0,0 +1,12 @@ +public class Solution { + public int ChalkReplacer(int[] chalk, int k) { + long total = 0; + foreach (int amount in chalk) total += amount; + long remaining = k % total; + for (int i = 0; i < chalk.Length; i++) { + if (remaining < chalk[i]) return i; + remaining -= chalk[i]; + } + return 0; + } +} diff --git a/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.dart b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.dart new file mode 100644 index 00000000..786394b2 --- /dev/null +++ b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.dart @@ -0,0 +1,11 @@ +class Solution { + int chalkReplacer(List chalk, int k) { + int total = chalk.fold(0, (a, b) => a + b); + int remaining = k % total; + for (int i = 0; i < chalk.length; i++) { + if (remaining < chalk[i]) return i; + remaining -= chalk[i]; + } + return 0; + } +} diff --git a/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.go b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.go new file mode 100644 index 00000000..93616d49 --- /dev/null +++ b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.go @@ -0,0 +1,14 @@ +func chalkReplacer(chalk []int, k int) int { + total := int64(0) + for _, amount := range chalk { + total += int64(amount) + } + remaining := int64(k) % total + for i, amount := range chalk { + if remaining < int64(amount) { + return i + } + remaining -= int64(amount) + } + return 0 +} diff --git a/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.java b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.java new file mode 100644 index 00000000..1c898185 --- /dev/null +++ b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.java @@ -0,0 +1,12 @@ +class Solution { + public int chalkReplacer(int[] chalk, int k) { + long total = 0; + for (int amount : chalk) total += amount; + k %= total; + for (int i = 0; i < chalk.length; i++) { + if (k < chalk[i]) return i; + k -= chalk[i]; + } + return 0; // unreachable + } +} diff --git a/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.kt b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.kt new file mode 100644 index 00000000..126d4802 --- /dev/null +++ b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.kt @@ -0,0 +1,11 @@ +class Solution { + fun chalkReplacer(chalk: IntArray, k: Int): Int { + val total = chalk.sumOf { it.toLong() } + var remaining = k % total + for (i in chalk.indices) { + if (remaining < chalk[i]) return i + remaining -= chalk[i] + } + return 0 + } +} diff --git a/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.py b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.py new file mode 100644 index 00000000..af017ce3 --- /dev/null +++ b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.py @@ -0,0 +1,8 @@ +class Solution: + def chalkReplacer(self, chalk, k): + total = sum(chalk) + k %= total + for i, amount in enumerate(chalk): + if k < amount: + return i + k -= amount diff --git a/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.py2 b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.py2 new file mode 100644 index 00000000..fb8f5999 --- /dev/null +++ b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.py2 @@ -0,0 +1,13 @@ +class Solution(object): + def chalkReplacer(self, chalk, k): + """ + :type chalk: List[int] + :type k: int + :rtype: int + """ + total = sum(chalk) + k %= total + for i, amount in enumerate(chalk): + if k < amount: + return i + k -= amount diff --git a/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.rb b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.rb new file mode 100644 index 00000000..8e9acbb1 --- /dev/null +++ b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.rb @@ -0,0 +1,11 @@ +# @param {Integer[]} chalk +# @param {Integer} k +# @return {Integer} +def chalk_replacer(chalk, k) + total = chalk.sum + k %= total + chalk.each_with_index do |amount, i| + return i if k < amount + k -= amount + end +end diff --git a/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.rs b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.rs new file mode 100644 index 00000000..017dfa63 --- /dev/null +++ b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn chalk_replacer(chalk: Vec, k: i32) -> i32 { + let total: i64 = chalk.iter().map(|&x| x as i64).sum(); + let mut remaining = (k as i64) % total; + for (i, &amount) in chalk.iter().enumerate() { + if remaining < amount as i64 { + return i as i32; + } + remaining -= amount as i64; + } + 0 + } +} diff --git a/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.swift b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.swift new file mode 100644 index 00000000..8f6f0181 --- /dev/null +++ b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.swift @@ -0,0 +1,11 @@ +class Solution { + func chalkReplacer(_ chalk: [Int], _ k: Int) -> Int { + let total = chalk.reduce(0, +) + var remaining = k % total + for (i, amount) in chalk.enumerated() { + if remaining < amount { return i } + remaining -= amount + } + return 0 + } +} diff --git a/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.ts b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.ts new file mode 100644 index 00000000..2fff7f3b --- /dev/null +++ b/tests/1501-2000/1894. find-the-student-that-will-replace-the-chalk/sol.ts @@ -0,0 +1,9 @@ +function chalkReplacer(chalk: number[], k: number): number { + const total = chalk.reduce((a, b) => a + b, 0); + let remaining = k % total; + for (let i = 0; i < chalk.length; i++) { + if (remaining < chalk[i]) return i; + remaining -= chalk[i]; + } + return 0; +} diff --git a/tests/1501-2000/1895. largest-magic-square/manifest.yaml b/tests/1501-2000/1895. largest-magic-square/manifest.yaml new file mode 100644 index 00000000..d7eedcc5 --- /dev/null +++ b/tests/1501-2000/1895. largest-magic-square/manifest.yaml @@ -0,0 +1,348 @@ +entry: + id: 1895 + title: "largest-magic-square" + params: + grid: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().largestMagicSquare({grid})" + rust: "Solution::largest_magic_square({grid})" + python3: "Solution().largestMagicSquare({grid})" + python2: "Solution().largestMagicSquare({grid})" + ruby: "largest_magic_square({grid})" + java: "new Solution().largestMagicSquare({grid})" + csharp: "new Solution().LargestMagicSquare({grid})" + kotlin: "Solution().largestMagicSquare({grid})" + go: "largestMagicSquare({grid})" + dart: "Solution().largestMagicSquare({grid})" + swift: "Solution().largestMagicSquare({grid})" + typescript: "largestMagicSquare({grid})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().largestMagicSquare(grid, {result})" + checker: | + class Checker: + def largestMagicSquare(self, grid, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + m = len(grid) + n = len(grid[0]) if m else 0 + best = 1 + for k in range(2, min(m, n) + 1): + for i in range(m - k + 1): + for j in range(n - k + 1): + rows = [sum(grid[x][j:j + k]) for x in range(i, i + k)] + s = rows[0] + if any(v != s for v in rows): + continue + if any(sum(grid[x][y] for x in range(i, i + k)) != s for y in range(j, j + k)): + continue + if sum(grid[i + d][j + d] for d in range(k)) != s: + continue + if sum(grid[i + d][j + k - 1 - d] for d in range(k)) != s: + continue + best = max(best, k) + return result == best + +seed: 1895001 + +tests: + - name: "example_one" + in: + grid: + - [7, 1, 4, 5, 6] + - [2, 5, 1, 6, 4] + - [1, 5, 4, 3, 2] + - [1, 2, 7, 3, 4] + out: 3 + - name: "example_two" + in: + grid: + - [5, 1, 3, 1] + - [9, 3, 3, 1] + - [1, 3, 3, 8] + out: 2 + - name: "single_cell" + in: + grid: + - [1] + out: 1 + - name: "single_row" + in: + grid: + - [1, 2, 3, 4, 5] + out: 1 + - name: "single_column" + in: + grid: + - [1] + - [2] + - [3] + - [4] + out: 1 + - name: "constant_two" + in: + grid: + - [7, 7] + - [7, 7] + out: 2 + - name: "constant_three" + in: + grid: + - [4, 4, 4] + - [4, 4, 4] + - [4, 4, 4] + out: 3 + - name: "constant_four_by_two" + in: + grid: + - [9, 9] + - [9, 9] + - [9, 9] + - [9, 9] + out: 2 + - name: "constant_two_by_four" + in: + grid: + - [6, 6, 6, 6] + - [6, 6, 6, 6] + out: 2 + - name: "constant_five" + in: + grid: + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + out: 5 + - name: "constant_six_by_three" + in: + grid: + - [2, 2, 2] + - [2, 2, 2] + - [2, 2, 2] + - [2, 2, 2] + - [2, 2, 2] + - [2, 2, 2] + out: 3 + - name: "zero_not_allowed_but_positive" + in: + grid: + - [1000000, 1000000] + - [1000000, 1000000] + out: 2 + - name: "nonmagic_two" + in: + grid: + - [1, 2] + - [3, 4] + out: 1 + - name: "nonmagic_three" + in: + grid: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + out: 1 + - name: "magic_three_with_noise" + in: + grid: + - [8, 1, 6, 20] + - [3, 5, 7, 21] + - [4, 9, 2, 22] + - [30, 31, 32, 33] + out: 3 + - name: "magic_two_in_corner" + in: + grid: + - [1, 1, 8] + - [1, 1, 9] + - [7, 6, 5] + out: 2 + - name: "magic_two_bottom_right" + in: + grid: + - [9, 8, 7] + - [6, 2, 3] + - [5, 4, 2] + out: 1 + - name: "magic_three_offset" + in: + grid: + - [50, 50, 50, 50] + - [50, 2, 7, 6] + - [50, 9, 5, 1] + - [50, 4, 3, 8] + out: 3 + - name: "negative_not_in_constraints" + in: + grid: + - [1, 1000000, 1] + - [1000000, 1, 1000000] + - [1, 1000000, 1] + out: 1 + - name: "four_magic" + in: + grid: + - [16, 2, 3, 13] + - [5, 11, 10, 8] + - [9, 7, 6, 12] + - [4, 14, 15, 1] + out: 4 + - name: "four_magic_with_border" + in: + grid: + - [99, 99, 99, 99, 99] + - [99, 16, 2, 3, 13] + - [99, 5, 11, 10, 8] + - [99, 9, 7, 6, 12] + - [99, 4, 14, 15, 1] + out: 4 + - name: "five_magic_with_border" + in: + grid: + - [99, 99, 99, 99, 99, 99] + - [99, 1, 1, 1, 1, 99] + - [99, 1, 1, 1, 1, 99] + - [99, 1, 1, 1, 1, 99] + - [99, 1, 1, 1, 1, 99] + - [99, 99, 99, 99, 99, 99] + out: 4 + - name: "large_constant_six" + in: + grid: + - [3, 3, 3, 3, 3, 3] + - [3, 3, 3, 3, 3, 3] + - [3, 3, 3, 3, 3, 3] + - [3, 3, 3, 3, 3, 3] + - [3, 3, 3, 3, 3, 3] + - [3, 3, 3, 3, 3, 3] + out: 6 + - name: "large_constant_seven" + in: + grid: + - [5, 5, 5, 5, 5, 5, 5] + - [5, 5, 5, 5, 5, 5, 5] + - [5, 5, 5, 5, 5, 5, 5] + - [5, 5, 5, 5, 5, 5, 5] + - [5, 5, 5, 5, 5, 5, 5] + - [5, 5, 5, 5, 5, 5, 5] + - [5, 5, 5, 5, 5, 5, 5] + out: 7 + - name: "rectangular_three_by_five" + in: + grid: + - [2, 2, 2, 2, 2] + - [2, 2, 2, 2, 2] + - [2, 2, 2, 2, 2] + out: 3 + - name: "rectangular_five_by_three" + in: + grid: + - [8, 8, 8] + - [8, 8, 8] + - [8, 8, 8] + - [8, 8, 8] + - [8, 8, 8] + out: 3 + - name: "all_distinct_small" + in: + grid: + - [1, 2, 4] + - [8, 16, 32] + - [64, 128, 256] + out: 1 + - name: "diagonal_equal_only" + in: + grid: + - [5, 1, 5] + - [1, 5, 1] + - [5, 1, 5] + out: 1 + - name: "two_equal_rows_not_square" + in: + grid: + - [2, 2, 2] + - [2, 2, 2] + - [1, 1, 4] + out: 2 + - name: "max_value_single" + in: + grid: + - [1000000] + out: 1 + - name: "max_value_rectangular" + in: + grid: + - [1000000, 1000000, 1000000] + - [1000000, 1000000, 1000000] + out: 2 + - name: "mixed_four_by_five" + in: + grid: + - [1, 1, 1, 2, 3] + - [1, 1, 1, 4, 5] + - [1, 1, 1, 6, 7] + - [8, 9, 10, 11, 12] + out: 3 + - name: "mixed_five_by_four" + in: + grid: + - [1, 1, 1, 8] + - [1, 1, 1, 9] + - [1, 1, 1, 10] + - [2, 3, 4, 5] + - [6, 7, 8, 9] + out: 3 + - name: "constant_eight" + in: + grid: + - [12, 12, 12, 12, 12, 12, 12, 12] + - [12, 12, 12, 12, 12, 12, 12, 12] + - [12, 12, 12, 12, 12, 12, 12, 12] + - [12, 12, 12, 12, 12, 12, 12, 12] + - [12, 12, 12, 12, 12, 12, 12, 12] + - [12, 12, 12, 12, 12, 12, 12, 12] + - [12, 12, 12, 12, 12, 12, 12, 12] + - [12, 12, 12, 12, 12, 12, 12, 12] + out: 8 + - name: "constant_nine_by_four" + in: + grid: + - [13, 13, 13, 13] + - [13, 13, 13, 13] + - [13, 13, 13, 13] + - [13, 13, 13, 13] + - [13, 13, 13, 13] + - [13, 13, 13, 13] + - [13, 13, 13, 13] + - [13, 13, 13, 13] + - [13, 13, 13, 13] + out: 4 + - name: "constant_ten" + in: + grid: + - [14, 14, 14, 14, 14, 14, 14, 14, 14, 14] + - [14, 14, 14, 14, 14, 14, 14, 14, 14, 14] + - [14, 14, 14, 14, 14, 14, 14, 14, 14, 14] + - [14, 14, 14, 14, 14, 14, 14, 14, 14, 14] + - [14, 14, 14, 14, 14, 14, 14, 14, 14, 14] + - [14, 14, 14, 14, 14, 14, 14, 14, 14, 14] + - [14, 14, 14, 14, 14, 14, 14, 14, 14, 14] + - [14, 14, 14, 14, 14, 14, 14, 14, 14, 14] + - [14, 14, 14, 14, 14, 14, 14, 14, 14, 14] + - [14, 14, 14, 14, 14, 14, 14, 14, 14, 14] + out: 10 diff --git a/tests/1501-2000/1895. largest-magic-square/sol.cpp b/tests/1501-2000/1895. largest-magic-square/sol.cpp new file mode 100644 index 00000000..12e7587a --- /dev/null +++ b/tests/1501-2000/1895. largest-magic-square/sol.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + int largestMagicSquare(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int res = 1; + + auto isValid = [&](int i, int j, int k) { + int s = -1; + for (int x = i; x < i + k; x++) { + int row = 0; + for (int y = j; y < j + k; y++) row += grid[x][y]; + if (s == -1) s = row; + else if (s != row) return false; + } + + for (int y = j; y < j + k; y++) { + int col = 0; + for (int x = i; x < i + k; x++) col += grid[x][y]; + if (col != s) return false; + } + + int d1 = 0, d2 = 0; + for (int d = 0; d < k; d++) { + d1 += grid[i + d][j + d]; + d2 += grid[i + d][j + k - 1 - d]; + } + if (d1 != s || d2 != s) return false; + + return true; + }; + + for (int k = 2; k <= min(m, n); k++) { + for (int i = 0; i <= m - k; i++) { + for (int j = 0; j <= n - k; j++) { + if (isValid(i, j, k)) res = k; + } + } + } + return res; + } +}; diff --git a/tests/1501-2000/1895. largest-magic-square/sol.cs b/tests/1501-2000/1895. largest-magic-square/sol.cs new file mode 100644 index 00000000..ab8c4d7e --- /dev/null +++ b/tests/1501-2000/1895. largest-magic-square/sol.cs @@ -0,0 +1,38 @@ +public class Solution { + public int LargestMagicSquare(int[][] grid) { + int m = grid.Length, n = grid[0].Length; + int res = 1; + + bool isValid(int i, int j, int k) { + int s = -1; + for (int x = i; x < i + k; x++) { + int row = 0; + for (int y = j; y < j + k; y++) row += grid[x][y]; + if (s == -1) s = row; + else if (s != row) return false; + } + + for (int y = j; y < j + k; y++) { + int col = 0; + for (int x = i; x < i + k; x++) col += grid[x][y]; + if (col != s) return false; + } + + int d1 = 0, d2 = 0; + for (int d = 0; d < k; d++) { + d1 += grid[i + d][j + d]; + d2 += grid[i + d][j + k - 1 - d]; + } + return d1 == s && d2 == s; + } + + for (int k = 2; k <= Math.Min(m, n); k++) { + for (int i = 0; i <= m - k; i++) { + for (int j = 0; j <= n - k; j++) { + if (isValid(i, j, k)) res = k; + } + } + } + return res; + } +} diff --git a/tests/1501-2000/1895. largest-magic-square/sol.dart b/tests/1501-2000/1895. largest-magic-square/sol.dart new file mode 100644 index 00000000..c2794bea --- /dev/null +++ b/tests/1501-2000/1895. largest-magic-square/sol.dart @@ -0,0 +1,38 @@ +class Solution { + int largestMagicSquare(List> grid) { + int m = grid.length, n = grid[0].length; + int res = 1; + + bool isValid(int i, int j, int k) { + int s = -1; + for (int x = i; x < i + k; x++) { + int row = 0; + for (int y = j; y < j + k; y++) row += grid[x][y]; + if (s == -1) s = row; + else if (s != row) return false; + } + + for (int y = j; y < j + k; y++) { + int col = 0; + for (int x = i; x < i + k; x++) col += grid[x][y]; + if (col != s) return false; + } + + int d1 = 0, d2 = 0; + for (int d = 0; d < k; d++) { + d1 += grid[i + d][j + d]; + d2 += grid[i + d][j + k - 1 - d]; + } + return d1 == s && d2 == s; + } + + for (int k = 2; k <= min(m, n); k++) { + for (int i = 0; i <= m - k; i++) { + for (int j = 0; j <= n - k; j++) { + if (isValid(i, j, k)) res = k; + } + } + } + return res; + } +} diff --git a/tests/1501-2000/1895. largest-magic-square/sol.go b/tests/1501-2000/1895. largest-magic-square/sol.go new file mode 100644 index 00000000..1d5da647 --- /dev/null +++ b/tests/1501-2000/1895. largest-magic-square/sol.go @@ -0,0 +1,48 @@ +func largestMagicSquare(grid [][]int) int { + m := len(grid) + n := len(grid[0]) + res := 1 + + isValid := func(i, j, k int) bool { + s := -1 + for x := i; x < i+k; x++ { + row := 0 + for y := j; y < j+k; y++ { + row += grid[x][y] + } + if s == -1 { + s = row + } else if s != row { + return false + } + } + + for y := j; y < j+k; y++ { + col := 0 + for x := i; x < i+k; x++ { + col += grid[x][y] + } + if col != s { + return false + } + } + + d1, d2 := 0, 0 + for d := 0; d < k; d++ { + d1 += grid[i+d][j+d] + d2 += grid[i+d][j+k-1-d] + } + return d1 == s && d2 == s + } + + for k := 2; k <= min(m, n); k++ { + for i := 0; i <= m-k; i++ { + for j := 0; j <= n-k; j++ { + if isValid(i, j, k) { + res = k + } + } + } + } + return res +} diff --git a/tests/1501-2000/1895. largest-magic-square/sol.java b/tests/1501-2000/1895. largest-magic-square/sol.java new file mode 100644 index 00000000..281a2f3f --- /dev/null +++ b/tests/1501-2000/1895. largest-magic-square/sol.java @@ -0,0 +1,38 @@ +class Solution { + public int largestMagicSquare(int[][] grid) { + int m = grid.length, n = grid[0].length; + int res = 1; + + for (int k = 2; k <= Math.min(m, n); k++) { + for (int i = 0; i <= m - k; i++) { + for (int j = 0; j <= n - k; j++) { + if (isValid(grid, i, j, k)) res = k; + } + } + } + return res; + } + + private boolean isValid(int[][] grid, int i, int j, int k) { + int s = -1; + for (int x = i; x < i + k; x++) { + int row = 0; + for (int y = j; y < j + k; y++) row += grid[x][y]; + if (s == -1) s = row; + else if (s != row) return false; + } + + for (int y = j; y < j + k; y++) { + int col = 0; + for (int x = i; x < i + k; x++) col += grid[x][y]; + if (col != s) return false; + } + + int d1 = 0, d2 = 0; + for (int d = 0; d < k; d++) { + d1 += grid[i + d][j + d]; + d2 += grid[i + d][j + k - 1 - d]; + } + return d1 == s && d2 == s; + } +} diff --git a/tests/1501-2000/1895. largest-magic-square/sol.kt b/tests/1501-2000/1895. largest-magic-square/sol.kt new file mode 100644 index 00000000..8ffe45cc --- /dev/null +++ b/tests/1501-2000/1895. largest-magic-square/sol.kt @@ -0,0 +1,34 @@ +class Solution { + fun largestMagicSquare(grid: Array): Int { + val m = grid.size + val n = grid[0].size + var res = 1 + + fun isValid(i: Int, j: Int, k: Int): Boolean { + var s = -1 + for (x in i until i + k) { + val row = (j until j + k).sumOf { grid[x][it] } + if (s == -1) s = row + else if (s != row) return false + } + + for (y in j until j + k) { + val col = (i until i + k).sumOf { grid[it][y] } + if (col != s) return false + } + + val d1 = (0 until k).sumOf { grid[i + it][j + it] } + val d2 = (0 until k).sumOf { grid[i + it][j + k - 1 - it] } + return d1 == s && d2 == s + } + + for (k in 2..minOf(m, n)) { + for (i in 0..(m - k)) { + for (j in 0..(n - k)) { + if (isValid(i, j, k)) res = k + } + } + } + return res + } +} diff --git a/tests/1501-2000/1895. largest-magic-square/sol.py b/tests/1501-2000/1895. largest-magic-square/sol.py new file mode 100644 index 00000000..b986ed3d --- /dev/null +++ b/tests/1501-2000/1895. largest-magic-square/sol.py @@ -0,0 +1,32 @@ +class Solution: + def largestMagicSquare(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + res = 1 + + def isValid(i, j, k): + s = None + for x in range(i, i + k): + row = sum(grid[x][j : j + k]) + if s is None: + s = row + elif s != row: + return False + + for y in range(j, j + k): + if sum(grid[x][y] for x in range(i, i + k)) != s: + return False + + if sum(grid[i + d][j + d] for d in range(k)) != s: + return False + + if sum(grid[i + d][j + k - 1 - d] for d in range(k)) != s: + return False + + return True + + for k in range(2, min(m, n) + 1): + for i in range(m - k + 1): + for j in range(n - k + 1): + if isValid(i, j, k): + res = k + return res diff --git a/tests/1501-2000/1895. largest-magic-square/sol.py2 b/tests/1501-2000/1895. largest-magic-square/sol.py2 new file mode 100644 index 00000000..cb7b4027 --- /dev/null +++ b/tests/1501-2000/1895. largest-magic-square/sol.py2 @@ -0,0 +1,30 @@ +class Solution(object): + def largestMagicSquare(self, grid): + m, n = len(grid), len(grid[0]) + res = 1 + + def isValid(i, j, k): + s = None + for x in range(i, i + k): + row = sum(grid[x][j:j + k]) + if s is None: s = row + elif s != row: return False + + for y in range(j, j + k): + if sum(grid[x][y] for x in range(i, i + k)) != s: + return False + + if sum(grid[i + d][j + d] for d in range(k)) != s: + return False + + if sum(grid[i + d][j + k - 1 - d] for d in range(k)) != s: + return False + + return True + + for k in range(2, min(m, n) + 1): + for i in range(m - k + 1): + for j in range(n - k + 1): + if isValid(i, j, k): + res = k + return res diff --git a/tests/1501-2000/1895. largest-magic-square/sol.rb b/tests/1501-2000/1895. largest-magic-square/sol.rb new file mode 100644 index 00000000..9fc9e5e1 --- /dev/null +++ b/tests/1501-2000/1895. largest-magic-square/sol.rb @@ -0,0 +1,37 @@ +def largest_magic_square(grid) + m = grid.length + n = grid[0].length + res = 1 + + isValid = lambda do |i, j, k| + s = nil + (i...(i+k)).each do |x| + row = grid[x][j...(j+k)].sum + if s.nil? + s = row + elsif s != row + return false + end + end + + (j...(j+k)).each do |y| + col = (i...(i+k)).sum { |x| grid[x][y] } + return false if col != s + end + + diag1 = (0...k).sum { |d| grid[i+d][j+d] } + diag2 = (0...k).sum { |d| grid[i+d][j+k-1-d] } + return false if diag1 != s || diag2 != s + + true + end + + (2..[m, n].min).each do |k| + (0..(m-k)).each do |i| + (0..(n-k)).each do |j| + res = k if isValid.call(i, j, k) + end + end + end + res +end diff --git a/tests/1501-2000/1895. largest-magic-square/sol.rs b/tests/1501-2000/1895. largest-magic-square/sol.rs new file mode 100644 index 00000000..8d9c86bf --- /dev/null +++ b/tests/1501-2000/1895. largest-magic-square/sol.rs @@ -0,0 +1,34 @@ +impl Solution { + pub fn largest_magic_square(grid: Vec>) -> i32 { + let m = grid.len(); + let n = grid[0].len(); + let mut res = 1; + + fn is_valid(grid: &Vec>, i: usize, j: usize, k: usize) -> bool { + let mut s = -1; + for x in i..(i + k) { + let row: i32 = grid[x][j..(j + k)].iter().sum(); + if s == -1 { s = row; } + else if s != row { return false; } + } + + for y in j..(j + k) { + let col: i32 = (i..(i + k)).map(|x| grid[x][y]).sum(); + if col != s { return false; } + } + + let d1: i32 = (0..k).map(|d| grid[i + d][j + d]).sum(); + let d2: i32 = (0..k).map(|d| grid[i + d][j + k - 1 - d]).sum(); + d1 == s && d2 == s + } + + for k in 2..=m.min(n) { + for i in 0..=(m - k) { + for j in 0..=(n - k) { + if is_valid(&grid, i, j, k) { res = k as i32; } + } + } + } + res + } +} diff --git a/tests/1501-2000/1895. largest-magic-square/sol.swift b/tests/1501-2000/1895. largest-magic-square/sol.swift new file mode 100644 index 00000000..a99acb0b --- /dev/null +++ b/tests/1501-2000/1895. largest-magic-square/sol.swift @@ -0,0 +1,39 @@ +class Solution { + func largestMagicSquare(_ grid: [[Int]]) -> Int { + let m = grid.count, n = grid[0].count + var res = 1 + + func isValid(_ i: Int, _ j: Int, _ k: Int) -> Bool { + var s = -1 + for x in i..<(i+k) { + var row = 0 + for y in j..<(j+k) { row += grid[x][y] } + if s == -1 { s = row } + else if s != row { return false } + } + + for y in j..<(j+k) { + var col = 0 + for x in i..<(i+k) { col += grid[x][y] } + if col != s { return false } + } + + var d1 = 0, d2 = 0 + for d in 0..= len(expression) or expression[pos] != ")": + raise ValueError + pos += 1 + return value + + def combine(left, right, op): + lv, lc = left + rv, rc = right + value = (lv & rv) if op == "&" else (lv | rv) + if lv == rv == (0 if op == "&" else 1): + cost = min(lc, rc) + elif lv == rv == (1 if op == "&" else 0): + cost = 1 + min(lc, rc) + else: + cost = 1 + return value, cost + + def parse_expr(): + nonlocal pos + current = parse_atom() + while pos < len(expression) and expression[pos] != ")": + op = expression[pos] + if op not in "&|": + raise ValueError + pos += 1 + current = combine(current, parse_atom(), op) + return current + + try: + value, cost = parse_expr() + if pos != len(expression): + return False + return cost == result and cost >= 1 + except (IndexError, ValueError, TypeError): + return False + +seed: 1896 + +tests: + - name: "single_zero" + in: + expression: "0" + out: 1 + - name: "single_one" + in: + expression: "1" + out: 1 + - name: "and_zeros" + in: + expression: "0&0" + out: 2 + - name: "and_ones" + in: + expression: "1&1" + out: 1 + - name: "or_zeros" + in: + expression: "0|0" + out: 1 + - name: "or_ones" + in: + expression: "1|1" + out: 2 + - name: "mixed_and" + in: + expression: "0&1" + out: 1 + - name: "mixed_and_reverse" + in: + expression: "1&0" + out: 1 + - name: "example_one" + in: + expression: "1&(0|1)" + out: 1 + - name: "example_two" + in: + expression: "(0&0)&(0&0&0)" + out: 3 + - name: "example_three" + in: + expression: "(0|(1|0&1))" + out: 1 + - name: "left_to_right_or_and" + in: + expression: "1|0&1" + out: 1 + - name: "left_to_right_and_or" + in: + expression: "1&0|1" + out: 1 + - name: "one_parenthesis" + in: + expression: "(1)" + out: 1 + - name: "nested_parentheses" + in: + expression: "(((1)))" + out: 1 + - name: "nested_zero" + in: + expression: "((0))" + out: 1 + - name: "all_zero_or_chain" + in: + expression: "0|0|0" + out: 1 + - name: "all_one_and_chain" + in: + expression: "1&1&1" + out: 1 + - name: "or_with_one" + in: + expression: "0|1|0" + out: 1 + - name: "and_with_zero" + in: + expression: "1&0&1" + out: 1 + - name: "balanced_or_and" + in: + expression: "(1|0)&(0|1)" + out: 1 + - name: "balanced_and_or" + in: + expression: "(1&0)|(0&1)" + out: 1 + - name: "both_true_or_groups" + in: + expression: "(1|1)&(1|1)" + out: 2 + - name: "both_false_and_groups" + in: + expression: "(0&0)|(0&0)" + out: 2 + - name: "false_or_groups_and" + in: + expression: "(0|0)&(0|0)" + out: 2 + - name: "long_mixed_chain" + in: + expression: "1|1|(0&0)&1" + out: 1 + - name: "zero_chain_final_one" + in: + expression: "0&0&0|1" + out: 1 + - name: "nested_zero_or" + in: + expression: "1&(0|0|0)" + out: 1 + - name: "nested_or_then_zero" + in: + expression: "(1&(0|1))|0" + out: 1 + - name: "nested_balanced_false" + in: + expression: "((1|0)&(1&0))" + out: 1 + - name: "deep_mixed_zero" + in: + expression: "0|(1&(0|1&0))" + out: 1 + - name: "and_after_or_groups" + in: + expression: "((0|0)|(1&1))&0" + out: 1 + - name: "deep_balanced" + in: + expression: "1&((1|0)&(0|1))" + out: 1 + - name: "three_false_terms" + in: + expression: "(0&1)|(1&0)|(0&0)" + out: 1 + - name: "alternating_and_chain" + in: + expression: "0&1&0&1&0&1" + out: 1 + - name: "alternating_or_chain" + in: + expression: "1|0|1|0|1|0" + out: 1 + - name: "two_complex_groups" + in: + expression: "(1|0&1|0)&(0|1&0|1)" + out: 1 + - name: "deep_true_or_false" + in: + expression: "((0&0)&(0&0))|((1&1)&(1&1))" + out: 1 + - name: "deep_right_nesting" + in: + expression: "1&(1&(1&(0|0)))" + out: 1 diff --git a/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.cpp b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.cpp new file mode 100644 index 00000000..209331d4 --- /dev/null +++ b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + int minOperationsToFlip(string expression) { + unordered_map loc; + vector stack; + for (int i = expression.size() - 1; i >= 0; --i) { + if (expression[i] == ')') stack.push_back(i); + else if (expression[i] == '(') { + loc[stack.back()] = i; + stack.pop_back(); + } + } + function(int,int)> fn = [&](int lo, int hi) -> pair { + if (lo == hi) return {expression[lo] - '0', 1}; + if (expression[hi] == ')' && loc[hi] == lo) return fn(lo+1, hi-1); + int mid = loc.count(hi) ? loc[hi] - 1 : hi - 1; + auto [v, c] = fn(mid+1, hi); + auto [vv, cc] = fn(lo, mid-1); + char op = expression[mid]; + int val, chg; + if (op == '|') { + val = v | vv; + if (v == 0 && vv == 0) chg = min(c, cc); + else if (v == 1 && vv == 1) chg = 1 + min(c, cc); + else chg = 1; + } else { + val = v & vv; + if (v == 0 && vv == 0) chg = 1 + min(c, cc); + else if (v == 1 && vv == 1) chg = min(c, cc); + else chg = 1; + } + return {val, chg}; + }; + return fn(0, expression.size()-1).second; + } +}; diff --git a/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.cs b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.cs new file mode 100644 index 00000000..85300835 --- /dev/null +++ b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.cs @@ -0,0 +1,35 @@ +public class Solution { + private Dictionary loc = new Dictionary(); + private string expr; + + public int MinOperationsToFlip(string expression) { + expr = expression; + var stack = new Stack(); + for (int i = expression.Length - 1; i >= 0; --i) { + if (expression[i] == ')') stack.Push(i); + else if (expression[i] == '(') loc[stack.Pop()] = i; + } + return Fn(0, expression.Length - 1).Item2; + } + + private (int, int) Fn(int lo, int hi) { + if (lo == hi) return (expr[lo] - '0', 1); + if (expr[hi] == ')' && loc[hi] == lo) return Fn(lo+1, hi-1); + int mid = (loc.ContainsKey(hi) ? loc[hi] : hi) - 1; + var (v, c) = Fn(mid+1, hi); + var (vv, cc) = Fn(lo, mid-1); + int val, chg; + if (expr[mid] == '|') { + val = v | vv; + if (v == 0 && vv == 0) chg = Math.Min(c, cc); + else if (v == 1 && vv == 1) chg = 1 + Math.Min(c, cc); + else chg = 1; + } else { + val = v & vv; + if (v == 0 && vv == 0) chg = 1 + Math.Min(c, cc); + else if (v == 1 && vv == 1) chg = Math.Min(c, cc); + else chg = 1; + } + return (val, chg); + } +} diff --git a/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.dart b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.dart new file mode 100644 index 00000000..02e99947 --- /dev/null +++ b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.dart @@ -0,0 +1,45 @@ +class Solution { + int minOperationsToFlip(String expression) { + Map loc = {}; + List stack = []; + for (int i = expression.length - 1; i >= 0; i--) { + if (expression[i] == ')') { + stack.add(i); + } else if (expression[i] == '(') { + loc[stack.removeLast()] = i; + } + } + + List fn(int lo, int hi) { + if (lo == hi) return [expression.codeUnitAt(lo) - 48, 1]; + if (expression[hi] == ')' && loc[hi] == lo) return fn(lo + 1, hi - 1); + int mid = (loc[hi] ?? hi) - 1; + List right = fn(mid + 1, hi); + List left = fn(lo, mid - 1); + int v = right[0], c = right[1], vv = left[0], cc = left[1]; + int val, chg; + if (expression[mid] == '|') { + val = v | vv; + if (v == 0 && vv == 0) { + chg = c < cc ? c : cc; + } else if (v == 1 && vv == 1) { + chg = 1 + (c < cc ? c : cc); + } else { + chg = 1; + } + } else { + val = v & vv; + if (v == 0 && vv == 0) { + chg = 1 + (c < cc ? c : cc); + } else if (v == 1 && vv == 1) { + chg = c < cc ? c : cc; + } else { + chg = 1; + } + } + return [val, chg]; + } + + return fn(0, expression.length - 1)[1]; + } +} diff --git a/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.go b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.go new file mode 100644 index 00000000..e4259916 --- /dev/null +++ b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.go @@ -0,0 +1,52 @@ +func minOperationsToFlip(expression string) int { + n := len(expression) + loc := make(map[int]int) + stack := []int{} + for i := n - 1; i >= 0; i-- { + if expression[i] == ')' { + stack = append(stack, i) + } else if expression[i] == '(' { + loc[stack[len(stack)-1]] = i + stack = stack[:len(stack)-1] + } + } + + var fn func(int, int) (int, int) + fn = func(lo, hi int) (int, int) { + if lo == hi { + return int(expression[lo] - '0'), 1 + } + if expression[hi] == ')' && loc[hi] == lo { + return fn(lo+1, hi-1) + } + mid := hi - 1 + if m, ok := loc[hi]; ok { + mid = m - 1 + } + v, c := fn(mid+1, hi) + vv, cc := fn(lo, mid-1) + val, chg := 0, 0 + if expression[mid] == '|' { + val = v | vv + if v == 0 && vv == 0 { + if c < cc { chg = c } else { chg = cc } + } else if v == 1 && vv == 1 { + if c < cc { chg = c + 1 } else { chg = cc + 1 } + } else { + chg = 1 + } + } else { + val = v & vv + if v == 0 && vv == 0 { + if c < cc { chg = c + 1 } else { chg = cc + 1 } + } else if v == 1 && vv == 1 { + if c < cc { chg = c } else { chg = cc } + } else { + chg = 1 + } + } + return val, chg + } + _, ans := fn(0, n-1) + return ans +} diff --git a/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.java b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.java new file mode 100644 index 00000000..4a3a884e --- /dev/null +++ b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.java @@ -0,0 +1,39 @@ +import java.util.*; + +class Solution { + private Map loc = new HashMap<>(); + private String expr; + + public int minOperationsToFlip(String expression) { + expr = expression; + Deque stack = new ArrayDeque<>(); + for (int i = expression.length() - 1; i >= 0; --i) { + char ch = expression.charAt(i); + if (ch == ')') stack.push(i); + else if (ch == '(') loc.put(stack.pop(), i); + } + return fn(0, expression.length()-1)[1]; + } + + private int[] fn(int lo, int hi) { + if (lo == hi) return new int[]{expr.charAt(lo) - '0', 1}; + if (expr.charAt(hi) == ')' && loc.get(hi) == lo) return fn(lo+1, hi-1); + int mid = (loc.containsKey(hi) ? loc.get(hi) : hi) - 1; + int[] right = fn(mid+1, hi); + int[] left = fn(lo, mid-1); + int v = right[0], c = right[1], vv = left[0], cc = left[1]; + int val, chg; + if (expr.charAt(mid) == '|') { + val = v | vv; + if (v == 0 && vv == 0) chg = Math.min(c, cc); + else if (v == 1 && vv == 1) chg = 1 + Math.min(c, cc); + else chg = 1; + } else { + val = v & vv; + if (v == 0 && vv == 0) chg = 1 + Math.min(c, cc); + else if (v == 1 && vv == 1) chg = Math.min(c, cc); + else chg = 1; + } + return new int[]{val, chg}; + } +} diff --git a/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.kt b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.kt new file mode 100644 index 00000000..c4f9bdaa --- /dev/null +++ b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.kt @@ -0,0 +1,38 @@ +class Solution { + private lateinit var expr: String + private val loc = HashMap() + + fun minOperationsToFlip(expression: String): Int { + expr = expression + val stack = ArrayDeque() + for (i in expression.length - 1 downTo 0) { + when (expression[i]) { + ')' -> stack.add(i) + '(' -> loc[stack.removeLast()] = i + } + } + return fn(0, expression.length - 1).second + } + + private fun fn(lo: Int, hi: Int): Pair { + if (lo == hi) return expr[lo] - '0' to 1 + if (expr[hi] == ')' && loc[hi] == lo) return fn(lo + 1, hi - 1) + val mid = (loc[hi] ?: hi) - 1 + val (v, c) = fn(mid + 1, hi) + val (vv, cc) = fn(lo, mid - 1) + val valv: Int + val chg: Int + if (expr[mid] == '|') { + valv = v or vv + if (v == 0 && vv == 0) chg = minOf(c, cc) + else if (v == 1 && vv == 1) chg = 1 + minOf(c, cc) + else chg = 1 + } else { + valv = v and vv + if (v == 0 && vv == 0) chg = 1 + minOf(c, cc) + else if (v == 1 && vv == 1) chg = minOf(c, cc) + else chg = 1 + } + return valv to chg + } +} diff --git a/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.py b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.py new file mode 100644 index 00000000..150ef377 --- /dev/null +++ b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.py @@ -0,0 +1,38 @@ +class Solution: + def minOperationsToFlip(self, expression: str) -> int: + loc = {} + stack = [] + for i in reversed(range(len(expression))): + if expression[i] == ")": + stack.append(i) + elif expression[i] == "(": + loc[stack.pop()] = i + + def fn(lo, hi): + """Return value and min op to change value.""" + if lo == hi: + return int(expression[lo]), 1 + if expression[hi] == ")" and loc[hi] == lo: + return fn(lo + 1, hi - 1) # strip parenthesis + mid = loc.get(hi, hi) - 1 + v, c = fn(mid + 1, hi) + vv, cc = fn(lo, mid - 1) + if expression[mid] == "|": + val = v | vv + if v == vv == 0: + chg = min(c, cc) + elif v == vv == 1: + chg = 1 + min(c, cc) + else: + chg = 1 + else: # expression[k] == "&" + val = v & vv + if v == vv == 0: + chg = 1 + min(c, cc) + elif v == vv == 1: + chg = min(c, cc) + else: + chg = 1 + return val, chg + + return fn(0, len(expression) - 1)[1] diff --git a/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.py2 b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.py2 new file mode 100644 index 00000000..435e0043 --- /dev/null +++ b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.py2 @@ -0,0 +1,31 @@ +class Solution(object): + def minOperationsToFlip(self, expression): + """ + :type expression: str + :rtype: int + """ + loc = {} + stack = [] + for i in reversed(range(len(expression))): + if expression[i] == ")": stack.append(i) + elif expression[i] == "(": loc[stack.pop()] = i + + def fn(lo, hi): + if lo == hi: return int(expression[lo]), 1 + if expression[hi] == ")" and loc[hi] == lo: return fn(lo+1, hi-1) + mid = loc.get(hi, hi) - 1 + v, c = fn(mid+1, hi) + vv, cc = fn(lo, mid-1) + if expression[mid] == "|": + val = v | vv + if v == vv == 0: chg = min(c, cc) + elif v == vv == 1: chg = 1 + min(c, cc) + else: chg = 1 + else: + val = v & vv + if v == vv == 0: chg = 1 + min(c, cc) + elif v == vv == 1: chg = min(c, cc) + else: chg = 1 + return val, chg + + return fn(0, len(expression)-1)[1] diff --git a/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.rb b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.rb new file mode 100644 index 00000000..9b9ffe86 --- /dev/null +++ b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.rb @@ -0,0 +1,48 @@ +# @param {String} expression +# @return {Integer} +def min_operations_to_flip(expression) + n = expression.length + loc = {} + stack = [] + (n-1).downto(0) do |i| + if expression[i] == ")" + stack << i + elsif expression[i] == "(" + loc[stack.pop] = i + end + end + + fn = lambda do |lo, hi| + if lo == hi + return expression[lo].to_i, 1 + end + if expression[hi] == ")" && loc[hi] == lo + return fn.call(lo+1, hi-1) + end + mid = (loc[hi] || hi) - 1 + v, c = fn.call(mid+1, hi) + vv, cc = fn.call(lo, mid-1) + if expression[mid] == "|" + val = v | vv + if v == 0 && vv == 0 + chg = [c, cc].min + elsif v == 1 && vv == 1 + chg = 1 + [c, cc].min + else + chg = 1 + end + else + val = v & vv + if v == 0 && vv == 0 + chg = 1 + [c, cc].min + elsif v == 1 && vv == 1 + chg = [c, cc].min + else + chg = 1 + end + end + [val, chg] + end + + fn.call(0, n-1)[1] +end diff --git a/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.rs b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.rs new file mode 100644 index 00000000..6e14b8b8 --- /dev/null +++ b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.rs @@ -0,0 +1,39 @@ +use std::collections::HashMap; + +impl Solution { + pub fn min_operations_to_flip(expression: String) -> i32 { + let chars: Vec = expression.chars().collect(); + let n = chars.len(); + let mut loc = HashMap::new(); + let mut stack = vec![]; + for i in (0..n).rev() { + if chars[i] == ')' { stack.push(i); } + else if chars[i] == '(' { loc.insert(stack.pop().unwrap(), i); } + } + + fn solve(chars: &[char], loc: &HashMap, lo: usize, hi: usize) -> (i32, i32) { + if lo == hi { return ((chars[lo] as u8 - '0' as u8) as i32, 1); } + if chars[hi] == ')' && loc[&hi] == lo { return solve(chars, loc, lo+1, hi-1); } + let mid = loc.get(&hi).map(|&x| x - 1).unwrap_or(hi - 1); + let (v, c) = solve(chars, loc, mid+1, hi); + let (vv, cc) = solve(chars, loc, lo, mid-1); + let op = chars[mid]; + let val; + let chg; + if op == '|' { + val = v | vv; + if v == 0 && vv == 0 { chg = c.min(cc); } + else if v == 1 && vv == 1 { chg = 1 + c.min(cc); } + else { chg = 1; } + } else { + val = v & vv; + if v == 0 && vv == 0 { chg = 1 + c.min(cc); } + else if v == 1 && vv == 1 { chg = c.min(cc); } + else { chg = 1; } + } + (val, chg) + } + + solve(&chars, &loc, 0, n-1).1 + } +} diff --git a/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.swift b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.swift new file mode 100644 index 00000000..a5aa6dac --- /dev/null +++ b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.swift @@ -0,0 +1,39 @@ +class Solution { + func minOperationsToFlip(_ expression: String) -> Int { + let chars = Array(expression) + let n = chars.count + var loc: [Int: Int] = [:] + var stack: [Int] = [] + for i in stride(from: n-1, through: 0, by: -1) { + if chars[i] == ")" { + stack.append(i) + } else if chars[i] == "(" { + loc[stack.removeLast()] = i + } + } + + func solve(_ lo: Int, _ hi: Int) -> (Int, Int) { + if lo == hi { return (Int(String(chars[lo]))!, 1) } + if chars[hi] == ")" && loc[hi] == lo { return solve(lo+1, hi-1) } + let mid = (loc[hi] ?? hi) - 1 + let (v, c) = solve(mid+1, hi) + let (vv, cc) = solve(lo, mid-1) + let val: Int + let chg: Int + if chars[mid] == "|" { + val = v | vv + if v == 0 && vv == 0 { chg = min(c, cc) } + else if v == 1 && vv == 1 { chg = 1 + min(c, cc) } + else { chg = 1 } + } else { + val = v & vv + if v == 0 && vv == 0 { chg = 1 + min(c, cc) } + else if v == 1 && vv == 1 { chg = min(c, cc) } + else { chg = 1 } + } + return (val, chg) + } + + return solve(0, n-1).1 + } +} diff --git a/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.ts b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.ts new file mode 100644 index 00000000..9f643426 --- /dev/null +++ b/tests/1501-2000/1896. minimum-cost-to-change-the-final-value-of-expression/sol.ts @@ -0,0 +1,33 @@ +function minOperationsToFlip(expression: string): number { + const n = expression.length; + const loc = new Map(); + const stack: number[] = []; + for (let i = n - 1; i >= 0; --i) { + if (expression[i] === ")") stack.push(i); + else if (expression[i] === "(") loc.set(stack.pop()!, i); + } + + const solve = (lo: number, hi: number): [number, number] => { + if (lo === hi) return [Number(expression[lo]), 1]; + if (expression[hi] === ")" && loc.get(hi) === lo) + return solve(lo + 1, hi - 1); + let mid = (loc.get(hi) ?? hi) - 1; + const [v, c] = solve(mid + 1, hi); + const [vv, cc] = solve(lo, mid - 1); + let val: number, chg: number; + if (expression[mid] === "|") { + val = v | vv; + if (v === 0 && vv === 0) chg = Math.min(c, cc); + else if (v === 1 && vv === 1) chg = 1 + Math.min(c, cc); + else chg = 1; + } else { + val = v & vv; + if (v === 0 && vv === 0) chg = 1 + Math.min(c, cc); + else if (v === 1 && vv === 1) chg = Math.min(c, cc); + else chg = 1; + } + return [val, chg]; + }; + + return solve(0, n - 1)[1]; +} diff --git a/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/manifest.yaml b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/manifest.yaml new file mode 100644 index 00000000..a6703cca --- /dev/null +++ b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/manifest.yaml @@ -0,0 +1,246 @@ +entry: + id: 1897 + title: "redistribute-characters-to-make-all-strings-equal" + params: + words: + type: array + items: + type: string + call: + cpp: "Solution().makeEqual({words})" + rust: "Solution::make_equal({words})" + python3: "Solution().makeEqual({words})" + python2: "Solution().makeEqual({words})" + ruby: "make_equal({words})" + java: "new Solution().makeEqual({words})" + csharp: "new Solution().MakeEqual({words})" + kotlin: "Solution().makeEqual({words})" + go: "makeEqual({words})" + dart: "Solution().makeEqual({words})" + swift: "Solution().makeEqual({words})" + typescript: "makeEqual({words})" + +judge: + type: exact + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().makeEqual(words, {result})" + checker: | + class Checker: + def makeEqual(self, words, result): + if not isinstance(result, bool): + return False + total = [0] * 26 + for word in words: + for ch in word: + total[ord(ch) - 97] += 1 + n = len(words) + expected = all(count % n == 0 for count in total) + return result == expected + +seed: 1897 + +tests: + - name: example-true + in: + words: ["abc", "aabc", "bc"] + out: true + - name: example-false + in: + words: ["ab", "a"] + out: false + - name: single-word + in: + words: ["leetcode"] + out: true + - name: two-identical + in: + words: ["aa", "aa"] + out: true + - name: two-different-same-count + in: + words: ["ab", "ba"] + out: true + - name: missing-character + in: + words: ["a", "b"] + out: false + - name: uneven-count + in: + words: ["a", "aa", "aaa"] + out: true + - name: uneven-count-false + in: + words: ["a", "a", "aa"] + out: false + - name: repeated-one-letter + in: + words: ["aaaa", "", "aaaa"] + out: false + - name: balanced-one-letter + in: + words: ["aaa", "a", "aa"] + out: true + - name: all-alphabet-equal + in: + words: ["abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz"] + out: true + - name: alphabet-three-way + in: + words: ["abc", "bca", "cab"] + out: true + - name: alphabet-four-way-false + in: + words: ["abc", "abc", "abc", "ab"] + out: false + - name: one-character-three + in: + words: ["x", "x", "x"] + out: true + - name: one-character-mixed + in: + words: ["x", "x", "y"] + out: false + - name: empty-string-invalid-balance + in: + words: ["ab", "", "ab"] + out: false + - name: empty-string-balanced + in: + words: ["", "", ""] + out: true + - name: duplicate-permutations + in: + words: ["aabb", "baba", "abba", "baab"] + out: true + - name: duplicate-permutations-false + in: + words: ["aabb", "baba", "abba", "baa"] + out: false + - name: three-letters-four-words + in: + words: ["ab", "bc", "cd", "da"] + out: false + - name: three-letters-four-words-false + in: + words: ["ab", "bc", "cd", "db"] + out: false + - name: two-long-balanced + in: + words: ["aabbccddeeff", "ffeeddccbbaa"] + out: true + - name: two-long-unbalanced + in: + words: ["aabbccddeeff", "ffeeddccbb"] + out: true + - name: three-long-balanced + in: + words: ["aaaabbbb", "bbbbaaaa", "aabbbbaa"] + out: true + - name: three-long-unbalanced + in: + words: ["aaaabbbb", "bbbbaaaa", "aabbbba"] + out: false + - name: many-identical + in: + words: + ["abc", "abc", "abc", "abc", "abc", "abc", "abc", "abc", "abc", "abc"] + out: true + - name: many-identical-one-extra + in: + words: + ["abc", "abc", "abc", "abc", "abc", "abc", "abc", "abc", "abc", "ab"] + out: false + - name: counts-divisible-by-five + in: + words: + ["aaaaabbbbb", "ababababab", "bbaaaabbaa", "aabbaabbaa", "bbaaabaaaa"] + out: false + - name: counts-not-divisible-by-five + in: + words: + ["aaaaabbbbb", "ababababab", "bbaaaabbaa", "aabbaabbaa", "bbaaabaaa"] + out: false + - name: ten-single-letter + in: + words: ["q", "q", "q", "q", "q", "q", "q", "q", "q", "q"] + out: true + - name: ten-single-letter-one-other + in: + words: ["q", "q", "q", "q", "q", "q", "q", "q", "q", "r"] + out: false + - name: five-balanced-symbols + in: + words: ["abcde", "bcdea", "cdeab", "deabc", "eabcd"] + out: true + - name: large-static-balanced + in: + words: + [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + ] + out: true + - name: large-static-unbalanced + in: + words: + [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + ] + out: false + - name: gen-small-random + in: + words: + gen: array + len: 7 + of: + gen: str + len: 8 + alphabet: "abc" + seed: 189701 + - name: gen-medium-random + in: + words: + gen: array + len: 25 + of: + gen: str + len: 40 + alphabet: "abcdef" + seed: 189702 + - name: gen-max-words + in: + words: + gen: array + len: 100 + of: + gen: str + len: 100 + alphabet: "abcd" + seed: 189703 + - name: gen-max-length + in: + words: + gen: array + len: 2 + of: + gen: str + len: 100 + alphabet: "xyz" + seed: 189704 + - name: gen-full-alphabet + in: + words: + gen: array + len: 64 + of: + gen: str + len: 75 + alphabet: "abcdefghijklmnopqrstuvwxyz" + seed: 189705 diff --git a/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.cpp b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.cpp new file mode 100644 index 00000000..cbc89115 --- /dev/null +++ b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + bool makeEqual(vector& words) { + vector freq(26, 0); + int n = words.size(); + for (const string& word : words) { + for (char ch : word) { + freq[ch - 'a']++; + } + } + for (int count : freq) { + if (count % n != 0) { + return false; + } + } + return true; + } +}; diff --git a/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.cs b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.cs new file mode 100644 index 00000000..41ab5231 --- /dev/null +++ b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.cs @@ -0,0 +1,17 @@ +public class Solution { + public bool MakeEqual(string[] words) { + int[] freq = new int[26]; + int n = words.Length; + foreach (string word in words) { + foreach (char ch in word) { + freq[ch - 'a']++; + } + } + foreach (int count in freq) { + if (count % n != 0) { + return false; + } + } + return true; + } +} diff --git a/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.dart b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.dart new file mode 100644 index 00000000..a4ecf1c4 --- /dev/null +++ b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.dart @@ -0,0 +1,17 @@ +class Solution { + bool makeEqual(List words) { + List freq = List.filled(26, 0); + int n = words.length; + for (String word in words) { + for (int i = 0; i < word.length; i++) { + freq[word.codeUnitAt(i) - 'a'.codeUnitAt(0)]++; + } + } + for (int count in freq) { + if (count % n != 0) { + return false; + } + } + return true; + } +} diff --git a/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.go b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.go new file mode 100644 index 00000000..b78bca38 --- /dev/null +++ b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.go @@ -0,0 +1,15 @@ +func makeEqual(words []string) bool { + freq := [26]int{} + n := len(words) + for _, word := range words { + for _, ch := range word { + freq[ch-'a']++ + } + } + for _, count := range freq { + if count%n != 0 { + return false + } + } + return true +} diff --git a/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.java b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.java new file mode 100644 index 00000000..d2c0074e --- /dev/null +++ b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.java @@ -0,0 +1,17 @@ +class Solution { + public boolean makeEqual(String[] words) { + int[] freq = new int[26]; + int n = words.length; + for (String word : words) { + for (char ch : word.toCharArray()) { + freq[ch - 'a']++; + } + } + for (int count : freq) { + if (count % n != 0) { + return false; + } + } + return true; + } +} diff --git a/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.kt b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.kt new file mode 100644 index 00000000..60fae5f6 --- /dev/null +++ b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.kt @@ -0,0 +1,17 @@ +class Solution { + fun makeEqual(words: Array): Boolean { + val freq = IntArray(26) + val n = words.size + for (word in words) { + for (ch in word) { + freq[ch - 'a']++ + } + } + for (count in freq) { + if (count % n != 0) { + return false + } + } + return true + } +} diff --git a/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.py b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.py new file mode 100644 index 00000000..a81caa99 --- /dev/null +++ b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.py @@ -0,0 +1,11 @@ +class Solution: + def makeEqual(self, words): + freq = [0] * 26 + n = len(words) + for word in words: + for ch in word: + freq[ord(ch) - ord("a")] += 1 + for count in freq: + if count % n != 0: + return False + return True diff --git a/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.py2 b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.py2 new file mode 100644 index 00000000..55429fd6 --- /dev/null +++ b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def makeEqual(self, words): + """ + :type words: List[str] + :rtype: bool + """ + freq = [0] * 26 + n = len(words) + for word in words: + for ch in word: + freq[ord(ch) - ord('a')] += 1 + for count in freq: + if count % n != 0: + return False + return True diff --git a/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.rb b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.rb new file mode 100644 index 00000000..6b54bc78 --- /dev/null +++ b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.rb @@ -0,0 +1,15 @@ +# @param {String[]} words +# @return {Boolean} +def make_equal(words) + freq = Array.new(26, 0) + n = words.length + words.each do |word| + word.each_char do |ch| + freq[ch.ord - 'a'.ord] += 1 + end + end + freq.each do |count| + return false if count % n != 0 + end + true +end diff --git a/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.rs b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.rs new file mode 100644 index 00000000..a73308d3 --- /dev/null +++ b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn make_equal(words: Vec) -> bool { + let mut freq = vec![0; 26]; + let n = words.len(); + for word in words { + for ch in word.bytes() { + freq[(ch - b'a') as usize] += 1; + } + } + for count in freq { + if count % n != 0 { + return false; + } + } + true + } +} diff --git a/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.swift b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.swift new file mode 100644 index 00000000..edf7ec5f --- /dev/null +++ b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.swift @@ -0,0 +1,17 @@ +class Solution { + func makeEqual(_ words: [String]) -> Bool { + var freq = [Int](repeating: 0, count: 26) + let n = words.count + for word in words { + for ch in word.unicodeScalars { + freq[Int(ch.value - 97)] += 1 + } + } + for count in freq { + if count % n != 0 { + return false + } + } + return true + } +} diff --git a/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.ts b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.ts new file mode 100644 index 00000000..f1644368 --- /dev/null +++ b/tests/1501-2000/1897. redistribute-characters-to-make-all-strings-equal/sol.ts @@ -0,0 +1,15 @@ +function makeEqual(words: string[]): boolean { + const freq = new Array(26).fill(0); + const n = words.length; + for (const word of words) { + for (const ch of word) { + freq[ch.charCodeAt(0) - "a".charCodeAt(0)]++; + } + } + for (const count of freq) { + if (count % n !== 0) { + return false; + } + } + return true; +} diff --git a/tests/1501-2000/1898. maximum-number-of-removable-characters/manifest.yaml b/tests/1501-2000/1898. maximum-number-of-removable-characters/manifest.yaml new file mode 100644 index 00000000..c20eadeb --- /dev/null +++ b/tests/1501-2000/1898. maximum-number-of-removable-characters/manifest.yaml @@ -0,0 +1,439 @@ +entry: + id: 1898 + title: "maximum-number-of-removable-characters" + params: + s: + type: string + p: + type: string + removable: + type: array + items: + type: int + call: + cpp: "Solution().maximumRemovals({s}, {p}, {removable})" + rust: "Solution::maximum_removals({s}, {p}, {removable})" + python3: "Solution().maximumRemovals({s}, {p}, {removable})" + python2: "Solution().maximumRemovals({s}, {p}, {removable})" + ruby: "maximum_removals({s}, {p}, {removable})" + java: "new Solution().maximumRemovals({s}, {p}, {removable})" + csharp: "new Solution().MaximumRemovals({s}, {p}, {removable})" + kotlin: "Solution().maximumRemovals({s}, {p}, {removable})" + go: "maximumRemovals({s}, {p}, {removable})" + dart: "Solution().maximumRemovals({s}, {p}, {removable})" + swift: "Solution().maximumRemovals({s}, {p}, {removable})" + typescript: "maximumRemovals({s}, {p}, {removable})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maximumRemovals(s, p, removable, {result})" + checker: | + class Checker: + def maximumRemovals(self, s, p, removable, result): + def ok(k): + removed = set(removable[:k]) + j = 0 + for i, ch in enumerate(s): + if i not in removed and j < len(p) and ch == p[j]: + j += 1 + return j == len(p) + expected = 0 + lo, hi = 0, len(removable) + while lo <= hi: + mid = (lo + hi) // 2 + if ok(mid): + expected = mid + lo = mid + 1 + else: + hi = mid - 1 + return result == expected + +seed: 1898 + +tests: + - name: example-one + in: + s: "abcacb" + p: "ab" + removable: [3, 1, 0] + out: 2 + judge: + type: "exact" + - name: example-two + in: + s: "abcbddddd" + p: "abcd" + removable: [3, 2, 1, 4, 5, 6] + out: 1 + judge: + type: "exact" + - name: example-three + in: + s: "abcab" + p: "abc" + removable: [0, 1, 2, 3, 4] + out: 0 + judge: + type: "exact" + - name: no-removable + in: + s: "abc" + p: "abc" + removable: [] + out: 0 + judge: + type: "exact" + - name: remove-unneeded-middle + in: + s: "abc" + p: "ac" + removable: [1, 0] + out: 1 + judge: + type: "exact" + - name: two-unneeded-middle + in: + s: "abcd" + p: "ad" + removable: [1, 2, 0] + out: 2 + judge: + type: "exact" + - name: repeated-character-slack + in: + s: "aaaaa" + p: "aa" + removable: [0, 1, 2, 3] + out: 3 + judge: + type: "exact" + - name: alternating-slack + in: + s: "abcde" + p: "ace" + removable: [1, 3, 0, 2] + out: 2 + judge: + type: "exact" + - name: first-character-critical + in: + s: "zzabczz" + p: "abc" + removable: [0, 1, 2, 3, 4] + out: 2 + judge: + type: "exact" + - name: last-character-critical + in: + s: "abczz" + p: "abcz" + removable: [3, 4, 0, 1] + out: 1 + judge: + type: "exact" + - name: all-redundant-prefix + in: + s: "aab" + p: "ab" + removable: [0, 1] + out: 1 + judge: + type: "exact" + - name: duplicate-target + in: + s: "ababab" + p: "ab" + removable: [0, 1, 2, 3, 4] + out: 4 + judge: + type: "exact" + - name: reverse-removal + in: + s: "abcdef" + p: "ace" + removable: [5, 4, 3, 2, 1] + out: 1 + judge: + type: "exact" + - name: only-essential-indices + in: + s: "abc" + p: "a" + removable: [1, 2] + out: 2 + judge: + type: "exact" + - name: essential-at-end + in: + s: "abc" + p: "c" + removable: [0, 1, 2] + out: 2 + judge: + type: "exact" + - name: alternating-removals + in: + s: "abababab" + p: "abab" + removable: [1, 3, 5, 7, 0, 2, 4] + out: 2 + judge: + type: "exact" + - name: repeated-required + in: + s: "baaacaa" + p: "aaa" + removable: [0, 4, 5, 1, 2] + out: 4 + judge: + type: "exact" + - name: scattered-required + in: + s: "axbycz" + p: "abc" + removable: [1, 3, 5, 0, 2] + out: 3 + judge: + type: "exact" + - name: all-but-one + in: + s: "abca" + p: "a" + removable: [1, 2, 3] + out: 3 + judge: + type: "exact" + - name: early-failure + in: + s: "abcd" + p: "abcd" + removable: [0, 2, 1] + out: 0 + judge: + type: "exact" + - name: one-character-pattern + in: + s: "bbbbba" + p: "a" + removable: [0, 1, 2, 3, 4] + out: 5 + judge: + type: "exact" + - name: one-character-source + in: + s: "a" + p: "a" + removable: [] + out: 0 + judge: + type: "exact" + - name: two-character-source + in: + s: "aa" + p: "a" + removable: [0] + out: 1 + judge: + type: "exact" + - name: pattern-near-end + in: + s: "qwerty" + p: "ty" + removable: [0, 1, 2, 3] + out: 4 + judge: + type: "exact" + - name: removal-order-matters + in: + s: "aabba" + p: "aba" + removable: [1, 2, 0, 3] + out: 2 + judge: + type: "exact" + - name: multiple-copies + in: + s: "aaaaabbbbb" + p: "aab" + removable: [0, 1, 2, 5, 6, 7, 8] + out: 7 + judge: + type: "exact" + - name: mixed-lowercase + in: + s: "thequickbrownfox" + p: "quick" + removable: [0, 1, 2, 3, 4, 5, 6, 7] + out: 3 + judge: + type: "exact" + - name: long-redundant-tail + in: + s: "abcxxxxxxxxxx" + p: "abc" + removable: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + out: 10 + judge: + type: "exact" + - name: long-redundant-prefix + in: + s: "xxxxxxxxxxabc" + p: "abc" + removable: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + out: 10 + judge: + type: "exact" + - name: alternating-large-slack + in: + s: "abababababab" + p: "ababa" + removable: [1, 3, 5, 7, 9, 11, 0, 2, 4, 6, 8] + out: 3 + judge: + type: "exact" + - name: all-removable-except-pattern + in: + s: "abcxxxxxxxxxxxxxxxx" + p: "abc" + removable: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17] + out: 15 + judge: + type: "exact" + - name: duplicate-a-reserve + in: + s: "baaaaa" + p: "aaa" + removable: [1, 2, 3, 4, 0] + out: 2 + judge: + type: "exact" + - name: suffix-reserve + in: + s: "abcabcabc" + p: "abc" + removable: [0, 1, 2, 3, 4, 5, 6, 7] + out: 6 + judge: + type: "exact" + - name: large-static-one + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + p: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + removable: + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + ] + out: 50 + judge: + type: "exact" + - name: large-static-two + in: + s: "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc" + p: "abcabcabcabcabc" + removable: + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + ] + out: 45 + judge: + type: "exact" diff --git a/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.cpp b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.cpp new file mode 100644 index 00000000..a2028195 --- /dev/null +++ b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int maximumRemovals(string s, string p, vector& removable) { + int left = 0, right = removable.size(); + int max_k = 0; + while (left <= right) { + int mid = (left + right) / 2; + vector removed(s.size(), false); + for (int i = 0; i < mid; ++i) { + removed[removable[i]] = true; + } + int j = 0; + for (int i = 0; i < s.size() && j < p.size(); ++i) { + if (!removed[i] && s[i] == p[j]) { + ++j; + } + } + if (j == p.size()) { + max_k = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + return max_k; + } +}; diff --git a/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.cs b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.cs new file mode 100644 index 00000000..26e24834 --- /dev/null +++ b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.cs @@ -0,0 +1,26 @@ +public class Solution { + public int MaximumRemovals(string s, string p, int[] removable) { + int left = 0, right = removable.Length; + int max_k = 0; + while (left <= right) { + int mid = (left + right) / 2; + bool[] removed = new bool[s.Length]; + for (int i = 0; i < mid; ++i) { + removed[removable[i]] = true; + } + int j = 0; + for (int i = 0; i < s.Length && j < p.Length; ++i) { + if (!removed[i] && s[i] == p[j]) { + ++j; + } + } + if (j == p.Length) { + max_k = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + return max_k; + } +} diff --git a/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.dart b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.dart new file mode 100644 index 00000000..e96405a4 --- /dev/null +++ b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.dart @@ -0,0 +1,26 @@ +class Solution { + int maximumRemovals(String s, String p, List removable) { + int left = 0, right = removable.length; + int maxK = 0; + while (left <= right) { + int mid = (left + right) ~/ 2; + List removed = List.filled(s.length, false); + for (int i = 0; i < mid; i++) { + removed[removable[i]] = true; + } + int j = 0; + for (int i = 0; i < s.length && j < p.length; i++) { + if (!removed[i] && s[i] == p[j]) { + j++; + } + } + if (j == p.length) { + maxK = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + return maxK; + } +} diff --git a/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.go b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.go new file mode 100644 index 00000000..ed944367 --- /dev/null +++ b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.go @@ -0,0 +1,24 @@ +func maximumRemovals(s string, p string, removable []int) int { + left, right := 0, len(removable) + maxK := 0 + for left <= right { + mid := (left + right) / 2 + removed := make([]bool, len(s)) + for i := 0; i < mid; i++ { + removed[removable[i]] = true + } + j := 0 + for i := 0; i < len(s) && j < len(p); i++ { + if !removed[i] && s[i] == p[j] { + j++ + } + } + if j == len(p) { + maxK = mid + left = mid + 1 + } else { + right = mid - 1 + } + } + return maxK +} diff --git a/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.java b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.java new file mode 100644 index 00000000..c238769d --- /dev/null +++ b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.java @@ -0,0 +1,26 @@ +class Solution { + public int maximumRemovals(String s, String p, int[] removable) { + int left = 0, right = removable.length; + int max_k = 0; + while (left <= right) { + int mid = (left + right) / 2; + boolean[] removed = new boolean[s.length()]; + for (int i = 0; i < mid; ++i) { + removed[removable[i]] = true; + } + int j = 0; + for (int i = 0; i < s.length() && j < p.length(); ++i) { + if (!removed[i] && s.charAt(i) == p.charAt(j)) { + ++j; + } + } + if (j == p.length()) { + max_k = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + return max_k; + } +} diff --git a/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.kt b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.kt new file mode 100644 index 00000000..84eeefa4 --- /dev/null +++ b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.kt @@ -0,0 +1,28 @@ +class Solution { + fun maximumRemovals(s: String, p: String, removable: IntArray): Int { + var left = 0 + var right = removable.size + var maxK = 0 + while (left <= right) { + val mid = (left + right) / 2 + val removed = BooleanArray(s.length) + for (i in 0 until mid) { + removed[removable[i]] = true + } + var j = 0 + for (i in s.indices) { + if (j >= p.length) break + if (!removed[i] && s[i] == p[j]) { + j++ + } + } + if (j == p.length) { + maxK = mid + left = mid + 1 + } else { + right = mid - 1 + } + } + return maxK + } +} diff --git a/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.py b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.py new file mode 100644 index 00000000..d3e41962 --- /dev/null +++ b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.py @@ -0,0 +1,30 @@ +class Solution(object): + def maximumRemovals(self, s, p, removable): + """ + :type s: str + :type p: str + :type removable: List[int] + :rtype: int + """ + + def is_subsequence(s, p, removed): + i = j = 0 + while i < len(s) and j < len(p): + if i in removed or s[i] != p[j]: + i += 1 + else: + i += 1 + j += 1 + return j == len(p) + + left, right = 0, len(removable) + max_k = 0 + while left <= right: + mid = (left + right) // 2 + removed = set(removable[:mid]) + if is_subsequence(s, p, removed): + max_k = mid + left = mid + 1 + else: + right = mid - 1 + return max_k diff --git a/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.py2 b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.py2 new file mode 100644 index 00000000..d5b0d8f2 --- /dev/null +++ b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.py2 @@ -0,0 +1,29 @@ +class Solution(object): + def maximumRemovals(self, s, p, removable): + """ + :type s: str + :type p: str + :type removable: List[int] + :rtype: int + """ + def is_subsequence(s, p, removed): + i = j = 0 + while i < len(s) and j < len(p): + if i in removed or s[i] != p[j]: + i += 1 + else: + i += 1 + j += 1 + return j == len(p) + + left, right = 0, len(removable) + max_k = 0 + while left <= right: + mid = (left + right) // 2 + removed = set(removable[:mid]) + if is_subsequence(s, p, removed): + max_k = mid + left = mid + 1 + else: + right = mid - 1 + return max_k diff --git a/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.rb b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.rb new file mode 100644 index 00000000..7efe975a --- /dev/null +++ b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.rb @@ -0,0 +1,30 @@ +# @param {String} s +# @param {String} p +# @param {Integer[]} removable +# @return {Integer} +def maximum_removals(s, p, removable) + left = 0 + right = removable.length + max_k = 0 + while left <= right + mid = (left + right) / 2 + removed = Array.new(s.length, false) + (0...mid).each do |i| + removed[removable[i]] = true + end + j = 0 + (0...s.length).each do |i| + break if j >= p.length + if !removed[i] && s[i] == p[j] + j += 1 + end + end + if j == p.length + max_k = mid + left = mid + 1 + else + right = mid - 1 + end + end + max_k +end diff --git a/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.rs b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.rs new file mode 100644 index 00000000..fd30febb --- /dev/null +++ b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.rs @@ -0,0 +1,32 @@ +impl Solution { + pub fn maximum_removals(s: String, p: String, removable: Vec) -> i32 { + let s: Vec = s.chars().collect(); + let p: Vec = p.chars().collect(); + let mut left = 0; + let mut right = removable.len(); + let mut max_k = 0; + while left <= right { + let mid = (left + right) / 2; + let mut removed = vec![false; s.len()]; + for i in 0..mid { + removed[removable[i] as usize] = true; + } + let mut j = 0; + for i in 0..s.len() { + if j >= p.len() { + break; + } + if !removed[i] && s[i] == p[j] { + j += 1; + } + } + if j == p.len() { + max_k = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + max_k as i32 + } +} diff --git a/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.swift b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.swift new file mode 100644 index 00000000..f68c964e --- /dev/null +++ b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.swift @@ -0,0 +1,29 @@ +class Solution { + func maximumRemovals(_ s: String, _ p: String, _ removable: [Int]) -> Int { + let sArr = Array(s) + let pArr = Array(p) + var left = 0, right = removable.count + var maxK = 0 + while left <= right { + let mid = (left + right) / 2 + var removed = Array(repeating: false, count: sArr.count) + for i in 0..= pArr.count { break } + if !removed[i] && sArr[i] == pArr[j] { + j += 1 + } + } + if j == pArr.count { + maxK = mid + left = mid + 1 + } else { + right = mid - 1 + } + } + return maxK + } +} diff --git a/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.ts b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.ts new file mode 100644 index 00000000..74544a90 --- /dev/null +++ b/tests/1501-2000/1898. maximum-number-of-removable-characters/sol.ts @@ -0,0 +1,25 @@ +function maximumRemovals(s: string, p: string, removable: number[]): number { + let left = 0, + right = removable.length; + let maxK = 0; + while (left <= right) { + const mid = Math.floor((left + right) / 2); + const removed = new Array(s.length).fill(false); + for (let i = 0; i < mid; i++) { + removed[removable[i]] = true; + } + let j = 0; + for (let i = 0; i < s.length && j < p.length; i++) { + if (!removed[i] && s[i] === p[j]) { + j++; + } + } + if (j === p.length) { + maxK = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + return maxK; +} diff --git a/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/manifest.yaml b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/manifest.yaml new file mode 100644 index 00000000..0395f166 --- /dev/null +++ b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/manifest.yaml @@ -0,0 +1,346 @@ +entry: + id: 1899 + title: "merge-triplets-to-form-target-triplet" + params: + triplets: + type: array + items: + type: array + items: + type: int + target: + type: array + items: + type: int + call: + cpp: "Solution().mergeTriplets({triplets}, {target})" + rust: "Solution::merge_triplets({triplets}, {target})" + python3: "Solution().mergeTriplets({triplets}, {target})" + python2: "Solution().mergeTriplets({triplets}, {target})" + ruby: "merge_triplets({triplets}, {target})" + java: "new Solution().mergeTriplets({triplets}, {target})" + csharp: "new Solution().MergeTriplets({triplets}, {target})" + kotlin: "Solution().mergeTriplets({triplets}, {target})" + go: "mergeTriplets({triplets}, {target})" + dart: "Solution().mergeTriplets({triplets}, {target})" + swift: "Solution().mergeTriplets({triplets}, {target})" + typescript: "mergeTriplets({triplets}, {target})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().mergeTriplets(triplets, target, {result})" + checker: | + class Checker: + def mergeTriplets(self, triplets, target, result): + if not isinstance(result, bool): + return False + can = [False, False, False] + for triplet in triplets: + if all(triplet[i] <= target[i] for i in range(3)): + for i in range(3): + if triplet[i] == target[i]: + can[i] = True + expected = all(can) + return result is expected +seed: 1899 +tests: + - name: example-one + in: + triplets: + - [2, 5, 3] + - [1, 8, 4] + - [1, 7, 5] + target: [2, 7, 5] + out: true + - name: example-two + in: + triplets: + - [3, 4, 5] + - [4, 5, 6] + target: [3, 2, 5] + out: false + - name: example-three + in: + triplets: + - [2, 5, 3] + - [2, 3, 4] + - [1, 2, 5] + - [5, 2, 3] + target: [5, 5, 5] + out: true + - name: exact-single + in: + triplets: + - [4, 7, 9] + target: [4, 7, 9] + out: true + - name: single-mismatch + in: + triplets: + - [4, 7, 8] + target: [4, 7, 9] + out: false + - name: each-component-separate + in: + triplets: + - [5, 1, 1] + - [1, 6, 1] + - [1, 1, 7] + target: [5, 6, 7] + out: true + - name: one-triplet-too-large + in: + triplets: + - [5, 2, 3] + - [2, 8, 3] + - [2, 2, 9] + target: [5, 7, 9] + out: false + - name: all-components-one-valid + in: + triplets: + - [6, 6, 6] + - [5, 6, 5] + - [6, 5, 6] + target: [6, 6, 6] + out: true + - name: no-target-component + in: + triplets: + - [1, 2, 3] + - [2, 3, 4] + - [3, 4, 5] + target: [9, 9, 9] + out: false + - name: duplicate-valid + in: + triplets: + - [2, 4, 6] + - [2, 4, 6] + - [1, 3, 5] + target: [2, 4, 6] + out: true + - name: duplicate-invalid + in: + triplets: + - [2, 4, 5] + - [2, 4, 5] + - [1, 3, 4] + target: [2, 4, 6] + out: false + - name: target-ones + in: + triplets: + - [1, 1, 1] + - [1, 1, 2] + - [1, 2, 1] + - [2, 1, 1] + target: [1, 1, 1] + out: true + - name: target-thousands + in: + triplets: + - [1000, 1, 1] + - [1, 1000, 1] + - [1, 1, 1000] + target: [1000, 1000, 1000] + out: true + - name: thousand-overflow + in: + triplets: + - [1000, 1000, 999] + - [999, 1000, 1000] + - [1000, 999, 1000] + target: [999, 999, 999] + out: false + - name: two-valid-one-blocked + in: + triplets: + - [4, 5, 1] + - [4, 1, 6] + - [1, 5, 6] + target: [4, 5, 6] + out: true + - name: blocked-by-first + in: + triplets: + - [5, 1, 1] + - [4, 6, 6] + target: [4, 6, 6] + out: true + - name: blocked-first-unavailable + in: + triplets: + - [5, 1, 1] + - [4, 6, 6] + target: [4, 6, 5] + out: false + - name: order-independent + in: + triplets: + - [1, 1, 8] + - [7, 1, 1] + - [1, 6, 1] + target: [7, 6, 8] + out: true + - name: irrelevant-large + in: + triplets: + - [2, 2, 2] + - [9, 9, 9] + - [2, 5, 2] + target: [2, 5, 2] + out: true + - name: irrelevant-large-no-exact + in: + triplets: + - [2, 2, 2] + - [9, 9, 9] + - [2, 5, 1] + target: [2, 5, 2] + out: true + - name: four-components-repeated + in: + triplets: + - [3, 1, 1] + - [1, 4, 1] + - [1, 1, 5] + - [3, 4, 5] + target: [3, 4, 5] + out: true + - name: all-below + in: + triplets: + - [1, 2, 3] + - [2, 3, 4] + - [3, 4, 5] + target: [4, 5, 6] + out: false + - name: exact-after-filtering + in: + triplets: + - [5, 5, 1] + - [1, 5, 5] + - [5, 1, 5] + - [5, 5, 5] + target: [5, 5, 5] + out: true + - name: target-middle-values + in: + triplets: + - [10, 1, 1] + - [1, 20, 1] + - [1, 1, 30] + target: [10, 20, 30] + out: true + - name: middle-value-too-high + in: + triplets: + - [10, 1, 1] + - [1, 21, 1] + - [1, 1, 30] + target: [10, 20, 30] + out: false + - name: only-two-components-same + in: + triplets: + - [8, 8, 1] + - [8, 1, 8] + - [1, 8, 8] + target: [8, 8, 8] + out: true + - name: impossible-missing-coordinate + in: + triplets: + - [8, 7, 6] + - [7, 6, 8] + - [6, 8, 7] + target: [8, 8, 8] + out: true + - name: many-irrelevant + in: + triplets: + - [1, 1, 1] + - [2, 2, 2] + - [3, 3, 3] + - [4, 4, 4] + - [5, 5, 5] + - [6, 6, 6] + - [7, 7, 7] + target: [5, 5, 5] + out: true + - name: many-irrelevant-false + in: + triplets: + - [1, 1, 1] + - [2, 2, 2] + - [3, 3, 3] + - [4, 4, 4] + - [6, 6, 6] + - [7, 7, 7] + target: [5, 5, 5] + out: false + - name: component-from-two + in: + triplets: + - [9, 2, 2] + - [9, 9, 2] + - [2, 9, 9] + target: [9, 9, 9] + out: true + - name: component-from-three + in: + triplets: + - [9, 1, 1] + - [1, 9, 1] + - [1, 1, 9] + - [8, 8, 8] + target: [9, 9, 9] + out: true + - name: high-value-distractor + in: + triplets: + - [1000, 1000, 1000] + - [4, 5, 1] + - [1, 4, 5] + - [5, 1, 4] + target: [5, 5, 5] + out: true + - name: exact-target-late + in: + triplets: + - [1, 2, 3] + - [3, 2, 1] + - [2, 3, 1] + - [6, 6, 6] + - [3, 3, 3] + target: [3, 3, 3] + out: true + - name: exact-target-first + in: + triplets: + - [3, 3, 3] + - [1000, 1, 1] + - [1, 1000, 1] + target: [3, 3, 3] + out: true + - name: zero-not-allowed-boundary + in: + triplets: + - [1, 1, 2] + - [1, 2, 1] + - [2, 1, 1] + target: [2, 2, 2] + out: true + - name: close-but-not-enough + in: + triplets: + - [10, 10, 9] + - [10, 9, 10] + - [9, 10, 10] + target: [10, 10, 10] + out: true diff --git a/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.cpp b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.cpp new file mode 100644 index 00000000..d323c90c --- /dev/null +++ b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + bool mergeTriplets(vector>& triplets, vector& target) { + for (auto& t : triplets) { + if (t == target) { + return true; + } + } + vector curr = {0, 0, 0}; + for (auto& t : triplets) { + bool flag = false; + if (target[0] == t[0] && curr[0] != target[0]) { + flag = true; + } + if (target[1] == t[1] && curr[1] != target[1]) { + flag = true; + } + if (target[2] == t[2] && curr[2] != target[2]) { + flag = true; + } + if (flag) { + vector temp = curr; + curr = { + max(curr[0], t[0]), + max(curr[1], t[1]), + max(curr[2], t[2]) + }; + if (curr[0] > target[0] || curr[1] > target[1] || curr[2] > target[2]) { + curr = temp; + } + } + } + return curr == target; + } +}; diff --git a/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.cs b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.cs new file mode 100644 index 00000000..c69814ea --- /dev/null +++ b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.cs @@ -0,0 +1,32 @@ +public class Solution { + public bool MergeTriplets(int[][] triplets, int[] target) { + foreach (var t in triplets) { + if (t[0] == target[0] && t[1] == target[1] && t[2] == target[2]) { + return true; + } + } + int[] curr = new int[] {0, 0, 0}; + foreach (var t in triplets) { + bool flag = false; + if (target[0] == t[0] && curr[0] != target[0]) { + flag = true; + } + if (target[1] == t[1] && curr[1] != target[1]) { + flag = true; + } + if (target[2] == t[2] && curr[2] != target[2]) { + flag = true; + } + if (flag) { + int[] temp = (int[])curr.Clone(); + curr[0] = Math.Max(curr[0], t[0]); + curr[1] = Math.Max(curr[1], t[1]); + curr[2] = Math.Max(curr[2], t[2]); + if (curr[0] > target[0] || curr[1] > target[1] || curr[2] > target[2]) { + curr = temp; + } + } + } + return curr[0] == target[0] && curr[1] == target[1] && curr[2] == target[2]; + } +} diff --git a/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.dart b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.dart new file mode 100644 index 00000000..2efe9785 --- /dev/null +++ b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.dart @@ -0,0 +1,32 @@ +class Solution { + bool mergeTriplets(List> triplets, List target) { + for (var t in triplets) { + if (t[0] == target[0] && t[1] == target[1] && t[2] == target[2]) { + return true; + } + } + var curr = [0, 0, 0]; + for (var t in triplets) { + var flag = false; + if (target[0] == t[0] && curr[0] != target[0]) { + flag = true; + } + if (target[1] == t[1] && curr[1] != target[1]) { + flag = true; + } + if (target[2] == t[2] && curr[2] != target[2]) { + flag = true; + } + if (flag) { + var temp = List.from(curr); + curr[0] = [curr[0], t[0]].reduce((a, b) => a > b ? a : b); + curr[1] = [curr[1], t[1]].reduce((a, b) => a > b ? a : b); + curr[2] = [curr[2], t[2]].reduce((a, b) => a > b ? a : b); + if (curr[0] > target[0] || curr[1] > target[1] || curr[2] > target[2]) { + curr = temp; + } + } + } + return curr[0] == target[0] && curr[1] == target[1] && curr[2] == target[2]; + } +} diff --git a/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.go b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.go new file mode 100644 index 00000000..9137c5df --- /dev/null +++ b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.go @@ -0,0 +1,38 @@ +func mergeTriplets(triplets [][]int, target []int) bool { + for _, t := range triplets { + if t[0] == target[0] && t[1] == target[1] && t[2] == target[2] { + return true + } + } + curr := []int{0, 0, 0} + for _, t := range triplets { + flag := false + if target[0] == t[0] && curr[0] != target[0] { + flag = true + } + if target[1] == t[1] && curr[1] != target[1] { + flag = true + } + if target[2] == t[2] && curr[2] != target[2] { + flag = true + } + if flag { + temp := make([]int, 3) + copy(temp, curr) + curr[0] = max(curr[0], t[0]) + curr[1] = max(curr[1], t[1]) + curr[2] = max(curr[2], t[2]) + if curr[0] > target[0] || curr[1] > target[1] || curr[2] > target[2] { + curr = temp + } + } + } + return curr[0] == target[0] && curr[1] == target[1] && curr[2] == target[2] +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} diff --git a/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.java b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.java new file mode 100644 index 00000000..96c276e6 --- /dev/null +++ b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.java @@ -0,0 +1,26 @@ +class Solution { + public boolean mergeTriplets(int[][] triplets, int[] target) { + for (int[] t : triplets) { + if (t[0] == target[0] && t[1] == target[1] && t[2] == target[2]) { + return true; + } + } + int[] curr = new int[]{0, 0, 0}; + for (int[] t : triplets) { + boolean flag = false; + if (target[0] == t[0] && curr[0] != target[0]) flag = true; + if (target[1] == t[1] && curr[1] != target[1]) flag = true; + if (target[2] == t[2] && curr[2] != target[2]) flag = true; + if (flag) { + int[] temp = curr.clone(); + curr[0] = Math.max(curr[0], t[0]); + curr[1] = Math.max(curr[1], t[1]); + curr[2] = Math.max(curr[2], t[2]); + if (curr[0] > target[0] || curr[1] > target[1] || curr[2] > target[2]) { + curr = temp; + } + } + } + return curr[0] == target[0] && curr[1] == target[1] && curr[2] == target[2]; + } +} diff --git a/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.kt b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.kt new file mode 100644 index 00000000..a063737a --- /dev/null +++ b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.kt @@ -0,0 +1,22 @@ +class Solution { + fun mergeTriplets(triplets: Array, target: IntArray): Boolean { + if (triplets.any { it.contentEquals(target) }) return true + var curr = intArrayOf(0, 0, 0) + for (t in triplets) { + var flag = false + if (target[0] == t[0] && curr[0] != target[0]) flag = true + if (target[1] == t[1] && curr[1] != target[1]) flag = true + if (target[2] == t[2] && curr[2] != target[2]) flag = true + if (flag) { + val temp = curr.copyOf() + curr[0] = maxOf(curr[0], t[0]) + curr[1] = maxOf(curr[1], t[1]) + curr[2] = maxOf(curr[2], t[2]) + if (curr[0] > target[0] || curr[1] > target[1] || curr[2] > target[2]) { + curr = temp + } + } + } + return curr.contentEquals(target) + } +} diff --git a/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.py b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.py new file mode 100644 index 00000000..ee5196e5 --- /dev/null +++ b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.py @@ -0,0 +1,25 @@ +class Solution: + def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool: + if target in triplets: + return True + curr = [0, 0, 0] + for i in range(len(triplets)): + flag = False + if target[0] == triplets[i][0] and curr[0] != target[0]: + flag = True + if target[1] == triplets[i][1] and curr[1] != target[1]: + flag = True + if target[2] == triplets[i][2] and curr[2] != target[2]: + flag = True + if flag: + temp = curr + curr = [ + max(curr[0], triplets[i][0]), + max(curr[1], triplets[i][1]), + max(curr[2], triplets[i][2]), + ] + if curr[0] > target[0] or curr[1] > target[1] or curr[2] > target[2]: + curr = temp + if curr == target: + return True + return False diff --git a/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.py2 b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.py2 new file mode 100644 index 00000000..8dcbf0d1 --- /dev/null +++ b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.py2 @@ -0,0 +1,24 @@ +class Solution(object): + def mergeTriplets(self, triplets, target): + """ + :type triplets: List[List[int]] + :type target: List[int] + :rtype: bool + """ + if target in triplets: + return True + curr = [0, 0, 0] + for i in range(len(triplets)): + flag = False + if target[0] == triplets[i][0] and curr[0] != target[0]: + flag = True + if target[1] == triplets[i][1] and curr[1] != target[1]: + flag = True + if target[2] == triplets[i][2] and curr[2] != target[2]: + flag = True + if flag: + temp = curr[:] + curr = [max(curr[0], triplets[i][0]), max(curr[1], triplets[i][1]), max(curr[2], triplets[i][2])] + if curr[0] > target[0] or curr[1] > target[1] or curr[2] > target[2]: + curr = temp + return curr == target diff --git a/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.rb b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.rb new file mode 100644 index 00000000..b814e224 --- /dev/null +++ b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.rb @@ -0,0 +1,21 @@ +# @param {Integer[][]} triplets +# @param {Integer[]} target +# @return {Boolean} +def merge_triplets(triplets, target) + return true if triplets.include?(target) + curr = [0, 0, 0] + triplets.each do |t| + flag = false + flag = true if target[0] == t[0] && curr[0] != target[0] + flag = true if target[1] == t[1] && curr[1] != target[1] + flag = true if target[2] == t[2] && curr[2] != target[2] + if flag + temp = curr.dup + curr = [ [curr[0], t[0]].max, [curr[1], t[1]].max, [curr[2], t[2]].max ] + if curr[0] > target[0] || curr[1] > target[1] || curr[2] > target[2] + curr = temp + end + end + end + curr == target +end diff --git a/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.rs b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.rs new file mode 100644 index 00000000..fcd64dde --- /dev/null +++ b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.rs @@ -0,0 +1,32 @@ +impl Solution { + pub fn merge_triplets(triplets: Vec>, target: Vec) -> bool { + for t in &triplets { + if *t == target { + return true; + } + } + let mut curr = vec![0, 0, 0]; + for t in &triplets { + let mut flag = false; + if target[0] == t[0] && curr[0] != target[0] { + flag = true; + } + if target[1] == t[1] && curr[1] != target[1] { + flag = true; + } + if target[2] == t[2] && curr[2] != target[2] { + flag = true; + } + if flag { + let temp = curr.clone(); + curr[0] = curr[0].max(t[0]); + curr[1] = curr[1].max(t[1]); + curr[2] = curr[2].max(t[2]); + if curr[0] > target[0] || curr[1] > target[1] || curr[2] > target[2] { + curr = temp; + } + } + } + curr == target + } +} diff --git a/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.swift b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.swift new file mode 100644 index 00000000..c14898c3 --- /dev/null +++ b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.swift @@ -0,0 +1,30 @@ +class Solution { + func mergeTriplets(_ triplets: [[Int]], _ target: [Int]) -> Bool { + if triplets.contains(where: { $0 == target }) { + return true + } + var curr = [0, 0, 0] + for t in triplets { + var flag = false + if target[0] == t[0] && curr[0] != target[0] { + flag = true + } + if target[1] == t[1] && curr[1] != target[1] { + flag = true + } + if target[2] == t[2] && curr[2] != target[2] { + flag = true + } + if flag { + let temp = curr + curr[0] = max(curr[0], t[0]) + curr[1] = max(curr[1], t[1]) + curr[2] = max(curr[2], t[2]) + if curr[0] > target[0] || curr[1] > target[1] || curr[2] > target[2] { + curr = temp + } + } + } + return curr == target + } +} diff --git a/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.ts b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.ts new file mode 100644 index 00000000..2879f1b3 --- /dev/null +++ b/tests/1501-2000/1899. merge-triplets-to-form-target-triplet/sol.ts @@ -0,0 +1,34 @@ +function mergeTriplets(triplets: number[][], target: number[]): boolean { + for (const t of triplets) { + if (t[0] === target[0] && t[1] === target[1] && t[2] === target[2]) { + return true; + } + } + let curr = [0, 0, 0]; + for (const t of triplets) { + let flag = false; + if (target[0] === t[0] && curr[0] !== target[0]) { + flag = true; + } + if (target[1] === t[1] && curr[1] !== target[1]) { + flag = true; + } + if (target[2] === t[2] && curr[2] !== target[2]) { + flag = true; + } + if (flag) { + const temp = [...curr]; + curr = [ + Math.max(curr[0], t[0]), + Math.max(curr[1], t[1]), + Math.max(curr[2], t[2]), + ]; + if (curr[0] > target[0] || curr[1] > target[1] || curr[2] > target[2]) { + curr = temp; + } + } + } + return ( + curr[0] === target[0] && curr[1] === target[1] && curr[2] === target[2] + ); +} diff --git a/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/manifest.yaml b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/manifest.yaml new file mode 100644 index 00000000..e2cb63ec --- /dev/null +++ b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/manifest.yaml @@ -0,0 +1,318 @@ +entry: + id: 1900 + title: "the-earliest-and-latest-rounds-where-players-compete" + params: + n: + type: int + firstPlayer: + type: int + secondPlayer: + type: int + call: + cpp: "Solution().earliestAndLatest({n}, {firstPlayer}, {secondPlayer})" + rust: "Solution::earliest_and_latest({n}, {firstPlayer}, {secondPlayer})" + python3: "Solution().earliestAndLatest({n}, {firstPlayer}, {secondPlayer})" + python2: "Solution().earliestAndLatest({n}, {firstPlayer}, {secondPlayer})" + ruby: "earliest_and_latest({n}, {firstPlayer}, {secondPlayer})" + java: "new Solution().earliestAndLatest({n}, {firstPlayer}, {secondPlayer})" + csharp: "new Solution().EarliestAndLatest({n}, {firstPlayer}, {secondPlayer})" + kotlin: "Solution().earliestAndLatest({n}, {firstPlayer}, {secondPlayer})" + go: "earliestAndLatest({n}, {firstPlayer}, {secondPlayer})" + dart: "Solution().earliestAndLatest({n}, {firstPlayer}, {secondPlayer})" + swift: "Solution().earliestAndLatest({n}, {firstPlayer}, {secondPlayer})" + typescript: "earliestAndLatest({n}, {firstPlayer}, {secondPlayer})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().check(n, firstPlayer, secondPlayer, {result})" + checker: | + from functools import lru_cache + + class Checker: + def check(self, n, firstPlayer, secondPlayer, result): + if not isinstance(result, list) or len(result) != 2: + return False + @lru_cache(None) + def solve(size, a, b): + if a + b == size + 1: + return (1, 1) + if a > b: + a, b = b, a + if size <= 4: + return (2, 2) + m = (size + 1) // 2 + lo, hi = 10**9, -1 + if a - 1 > size - b: + a, b = size + 1 - b, size + 1 - a + if b * 2 <= size + 1: + left = a - 1 + gap = b - a - 1 + for i in range(left + 1): + for j in range(gap + 1): + x, y = solve(m, i + 1, i + j + 2) + lo = min(lo, x + 1) + hi = max(hi, y + 1) + else: + mirror = size + 1 - b + left = a - 1 + gap = mirror - a - 1 + right = b - mirror - 1 + for i in range(left + 1): + for j in range(gap + 1): + offset = i + j + 1 + (right + 1) // 2 + 1 + x, y = solve(m, i + 1, offset) + lo = min(lo, x + 1) + hi = max(hi, y + 1) + return lo, hi + return result == list(solve(n, firstPlayer, secondPlayer)) + +seed: 1900 + +tests: + - name: "n3-first-pair" + in: + n: 3 + firstPlayer: 1 + secondPlayer: 2 + out: [2, 2] + - name: "n3-outer-pair" + in: + n: 3 + firstPlayer: 1 + secondPlayer: 3 + out: [1, 1] + - name: "n3-last-pair" + in: + n: 3 + firstPlayer: 2 + secondPlayer: 3 + out: [2, 2] + - name: "n4-left-adjacent" + in: + n: 4 + firstPlayer: 1 + secondPlayer: 2 + out: [2, 2] + - name: "n4-inner-pair" + in: + n: 4 + firstPlayer: 1 + secondPlayer: 3 + out: [2, 2] + - name: "n4-opposite" + in: + n: 4 + firstPlayer: 1 + secondPlayer: 4 + out: [1, 1] + - name: "n4-middle-opponents" + in: + n: 4 + firstPlayer: 2 + secondPlayer: 3 + out: [1, 1] + - name: "n5-left-edge" + in: + n: 5 + firstPlayer: 1 + secondPlayer: 2 + out: [3, 3] + - name: "n5-left-middle" + in: + n: 5 + firstPlayer: 1 + secondPlayer: 3 + out: [2, 3] + - name: "n5-left-four" + in: + n: 5 + firstPlayer: 1 + secondPlayer: 4 + out: [2, 2] + - name: "n5-outer" + in: + n: 5 + firstPlayer: 1 + secondPlayer: 5 + out: [1, 1] + - name: "n5-two-three" + in: + n: 5 + firstPlayer: 2 + secondPlayer: 3 + out: [3, 3] + - name: "n5-two-four" + in: + n: 5 + firstPlayer: 2 + secondPlayer: 4 + out: [1, 1] + - name: "n5-two-five" + in: + n: 5 + firstPlayer: 2 + secondPlayer: 5 + out: [2, 2] + - name: "n5-middle-four" + in: + n: 5 + firstPlayer: 3 + secondPlayer: 4 + out: [3, 3] + - name: "n5-middle-last" + in: + n: 5 + firstPlayer: 3 + secondPlayer: 5 + out: [2, 3] + - name: "n6-left-two" + in: + n: 6 + firstPlayer: 1 + secondPlayer: 2 + out: [3, 3] + - name: "n6-left-three" + in: + n: 6 + firstPlayer: 1 + secondPlayer: 3 + out: [2, 3] + - name: "n6-left-four" + in: + n: 6 + firstPlayer: 1 + secondPlayer: 4 + out: [2, 3] + - name: "n6-outer" + in: + n: 6 + firstPlayer: 1 + secondPlayer: 6 + out: [1, 1] + - name: "n6-two-three" + in: + n: 6 + firstPlayer: 2 + secondPlayer: 3 + out: [3, 3] + - name: "n6-two-five" + in: + n: 6 + firstPlayer: 2 + secondPlayer: 5 + out: [1, 1] + - name: "n6-three-four" + in: + n: 6 + firstPlayer: 3 + secondPlayer: 4 + out: [1, 1] + - name: "n7-outer" + in: + n: 7 + firstPlayer: 1 + secondPlayer: 7 + out: [1, 1] + - name: "n7-two-three" + in: + n: 7 + firstPlayer: 2 + secondPlayer: 3 + out: [2, 3] + - name: "n7-two-six" + in: + n: 7 + firstPlayer: 2 + secondPlayer: 6 + out: [1, 1] + - name: "n7-three-five" + in: + n: 7 + firstPlayer: 3 + secondPlayer: 5 + out: [1, 1] + - name: "n7-three-six" + in: + n: 7 + firstPlayer: 3 + secondPlayer: 6 + out: [3, 3] + - name: "n7-middle-pair" + in: + n: 7 + firstPlayer: 4 + secondPlayer: 5 + out: [2, 3] + - name: "n8-outer" + in: + n: 8 + firstPlayer: 1 + secondPlayer: 8 + out: [1, 1] + - name: "n8-two-seven" + in: + n: 8 + firstPlayer: 2 + secondPlayer: 7 + out: [1, 1] + - name: "n8-three-six" + in: + n: 8 + firstPlayer: 3 + secondPlayer: 6 + out: [1, 1] + - name: "n8-middle" + in: + n: 8 + firstPlayer: 4 + secondPlayer: 5 + out: [1, 1] + - name: "example-one" + in: + n: 11 + firstPlayer: 2 + secondPlayer: 4 + out: [3, 4] + - name: "n11-middle-range" + in: + n: 11 + firstPlayer: 3 + secondPlayer: 9 + out: [1, 1] + - name: "n11-central" + in: + n: 11 + firstPlayer: 5 + secondPlayer: 7 + out: [1, 1] + - name: "n16-near-edges" + in: + n: 16 + firstPlayer: 2 + secondPlayer: 15 + out: [1, 1] + - name: "n16-inner-symmetric" + in: + n: 16 + firstPlayer: 4 + secondPlayer: 13 + out: [1, 1] + - name: "n20-symmetric" + in: + n: 20 + firstPlayer: 7 + secondPlayer: 14 + out: [1, 1] + - name: "n28-large" + in: + n: 28 + firstPlayer: 9 + secondPlayer: 20 + out: [1, 1] diff --git a/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.cpp b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.cpp new file mode 100644 index 00000000..e1b6bf11 --- /dev/null +++ b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.cpp @@ -0,0 +1,49 @@ +class Solution { +public: + vector earliestAndLatest(int n, int firstPlayer, int secondPlayer) { + return dfs(n, firstPlayer, secondPlayer); + } + +private: + vector dfs(int n, int p1, int p2) { + if (p1 + p2 == n + 1) return {1, 1}; + if (p1 > p2) swap(p1, p2); + if (n <= 4) return {2, 2}; + + int m = (n + 1) / 2; + int minR = INT_MAX, maxR = INT_MIN; + + if (p1 - 1 > n - p2) { + int t = n + 1 - p1; + p1 = n + 1 - p2; + p2 = t; + } + + if (p2 * 2 <= n + 1) { + int a = p1 - 1; + int b = p2 - p1 - 1; + for (int i = 0; i <= a; i++) { + for (int j = 0; j <= b; j++) { + auto r = dfs(m, i + 1, i + j + 2); + minR = min(minR, r[0] + 1); + maxR = max(maxR, r[1] + 1); + } + } + } else { + int p4 = n + 1 - p2; + int a = p1 - 1; + int b = p4 - p1 - 1; + int c = p2 - p4 - 1; + for (int i = 0; i <= a; i++) { + for (int j = 0; j <= b; j++) { + int offset = i + j + 1 + (c + 1) / 2 + 1; + auto r = dfs(m, i + 1, offset); + minR = min(minR, r[0] + 1); + maxR = max(maxR, r[1] + 1); + } + } + } + + return {minR, maxR}; + } +}; diff --git a/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.cs b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.cs new file mode 100644 index 00000000..48e49184 --- /dev/null +++ b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.cs @@ -0,0 +1,47 @@ +public class Solution { + public int[] EarliestAndLatest(int n, int firstPlayer, int secondPlayer) { + return Dfs(n, firstPlayer, secondPlayer); + } + + private int[] Dfs(int n, int p1, int p2) { + if (p1 + p2 == n + 1) return new int[] {1, 1}; + if (p1 > p2) { int t = p1; p1 = p2; p2 = t; } + if (n <= 4) return new int[] {2, 2}; + + int m = (n + 1) / 2; + int minR = int.MaxValue, maxR = int.MinValue; + + if (p1 - 1 > n - p2) { + int t = n + 1 - p1; + p1 = n + 1 - p2; + p2 = t; + } + + if (p2 * 2 <= n + 1) { + int a = p1 - 1; + int b = p2 - p1 - 1; + for (int i = 0; i <= a; i++) { + for (int j = 0; j <= b; j++) { + int[] r = Dfs(m, i + 1, i + j + 2); + minR = Math.Min(minR, r[0] + 1); + maxR = Math.Max(maxR, r[1] + 1); + } + } + } else { + int p4 = n + 1 - p2; + int a = p1 - 1; + int b = p4 - p1 - 1; + int c = p2 - p4 - 1; + for (int i = 0; i <= a; i++) { + for (int j = 0; j <= b; j++) { + int offset = i + j + 1 + (c + 1) / 2 + 1; + int[] r = Dfs(m, i + 1, offset); + minR = Math.Min(minR, r[0] + 1); + maxR = Math.Max(maxR, r[1] + 1); + } + } + } + + return new int[] {minR, maxR}; + } +} diff --git a/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.dart b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.dart new file mode 100644 index 00000000..a8aceb7a --- /dev/null +++ b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.dart @@ -0,0 +1,51 @@ +class Solution { + List earliestAndLatest(int n, int firstPlayer, int secondPlayer) { + return dfs(n, firstPlayer, secondPlayer); + } + + List dfs(int n, int p1, int p2) { + if (p1 + p2 == n + 1) return [1, 1]; + if (p1 > p2) { int t = p1; p1 = p2; p2 = t; } + if (n <= 4) return [2, 2]; + + int m = (n + 1) ~/ 2; + int minR = 1 << 30; + int maxR = -minR; + + if (p1 - 1 > n - p2) { + int t = n + 1 - p1; + p1 = n + 1 - p2; + p2 = t; + } + + if (p2 * 2 <= n + 1) { + int a = p1 - 1; + int b = p2 - p1 - 1; + for (int i = 0; i <= a; i++) { + for (int j = 0; j <= b; j++) { + List r = dfs(m, i + 1, i + j + 2); + minR = min(minR, r[0] + 1); + maxR = max(maxR, r[1] + 1); + } + } + } else { + int p4 = n + 1 - p2; + int a = p1 - 1; + int b = p4 - p1 - 1; + int c = p2 - p4 - 1; + for (int i = 0; i <= a; i++) { + for (int j = 0; j <= b; j++) { + int offset = i + j + 1 + (c + 1) ~/ 2 + 1; + List r = dfs(m, i + 1, offset); + minR = min(minR, r[0] + 1); + maxR = max(maxR, r[1] + 1); + } + } + } + + return [minR, maxR]; + } + + int min(int a, int b) => a < b ? a : b; + int max(int a, int b) => a > b ? a : b; +} diff --git a/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.go b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.go new file mode 100644 index 00000000..ddfff499 --- /dev/null +++ b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.go @@ -0,0 +1,60 @@ +func earliestAndLatest(n int, firstPlayer int, secondPlayer int) []int { + return dfs(n, firstPlayer, secondPlayer) +} + +func dfs(n, p1, p2 int) []int { + if p1 + p2 == n + 1 { + return []int{1, 1} + } + if p1 > p2 { + p1, p2 = p2, p1 + } + if n <= 4 { + return []int{2, 2} + } + + m := (n + 1) / 2 + minR := int(^uint(0) >> 1) // max int + maxR := -minR - 1 // min int + + if p1 - 1 > n - p2 { + t := n + 1 - p1 + p1 = n + 1 - p2 + p2 = t + } + + if p2 * 2 <= n + 1 { + a := p1 - 1 + b := p2 - p1 - 1 + for i := 0; i <= a; i++ { + for j := 0; j <= b; j++ { + r := dfs(m, i + 1, i + j + 2) + if r[0] + 1 < minR { + minR = r[0] + 1 + } + if r[1] + 1 > maxR { + maxR = r[1] + 1 + } + } + } + } else { + p4 := n + 1 - p2 + a := p1 - 1 + b := p4 - p1 - 1 + c := p2 - p4 - 1 + for i := 0; i <= a; i++ { + for j := 0; j <= b; j++ { + offset := i + j + 1 + (c + 1) / 2 + 1 + r := dfs(m, i + 1, offset) + if r[0] + 1 < minR { + minR = r[0] + 1 + } + if r[1] + 1 > maxR { + maxR = r[1] + 1 + } + } + } + } + + return []int{minR, maxR} +} diff --git a/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.java b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.java new file mode 100644 index 00000000..e11ef17e --- /dev/null +++ b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.java @@ -0,0 +1,47 @@ +class Solution { + public int[] earliestAndLatest(int n, int firstPlayer, int secondPlayer) { + return dfs(n, firstPlayer, secondPlayer); + } + + private int[] dfs(int n, int p1, int p2) { + if (p1 + p2 == n + 1) return new int[]{1, 1}; + if (p1 > p2) { int t = p1; p1 = p2; p2 = t; } + if (n <= 4) return new int[]{2, 2}; + + int m = (n + 1) / 2; + int minR = Integer.MAX_VALUE, maxR = Integer.MIN_VALUE; + + if (p1 - 1 > n - p2) { + int t = n + 1 - p1; + p1 = n + 1 - p2; + p2 = t; + } + + if (p2 * 2 <= n + 1) { + int a = p1 - 1; + int b = p2 - p1 - 1; + for (int i = 0; i <= a; i++) { + for (int j = 0; j <= b; j++) { + int[] r = dfs(m, i + 1, i + j + 2); + minR = Math.min(minR, r[0] + 1); + maxR = Math.max(maxR, r[1] + 1); + } + } + } else { + int p4 = n + 1 - p2; + int a = p1 - 1; + int b = p4 - p1 - 1; + int c = p2 - p4 - 1; + for (int i = 0; i <= a; i++) { + for (int j = 0; j <= b; j++) { + int offset = i + j + 1 + (c + 1) / 2 + 1; + int[] r = dfs(m, i + 1, offset); + minR = Math.min(minR, r[0] + 1); + maxR = Math.max(maxR, r[1] + 1); + } + } + } + + return new int[]{minR, maxR}; + } +} diff --git a/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.kt b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.kt new file mode 100644 index 00000000..a1a12947 --- /dev/null +++ b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.kt @@ -0,0 +1,50 @@ +class Solution { + fun earliestAndLatest(n: Int, firstPlayer: Int, secondPlayer: Int): IntArray { + return dfs(n, firstPlayer, secondPlayer) + } + + private fun dfs(n: Int, p1: Int, p2: Int): IntArray { + if (p1 + p2 == n + 1) return intArrayOf(1, 1) + var p1 = p1 + var p2 = p2 + if (p1 > p2) { val t = p1; p1 = p2; p2 = t } + if (n <= 4) return intArrayOf(2, 2) + + val m = (n + 1) / 2 + var minR = Int.MAX_VALUE + var maxR = Int.MIN_VALUE + + if (p1 - 1 > n - p2) { + val t = n + 1 - p1 + p1 = n + 1 - p2 + p2 = t + } + + if (p2 * 2 <= n + 1) { + val a = p1 - 1 + val b = p2 - p1 - 1 + for (i in 0..a) { + for (j in 0..b) { + val r = dfs(m, i + 1, i + j + 2) + minR = minOf(minR, r[0] + 1) + maxR = maxOf(maxR, r[1] + 1) + } + } + } else { + val p4 = n + 1 - p2 + val a = p1 - 1 + val b = p4 - p1 - 1 + val c = p2 - p4 - 1 + for (i in 0..a) { + for (j in 0..b) { + val offset = i + j + 1 + (c + 1) / 2 + 1 + val r = dfs(m, i + 1, offset) + minR = minOf(minR, r[0] + 1) + maxR = maxOf(maxR, r[1] + 1) + } + } + } + + return intArrayOf(minR, maxR) + } +} diff --git a/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.py b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.py new file mode 100644 index 00000000..7ecd96f2 --- /dev/null +++ b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.py @@ -0,0 +1,49 @@ +class Solution: + def earliestAndLatest( + self, n: int, firstPlayer: int, secondPlayer: int + ) -> list[int]: + def dfs(n, p1, p2): + # Step 1: Normalize + if p1 + p2 == n + 1: + return (1, 1) + if p1 > p2: + p1, p2 = p2, p1 + if n <= 4: + return (2, 2) + + m = (n + 1) // 2 + minR, maxR = float("inf"), float("-inf") + + # Step 2: Use symmetry + if p1 - 1 > n - p2: + t = n + 1 - p1 + p1 = n + 1 - p2 + p2 = t + + # Step 3: Simulate possibilities + if p2 * 2 <= n + 1: + a = p1 - 1 + b = p2 - p1 - 1 + + for i in range(a + 1): + for j in range(b + 1): + r1, r2 = dfs(m, i + 1, i + j + 2) + minR = min(minR, r1 + 1) + maxR = max(maxR, r2 + 1) + else: + p4 = n + 1 - p2 + a = p1 - 1 + b = p4 - p1 - 1 + c = p2 - p4 - 1 + + for i in range(a + 1): + for j in range(b + 1): + offset = i + j + 1 + (c + 1) // 2 + 1 + r1, r2 = dfs(m, i + 1, offset) + minR = min(minR, r1 + 1) + maxR = max(maxR, r2 + 1) + + # Step 4: Return earliest and latest round + return (minR, maxR) + + return list(dfs(n, firstPlayer, secondPlayer)) diff --git a/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.py2 b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.py2 new file mode 100644 index 00000000..b6197dda --- /dev/null +++ b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.py2 @@ -0,0 +1,47 @@ +class Solution(object): + def earliestAndLatest(self, n, firstPlayer, secondPlayer): + """ + :type n: int + :type firstPlayer: int + :type secondPlayer: int + :rtype: List[int] + """ + def dfs(n, p1, p2): + if p1 + p2 == n + 1: + return (1, 1) + if p1 > p2: + p1, p2 = p2, p1 + if n <= 4: + return (2, 2) + + m = (n + 1) // 2 + minR, maxR = float('inf'), float('-inf') + + if p1 - 1 > n - p2: + t = n + 1 - p1 + p1 = n + 1 - p2 + p2 = t + + if p2 * 2 <= n + 1: + a = p1 - 1 + b = p2 - p1 - 1 + for i in range(a + 1): + for j in range(b + 1): + r1, r2 = dfs(m, i + 1, i + j + 2) + minR = min(minR, r1 + 1) + maxR = max(maxR, r2 + 1) + else: + p4 = n + 1 - p2 + a = p1 - 1 + b = p4 - p1 - 1 + c = p2 - p4 - 1 + for i in range(a + 1): + for j in range(b + 1): + offset = i + j + 1 + (c + 1) // 2 + 1 + r1, r2 = dfs(m, i + 1, offset) + minR = min(minR, r1 + 1) + maxR = max(maxR, r2 + 1) + + return (minR, maxR) + + return list(dfs(n, firstPlayer, secondPlayer)) diff --git a/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.rb b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.rb new file mode 100644 index 00000000..9a3ee84b --- /dev/null +++ b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.rb @@ -0,0 +1,51 @@ +# @param {Integer} n +# @param {Integer} first_player +# @param {Integer} second_player +# @return {Integer[]} +def earliest_and_latest(n, first_player, second_player) + dfs = lambda do |n, p1, p2| + return [1, 1] if p1 + p2 == n + 1 + if p1 > p2 + p1, p2 = p2, p1 + end + return [2, 2] if n <= 4 + + m = (n + 1) / 2 + min_r, max_r = Float::INFINITY, -Float::INFINITY + + if p1 - 1 > n - p2 + t = n + 1 - p1 + p1 = n + 1 - p2 + p2 = t + end + + if p2 * 2 <= n + 1 + a = p1 - 1 + b = p2 - p1 - 1 + (0..a).each do |i| + (0..b).each do |j| + r1, r2 = dfs.call(m, i + 1, i + j + 2) + min_r = [min_r, r1 + 1].min + max_r = [max_r, r2 + 1].max + end + end + else + p4 = n + 1 - p2 + a = p1 - 1 + b = p4 - p1 - 1 + c = p2 - p4 - 1 + (0..a).each do |i| + (0..b).each do |j| + offset = i + j + 1 + (c + 1) / 2 + 1 + r1, r2 = dfs.call(m, i + 1, offset) + min_r = [min_r, r1 + 1].min + max_r = [max_r, r2 + 1].max + end + end + end + + [min_r, max_r] + end + + dfs.call(n, first_player, second_player) +end diff --git a/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.rs b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.rs new file mode 100644 index 00000000..b44667fd --- /dev/null +++ b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.rs @@ -0,0 +1,55 @@ +impl Solution { + pub fn earliest_and_latest(n: i32, first_player: i32, second_player: i32) -> Vec { + Self::dfs(n, first_player, second_player) + } + + fn dfs(n: i32, p1: i32, p2: i32) -> Vec { + if p1 + p2 == n + 1 { + return vec![1, 1]; + } + let (mut p1, mut p2) = (p1, p2); + if p1 > p2 { + std::mem::swap(&mut p1, &mut p2); + } + if n <= 4 { + return vec![2, 2]; + } + + let m = (n + 1) / 2; + let mut min_r = i32::MAX; + let mut max_r = i32::MIN; + + if p1 - 1 > n - p2 { + let t = n + 1 - p1; + p1 = n + 1 - p2; + p2 = t; + } + + if p2 * 2 <= n + 1 { + let a = p1 - 1; + let b = p2 - p1 - 1; + for i in 0..=a { + for j in 0..=b { + let r = Self::dfs(m, i + 1, i + j + 2); + min_r = min_r.min(r[0] + 1); + max_r = max_r.max(r[1] + 1); + } + } + } else { + let p4 = n + 1 - p2; + let a = p1 - 1; + let b = p4 - p1 - 1; + let c = p2 - p4 - 1; + for i in 0..=a { + for j in 0..=b { + let offset = i + j + 1 + (c + 1) / 2 + 1; + let r = Self::dfs(m, i + 1, offset); + min_r = min_r.min(r[0] + 1); + max_r = max_r.max(r[1] + 1); + } + } + } + + vec![min_r, max_r] + } +} diff --git a/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.swift b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.swift new file mode 100644 index 00000000..1195fc1f --- /dev/null +++ b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.swift @@ -0,0 +1,50 @@ +class Solution { + func earliestAndLatest(_ n: Int, _ firstPlayer: Int, _ secondPlayer: Int) -> [Int] { + return dfs(n, firstPlayer, secondPlayer) + } + + private func dfs(_ n: Int, _ p1: Int, _ p2: Int) -> [Int] { + if p1 + p2 == n + 1 { return [1, 1] } + var p1 = p1 + var p2 = p2 + if p1 > p2 { swap(&p1, &p2) } + if n <= 4 { return [2, 2] } + + let m = (n + 1) / 2 + var minR = Int.max + var maxR = Int.min + + if p1 - 1 > n - p2 { + let t = n + 1 - p1 + p1 = n + 1 - p2 + p2 = t + } + + if p2 * 2 <= n + 1 { + let a = p1 - 1 + let b = p2 - p1 - 1 + for i in 0...a { + for j in 0...b { + let r = dfs(m, i + 1, i + j + 2) + minR = min(minR, r[0] + 1) + maxR = max(maxR, r[1] + 1) + } + } + } else { + let p4 = n + 1 - p2 + let a = p1 - 1 + let b = p4 - p1 - 1 + let c = p2 - p4 - 1 + for i in 0...a { + for j in 0...b { + let offset = i + j + 1 + (c + 1) / 2 + 1 + let r = dfs(m, i + 1, offset) + minR = min(minR, r[0] + 1) + maxR = max(maxR, r[1] + 1) + } + } + } + + return [minR, maxR] + } +} diff --git a/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.ts b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.ts new file mode 100644 index 00000000..53cc2d17 --- /dev/null +++ b/tests/1501-2000/1900. the-earliest-and-latest-rounds-where-players-compete/sol.ts @@ -0,0 +1,52 @@ +function earliestAndLatest( + n: number, + firstPlayer: number, + secondPlayer: number, +): number[] { + return dfs(n, firstPlayer, secondPlayer); +} + +function dfs(n: number, p1: number, p2: number): number[] { + if (p1 + p2 === n + 1) return [1, 1]; + if (p1 > p2) { + [p1, p2] = [p2, p1]; + } + if (n <= 4) return [2, 2]; + + const m = Math.floor((n + 1) / 2); + let minR = Number.MAX_SAFE_INTEGER; + let maxR = Number.MIN_SAFE_INTEGER; + + if (p1 - 1 > n - p2) { + const t = n + 1 - p1; + p1 = n + 1 - p2; + p2 = t; + } + + if (p2 * 2 <= n + 1) { + const a = p1 - 1; + const b = p2 - p1 - 1; + for (let i = 0; i <= a; i++) { + for (let j = 0; j <= b; j++) { + const r = dfs(m, i + 1, i + j + 2); + minR = Math.min(minR, r[0] + 1); + maxR = Math.max(maxR, r[1] + 1); + } + } + } else { + const p4 = n + 1 - p2; + const a = p1 - 1; + const b = p4 - p1 - 1; + const c = p2 - p4 - 1; + for (let i = 0; i <= a; i++) { + for (let j = 0; j <= b; j++) { + const offset = i + j + 1 + Math.floor((c + 1) / 2) + 1; + const r = dfs(m, i + 1, offset); + minR = Math.min(minR, r[0] + 1); + maxR = Math.max(maxR, r[1] + 1); + } + } + } + + return [minR, maxR]; +} diff --git a/tests/1501-2000/1901. find-a-peak-element-ii/manifest.yaml b/tests/1501-2000/1901. find-a-peak-element-ii/manifest.yaml new file mode 100644 index 00000000..7ae17da6 --- /dev/null +++ b/tests/1501-2000/1901. find-a-peak-element-ii/manifest.yaml @@ -0,0 +1,375 @@ +entry: + id: 1901 + title: "find-a-peak-element-ii" + params: + mat: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().findPeakGrid({mat})" + rust: "Solution::find_peak_grid({mat})" + python3: "Solution().findPeakGrid({mat})" + python2: "Solution().findPeakGrid({mat})" + ruby: "find_peak_grid({mat})" + java: "new Solution().findPeakGrid({mat})" + csharp: "new Solution().FindPeakGrid({mat})" + kotlin: "Solution().findPeakGrid({mat})" + go: "findPeakGrid({mat})" + dart: "Solution().findPeakGrid({mat})" + swift: "Solution().findPeakGrid({mat})" + typescript: "findPeakGrid({mat})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().findPeakGrid(mat, {result})" + checker: | + class Checker: + def findPeakGrid(self, mat, result): + if not isinstance(result, list) or len(result) != 2: + return False + i, j = result + if not isinstance(i, int) or not isinstance(j, int): + return False + if not mat or not mat[0] or i < 0 or i >= len(mat) or j < 0 or j >= len(mat[0]): + return False + value = mat[i][j] + for di, dj in ((-1, 0), (1, 0), (0, -1), (0, 1)): + ni, nj = i + di, j + dj + if 0 <= ni < len(mat) and 0 <= nj < len(mat[0]) and value <= mat[ni][nj]: + return False + return True + +seed: 1901 + +tests: + - name: "example-one" + in: + mat: + elemType: "int" + value: + - [1, 4] + - [3, 2] + - name: "example-two" + in: + mat: + elemType: "int" + value: + - [10, 20, 15] + - [21, 30, 14] + - [7, 16, 32] + - name: "one-by-one" + in: + mat: + elemType: "int" + value: + - [1] + - name: "one-row" + in: + mat: + elemType: "int" + value: + - [1, 3, 2, 5, 4] + - name: "one-column" + in: + mat: + elemType: "int" + value: + - [1] + - [4] + - [2] + - [5] + - [3] + - name: "all-increasing-row" + in: + mat: + elemType: "int" + value: + - [1, 2, 3, 4, 5, 6] + - name: "all-decreasing-row" + in: + mat: + elemType: "int" + value: + - [6, 5, 4, 3, 2, 1] + - name: "all-increasing-column" + in: + mat: + elemType: "int" + value: + - [1] + - [2] + - [3] + - [4] + - [5] + - name: "all-decreasing-column" + in: + mat: + elemType: "int" + value: + - [5] + - [4] + - [3] + - [2] + - [1] + - name: "two-by-two-high-left" + in: + mat: + elemType: "int" + value: + - [9, 1] + - [2, 3] + - name: "two-by-two-high-right" + in: + mat: + elemType: "int" + value: + - [1, 9] + - [2, 3] + - name: "two-by-three" + in: + mat: + elemType: "int" + value: + - [1, 8, 2] + - [3, 4, 7] + - name: "three-by-two" + in: + mat: + elemType: "int" + value: + - [1, 3] + - [8, 2] + - [4, 7] + - name: "center-peak" + in: + mat: + elemType: "int" + value: + - [1, 2, 3] + - [4, 9, 5] + - [6, 7, 8] + - name: "corner-peak" + in: + mat: + elemType: "int" + value: + - [100, 1, 2] + - [3, 4, 5] + - [6, 7, 8] + - name: "negative-not-allowed-small" + in: + mat: + elemType: "int" + value: + - [1, 100, 2] + - [3, 4, 5] + - [6, 7, 8] + - name: "multiple-peaks" + in: + mat: + elemType: "int" + value: + - [9, 1, 8, 2] + - [3, 4, 5, 6] + - [7, 0, 11, 10] + - name: "ridge" + in: + mat: + elemType: "int" + value: + - [1, 2, 3, 4] + - [5, 6, 20, 8] + - [9, 10, 11, 12] + - [13, 14, 15, 16] + - name: "deep-valley" + in: + mat: + elemType: "int" + value: + - [20, 19, 18, 17] + - [16, 1, 2, 3] + - [15, 6, 7, 8] + - [14, 13, 12, 11] + - name: "checkerboard" + in: + mat: + elemType: "int" + value: + - [1, 9, 1, 9, 1] + - [9, 1, 9, 1, 9] + - [1, 9, 1, 9, 1] + - [9, 1, 9, 1, 9] + - [1, 9, 1, 9, 1] + - name: "large-values" + in: + mat: + elemType: "int" + value: + - [99999, 1, 99998] + - [2, 99997, 3] + - [99996, 4, 99995] + - name: "strict-ramp" + in: + mat: + elemType: "int" + value: + - [1, 2, 3, 4, 5] + - [6, 7, 8, 9, 10] + - [11, 12, 13, 14, 15] + - [16, 17, 18, 19, 20] + - [21, 22, 23, 24, 25] + - name: "alternating-ramp" + in: + mat: + elemType: "int" + value: + - [1, 20, 3, 18, 5] + - [19, 2, 17, 4, 16] + - [6, 15, 8, 13, 10] + - [14, 7, 12, 9, 11] + - name: "wide-six" + in: + mat: + elemType: "int" + value: + - [5, 1, 7, 2, 9, 3] + - [4, 8, 6, 10, 11, 12] + - name: "tall-six" + in: + mat: + elemType: "int" + value: + - [5, 1, 7] + - [4, 8, 6] + - [3, 2, 10] + - [9, 11, 12] + - [13, 14, 15] + - [16, 17, 18] + - name: "peak-at-last-column" + in: + mat: + elemType: "int" + value: + - [1, 2, 3, 50] + - [4, 5, 6, 7] + - [8, 9, 10, 11] + - name: "peak-at-first-column" + in: + mat: + elemType: "int" + value: + - [50, 1, 2, 3] + - [4, 5, 6, 7] + - [8, 9, 10, 11] + - name: "narrow-three" + in: + mat: + elemType: "int" + value: + - [2, 1, 3] + - [4, 8, 5] + - [6, 7, 9] + - [10, 11, 12] + - [13, 14, 15] + - [16, 17, 18] + - name: "four-by-seven" + in: + mat: + elemType: "int" + value: + - [1, 4, 2, 8, 3, 6, 5] + - [7, 9, 10, 11, 12, 13, 14] + - [15, 16, 17, 18, 19, 20, 21] + - [22, 23, 24, 25, 26, 27, 100] + - name: "seven-by-four" + in: + mat: + elemType: "int" + value: + - [1, 4, 2, 8] + - [7, 9, 10, 11] + - [12, 13, 14, 15] + - [16, 17, 50, 19] + - [20, 21, 22, 23] + - [24, 25, 26, 27] + - [28, 29, 30, 31] + - name: "sparse-highs" + in: + mat: + elemType: "int" + value: + - [1, 50, 2, 40, 3] + - [4, 5, 6, 7, 8] + - [30, 9, 10, 11, 20] + - [12, 13, 14, 60, 15] + - name: "center-low-surrounded" + in: + mat: + elemType: "int" + value: + - [20, 19, 18] + - [17, 1, 16] + - [15, 14, 13] + - name: "boundary-saddle" + in: + mat: + elemType: "int" + value: + - [2, 3, 4, 100] + - [1, 5, 6, 7] + - [8, 9, 10, 11] + - [12, 13, 14, 15] + - name: "high-middle-column" + in: + mat: + elemType: "int" + value: + - [1, 80, 2, 3, 4] + - [5, 6, 7, 8, 9] + - [10, 11, 12, 13, 14] + - name: "large-rectangular" + in: + mat: + elemType: "int" + value: + - [1, 2, 3, 4, 5, 6, 7, 8] + - [9, 10, 11, 12, 13, 14, 15, 16] + - [17, 18, 19, 20, 21, 22, 23, 24] + - [25, 26, 27, 28, 29, 30, 31, 100] + - name: "descending-rectangular" + in: + mat: + elemType: "int" + value: + - [32, 31, 30, 29, 28, 27, 26, 25] + - [24, 23, 22, 21, 20, 19, 18, 17] + - [16, 15, 14, 13, 12, 11, 10, 9] + - [8, 7, 6, 5, 4, 3, 2, 1] + - name: "max-corner" + in: + mat: + elemType: "int" + value: + - [100000, 1, 2, 3] + - [4, 5, 6, 7] + - [8, 9, 10, 11] + - name: "max-center" + in: + mat: + elemType: "int" + value: + - [1, 2, 3, 4, 5] + - [6, 7, 8, 9, 10] + - [11, 12, 100000, 14, 15] + - [16, 17, 18, 19, 20] + - [21, 22, 23, 24, 25] diff --git a/tests/1501-2000/1901. find-a-peak-element-ii/sol.cpp b/tests/1501-2000/1901. find-a-peak-element-ii/sol.cpp new file mode 100644 index 00000000..af618dac --- /dev/null +++ b/tests/1501-2000/1901. find-a-peak-element-ii/sol.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + vector findPeakGrid(vector>& mat) { + int n = mat.size(); + int m = mat[0].size(); + + int low = 0, high = m - 1; + + while (low <= high) { + int mid = low + (high - low) / 2; + + int maxRow = 0; + for (int i = 1; i < n; i++) { + if (mat[i][mid] > mat[maxRow][mid]) { + maxRow = i; + } + } + + int left = mid > 0 ? mat[maxRow][mid - 1] : -1; + int right = mid < m - 1 ? mat[maxRow][mid + 1] : -1; + + if (mat[maxRow][mid] > left && mat[maxRow][mid] > right) { + return {maxRow, mid}; + } + + if (mat[maxRow][mid] < left) { + high = mid - 1; + } else { + low = mid + 1; + } + } + + return {-1, -1}; + } +}; diff --git a/tests/1501-2000/1901. find-a-peak-element-ii/sol.cs b/tests/1501-2000/1901. find-a-peak-element-ii/sol.cs new file mode 100644 index 00000000..b0480fb4 --- /dev/null +++ b/tests/1501-2000/1901. find-a-peak-element-ii/sol.cs @@ -0,0 +1,34 @@ +public class Solution { + public int[] FindPeakGrid(int[][] mat) { + int n = mat.Length; + int m = mat[0].Length; + + int low = 0, high = m - 1; + + while (low <= high) { + int mid = low + (high - low) / 2; + + int maxRow = 0; + for (int i = 1; i < n; i++) { + if (mat[i][mid] > mat[maxRow][mid]) { + maxRow = i; + } + } + + int left = mid > 0 ? mat[maxRow][mid - 1] : -1; + int right = mid < m - 1 ? mat[maxRow][mid + 1] : -1; + + if (mat[maxRow][mid] > left && mat[maxRow][mid] > right) { + return new int[] { maxRow, mid }; + } + + if (mat[maxRow][mid] < left) { + high = mid - 1; + } else { + low = mid + 1; + } + } + + return new int[] { -1, -1 }; + } +} diff --git a/tests/1501-2000/1901. find-a-peak-element-ii/sol.dart b/tests/1501-2000/1901. find-a-peak-element-ii/sol.dart new file mode 100644 index 00000000..309ee162 --- /dev/null +++ b/tests/1501-2000/1901. find-a-peak-element-ii/sol.dart @@ -0,0 +1,34 @@ +class Solution { + List findPeakGrid(List> mat) { + int n = mat.length; + int m = mat[0].length; + + int low = 0, high = m - 1; + + while (low <= high) { + int mid = low + (high - low) ~/ 2; + + int maxRow = 0; + for (int i = 1; i < n; i++) { + if (mat[i][mid] > mat[maxRow][mid]) { + maxRow = i; + } + } + + int left = mid > 0 ? mat[maxRow][mid - 1] : -1; + int right = mid < m - 1 ? mat[maxRow][mid + 1] : -1; + + if (mat[maxRow][mid] > left && mat[maxRow][mid] > right) { + return [maxRow, mid]; + } + + if (mat[maxRow][mid] < left) { + high = mid - 1; + } else { + low = mid + 1; + } + } + + return [-1, -1]; + } +} diff --git a/tests/1501-2000/1901. find-a-peak-element-ii/sol.go b/tests/1501-2000/1901. find-a-peak-element-ii/sol.go new file mode 100644 index 00000000..3c093ce2 --- /dev/null +++ b/tests/1501-2000/1901. find-a-peak-element-ii/sol.go @@ -0,0 +1,38 @@ +func findPeakGrid(mat [][]int) []int { + n := len(mat) + m := len(mat[0]) + + low, high := 0, m-1 + + for low <= high { + mid := low + (high-low)/2 + + maxRow := 0 + for i := 1; i < n; i++ { + if mat[i][mid] > mat[maxRow][mid] { + maxRow = i + } + } + + left := -1 + if mid > 0 { + left = mat[maxRow][mid-1] + } + right := -1 + if mid < m-1 { + right = mat[maxRow][mid+1] + } + + if mat[maxRow][mid] > left && mat[maxRow][mid] > right { + return []int{maxRow, mid} + } + + if mat[maxRow][mid] < left { + high = mid - 1 + } else { + low = mid + 1 + } + } + + return []int{-1, -1} +} diff --git a/tests/1501-2000/1901. find-a-peak-element-ii/sol.java b/tests/1501-2000/1901. find-a-peak-element-ii/sol.java new file mode 100644 index 00000000..7fc93092 --- /dev/null +++ b/tests/1501-2000/1901. find-a-peak-element-ii/sol.java @@ -0,0 +1,34 @@ +class Solution { + public int[] findPeakGrid(int[][] mat) { + int n = mat.length; + int m = mat[0].length; + + int low = 0, high = m - 1; + + while (low <= high) { + int mid = low + (high - low) / 2; + + int maxRow = 0; + for (int i = 1; i < n; i++) { + if (mat[i][mid] > mat[maxRow][mid]) { + maxRow = i; + } + } + + int left = mid > 0 ? mat[maxRow][mid - 1] : -1; + int right = mid < m - 1 ? mat[maxRow][mid + 1] : -1; + + if (mat[maxRow][mid] > left && mat[maxRow][mid] > right) { + return new int[]{maxRow, mid}; + } + + if (mat[maxRow][mid] < left) { + high = mid - 1; + } else { + low = mid + 1; + } + } + + return new int[]{-1, -1}; + } +} diff --git a/tests/1501-2000/1901. find-a-peak-element-ii/sol.kt b/tests/1501-2000/1901. find-a-peak-element-ii/sol.kt new file mode 100644 index 00000000..2e530975 --- /dev/null +++ b/tests/1501-2000/1901. find-a-peak-element-ii/sol.kt @@ -0,0 +1,35 @@ +class Solution { + fun findPeakGrid(mat: Array): IntArray { + val n = mat.size + val m = mat[0].size + + var low = 0 + var high = m - 1 + + while (low <= high) { + val mid = low + (high - low) / 2 + + var maxRow = 0 + for (i in 1 until n) { + if (mat[i][mid] > mat[maxRow][mid]) { + maxRow = i + } + } + + val left = if (mid > 0) mat[maxRow][mid - 1] else -1 + val right = if (mid < m - 1) mat[maxRow][mid + 1] else -1 + + if (mat[maxRow][mid] > left && mat[maxRow][mid] > right) { + return intArrayOf(maxRow, mid) + } + + if (mat[maxRow][mid] < left) { + high = mid - 1 + } else { + low = mid + 1 + } + } + + return intArrayOf(-1, -1) + } +} diff --git a/tests/1501-2000/1901. find-a-peak-element-ii/sol.py b/tests/1501-2000/1901. find-a-peak-element-ii/sol.py new file mode 100644 index 00000000..58029734 --- /dev/null +++ b/tests/1501-2000/1901. find-a-peak-element-ii/sol.py @@ -0,0 +1,33 @@ +class Solution: + def findMaxIndex(self, mat, col): + row = 0 + + for i in range(1, len(mat)): + if mat[i][col] > mat[row][col]: + row = i + + return row + + def findPeakGrid(self, mat): + n = len(mat) + m = len(mat[0]) + + low, high = 0, m - 1 + + while low <= high: + mid = low + (high - low) // 2 + + max_row = self.findMaxIndex(mat, mid) + + left = mat[max_row][mid - 1] if mid > 0 else -1 + right = mat[max_row][mid + 1] if mid < m - 1 else -1 + + if mat[max_row][mid] > left and mat[max_row][mid] > right: + return [max_row, mid] + + if mat[max_row][mid] < left: + high = mid - 1 + else: + low = mid + 1 + + return [-1, -1] diff --git a/tests/1501-2000/1901. find-a-peak-element-ii/sol.py2 b/tests/1501-2000/1901. find-a-peak-element-ii/sol.py2 new file mode 100644 index 00000000..b7a89182 --- /dev/null +++ b/tests/1501-2000/1901. find-a-peak-element-ii/sol.py2 @@ -0,0 +1,33 @@ +class Solution(object): + def findPeakGrid(self, mat): + """ + :type mat: List[List[int]] + :rtype: List[int] + """ + def find_max_index(col): + row = 0 + for i in range(1, len(mat)): + if mat[i][col] > mat[row][col]: + row = i + return row + + n = len(mat) + m = len(mat[0]) + low, high = 0, m - 1 + + while low <= high: + mid = low + (high - low) // 2 + max_row = find_max_index(mid) + + left = mat[max_row][mid - 1] if mid > 0 else -1 + right = mat[max_row][mid + 1] if mid < m - 1 else -1 + + if mat[max_row][mid] > left and mat[max_row][mid] > right: + return [max_row, mid] + + if mat[max_row][mid] < left: + high = mid - 1 + else: + low = mid + 1 + + return [-1, -1] diff --git a/tests/1501-2000/1901. find-a-peak-element-ii/sol.rb b/tests/1501-2000/1901. find-a-peak-element-ii/sol.rb new file mode 100644 index 00000000..6ddf249b --- /dev/null +++ b/tests/1501-2000/1901. find-a-peak-element-ii/sol.rb @@ -0,0 +1,37 @@ +# @param {Integer[][]} mat +# @return {Integer[]} +def find_peak_grid(mat) + n = mat.length + m = mat[0].length + + find_max = lambda do |col| + row = 0 + (1...n).each do |i| + row = i if mat[i][col] > mat[row][col] + end + row + end + + low = 0 + high = m - 1 + + while low <= high + mid = low + (high - low) / 2 + max_row = find_max.call(mid) + + left = mid > 0 ? mat[max_row][mid - 1] : -1 + right = mid < m - 1 ? mat[max_row][mid + 1] : -1 + + if mat[max_row][mid] > left && mat[max_row][mid] > right + return [max_row, mid] + end + + if mat[max_row][mid] < left + high = mid - 1 + else + low = mid + 1 + end + end + + [-1, -1] +end diff --git a/tests/1501-2000/1901. find-a-peak-element-ii/sol.rs b/tests/1501-2000/1901. find-a-peak-element-ii/sol.rs new file mode 100644 index 00000000..8135b344 --- /dev/null +++ b/tests/1501-2000/1901. find-a-peak-element-ii/sol.rs @@ -0,0 +1,35 @@ +impl Solution { + pub fn find_peak_grid(mat: Vec>) -> Vec { + let n = mat.len(); + let m = mat[0].len(); + + let mut low = 0; + let mut high = m as i32 - 1; + + while low <= high { + let mid = low + (high - low) / 2; + + let mut max_row = 0; + for i in 1..n { + if mat[i][mid as usize] > mat[max_row][mid as usize] { + max_row = i; + } + } + + let left = if mid > 0 { mat[max_row][(mid - 1) as usize] } else { -1 }; + let right = if (mid as usize) < m - 1 { mat[max_row][(mid + 1) as usize] } else { -1 }; + + if mat[max_row][mid as usize] > left && mat[max_row][mid as usize] > right { + return vec![max_row as i32, mid]; + } + + if mat[max_row][mid as usize] < left { + high = mid - 1; + } else { + low = mid + 1; + } + } + + vec![-1, -1] + } +} diff --git a/tests/1501-2000/1901. find-a-peak-element-ii/sol.swift b/tests/1501-2000/1901. find-a-peak-element-ii/sol.swift new file mode 100644 index 00000000..cba6487a --- /dev/null +++ b/tests/1501-2000/1901. find-a-peak-element-ii/sol.swift @@ -0,0 +1,35 @@ +class Solution { + func findPeakGrid(_ mat: [[Int]]) -> [Int] { + let n = mat.count + let m = mat[0].count + + var low = 0 + var high = m - 1 + + while low <= high { + let mid = low + (high - low) / 2 + + var maxRow = 0 + for i in 1.. mat[maxRow][mid] { + maxRow = i + } + } + + let left = mid > 0 ? mat[maxRow][mid - 1] : -1 + let right = mid < m - 1 ? mat[maxRow][mid + 1] : -1 + + if mat[maxRow][mid] > left && mat[maxRow][mid] > right { + return [maxRow, mid] + } + + if mat[maxRow][mid] < left { + high = mid - 1 + } else { + low = mid + 1 + } + } + + return [-1, -1] + } +} diff --git a/tests/1501-2000/1901. find-a-peak-element-ii/sol.ts b/tests/1501-2000/1901. find-a-peak-element-ii/sol.ts new file mode 100644 index 00000000..f0fa874d --- /dev/null +++ b/tests/1501-2000/1901. find-a-peak-element-ii/sol.ts @@ -0,0 +1,33 @@ +function findPeakGrid(mat: number[][]): number[] { + const n = mat.length; + const m = mat[0].length; + + let low = 0, + high = m - 1; + + while (low <= high) { + const mid = low + Math.floor((high - low) / 2); + + let maxRow = 0; + for (let i = 1; i < n; i++) { + if (mat[i][mid] > mat[maxRow][mid]) { + maxRow = i; + } + } + + const left = mid > 0 ? mat[maxRow][mid - 1] : -1; + const right = mid < m - 1 ? mat[maxRow][mid + 1] : -1; + + if (mat[maxRow][mid] > left && mat[maxRow][mid] > right) { + return [maxRow, mid]; + } + + if (mat[maxRow][mid] < left) { + high = mid - 1; + } else { + low = mid + 1; + } + } + + return [-1, -1]; +} diff --git a/tests/1501-2000/1903. largest-odd-number-in-string/manifest.yaml b/tests/1501-2000/1903. largest-odd-number-in-string/manifest.yaml new file mode 100644 index 00000000..0b8ebc25 --- /dev/null +++ b/tests/1501-2000/1903. largest-odd-number-in-string/manifest.yaml @@ -0,0 +1,283 @@ +entry: + id: 1903 + title: largest-odd-number-in-string + params: + num: + type: string + call: + cpp: "Solution().largestOddNumber({num})" + rust: "Solution::largest_odd_number({num})" + python3: "Solution().largestOddNumber({num})" + python2: "Solution().largestOddNumber({num})" + ruby: "largest_odd_number({num})" + java: "new Solution().largestOddNumber({num})" + csharp: "new Solution().LargestOddNumber({num})" + kotlin: "Solution().largestOddNumber({num})" + go: "largestOddNumber({num})" + dart: "Solution().largestOddNumber({num})" + swift: "Solution().largestOddNumber({num})" + typescript: "largestOddNumber({num})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().largestOddNumber(num, {result})" + checker: | + class Checker: + def largestOddNumber(self, num, result): + expected = "" + for i in range(len(num) - 1, -1, -1): + if (ord(num[i]) - ord("0")) % 2 == 1: + expected = num[:i + 1] + break + return result == expected + +seed: 1903 + +tests: + - name: example-52 + in: + num: "52" + out: '"5"' + judge: + type: "exact" + - name: example-no-odd + in: + num: "4206" + out: '""' + judge: + type: "exact" + - name: example-full + in: + num: "35427" + out: '"35427"' + judge: + type: "exact" + - name: single-odd + in: + num: "7" + out: '"7"' + judge: + type: "exact" + - name: single-even + in: + num: "8" + out: '""' + judge: + type: "exact" + - name: odd-at-start + in: + num: "1234" + out: '"123"' + judge: + type: "exact" + - name: odd-at-end + in: + num: "24681" + out: '"24681"' + judge: + type: "exact" + - name: trim-one-even + in: + num: "1358" + out: '"135"' + judge: + type: "exact" + - name: trim-many-even + in: + num: "987654320" + out: '"9876543"' + judge: + type: "exact" + - name: all-even + in: + num: "246824682468" + out: '""' + judge: + type: "exact" + - name: all-odd + in: + num: "1357913579" + out: '"1357913579"' + judge: + type: "exact" + - name: zeros-after-odd + in: + num: "50000" + out: '"5"' + judge: + type: "exact" + - name: odd-after-zero + in: + num: "10007" + out: '"10007"' + judge: + type: "exact" + - name: leading-one + in: + num: "1000" + out: '"1"' + judge: + type: "exact" + - name: leading-nine + in: + num: "900000" + out: '"9"' + judge: + type: "exact" + - name: alternating + in: + num: "21212120" + out: '"212121"' + judge: + type: "exact" + - name: alternating-odd-end + in: + num: "1212121" + out: '"1212121"' + judge: + type: "exact" + - name: internal-last-odd + in: + num: "864213000" + out: '"864213"' + judge: + type: "exact" + - name: repeated-seven + in: + num: "777777" + out: '"777777"' + judge: + type: "exact" + - name: repeated-two + in: + num: "222222" + out: '""' + judge: + type: "exact" + - name: max-digit-prefix + in: + num: "999999998" + out: '"99999999"' + judge: + type: "exact" + - name: max-digit-full + in: + num: "999999999" + out: '"999999999"' + judge: + type: "exact" + - name: mixed-zero-block + in: + num: "1200000004" + out: '"1"' + judge: + type: "exact" + - name: mixed-zero-block-odd + in: + num: "1200000005" + out: '"1200000005"' + judge: + type: "exact" + - name: odd-near-end + in: + num: "2468024683" + out: '"2468024683"' + judge: + type: "exact" + - name: even-suffix + in: + num: "31415926535897932" + out: '"3141592653589793"' + judge: + type: "exact" + - name: odd-suffix + in: + num: "2718281828459045235" + out: '"2718281828459045235"' + judge: + type: "exact" + - name: large-odd-prefix + in: + num: "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001" + out: '"10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"' + judge: + type: "exact" + - name: large-even-suffix + in: + num: "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999998" + out: '"999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999"' + judge: + type: "exact" + - name: zero-free-even-tail + in: + num: "86420000000000000002" + out: '""' + judge: + type: "exact" + - name: odd-after-long-zero-tail + in: + num: "86420000000000000003" + out: '"86420000000000000003"' + judge: + type: "exact" + - name: interior-odd + in: + num: "40000000000000000007" + out: '"40000000000000000007"' + judge: + type: "exact" + - name: trailing-even-zeros + in: + num: "111111111111111111110000" + out: '"11111111111111111111"' + judge: + type: "exact" + - name: first-digit-only + in: + num: "800000000000000000001" + out: '"800000000000000000001"' + judge: + type: "exact" + - name: large-alternating + in: + num: "909090909090909090908" + out: '"9090909090909090909"' + judge: + type: "exact" + - name: odd-seven-tail + in: + num: "700000000000000000007" + out: '"700000000000000000007"' + judge: + type: "exact" + - name: final-even-after-nine + in: + num: "1234567890" + out: '"123456789"' + judge: + type: "exact" + - name: final-even-after-five + in: + num: "5555555550" + out: '"555555555"' + judge: + type: "exact" + - name: long-all-even + in: + num: "20000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + out: '""' + judge: + type: "exact" + - name: long-last-odd + in: + num: "20000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007" + out: '"20000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007"' + judge: + type: "exact" diff --git a/tests/1501-2000/1903. largest-odd-number-in-string/sol.cpp b/tests/1501-2000/1903. largest-odd-number-in-string/sol.cpp new file mode 100644 index 00000000..4310cf82 --- /dev/null +++ b/tests/1501-2000/1903. largest-odd-number-in-string/sol.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + string largestOddNumber(string num) { + for (int i = num.size() - 1; i >= 0; i--) { + if ((num[i] - '0') % 2 == 1) { + return num.substr(0, i + 1); + } + } + return ""; + } +}; diff --git a/tests/1501-2000/1903. largest-odd-number-in-string/sol.cs b/tests/1501-2000/1903. largest-odd-number-in-string/sol.cs new file mode 100644 index 00000000..72156a33 --- /dev/null +++ b/tests/1501-2000/1903. largest-odd-number-in-string/sol.cs @@ -0,0 +1,10 @@ +public class Solution { + public string LargestOddNumber(string num) { + for (int i = num.Length - 1; i >= 0; i--) { + if ((num[i] - '0') % 2 == 1) { + return num.Substring(0, i + 1); + } + } + return ""; + } +} diff --git a/tests/1501-2000/1903. largest-odd-number-in-string/sol.dart b/tests/1501-2000/1903. largest-odd-number-in-string/sol.dart new file mode 100644 index 00000000..a0e2aa94 --- /dev/null +++ b/tests/1501-2000/1903. largest-odd-number-in-string/sol.dart @@ -0,0 +1,10 @@ +class Solution { + String largestOddNumber(String num) { + for (int i = num.length - 1; i >= 0; i--) { + if (int.parse(num[i]) % 2 == 1) { + return num.substring(0, i + 1); + } + } + return ""; + } +} diff --git a/tests/1501-2000/1903. largest-odd-number-in-string/sol.go b/tests/1501-2000/1903. largest-odd-number-in-string/sol.go new file mode 100644 index 00000000..4ea78635 --- /dev/null +++ b/tests/1501-2000/1903. largest-odd-number-in-string/sol.go @@ -0,0 +1,8 @@ +func largestOddNumber(num string) string { + for i := len(num) - 1; i >= 0; i-- { + if int(num[i]-'0')%2 == 1 { + return num[:i+1] + } + } + return "" +} diff --git a/tests/1501-2000/1903. largest-odd-number-in-string/sol.java b/tests/1501-2000/1903. largest-odd-number-in-string/sol.java new file mode 100644 index 00000000..825fcd39 --- /dev/null +++ b/tests/1501-2000/1903. largest-odd-number-in-string/sol.java @@ -0,0 +1,10 @@ +class Solution { + public String largestOddNumber(String num) { + for (int i = num.length() - 1; i >= 0; i--) { + if ((num.charAt(i) - '0') % 2 == 1) { + return num.substring(0, i + 1); + } + } + return ""; + } +} diff --git a/tests/1501-2000/1903. largest-odd-number-in-string/sol.kt b/tests/1501-2000/1903. largest-odd-number-in-string/sol.kt new file mode 100644 index 00000000..4a610b9d --- /dev/null +++ b/tests/1501-2000/1903. largest-odd-number-in-string/sol.kt @@ -0,0 +1,10 @@ +class Solution { + fun largestOddNumber(num: String): String { + for (i in num.length - 1 downTo 0) { + if (num[i].digitToInt() % 2 == 1) { + return num.substring(0, i + 1) + } + } + return "" + } +} diff --git a/tests/1501-2000/1903. largest-odd-number-in-string/sol.py b/tests/1501-2000/1903. largest-odd-number-in-string/sol.py new file mode 100644 index 00000000..0e5e38cf --- /dev/null +++ b/tests/1501-2000/1903. largest-odd-number-in-string/sol.py @@ -0,0 +1,6 @@ +class Solution: + def largestOddNumber(self, num: str) -> str: + for i in range(len(num) - 1, -1, -1): + if (int(num[i]) % 2) == 1: + return num[: i + 1] + return "" diff --git a/tests/1501-2000/1903. largest-odd-number-in-string/sol.py2 b/tests/1501-2000/1903. largest-odd-number-in-string/sol.py2 new file mode 100644 index 00000000..ffcdadc6 --- /dev/null +++ b/tests/1501-2000/1903. largest-odd-number-in-string/sol.py2 @@ -0,0 +1,10 @@ +class Solution(object): + def largestOddNumber(self, num): + """ + :type num: str + :rtype: str + """ + for i in range(len(num) - 1, -1, -1): + if int(num[i]) % 2 == 1: + return num[:i + 1] + return "" diff --git a/tests/1501-2000/1903. largest-odd-number-in-string/sol.rb b/tests/1501-2000/1903. largest-odd-number-in-string/sol.rb new file mode 100644 index 00000000..f04637ad --- /dev/null +++ b/tests/1501-2000/1903. largest-odd-number-in-string/sol.rb @@ -0,0 +1,8 @@ +# @param {String} num +# @return {String} +def largest_odd_number(num) + (num.length - 1).downto(0) do |i| + return num[0..i] if num[i].to_i.odd? + end + "" +end diff --git a/tests/1501-2000/1903. largest-odd-number-in-string/sol.rs b/tests/1501-2000/1903. largest-odd-number-in-string/sol.rs new file mode 100644 index 00000000..a7874d4d --- /dev/null +++ b/tests/1501-2000/1903. largest-odd-number-in-string/sol.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn largest_odd_number(num: String) -> String { + for (i, ch) in num.chars().rev().enumerate() { + if ch.to_digit(10).unwrap() % 2 == 1 { + let len = num.len() - i; + return num[..len].to_string(); + } + } + String::new() + } +} diff --git a/tests/1501-2000/1903. largest-odd-number-in-string/sol.swift b/tests/1501-2000/1903. largest-odd-number-in-string/sol.swift new file mode 100644 index 00000000..f6018c4c --- /dev/null +++ b/tests/1501-2000/1903. largest-odd-number-in-string/sol.swift @@ -0,0 +1,11 @@ +class Solution { + func largestOddNumber(_ num: String) -> String { + let chars = Array(num) + for i in stride(from: chars.count - 1, through: 0, by: -1) { + if Int(String(chars[i]))! % 2 == 1 { + return String(chars[0...i]) + } + } + return "" + } +} diff --git a/tests/1501-2000/1903. largest-odd-number-in-string/sol.ts b/tests/1501-2000/1903. largest-odd-number-in-string/sol.ts new file mode 100644 index 00000000..fb6f974f --- /dev/null +++ b/tests/1501-2000/1903. largest-odd-number-in-string/sol.ts @@ -0,0 +1,8 @@ +function largestOddNumber(num: string): string { + for (let i = num.length - 1; i >= 0; i--) { + if (parseInt(num[i]) % 2 === 1) { + return num.substring(0, i + 1); + } + } + return ""; +} diff --git a/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/manifest.yaml b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/manifest.yaml new file mode 100644 index 00000000..f22fa2ab --- /dev/null +++ b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/manifest.yaml @@ -0,0 +1,329 @@ +entry: + id: 1904 + title: the-number-of-full-rounds-you-have-played + params: + loginTime: + type: string + logoutTime: + type: string + call: + cpp: "Solution().numberOfRounds({loginTime}, {logoutTime})" + rust: "Solution::number_of_rounds({loginTime}, {logoutTime})" + python3: "Solution().numberOfRounds({loginTime}, {logoutTime})" + python2: "Solution().numberOfRounds({loginTime}, {logoutTime})" + ruby: "number_of_rounds({loginTime}, {logoutTime})" + java: "new Solution().numberOfRounds({loginTime}, {logoutTime})" + csharp: "new Solution().NumberOfRounds({loginTime}, {logoutTime})" + kotlin: "Solution().numberOfRounds({loginTime}, {logoutTime})" + go: "numberOfRounds({loginTime}, {logoutTime})" + dart: "Solution().numberOfRounds({loginTime}, {logoutTime})" + swift: "Solution().numberOfRounds({loginTime}, {logoutTime})" + typescript: "numberOfRounds({loginTime}, {logoutTime})" + +judge: + type: exact + +limits: + time_ms: 1000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().numberOfRounds(loginTime, logoutTime, {result})" + checker: | + class Checker: + def numberOfRounds(self, loginTime, logoutTime, result): + def minutes(value): + hours, mins = map(int, value.split(":")) + return hours * 60 + mins + + start = minutes(loginTime) + end = minutes(logoutTime) + if end < start: + end += 24 * 60 + expected = max(0, end // 15 - (start + 14) // 15) + return result == expected + +seed: 1904 + +tests: + - name: example-one + in: + loginTime: "09:31" + logoutTime: "10:14" + out: 1 + judge: + type: exact + - name: example-two-midnight + in: + loginTime: "21:30" + logoutTime: "03:00" + out: 22 + judge: + type: exact + - name: exact-one-round + in: + loginTime: "09:30" + logoutTime: "09:45" + out: 1 + judge: + type: exact + - name: less-than-round + in: + loginTime: "09:31" + logoutTime: "09:44" + out: 0 + judge: + type: exact + - name: same-quarter-boundaries + in: + loginTime: "12:00" + logoutTime: "12:15" + out: 1 + judge: + type: exact + - name: login-after-boundary + in: + loginTime: "12:01" + logoutTime: "12:15" + out: 0 + judge: + type: exact + - name: logout-before-boundary + in: + loginTime: "12:00" + logoutTime: "12:14" + out: 0 + judge: + type: exact + - name: two-rounds + in: + loginTime: "00:00" + logoutTime: "00:30" + out: 2 + judge: + type: exact + - name: full-day-wrap + in: + loginTime: "00:01" + logoutTime: "00:00" + out: 95 + judge: + type: exact + - name: first-quarter + in: + loginTime: "00:00" + logoutTime: "00:15" + out: 1 + judge: + type: exact + - name: before-first-round + in: + loginTime: "00:01" + logoutTime: "00:14" + out: 0 + judge: + type: exact + - name: last-quarter + in: + loginTime: "23:45" + logoutTime: "23:59" + out: 0 + judge: + type: exact + - name: last-quarter-full + in: + loginTime: "23:45" + logoutTime: "00:00" + out: 1 + judge: + type: exact + - name: nearly-full-day + in: + loginTime: "00:00" + logoutTime: "23:59" + out: 95 + judge: + type: exact + - name: wrap-one-quarter + in: + loginTime: "23:45" + logoutTime: "00:15" + out: 2 + judge: + type: exact + - name: wrap-partial-start + in: + loginTime: "23:46" + logoutTime: "00:15" + out: 1 + judge: + type: exact + - name: wrap-partial-end + in: + loginTime: "23:45" + logoutTime: "00:14" + out: 1 + judge: + type: exact + - name: hour-aligned + in: + loginTime: "08:00" + logoutTime: "17:00" + out: 36 + judge: + type: exact + - name: hour-aligned-wrap + in: + loginTime: "18:00" + logoutTime: "06:00" + out: 48 + judge: + type: exact + - name: start-five + in: + loginTime: "05:05" + logoutTime: "06:05" + out: 3 + judge: + type: exact + - name: start-fourteen + in: + loginTime: "05:14" + logoutTime: "06:14" + out: 3 + judge: + type: exact + - name: start-fifteen + in: + loginTime: "05:15" + logoutTime: "06:15" + out: 4 + judge: + type: exact + - name: end-one + in: + loginTime: "05:00" + logoutTime: "06:01" + out: 4 + judge: + type: exact + - name: end-fourteen + in: + loginTime: "05:00" + logoutTime: "06:14" + out: 4 + judge: + type: exact + - name: end-fifteen + in: + loginTime: "05:00" + logoutTime: "06:15" + out: 5 + judge: + type: exact + - name: zero-after-login + in: + loginTime: "10:16" + logoutTime: "10:17" + out: 0 + judge: + type: exact + - name: one-minute-before-midnight + in: + loginTime: "23:58" + logoutTime: "00:01" + out: 0 + judge: + type: exact + - name: midnight-to-morning + in: + loginTime: "00:00" + logoutTime: "03:01" + out: 12 + judge: + type: exact + - name: morning-to-midnight + in: + loginTime: "03:00" + logoutTime: "23:59" + out: 83 + judge: + type: exact + - name: quarter-to-quarter + in: + loginTime: "07:15" + logoutTime: "08:45" + out: 6 + judge: + type: exact + - name: quarter-to-nonquarter + in: + loginTime: "07:15" + logoutTime: "08:44" + out: 5 + judge: + type: exact + - name: nonquarter-to-quarter + in: + loginTime: "07:16" + logoutTime: "08:45" + out: 5 + judge: + type: exact + - name: afternoon-wrap + in: + loginTime: "16:29" + logoutTime: "02:31" + out: 40 + judge: + type: exact + - name: long-same-day + in: + loginTime: "01:02" + logoutTime: "22:58" + out: 86 + judge: + type: exact + - name: one-round-late-start + in: + loginTime: "14:16" + logoutTime: "14:30" + out: 0 + judge: + type: exact + - name: one-round-late-end + in: + loginTime: "14:15" + logoutTime: "14:29" + out: 0 + judge: + type: exact + - name: two-rounds-offset + in: + loginTime: "14:16" + logoutTime: "14:46" + out: 1 + judge: + type: exact + - name: evening-boundary + in: + loginTime: "20:59" + logoutTime: "21:46" + out: 3 + judge: + type: exact + - name: wrap-even-boundaries + in: + loginTime: "22:15" + logoutTime: "01:15" + out: 12 + judge: + type: exact + - name: last-login-before-midnight + in: + loginTime: "23:59" + logoutTime: "00:01" + out: 0 + judge: + type: exact diff --git a/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.cpp b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.cpp new file mode 100644 index 00000000..0cbcef67 --- /dev/null +++ b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int numberOfRounds(string loginTime, string logoutTime) { + auto toMinutes = [](const string& t) { + int h = stoi(t.substr(0, 2)); + int m = stoi(t.substr(3, 2)); + return h * 60 + m; + }; + + int start = toMinutes(loginTime); + int end = toMinutes(logoutTime); + + if (end < start) { + end += 24 * 60; + } + + int startRound = (start + 14) / 15; + int endRound = end / 15; + + return max(0, endRound - startRound); + } +}; diff --git a/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.cs b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.cs new file mode 100644 index 00000000..f7641830 --- /dev/null +++ b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public int NumberOfRounds(string loginTime, string logoutTime) { + Func toMinutes = t => { + var parts = t.Split(':'); + return int.Parse(parts[0]) * 60 + int.Parse(parts[1]); + }; + + int start = toMinutes(loginTime); + int end = toMinutes(logoutTime); + + if (end < start) { + end += 24 * 60; + } + + int startRound = (start + 14) / 15; + int endRound = end / 15; + + return Math.Max(0, endRound - startRound); + } +} diff --git a/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.dart b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.dart new file mode 100644 index 00000000..654e4e28 --- /dev/null +++ b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.dart @@ -0,0 +1,20 @@ +class Solution { + int numberOfRounds(String loginTime, String logoutTime) { + int toMinutes(String t) { + List parts = t.split(":"); + return int.parse(parts[0]) * 60 + int.parse(parts[1]); + } + + int start = toMinutes(loginTime); + int end = toMinutes(logoutTime); + + if (end < start) { + end += 24 * 60; + } + + int startRound = (start + 14) ~/ 15; + int endRound = end ~/ 15; + + return (endRound - startRound) < 0 ? 0 : endRound - startRound; + } +} diff --git a/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.go b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.go new file mode 100644 index 00000000..862d39f7 --- /dev/null +++ b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.go @@ -0,0 +1,22 @@ +func numberOfRounds(loginTime string, logoutTime string) int { + toMinutes := func(t string) int { + h, m := 0, 0 + fmt.Sscanf(t, "%d:%d", &h, &m) + return h*60 + m + } + + start := toMinutes(loginTime) + end := toMinutes(logoutTime) + + if end < start { + end += 24 * 60 + } + + startRound := (start + 14) / 15 + endRound := end / 15 + + if endRound-startRound < 0 { + return 0 + } + return endRound - startRound +} diff --git a/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.java b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.java new file mode 100644 index 00000000..ee1d9be6 --- /dev/null +++ b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.java @@ -0,0 +1,20 @@ +class Solution { + public int numberOfRounds(String loginTime, String logoutTime) { + java.util.function.Function toMinutes = t -> { + String[] parts = t.split(":"); + return Integer.parseInt(parts[0]) * 60 + Integer.parseInt(parts[1]); + }; + + int start = toMinutes.apply(loginTime); + int end = toMinutes.apply(logoutTime); + + if (end < start) { + end += 24 * 60; + } + + int startRound = (start + 14) / 15; + int endRound = end / 15; + + return Math.max(0, endRound - startRound); + } +} diff --git a/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.kt b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.kt new file mode 100644 index 00000000..6e311cec --- /dev/null +++ b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.kt @@ -0,0 +1,20 @@ +class Solution { + fun numberOfRounds(loginTime: String, logoutTime: String): Int { + fun toMinutes(t: String): Int { + val parts = t.split(":") + return parts[0].toInt() * 60 + parts[1].toInt() + } + + val start = toMinutes(loginTime) + var end = toMinutes(logoutTime) + + if (end < start) { + end += 24 * 60 + } + + val startRound = (start + 14) / 15 + val endRound = end / 15 + + return maxOf(0, endRound - startRound) + } +} diff --git a/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.py b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.py new file mode 100644 index 00000000..38945303 --- /dev/null +++ b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.py @@ -0,0 +1,22 @@ +class Solution(object): + def numberOfRounds(self, loginTime, logoutTime): + """ + :type loginTime: str + :type logoutTime: str + :rtype: int + """ + + def to_minutes(t): + h, m = map(int, t.split(":")) + return h * 60 + m + + start = to_minutes(loginTime) + end = to_minutes(logoutTime) + + if end < start: + end += 24 * 60 + + start_round = (start + 14) // 15 + end_round = end // 15 + + return max(0, end_round - start_round) diff --git a/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.py2 b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.py2 new file mode 100644 index 00000000..e522e2be --- /dev/null +++ b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def numberOfRounds(self, loginTime, logoutTime): + """ + :type loginTime: str + :type logoutTime: str + :rtype: int + """ + def to_minutes(t): + h, m = map(int, t.split(":")) + return h * 60 + m + + start = to_minutes(loginTime) + end = to_minutes(logoutTime) + + if end < start: + end += 24 * 60 + + start_round = (start + 14) // 15 + end_round = end // 15 + + return max(0, end_round - start_round) diff --git a/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.rb b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.rb new file mode 100644 index 00000000..a4805c23 --- /dev/null +++ b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.rb @@ -0,0 +1,19 @@ +# @param {String} login_time +# @param {String} logout_time +# @return {Integer} +def number_of_rounds(login_time, logout_time) + def to_minutes(t) + h, m = t.split(":").map(&:to_i) + h * 60 + m + end + + start = to_minutes(login_time) + finish = to_minutes(logout_time) + + finish += 24 * 60 if finish < start + + start_round = (start + 14) / 15 + end_round = finish / 15 + + [0, end_round - start_round].max +end diff --git a/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.rs b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.rs new file mode 100644 index 00000000..4d646793 --- /dev/null +++ b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn number_of_rounds(login_time: String, logout_time: String) -> i32 { + fn to_minutes(t: &str) -> i32 { + let parts: Vec = t.split(':').map(|s| s.parse().unwrap()).collect(); + parts[0] * 60 + parts[1] + } + + let start = to_minutes(&login_time); + let mut end = to_minutes(&logout_time); + + if end < start { + end += 24 * 60; + } + + let start_round = (start + 14) / 15; + let end_round = end / 15; + + (end_round - start_round).max(0) + } +} diff --git a/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.swift b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.swift new file mode 100644 index 00000000..75c496ef --- /dev/null +++ b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.swift @@ -0,0 +1,20 @@ +class Solution { + func numberOfRounds(_ loginTime: String, _ logoutTime: String) -> Int { + func toMinutes(_ t: String) -> Int { + let parts = t.split(separator: ":").map { Int($0)! } + return parts[0] * 60 + parts[1] + } + + let start = toMinutes(loginTime) + var end = toMinutes(logoutTime) + + if end < start { + end += 24 * 60 + } + + let startRound = (start + 14) / 15 + let endRound = end / 15 + + return max(0, endRound - startRound) + } +} diff --git a/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.ts b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.ts new file mode 100644 index 00000000..c611b5e2 --- /dev/null +++ b/tests/1501-2000/1904. the-number-of-full-rounds-you-have-played/sol.ts @@ -0,0 +1,18 @@ +function numberOfRounds(loginTime: string, logoutTime: string): number { + const toMinutes = (t: string): number => { + const [h, m] = t.split(":").map(Number); + return h * 60 + m; + }; + + let start = toMinutes(loginTime); + let end = toMinutes(logoutTime); + + if (end < start) { + end += 24 * 60; + } + + const startRound = Math.floor((start + 14) / 15); + const endRound = Math.floor(end / 15); + + return Math.max(0, endRound - startRound); +} diff --git a/tests/1501-2000/1905. count-sub-islands/manifest.yaml b/tests/1501-2000/1905. count-sub-islands/manifest.yaml new file mode 100644 index 00000000..781c0fa0 --- /dev/null +++ b/tests/1501-2000/1905. count-sub-islands/manifest.yaml @@ -0,0 +1,500 @@ +entry: + id: 1905 + title: count-sub-islands + params: + grid1: + type: array + items: + type: array + items: + type: int + grid2: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().countSubIslands({grid1}, {grid2})" + rust: "Solution::count_sub_islands({grid1}, {grid2})" + python3: "Solution().countSubIslands({grid1}, {grid2})" + python2: "Solution().countSubIslands({grid1}, {grid2})" + ruby: "count_sub_islands({grid1}, {grid2})" + java: "new Solution().countSubIslands({grid1}, {grid2})" + csharp: "new Solution().CountSubIslands({grid1}, {grid2})" + kotlin: "Solution().countSubIslands({grid1}, {grid2})" + go: "countSubIslands({grid1}, {grid2})" + dart: "Solution().countSubIslands({grid1}, {grid2})" + swift: "Solution().countSubIslands({grid1}, {grid2})" + typescript: "countSubIslands({grid1}, {grid2})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().countSubIslands(grid1, grid2, {result})" + checker: | + class Checker: + def countSubIslands(self, grid1, grid2, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + m, n = len(grid1), len(grid1[0]) + seen = [[False] * n for _ in range(m)] + expected = 0 + for i in range(m): + for j in range(n): + if grid2[i][j] != 1 or seen[i][j]: + continue + stack = [(i, j)] + seen[i][j] = True + valid = True + while stack: + r, c = stack.pop() + if grid1[r][c] != 1: + valid = False + for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): + nr, nc = r + dr, c + dc + if 0 <= nr < m and 0 <= nc < n and grid2[nr][nc] == 1 and not seen[nr][nc]: + seen[nr][nc] = True + stack.append((nr, nc)) + expected += int(valid) + return result == expected + +seed: 1905 + +tests: + - name: example-one + in: + grid1: + - [1, 1, 1, 0, 0] + - [0, 1, 1, 1, 1] + - [0, 0, 0, 0, 0] + - [1, 0, 0, 0, 0] + - [1, 1, 0, 1, 1] + grid2: + - [1, 1, 1, 0, 0] + - [0, 0, 1, 1, 1] + - [0, 1, 0, 0, 0] + - [1, 0, 1, 1, 0] + - [0, 1, 0, 1, 0] + - name: example-two + in: + grid1: + - [1, 0, 1, 0, 1] + - [1, 1, 1, 1, 1] + - [0, 0, 0, 0, 0] + - [1, 1, 1, 1, 1] + - [1, 0, 1, 0, 1] + grid2: + - [0, 0, 0, 0, 0] + - [1, 1, 1, 1, 1] + - [0, 1, 0, 1, 0] + - [0, 1, 0, 1, 0] + - [1, 0, 0, 0, 1] + - name: one-cell-valid + in: + grid1: + - [1] + grid2: + - [1] + - name: one-cell-invalid + in: + grid1: + - [0] + grid2: + - [1] + - name: one-cell-water + in: + grid1: + - [0] + grid2: + - [0] + - name: all-land-valid-2x2 + in: + grid1: + - [1, 1] + - [1, 1] + grid2: + - [1, 1] + - [1, 1] + - name: all-land-invalid-2x2 + in: + grid1: + - [1, 0] + - [0, 1] + grid2: + - [1, 1] + - [1, 1] + - name: diagonal-islands + in: + grid1: + - [1, 0, 1] + - [0, 1, 0] + - [1, 0, 1] + grid2: + - [1, 0, 1] + - [0, 1, 0] + - [1, 0, 1] + - name: horizontal-split + in: + grid1: + - [1, 1, 0, 1, 1] + grid2: + - [1, 1, 1, 1, 1] + - name: vertical-split + in: + grid1: + - [1] + - [1] + - [0] + - [1] + - [1] + grid2: + - [1] + - [1] + - [1] + - [1] + - [1] + - name: hole-in-grid1 + in: + grid1: + - [1, 1, 1] + - [1, 0, 1] + - [1, 1, 1] + grid2: + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + - name: separate-valid-components + in: + grid1: + - [1, 0, 1, 0, 1] + - [1, 0, 1, 0, 1] + grid2: + - [1, 0, 1, 0, 1] + - [1, 0, 1, 0, 1] + - name: touching-invalid-component + in: + grid1: + - [1, 1, 0] + - [1, 0, 1] + - [0, 1, 1] + grid2: + - [1, 1, 0] + - [1, 1, 1] + - [0, 1, 1] + - name: border-valid + in: + grid1: + - [1, 1, 1, 1] + - [1, 0, 0, 1] + - [1, 0, 0, 1] + - [1, 1, 1, 1] + grid2: + - [1, 1, 0, 0] + - [1, 0, 0, 1] + - [1, 0, 0, 1] + - [1, 1, 1, 1] + - name: corner-singletons + in: + grid1: + - [1, 0, 0, 1] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - [1, 0, 0, 1] + grid2: + - [1, 0, 0, 1] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - [1, 0, 0, 1] + - name: grid2-empty + in: + grid1: + - [1, 1, 1] + - [1, 1, 1] + grid2: + - [0, 0, 0] + - [0, 0, 0] + - name: grid1-empty + in: + grid1: + - [0, 0, 0] + - [0, 0, 0] + grid2: + - [1, 0, 1] + - [0, 1, 0] + - name: checkerboard + in: + grid1: + - [1, 0, 1, 0] + - [0, 1, 0, 1] + - [1, 0, 1, 0] + grid2: + - [1, 0, 1, 0] + - [0, 1, 0, 1] + - [1, 0, 1, 0] + - name: one-row-mixed + in: + grid1: + - [1, 0, 1, 1, 0, 1, 0, 1] + grid2: + - [1, 1, 1, 1, 0, 1, 1, 1] + - name: one-column-mixed + in: + grid1: + - [1] + - [0] + - [1] + - [1] + - [0] + - [1] + - [0] + - [1] + grid2: + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [0] + - [1] + - name: thin-l-shape + in: + grid1: + - [1, 1, 0] + - [1, 0, 0] + - [1, 1, 1] + grid2: + - [1, 1, 0] + - [1, 0, 0] + - [1, 1, 1] + - name: thin-l-invalid + in: + grid1: + - [1, 1, 0] + - [1, 0, 0] + - [1, 1, 0] + grid2: + - [1, 1, 0] + - [1, 1, 0] + - [1, 1, 1] + - name: two-by-five + in: + grid1: + - [1, 1, 0, 0, 1] + - [0, 1, 1, 1, 1] + grid2: + - [1, 1, 0, 1, 1] + - [0, 1, 1, 1, 1] + - name: five-by-two + in: + grid1: + - [1, 0] + - [1, 1] + - [0, 1] + - [1, 0] + - [1, 1] + grid2: + - [1, 0] + - [1, 1] + - [1, 1] + - [1, 0] + - [1, 1] + - name: two-large-components + in: + grid1: + - [1, 1, 1, 0, 1, 1] + - [1, 0, 1, 0, 1, 1] + - [1, 1, 1, 0, 0, 0] + grid2: + - [1, 1, 0, 0, 1, 1] + - [1, 0, 1, 0, 1, 0] + - [1, 1, 1, 0, 0, 0] + - name: narrow-bridge + in: + grid1: + - [1, 1, 1, 1, 1] + - [1, 0, 0, 0, 1] + - [1, 1, 1, 1, 1] + grid2: + - [1, 1, 1, 1, 1] + - [1, 0, 1, 0, 1] + - [1, 1, 1, 1, 1] + - name: all-zero-4x4 + in: + grid1: + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + grid2: + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - name: all-one-4x4 + in: + grid1: + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - [1, 1, 1, 1] + grid2: + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - name: diagonal-touch-not-connected + in: + grid1: + - [1, 0, 0] + - [0, 1, 0] + - [0, 0, 1] + grid2: + - [1, 1, 0] + - [0, 1, 1] + - [0, 0, 1] + - name: invalid-cell-inside + in: + grid1: + - [1, 1, 1, 1] + - [1, 1, 0, 1] + - [1, 1, 1, 1] + grid2: + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - [1, 1, 1, 1] + - name: multiple-singletons-and-pair + in: + grid1: + - [1, 0, 1, 1, 0, 1] + - [0, 0, 0, 0, 0, 0] + - [1, 1, 0, 0, 1, 1] + grid2: + - [1, 0, 1, 1, 1, 1] + - [0, 1, 0, 0, 0, 0] + - [1, 1, 0, 0, 1, 0] + - name: irregular-5x5 + in: + grid1: + - [1, 1, 0, 1, 0] + - [1, 0, 0, 1, 1] + - [0, 0, 1, 0, 0] + - [1, 1, 1, 0, 1] + - [0, 1, 0, 1, 1] + grid2: + - [1, 1, 0, 1, 1] + - [1, 0, 0, 1, 1] + - [0, 0, 1, 1, 0] + - [1, 1, 1, 0, 1] + - [0, 1, 0, 1, 1] + - name: full-grid-with-one-mismatch + in: + grid1: + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + - [1, 1, 0, 1, 1] + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + grid2: + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + - name: separated-columns + in: + grid1: + - [1, 0, 1, 0, 1, 0] + - [1, 0, 1, 0, 1, 0] + - [1, 0, 1, 0, 1, 0] + grid2: + - [1, 1, 1, 1, 1, 1] + - [1, 0, 1, 0, 1, 0] + - [1, 1, 1, 1, 1, 1] + - name: nested-square + in: + grid1: + - [1, 1, 1, 1, 1] + - [1, 0, 0, 0, 1] + - [1, 0, 1, 0, 1] + - [1, 0, 0, 0, 1] + - [1, 1, 1, 1, 1] + grid2: + - [1, 1, 1, 1, 1] + - [1, 0, 0, 0, 1] + - [1, 0, 1, 0, 1] + - [1, 0, 0, 0, 1] + - [1, 1, 1, 1, 1] + - name: nested-square-invalid-center + in: + grid1: + - [1, 1, 1, 1, 1] + - [1, 0, 0, 0, 1] + - [1, 0, 0, 0, 1] + - [1, 0, 0, 0, 1] + - [1, 1, 1, 1, 1] + grid2: + - [1, 1, 1, 1, 1] + - [1, 0, 0, 0, 1] + - [1, 0, 1, 0, 1] + - [1, 0, 0, 0, 1] + - [1, 1, 1, 1, 1] + - name: alternating-stripes + in: + grid1: + - [1, 1, 1, 1, 1, 1] + - [0, 0, 0, 0, 0, 0] + - [1, 1, 1, 1, 1, 1] + - [0, 0, 0, 0, 0, 0] + grid2: + - [1, 1, 0, 1, 1, 0] + - [1, 1, 1, 1, 1, 1] + - [1, 1, 1, 0, 1, 1] + - [0, 0, 0, 0, 0, 0] + - name: four-by-seven + in: + grid1: + - [1, 0, 1, 1, 0, 1, 1] + - [1, 1, 0, 1, 0, 0, 1] + - [0, 1, 1, 1, 1, 1, 1] + - [1, 0, 0, 0, 1, 0, 1] + grid2: + - [1, 1, 1, 1, 0, 1, 1] + - [1, 1, 0, 1, 0, 0, 1] + - [0, 1, 1, 1, 1, 1, 1] + - [1, 0, 0, 0, 1, 1, 1] + - name: five-by-five-sparse + in: + grid1: + - [1, 0, 1, 0, 1] + - [0, 1, 0, 1, 0] + - [1, 0, 1, 0, 1] + - [0, 1, 0, 1, 0] + - [1, 0, 1, 0, 1] + grid2: + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1] + - name: final-boundary-case + in: + grid1: + - [1, 1, 0, 0, 1, 1, 0, 1] + - [0, 1, 1, 0, 1, 0, 0, 1] + - [1, 0, 1, 1, 1, 1, 1, 1] + - [1, 1, 0, 0, 0, 1, 0, 0] + - [0, 1, 1, 1, 0, 1, 1, 1] + grid2: + - [1, 1, 1, 0, 1, 1, 0, 1] + - [0, 1, 1, 0, 1, 0, 0, 1] + - [1, 0, 1, 1, 1, 1, 1, 1] + - [1, 1, 0, 0, 0, 1, 1, 0] + - [0, 1, 1, 1, 0, 1, 1, 1] diff --git a/tests/1501-2000/1905. count-sub-islands/sol.cpp b/tests/1501-2000/1905. count-sub-islands/sol.cpp new file mode 100644 index 00000000..ff93fe87 --- /dev/null +++ b/tests/1501-2000/1905. count-sub-islands/sol.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int countSubIslands(vector>& grid1, vector>& grid2) { + int m = grid1.size(), n = grid1[0].size(); + bool valid; + function dfs = [&](int i, int j) { + if (i < 0 || i >= m || j < 0 || j >= n) return; + if (grid2[i][j] == 0) return; + if (grid1[i][j] == 0) valid = false; + grid2[i][j] = 0; + dfs(i+1, j); + dfs(i-1, j); + dfs(i, j+1); + dfs(i, j-1); + }; + + int res = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid2[i][j] == 1) { + valid = true; + dfs(i, j); + if (valid) res++; + } + } + } + return res; + } +}; diff --git a/tests/1501-2000/1905. count-sub-islands/sol.cs b/tests/1501-2000/1905. count-sub-islands/sol.cs new file mode 100644 index 00000000..9901b1e6 --- /dev/null +++ b/tests/1501-2000/1905. count-sub-islands/sol.cs @@ -0,0 +1,29 @@ +public class Solution { + public int CountSubIslands(int[][] grid1, int[][] grid2) { + int m = grid1.Length, n = grid1[0].Length; + bool valid; + + void Dfs(int i, int j) { + if (i < 0 || i >= m || j < 0 || j >= n) return; + if (grid2[i][j] == 0) return; + if (grid1[i][j] == 0) valid = false; + grid2[i][j] = 0; + Dfs(i+1, j); + Dfs(i-1, j); + Dfs(i, j+1); + Dfs(i, j-1); + } + + int res = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid2[i][j] == 1) { + valid = true; + Dfs(i, j); + if (valid) res++; + } + } + } + return res; + } +} diff --git a/tests/1501-2000/1905. count-sub-islands/sol.dart b/tests/1501-2000/1905. count-sub-islands/sol.dart new file mode 100644 index 00000000..5b413049 --- /dev/null +++ b/tests/1501-2000/1905. count-sub-islands/sol.dart @@ -0,0 +1,29 @@ +class Solution { + int countSubIslands(List> grid1, List> grid2) { + int m = grid1.length, n = grid1[0].length; + bool valid = false; + + void dfs(int i, int j) { + if (i < 0 || i >= m || j < 0 || j >= n) return; + if (grid2[i][j] == 0) return; + if (grid1[i][j] == 0) valid = false; + grid2[i][j] = 0; + dfs(i+1, j); + dfs(i-1, j); + dfs(i, j+1); + dfs(i, j-1); + } + + int res = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid2[i][j] == 1) { + valid = true; + dfs(i, j); + if (valid) res++; + } + } + } + return res; + } +} diff --git a/tests/1501-2000/1905. count-sub-islands/sol.go b/tests/1501-2000/1905. count-sub-islands/sol.go new file mode 100644 index 00000000..e822137c --- /dev/null +++ b/tests/1501-2000/1905. count-sub-islands/sol.go @@ -0,0 +1,33 @@ +func countSubIslands(grid1 [][]int, grid2 [][]int) int { + m, n := len(grid1), len(grid1[0]) + var dfs func(i, j int, valid *bool) + dfs = func(i, j int, valid *bool) { + if i < 0 || i >= m || j < 0 || j >= n { + return + } + if grid2[i][j] == 0 { + return + } + if grid1[i][j] == 0 { + *valid = false + } + grid2[i][j] = 0 + dfs(i+1, j, valid) + dfs(i-1, j, valid) + dfs(i, j+1, valid) + dfs(i, j-1, valid) + } + res := 0 + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if grid2[i][j] == 1 { + valid := true + dfs(i, j, &valid) + if valid { + res++ + } + } + } + } + return res +} diff --git a/tests/1501-2000/1905. count-sub-islands/sol.java b/tests/1501-2000/1905. count-sub-islands/sol.java new file mode 100644 index 00000000..05efe48e --- /dev/null +++ b/tests/1501-2000/1905. count-sub-islands/sol.java @@ -0,0 +1,27 @@ +class Solution { + public int countSubIslands(int[][] grid1, int[][] grid2) { + int m = grid1.length, n = grid1[0].length; + boolean[] valid = new boolean[1]; + int res = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid2[i][j] == 1) { + valid[0] = true; + dfs(grid1, grid2, i, j, m, n, valid); + if (valid[0]) res++; + } + } + } + return res; + } + private void dfs(int[][] grid1, int[][] grid2, int i, int j, int m, int n, boolean[] valid) { + if (i < 0 || i >= m || j < 0 || j >= n) return; + if (grid2[i][j] == 0) return; + if (grid1[i][j] == 0) valid[0] = false; + grid2[i][j] = 0; + dfs(grid1, grid2, i+1, j, m, n, valid); + dfs(grid1, grid2, i-1, j, m, n, valid); + dfs(grid1, grid2, i, j+1, m, n, valid); + dfs(grid1, grid2, i, j-1, m, n, valid); + } +} diff --git a/tests/1501-2000/1905. count-sub-islands/sol.kt b/tests/1501-2000/1905. count-sub-islands/sol.kt new file mode 100644 index 00000000..36b3b257 --- /dev/null +++ b/tests/1501-2000/1905. count-sub-islands/sol.kt @@ -0,0 +1,28 @@ +class Solution { + fun countSubIslands(grid1: Array, grid2: Array): Int { + val m = grid1.size + val n = grid1[0].size + var valid = booleanArrayOf(true) + var res = 0 + for (i in 0 until m) { + for (j in 0 until n) { + if (grid2[i][j] == 1) { + valid[0] = true + dfs(grid1, grid2, i, j, m, n, valid) + if (valid[0]) res++ + } + } + } + return res + } + private fun dfs(grid1: Array, grid2: Array, i: Int, j: Int, m: Int, n: Int, valid: BooleanArray) { + if (i < 0 || i >= m || j < 0 || j >= n) return + if (grid2[i][j] == 0) return + if (grid1[i][j] == 0) valid[0] = false + grid2[i][j] = 0 + dfs(grid1, grid2, i+1, j, m, n, valid) + dfs(grid1, grid2, i-1, j, m, n, valid) + dfs(grid1, grid2, i, j+1, m, n, valid) + dfs(grid1, grid2, i, j-1, m, n, valid) + } +} diff --git a/tests/1501-2000/1905. count-sub-islands/sol.py b/tests/1501-2000/1905. count-sub-islands/sol.py new file mode 100644 index 00000000..5c102df5 --- /dev/null +++ b/tests/1501-2000/1905. count-sub-islands/sol.py @@ -0,0 +1,27 @@ +class Solution: + def countSubIslands(self, grid1: list[list[int]], grid2: list[list[int]]) -> int: + m, n = len(grid1), len(grid1[0]) + + def dfs(i, j): + if not 0 <= i < m or not 0 <= j < n: + return + nonlocal is_valid + if not grid2[i][j]: + return + if not grid1[i][j]: + is_valid = False + grid2[i][j] = 0 + for r, c in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]: + if 0 <= r < m and 0 <= c < n and grid2[r][c]: + dfs(r, c) + return + + res = 0 + for i in range(m): + for j in range(n): + is_valid = True + if grid2[i][j]: + dfs(i, j) + if is_valid: + res += 1 + return res diff --git a/tests/1501-2000/1905. count-sub-islands/sol.py2 b/tests/1501-2000/1905. count-sub-islands/sol.py2 new file mode 100644 index 00000000..dcab4351 --- /dev/null +++ b/tests/1501-2000/1905. count-sub-islands/sol.py2 @@ -0,0 +1,30 @@ +class Solution(object): + def countSubIslands(self, grid1, grid2): + """ + :type grid1: List[List[int]] + :type grid2: List[List[int]] + :rtype: int + """ + m, n = len(grid1), len(grid1[0]) + + def dfs(i, j): + if not (0 <= i < m and 0 <= j < n): + return + if not grid2[i][j]: + return + if not grid1[i][j]: + state[0] = False + grid2[i][j] = 0 + for r, c in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]: + if 0 <= r < m and 0 <= c < n and grid2[r][c]: + dfs(r, c) + + res = 0 + for i in range(m): + for j in range(n): + state = [True] + if grid2[i][j]: + dfs(i, j) + if state[0]: + res += 1 + return res diff --git a/tests/1501-2000/1905. count-sub-islands/sol.rb b/tests/1501-2000/1905. count-sub-islands/sol.rb new file mode 100644 index 00000000..0120b3e9 --- /dev/null +++ b/tests/1501-2000/1905. count-sub-islands/sol.rb @@ -0,0 +1,30 @@ +# @param {Integer[][]} grid1 +# @param {Integer[][]} grid2 +# @return {Integer} +def count_sub_islands(grid1, grid2) + m = grid1.length + n = grid1[0].length + + dfs = lambda do |i, j, is_valid| + return [is_valid] if i < 0 || i >= m || j < 0 || j >= n + is_valid = false if grid1[i][j] == 0 + grid2[i][j] = 0 + [[i+1, j], [i-1, j], [i, j+1], [i, j-1]].each do |r, c| + if r >= 0 && r < m && c >= 0 && c < n && grid2[r][c] == 1 + is_valid = dfs.call(r, c, is_valid)[0] + end + end + [is_valid] + end + + res = 0 + (0...m).each do |i| + (0...n).each do |j| + if grid2[i][j] == 1 + is_valid = dfs.call(i, j, true)[0] + res += 1 if is_valid + end + end + end + res +end diff --git a/tests/1501-2000/1905. count-sub-islands/sol.rs b/tests/1501-2000/1905. count-sub-islands/sol.rs new file mode 100644 index 00000000..0e79b875 --- /dev/null +++ b/tests/1501-2000/1905. count-sub-islands/sol.rs @@ -0,0 +1,31 @@ +impl Solution { + pub fn count_sub_islands(grid1: Vec>, grid2: Vec>) -> i32 { + let m = grid1.len(); + let n = grid1[0].len(); + let mut grid2 = grid2; + let mut valid = false; + + fn dfs(grid1: &Vec>, grid2: &mut Vec>, i: usize, j: usize, m: usize, n: usize, valid: &mut bool) { + if i >= m || j >= n { return; } + if grid2[i][j] == 0 { return; } + if grid1[i][j] == 0 { *valid = false; } + grid2[i][j] = 0; + if i+1 < m { dfs(grid1, grid2, i+1, j, m, n, valid); } + if i > 0 { dfs(grid1, grid2, i-1, j, m, n, valid); } + if j+1 < n { dfs(grid1, grid2, i, j+1, m, n, valid); } + if j > 0 { dfs(grid1, grid2, i, j-1, m, n, valid); } + } + + let mut res = 0; + for i in 0..m { + for j in 0..n { + if grid2[i][j] == 1 { + valid = true; + dfs(&grid1, &mut grid2, i, j, m, n, &mut valid); + if valid { res += 1; } + } + } + } + res + } +} diff --git a/tests/1501-2000/1905. count-sub-islands/sol.swift b/tests/1501-2000/1905. count-sub-islands/sol.swift new file mode 100644 index 00000000..be044695 --- /dev/null +++ b/tests/1501-2000/1905. count-sub-islands/sol.swift @@ -0,0 +1,30 @@ +class Solution { + func countSubIslands(_ grid1: [[Int]], _ grid2: [[Int]]) -> Int { + let m = grid1.count, n = grid1[0].count + var grid2 = grid2 + var valid = false + + func dfs(_ i: Int, _ j: Int) { + if i < 0 || i >= m || j < 0 || j >= n { return } + if grid2[i][j] == 0 { return } + if grid1[i][j] == 0 { valid = false } + grid2[i][j] = 0 + dfs(i+1, j) + dfs(i-1, j) + dfs(i, j+1) + dfs(i, j-1) + } + + var res = 0 + for i in 0..= m || j < 0 || j >= n) return; + if (grid2[i][j] === 0) return; + if (grid1[i][j] === 0) valid = false; + grid2[i][j] = 0; + dfs(i + 1, j); + dfs(i - 1, j); + dfs(i, j + 1); + dfs(i, j - 1); + } + + let res = 0; + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (grid2[i][j] === 1) { + valid = true; + dfs(i, j); + if (valid) res++; + } + } + } + return res; +} diff --git a/tests/1501-2000/1906. minimum-absolute-difference-queries/manifest.yaml b/tests/1501-2000/1906. minimum-absolute-difference-queries/manifest.yaml new file mode 100644 index 00000000..c7edded0 --- /dev/null +++ b/tests/1501-2000/1906. minimum-absolute-difference-queries/manifest.yaml @@ -0,0 +1,536 @@ +entry: + id: 1906 + title: minimum-absolute-difference-queries + params: + nums: + type: array + items: + type: int + queries: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().minDifference({nums}, {queries})" + rust: "Solution::min_difference({nums}, {queries})" + python3: "Solution().minDifference({nums}, {queries})" + python2: "Solution().minDifference({nums}, {queries})" + ruby: "min_difference({nums}, {queries})" + java: "new Solution().minDifference({nums}, {queries})" + csharp: "new Solution().MinDifference({nums}, {queries})" + kotlin: "Solution().minDifference({nums}, {queries})" + go: "minDifference({nums}, {queries})" + dart: "Solution().minDifference({nums}, {queries})" + swift: "Solution().minDifference({nums}, {queries})" + typescript: "minDifference({nums}, {queries})" + +judge: + type: exact + +limits: + time_ms: 5000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().check(nums, queries, {result})" + checker: | + class Checker: + def check(self, nums, queries, result): + if not isinstance(result, list) or len(result) != len(queries): + return False + expected = [] + for left, right in queries: + values = [False] * 101 + for value in nums[left:right + 1]: + values[value] = True + present = [value for value in range(1, 101) if values[value]] + best = -1 if len(present) < 2 else min(b - a for a, b in zip(present, present[1:])) + expected.append(best) + return result == expected + +seed: 1906 + +tests: + - name: example-one + in: + nums: [1, 3, 4, 8] + queries: + - [0, 1] + - [1, 2] + - [2, 3] + - [0, 3] + out: [2, 1, 4, 1] + - name: example-two + in: + nums: [4, 5, 2, 2, 7, 10] + queries: + - [2, 3] + - [0, 2] + - [0, 5] + - [3, 5] + out: [-1, 1, 1, 3] + - name: smallest-distinct + in: + nums: [1, 2] + queries: + - [0, 1] + out: [1] + - name: smallest-equal + in: + nums: [7, 7] + queries: + - [0, 1] + out: [-1] + - name: all-equal + in: + nums: [5, 5, 5, 5, 5] + queries: + - [0, 1] + - [1, 3] + - [0, 4] + - [3, 4] + out: [-1, -1, -1, -1] + - name: consecutive-values + in: + nums: [1, 2, 3, 4, 5, 6] + queries: + - [0, 5] + - [0, 1] + - [2, 4] + - [4, 5] + out: [1, 1, 1, 1] + - name: endpoints + in: + nums: [1, 100, 50, 99, 2, 98] + queries: + - [0, 1] + - [0, 5] + - [1, 3] + - [4, 5] + out: [99, 1, 1, 96] + - name: duplicate-does-not-give-zero + in: + nums: [10, 10, 20, 30, 30] + queries: + - [0, 4] + - [0, 1] + - [1, 3] + - [2, 4] + out: [10, -1, 10, 10] + - name: close-values + in: + nums: [1, 100, 99, 50, 51, 2] + queries: + - [0, 5] + - [1, 2] + - [3, 4] + - [0, 1] + out: [1, 1, 1, 99] + - name: narrow-windows + in: + nums: [8, 1, 9, 3, 7, 2, 6, 4, 5] + queries: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + out: [7, 8, 6, 4, 5, 4, 2, 1] + - name: repeated-windows + in: + nums: [2, 9, 2, 8, 3, 7, 3, 6] + queries: + - [0, 7] + - [0, 2] + - [2, 5] + - [4, 6] + - [6, 7] + out: [1, 7, 1, 4, 3] + - name: low-range-values + in: + nums: [1, 3, 1, 2, 3, 2, 1] + queries: + - [0, 6] + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + out: [1, 2, 2, 1, 1, 1] + - name: high-range-values + in: + nums: [98, 100, 99, 97, 96, 100, 95] + queries: + - [0, 6] + - [0, 1] + - [1, 2] + - [2, 4] + - [4, 6] + out: [1, 2, 1, 1, 1] + - name: alternating-extremes + in: + nums: [1, 100, 1, 100, 1, 100] + queries: + - [0, 5] + - [0, 1] + - [1, 3] + - [2, 4] + - [4, 5] + out: [99, 99, 99, 99, 99] + - name: one-close-pair + in: + nums: [1, 40, 80, 81, 20, 100] + queries: + - [0, 5] + - [0, 2] + - [1, 4] + - [2, 3] + - [3, 5] + out: [1, 39, 1, 1, 19] + - name: descending + in: + nums: [100, 90, 80, 70, 60, 50, 40] + queries: + - [0, 6] + - [0, 1] + - [1, 4] + - [3, 6] + out: [10, 10, 10, 10] + - name: singleton-queries-are-forbidden + in: + nums: [6, 14, 22, 30, 38, 46] + queries: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + out: [8, 8, 8, 8, 8] + - name: mixed-duplicates + in: + nums: [4, 4, 9, 1, 9, 2, 2, 8, 3] + queries: + - [0, 8] + - [0, 1] + - [1, 4] + - [3, 6] + - [5, 8] + out: [1, -1, 3, 1, 1] + - name: query-order + in: + nums: [12, 5, 19, 7, 13, 2, 18] + queries: + - [5, 6] + - [0, 6] + - [1, 3] + - [2, 4] + - [0, 1] + out: [16, 1, 2, 6, 7] + - name: every-prefix + in: + nums: [20, 1, 40, 2, 60, 3, 80, 4] + queries: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + - [0, 6] + - [0, 7] + out: [19, 19, 1, 1, 1, 1, 1] + - name: every-suffix + in: + nums: [1, 80, 2, 60, 3, 40, 4, 20] + queries: + - [0, 7] + - [1, 7] + - [2, 7] + - [3, 7] + - [4, 7] + - [5, 7] + - [6, 7] + out: [1, 1, 1, 1, 1, 16, 16] + - name: disjoint-ranges + in: + nums: [1, 2, 50, 51, 90, 100, 10, 11] + queries: + - [0, 1] + - [2, 3] + - [4, 5] + - [6, 7] + - [0, 7] + out: [1, 1, 10, 1, 1] + - name: values-1-5 + in: + nums: [5, 4, 3, 2, 1, 5, 4, 3, 2, 1] + queries: + - [0, 9] + - [0, 3] + - [4, 8] + - [5, 9] + out: [1, 1, 1, 1] + - name: values-96-100 + in: + nums: [100, 96, 100, 98, 97, 99, 96, 98] + queries: + - [0, 7] + - [0, 1] + - [2, 4] + - [5, 7] + out: [1, 4, 1, 1] + - name: separated-close-pair + in: + nums: [1, 50, 90, 10, 91, 30, 100, 92] + queries: + - [0, 7] + - [0, 2] + - [2, 4] + - [4, 7] + - [0, 3] + out: [1, 40, 1, 1, 9] + - name: long-equal-blocks + in: + nums: [7, 7, 7, 8, 8, 8, 20, 20, 20, 50, 50] + queries: + - [0, 2] + - [0, 3] + - [1, 5] + - [3, 8] + - [6, 10] + - [0, 10] + out: [-1, 1, 1, 12, 30, 1] + - name: crossing-ranges + in: + nums: [11, 90, 12, 89, 13, 88, 14, 87] + queries: + - [0, 7] + - [0, 2] + - [1, 3] + - [2, 5] + - [4, 7] + out: [1, 1, 1, 1, 1] + - name: four-values + in: + nums: [25, 25, 50, 75, 100, 50, 75, 100] + queries: + - [0, 1] + - [0, 2] + - [1, 4] + - [2, 7] + - [4, 7] + out: [-1, 25, 25, 25, 25] + - name: uneven-query-lengths + in: + nums: [3, 70, 40, 41, 2, 99, 100, 1, 42] + queries: + - [0, 1] + - [0, 8] + - [1, 2] + - [1, 4] + - [2, 8] + - [5, 8] + out: [67, 1, 30, 1, 1, 1] + - name: all-values-distinct + in: + nums: [17, 3, 92, 44, 68, 11, 35, 79, 56, 100] + queries: + - [0, 9] + - [0, 3] + - [2, 6] + - [5, 9] + - [1, 8] + out: [6, 14, 9, 21, 8] + - name: alternating-small-large + in: + nums: [2, 99, 4, 97, 6, 95, 8, 93, 10, 91] + queries: + - [0, 9] + - [0, 1] + - [2, 5] + - [4, 7] + - [6, 9] + out: [2, 97, 2, 2, 2] + - name: medium-random + in: + nums: [37, 12, 84, 55, 3, 71, 26, 98, 44, 19, 63, 7, 90, 31, 76, 48] + queries: + - [0, 15] + - [0, 5] + - [3, 10] + - [6, 13] + - [10, 15] + - [1, 14] + out: [4, 9, 7, 5, 13, 4] + - name: medium-repeated + in: + nums: [1, 50, 1, 75, 50, 100, 25, 75, 2, 99, 25, 98, 3, 97] + queries: + - [0, 13] + - [0, 2] + - [1, 7] + - [6, 11] + - [8, 13] + out: [1, 49, 24, 1, 1] + - name: max-value-boundary + in: + nums: [100, 1, 100, 1, 99, 2, 98, 3, 97, 4, 96, 5] + queries: + - [0, 11] + - [0, 1] + - [4, 7] + - [8, 11] + out: [1, 99, 1, 1] + - name: stress-1000-cyclic + in: + nums: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + 63, + 64, + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + 99, + 100, + ] + queries: + - [0, 99] + - [0, 1] + - [10, 20] + - [50, 99] + out: [1, 1, 1, 1] + - name: stress-1000-equal + in: + nums: + [ + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + ] + queries: + - [0, 19] + - [0, 1] + - [3, 12] + - [10, 19] + out: [-1, -1, -1, -1] + - name: final-boundaries + in: + nums: [1, 100] + queries: + - [0, 1] + out: [99] diff --git a/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.cpp b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.cpp new file mode 100644 index 00000000..d629e2dd --- /dev/null +++ b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + vector minDifference(vector& nums, vector>& queries) { + int maxVal = 0; + for (int x : nums) maxVal = max(maxVal, x); + vector> p(nums.size() + 1, vector(maxVal + 1, 0)); + for (int j = 0; j <= maxVal; j++) p[0][j] = 0; + for (int i = 0; i < nums.size(); i++) { + for (int j = 0; j <= maxVal; j++) { + p[i + 1][j] = p[i][j] + (nums[i] == j ? 1 : 0); + } + } + vector res(queries.size()); + for (int qi = 0; qi < queries.size(); qi++) { + int l = queries[qi][0], r = queries[qi][1]; + vector diff(maxVal + 1, 0); + for (int j = 0; j <= maxVal; j++) diff[j] = p[r + 1][j] - p[l][j]; + int prev = -1; + int best = -1; + for (int j = 0; j <= maxVal; j++) { + if (diff[j] > 0) { + if (prev >= 0) { + if (best == -1 || j - prev < best) best = j - prev; + } + prev = j; + } + } + res[qi] = best; + } + return res; + } +}; diff --git a/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.cs b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.cs new file mode 100644 index 00000000..934bb9ac --- /dev/null +++ b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.cs @@ -0,0 +1,32 @@ +public class Solution { + public int[] MinDifference(int[] nums, int[][] queries) { + int maxVal = 0; + foreach (int x in nums) maxVal = Math.Max(maxVal, x); + int[][] p = new int[nums.Length + 1][]; + for (int i = 0; i <= nums.Length; i++) p[i] = new int[maxVal + 1]; + for (int j = 0; j <= maxVal; j++) p[0][j] = 0; + for (int i = 0; i < nums.Length; i++) { + for (int j = 0; j <= maxVal; j++) { + p[i + 1][j] = p[i][j] + (nums[i] == j ? 1 : 0); + } + } + int[] res = new int[queries.Length]; + for (int qi = 0; qi < queries.Length; qi++) { + int l = queries[qi][0], r = queries[qi][1]; + int[] diff = new int[maxVal + 1]; + for (int j = 0; j <= maxVal; j++) diff[j] = p[r + 1][j] - p[l][j]; + int prev = -1; + int best = -1; + for (int j = 0; j <= maxVal; j++) { + if (diff[j] > 0) { + if (prev >= 0) { + if (best == -1 || j - prev < best) best = j - prev; + } + prev = j; + } + } + res[qi] = best; + } + return res; + } +} diff --git a/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.dart b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.dart new file mode 100644 index 00000000..58aa0288 --- /dev/null +++ b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.dart @@ -0,0 +1,33 @@ +class Solution { + List minDifference(List nums, List> queries) { + int maxVal = 0; + for (int x in nums) { + if (x > maxVal) maxVal = x; + } + List> p = List.generate(nums.length + 1, (_) => List.filled(maxVal + 1, 0)); + for (int j = 0; j <= maxVal; j++) p[0][j] = 0; + for (int i = 0; i < nums.length; i++) { + for (int j = 0; j <= maxVal; j++) { + p[i + 1][j] = p[i][j] + (nums[i] == j ? 1 : 0); + } + } + List res = []; + for (var q in queries) { + int l = q[0], r = q[1]; + List diff = List.filled(maxVal + 1, 0); + for (int j = 0; j <= maxVal; j++) diff[j] = p[r + 1][j] - p[l][j]; + int prev = -1; + int best = -1; + for (int j = 0; j <= maxVal; j++) { + if (diff[j] > 0) { + if (prev >= 0) { + if (best == -1 || j - prev < best) best = j - prev; + } + prev = j; + } + } + res.add(best); + } + return res; + } +} diff --git a/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.go b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.go new file mode 100644 index 00000000..5a7756d5 --- /dev/null +++ b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.go @@ -0,0 +1,46 @@ +func minDifference(nums []int, queries [][]int) []int { + maxVal := 0 + for _, x := range nums { + if x > maxVal { + maxVal = x + } + } + p := make([][]int, len(nums)+1) + for i := range p { + p[i] = make([]int, maxVal+1) + } + for j := 0; j <= maxVal; j++ { + p[0][j] = 0 + } + for i := 0; i < len(nums); i++ { + for j := 0; j <= maxVal; j++ { + add := 0 + if nums[i] == j { + add = 1 + } + p[i+1][j] = p[i][j] + add + } + } + res := make([]int, len(queries)) + for qi, q := range queries { + l, r := q[0], q[1] + diff := make([]int, maxVal+1) + for j := 0; j <= maxVal; j++ { + diff[j] = p[r+1][j] - p[l][j] + } + prev := -1 + best := -1 + for j := 0; j <= maxVal; j++ { + if diff[j] > 0 { + if prev >= 0 { + if best == -1 || j-prev < best { + best = j - prev + } + } + prev = j + } + } + res[qi] = best + } + return res +} diff --git a/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.java b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.java new file mode 100644 index 00000000..2c567372 --- /dev/null +++ b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.java @@ -0,0 +1,31 @@ +class Solution { + public int[] minDifference(int[] nums, int[][] queries) { + int maxVal = 0; + for (int x : nums) maxVal = Math.max(maxVal, x); + int[][] p = new int[nums.length + 1][maxVal + 1]; + for (int i = 0; i <= maxVal; i++) p[0][i] = 0; + for (int i = 0; i < nums.length; i++) { + for (int j = 0; j <= maxVal; j++) { + p[i + 1][j] = p[i][j] + (nums[i] == j ? 1 : 0); + } + } + int[] res = new int[queries.length]; + for (int qi = 0; qi < queries.length; qi++) { + int l = queries[qi][0], r = queries[qi][1]; + int[] diff = new int[maxVal + 1]; + for (int j = 0; j <= maxVal; j++) diff[j] = p[r + 1][j] - p[l][j]; + int prev = -1; + int best = -1; + for (int j = 0; j <= maxVal; j++) { + if (diff[j] > 0) { + if (prev >= 0) { + if (best == -1 || j - prev < best) best = j - prev; + } + prev = j; + } + } + res[qi] = best; + } + return res; + } +} diff --git a/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.kt b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.kt new file mode 100644 index 00000000..063e4513 --- /dev/null +++ b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.kt @@ -0,0 +1,31 @@ +class Solution { + fun minDifference(nums: IntArray, queries: Array): IntArray { + val maxVal = nums.maxOrNull() ?: 0 + val p = Array(nums.size + 1) { IntArray(maxVal + 1) } + for (j in 0..maxVal) p[0][j] = 0 + for (i in nums.indices) { + for (j in 0..maxVal) { + p[i + 1][j] = p[i][j] + if (nums[i] == j) 1 else 0 + } + } + val res = IntArray(queries.size) + for (qi in queries.indices) { + val l = queries[qi][0] + val r = queries[qi][1] + val diff = IntArray(maxVal + 1) + for (j in 0..maxVal) diff[j] = p[r + 1][j] - p[l][j] + var prev = -1 + var best = -1 + for (j in 0..maxVal) { + if (diff[j] > 0) { + if (prev >= 0) { + if (best == -1 || j - prev < best) best = j - prev + } + prev = j + } + } + res[qi] = best + } + return res + } +} diff --git a/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.py b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.py new file mode 100644 index 00000000..b048d18d --- /dev/null +++ b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.py @@ -0,0 +1,27 @@ +from itertools import accumulate, pairwise, starmap +from operator import sub +from typing import List + + +class Solution: + def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]: + a = nums + q = queries + p = [ + *accumulate( + a, + lambda p, v: [z + (v == i) for i, z in enumerate(p)], + initial=[0] * (max(a) + 1), + ) + ] + + return [ + -max( + starmap( + sub, + pairwise(i for i, z in enumerate(map(sub, p[r + 1], p[l])) if z), + ), + default=1, + ) + for l, r in q + ] diff --git a/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.py2 b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.py2 new file mode 100644 index 00000000..567ef627 --- /dev/null +++ b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.py2 @@ -0,0 +1,27 @@ +class Solution(object): + def minDifference(self, nums, queries): + """ + :type nums: List[int] + :type queries: List[List[int]] + :rtype: List[int] + """ + max_val = max(nums) if nums else 0 + p = [[0] * (max_val + 1) for _ in range(len(nums) + 1)] + for j in range(max_val + 1): + p[0][j] = 0 + for i in range(len(nums)): + for j in range(max_val + 1): + p[i + 1][j] = p[i][j] + (1 if nums[i] == j else 0) + res = [] + for l, r in queries: + diff = [p[r + 1][j] - p[l][j] for j in range(max_val + 1)] + prev = -1 + best = -1 + for j in range(max_val + 1): + if diff[j] > 0: + if prev >= 0: + if best == -1 or j - prev < best: + best = j - prev + prev = j + res.append(best) + return res diff --git a/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.rb b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.rb new file mode 100644 index 00000000..57273567 --- /dev/null +++ b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.rb @@ -0,0 +1,29 @@ +# @param {Integer[]} nums +# @param {Integer[][]} queries +# @return {Integer[]} +def min_difference(nums, queries) + max_val = nums.max || 0 + p = Array.new(nums.length + 1) { Array.new(max_val + 1, 0) } + (0..max_val).each { |j| p[0][j] = 0 } + nums.each_with_index do |x, i| + (0..max_val).each do |j| + p[i + 1][j] = p[i][j] + (x == j ? 1 : 0) + end + end + res = [] + queries.each do |l, r| + diff = (0..max_val).map { |j| p[r + 1][j] - p[l][j] } + prev = -1 + best = -1 + (0..max_val).each do |j| + if diff[j] > 0 + if prev >= 0 + best = j - prev if best == -1 || j - prev < best + end + prev = j + end + end + res << best + end + res +end diff --git a/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.rs b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.rs new file mode 100644 index 00000000..5598e20e --- /dev/null +++ b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.rs @@ -0,0 +1,31 @@ +impl Solution { + pub fn min_difference(nums: Vec, queries: Vec>) -> Vec { + let max_val = *nums.iter().max().unwrap_or(&0) as usize; + let mut p = vec![vec![0; max_val + 1]; nums.len() + 1]; + for j in 0..=max_val { p[0][j] = 0; } + for i in 0..nums.len() { + for j in 0..=max_val { + p[i + 1][j] = p[i][j] + if nums[i] as usize == j { 1 } else { 0 }; + } + } + let mut res = Vec::with_capacity(queries.len()); + for q in &queries { + let (l, r) = (q[0] as usize, q[1] as usize); + let mut diff = vec![0; max_val + 1]; + for j in 0..=max_val { diff[j] = p[r + 1][j] - p[l][j]; } + let mut prev = -1i32; + let mut best = -1i32; + for j in 0..=max_val { + if diff[j] > 0 { + if prev >= 0 { + let diff_val = j as i32 - prev; + if best == -1 || diff_val < best { best = diff_val; } + } + prev = j as i32; + } + } + res.push(best); + } + res + } +} diff --git a/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.swift b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.swift new file mode 100644 index 00000000..dc67e29e --- /dev/null +++ b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.swift @@ -0,0 +1,30 @@ +class Solution { + func minDifference(_ nums: [Int], _ queries: [[Int]]) -> [Int] { + let maxVal = nums.max() ?? 0 + var p = Array(repeating: Array(repeating: 0, count: maxVal + 1), count: nums.count + 1) + for j in 0...maxVal { p[0][j] = 0 } + for i in 0.. 0 { + if prev >= 0 { + if best == -1 || j - prev < best { best = j - prev } + } + prev = j + } + } + res.append(best) + } + return res + } +} diff --git a/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.ts b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.ts new file mode 100644 index 00000000..66c7dae0 --- /dev/null +++ b/tests/1501-2000/1906. minimum-absolute-difference-queries/sol.ts @@ -0,0 +1,29 @@ +function minDifference(nums: number[], queries: number[][]): number[] { + const maxVal = Math.max(...nums); + const p: number[][] = Array.from({ length: nums.length + 1 }, () => + Array(maxVal + 1).fill(0), + ); + for (let j = 0; j <= maxVal; j++) p[0][j] = 0; + for (let i = 0; i < nums.length; i++) { + for (let j = 0; j <= maxVal; j++) { + p[i + 1][j] = p[i][j] + (nums[i] === j ? 1 : 0); + } + } + const res: number[] = []; + for (const [l, r] of queries) { + const diff: number[] = Array(maxVal + 1).fill(0); + for (let j = 0; j <= maxVal; j++) diff[j] = p[r + 1][j] - p[l][j]; + let prev = -1; + let best = -1; + for (let j = 0; j <= maxVal; j++) { + if (diff[j] > 0) { + if (prev >= 0) { + if (best === -1 || j - prev < best) best = j - prev; + } + prev = j; + } + } + res.push(best); + } + return res; +} diff --git a/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/manifest.yaml b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/manifest.yaml new file mode 100644 index 00000000..1ae8026c --- /dev/null +++ b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/manifest.yaml @@ -0,0 +1,350 @@ +Exit code: 0 +Wall time: 0.2 seconds +Output: +entry: + id: 1909 + title: remove-one-element-to-make-the-array-strictly-increasing + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().canBeIncreasing({nums})" + rust: "Solution::can_be_increasing({nums})" + python3: "Solution().canBeIncreasing({nums})" + python2: "Solution().canBeIncreasing({nums})" + ruby: "can_be_increasing({nums})" + java: "new Solution().canBeIncreasing({nums})" + csharp: "new Solution().CanBeIncreasing({nums})" + kotlin: "Solution().canBeIncreasing({nums})" + go: "canBeIncreasing({nums})" + dart: "Solution().canBeIncreasing({nums})" + swift: "Solution().canBeIncreasing({nums})" + typescript: "canBeIncreasing({nums})" + +judge: + type: exact + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().canBeIncreasing(nums, {result})" + checker: | + class Checker: + def canBeIncreasing(self, nums, result): + if not isinstance(result, bool): + return False + for skip in range(len(nums)): + previous = None + valid = True + for index, value in enumerate(nums): + if index == skip: + continue + if previous is not None and previous >= value: + valid = False + break + previous = value + if valid: + return result is True + return result is False + +seed: 1909 + +tests: + - name: example-remove-middle + in: + nums: [1, 2, 10, 5, 7] + out: true + judge: + type: exact + - name: example-impossible + in: + nums: [2, 3, 1, 2] + out: false + judge: + type: exact + - name: example-duplicates + in: + nums: [1, 1, 1] + out: false + judge: + type: exact + - name: minimum-length-increasing + in: + nums: [1, 2] + out: true + judge: + type: exact + - name: minimum-length-equal + in: + nums: [7, 7] + out: true + judge: + type: exact + - name: minimum-length-decreasing + in: + nums: [2, 1] + out: true + judge: + type: exact + - name: already-increasing + in: + nums: [1, 3, 5, 7, 9] + out: true + judge: + type: exact + - name: remove-first + in: + nums: [5, 1, 2, 3, 4] + out: true + judge: + type: exact + - name: remove-last + in: + nums: [1, 2, 3, 4, 2] + out: true + judge: + type: exact + - name: remove-left-of-inversion + in: + nums: [1, 2, 3, 2, 4, 5] + out: true + judge: + type: exact + - name: remove-right-of-inversion + in: + nums: [1, 2, 4, 3, 5, 6] + out: true + judge: + type: exact + - name: equal-adjacent-middle + in: + nums: [1, 2, 3, 3, 4] + out: true + judge: + type: exact + - name: equal-adjacent-block + in: + nums: [1, 2, 3, 3, 3, 4] + out: false + judge: + type: exact + - name: two-inversions + in: + nums: [1, 5, 3, 4, 2, 6] + out: false + judge: + type: exact + - name: descending-four + in: + nums: [4, 3, 2, 1] + out: false + judge: + type: exact + - name: descending-three + in: + nums: [3, 2, 1] + out: false + judge: + type: exact + - name: large-gap-valid + in: + nums: [1, 1000, 2, 3] + out: true + judge: + type: exact + - name: large-gap-invalid + in: + nums: [1, 999, 2, 3, 4, 5] + out: true + judge: + type: exact + - name: prefix-conflict + in: + nums: [1, 4, 2, 3, 0] + out: false + judge: + type: exact + - name: suffix-conflict + in: + nums: [1, 0, 2, 4, 3] + out: false + judge: + type: exact + - name: inversion-at-start + in: + nums: [10, 1, 2, 3, 4] + out: true + judge: + type: exact + - name: inversion-at-end + in: + nums: [1, 2, 3, 4, 1] + out: true + judge: + type: exact + - name: duplicate-at-start + in: + nums: [2, 2, 3, 4] + out: true + judge: + type: exact + - name: duplicate-at-end + in: + nums: [1, 2, 3, 3] + out: true + judge: + type: exact + - name: duplicate-with-crossing + in: + nums: [1, 2, 2, 1, 3] + out: false + judge: + type: exact + - name: one-drop-valid + in: + nums: [1, 2, 8, 4, 5, 6, 7] + out: true + judge: + type: exact + - name: one-drop-too-deep + in: + nums: [1, 2, 8, 4, 3, 6, 7] + out: false + judge: + type: exact + - name: remove-high-peak + in: + nums: [1, 2, 1000, 3, 4, 5] + out: true + judge: + type: exact + - name: remove-low-valley + in: + nums: [1, 2, 0, 3, 4, 5] + out: true + judge: + type: exact + - name: peak-cannot-remove-left + in: + nums: [1, 10, 2, 3, 2] + out: false + judge: + type: exact + - name: peak-cannot-remove-right + in: + nums: [1, 2, 4, 3, 2] + out: false + judge: + type: exact + - name: alternating + in: + nums: [1, 3, 2, 4, 3, 5] + out: false + judge: + type: exact + - name: repeated-low-values + in: + nums: [1, 2, 1, 1, 3] + out: false + judge: + type: exact + - name: all-minimum + in: + nums: [1, 1, 1, 1, 1] + out: false + judge: + type: exact + - name: all-maximum + in: + nums: [1000, 1000, 1000, 1000] + out: false + judge: + type: exact + - name: narrow-valid + in: + nums: [1, 2, 3, 2, 3, 4] + out: false + judge: + type: exact + - name: valid-near-upper-bound + in: + nums: [997, 998, 1000, 999] + out: true + judge: + type: exact + - name: invalid-near-upper-bound + in: + nums: [996, 1000, 998, 999, 997] + out: false + judge: + type: exact + - name: generated-uniform-a + in: + nums: + gen: array + len: 1000 + of: + gen: int + min: 1 + max: 1000 + elemType: int + judge: + type: exact + seed: 1909001 + - name: generated-uniform-b + in: + nums: + gen: array + len: 997 + of: + gen: int + min: 1 + max: 1000 + elemType: int + judge: + type: exact + seed: 1909002 + - name: generated-short-random + in: + nums: + gen: array + len: 250 + of: + gen: int + min: 1 + max: 1000 + elemType: int + judge: + type: exact + seed: 1909003 + - name: generated-medium-random + in: + nums: + gen: array + len: 750 + of: + gen: int + min: 1 + max: 1000 + elemType: int + judge: + type: exact + seed: 1909004 + - name: generated-boundary-values + in: + nums: + gen: array + len: 1000 + of: + gen: int + min: 1 + max: 1000 + elemType: int + judge: + type: exact + seed: 1909005 diff --git a/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.cpp b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.cpp new file mode 100644 index 00000000..6b795a10 --- /dev/null +++ b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + bool canBeIncreasing(vector& nums) { + int n = nums.size(); + int idx = -1; + + for (int i = 0; i < n - 1; i++) { + if (nums[i] >= nums[i + 1]) { + idx = i; + break; + } + } + + bool flag = true; + for (int i = idx + 1; i < n - 1; i++) { + if (nums[i] >= nums[i + 1]) { + flag = false; + break; + } + } + + if ((idx == 0 || idx == n - 1) && flag) return true; + if (idx - 1 >= 0 && idx + 1 < n && nums[idx - 1] < nums[idx + 1] && flag) return true; + + for (int i = n - 1; i > 0; i--) { + if (nums[i] <= nums[i - 1]) { + idx = i; + break; + } + } + + flag = true; + for (int i = idx - 1; i > 0; i--) { + if (nums[i] <= nums[i - 1]) { + flag = false; + break; + } + } + + if ((idx == 0 || idx == n - 1) && flag) return true; + if (idx - 1 >= 0 && idx + 1 < n && nums[idx - 1] >= nums[idx + 1]) return false; + return flag; + } +}; diff --git a/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.cs b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.cs new file mode 100644 index 00000000..768cc353 --- /dev/null +++ b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.cs @@ -0,0 +1,43 @@ +public class Solution { + public bool CanBeIncreasing(int[] nums) { + int n = nums.Length; + int idx = -1; + + for (int i = 0; i < n - 1; i++) { + if (nums[i] >= nums[i + 1]) { + idx = i; + break; + } + } + + bool flag = true; + for (int i = idx + 1; i < n - 1; i++) { + if (nums[i] >= nums[i + 1]) { + flag = false; + break; + } + } + + if ((idx == 0 || idx == n - 1) && flag) return true; + if (idx - 1 >= 0 && idx + 1 < n && nums[idx - 1] < nums[idx + 1] && flag) return true; + + for (int i = n - 1; i > 0; i--) { + if (nums[i] <= nums[i - 1]) { + idx = i; + break; + } + } + + flag = true; + for (int i = idx - 1; i > 0; i--) { + if (nums[i] <= nums[i - 1]) { + flag = false; + break; + } + } + + if ((idx == 0 || idx == n - 1) && flag) return true; + if (idx - 1 >= 0 && idx + 1 < n && nums[idx - 1] >= nums[idx + 1]) return false; + return flag; + } +} diff --git a/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.dart b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.dart new file mode 100644 index 00000000..be044ac4 --- /dev/null +++ b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.dart @@ -0,0 +1,43 @@ +class Solution { + bool canBeIncreasing(List nums) { + int n = nums.length; + int idx = -1; + + for (int i = 0; i < n - 1; i++) { + if (nums[i] >= nums[i + 1]) { + idx = i; + break; + } + } + + bool flag = true; + for (int i = idx + 1; i < n - 1; i++) { + if (nums[i] >= nums[i + 1]) { + flag = false; + break; + } + } + + if ((idx == 0 || idx == n - 1) && flag) return true; + if (idx - 1 >= 0 && idx + 1 < n && nums[idx - 1] < nums[idx + 1] && flag) return true; + + for (int i = n - 1; i > 0; i--) { + if (nums[i] <= nums[i - 1]) { + idx = i; + break; + } + } + + flag = true; + for (int i = idx - 1; i > 0; i--) { + if (nums[i] <= nums[i - 1]) { + flag = false; + break; + } + } + + if ((idx == 0 || idx == n - 1) && flag) return true; + if (idx - 1 >= 0 && idx + 1 < n && nums[idx - 1] >= nums[idx + 1]) return false; + return flag; + } +} diff --git a/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.go b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.go new file mode 100644 index 00000000..9c370c5b --- /dev/null +++ b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.go @@ -0,0 +1,49 @@ +func canBeIncreasing(nums []int) bool { + n := len(nums) + idx := -1 + + for i := 0; i < n-1; i++ { + if nums[i] >= nums[i+1] { + idx = i + break + } + } + + flag := true + for i := idx + 1; i < n-1; i++ { + if nums[i] >= nums[i+1] { + flag = false + break + } + } + + if (idx == 0 || idx == n-1) && flag { + return true + } + if idx-1 >= 0 && idx+1 < n && nums[idx-1] < nums[idx+1] && flag { + return true + } + + for i := n - 1; i > 0; i-- { + if nums[i] <= nums[i-1] { + idx = i + break + } + } + + flag = true + for i := idx - 1; i > 0; i-- { + if nums[i] <= nums[i-1] { + flag = false + break + } + } + + if (idx == 0 || idx == n-1) && flag { + return true + } + if idx-1 >= 0 && idx+1 < n && nums[idx-1] >= nums[idx+1] { + return false + } + return flag +} diff --git a/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.java b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.java new file mode 100644 index 00000000..acb44deb --- /dev/null +++ b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.java @@ -0,0 +1,43 @@ +class Solution { + public boolean canBeIncreasing(int[] nums) { + int n = nums.length; + int idx = -1; + + for (int i = 0; i < n - 1; i++) { + if (nums[i] >= nums[i + 1]) { + idx = i; + break; + } + } + + boolean flag = true; + for (int i = idx + 1; i < n - 1; i++) { + if (nums[i] >= nums[i + 1]) { + flag = false; + break; + } + } + + if ((idx == 0 || idx == n - 1) && flag) return true; + if (idx - 1 >= 0 && idx + 1 < n && nums[idx - 1] < nums[idx + 1] && flag) return true; + + for (int i = n - 1; i > 0; i--) { + if (nums[i] <= nums[i - 1]) { + idx = i; + break; + } + } + + flag = true; + for (int i = idx - 1; i > 0; i--) { + if (nums[i] <= nums[i - 1]) { + flag = false; + break; + } + } + + if ((idx == 0 || idx == n - 1) && flag) return true; + if (idx - 1 >= 0 && idx + 1 < n && nums[idx - 1] >= nums[idx + 1]) return false; + return flag; + } +} diff --git a/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.kt b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.kt new file mode 100644 index 00000000..f753050d --- /dev/null +++ b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.kt @@ -0,0 +1,43 @@ +class Solution { + fun canBeIncreasing(nums: IntArray): Boolean { + val n = nums.size + var idx = -1 + + for (i in 0 until n - 1) { + if (nums[i] >= nums[i + 1]) { + idx = i + break + } + } + + var flag = true + for (i in idx + 1 until n - 1) { + if (nums[i] >= nums[i + 1]) { + flag = false + break + } + } + + if ((idx == 0 || idx == n - 1) && flag) return true + if (idx - 1 >= 0 && idx + 1 < n && nums[idx - 1] < nums[idx + 1] && flag) return true + + for (i in n - 1 downTo 1) { + if (nums[i] <= nums[i - 1]) { + idx = i + break + } + } + + flag = true + for (i in idx - 1 downTo 1) { + if (nums[i] <= nums[i - 1]) { + flag = false + break + } + } + + if ((idx == 0 || idx == n - 1) && flag) return true + if (idx - 1 >= 0 && idx + 1 < n && nums[idx - 1] >= nums[idx + 1]) return false + return flag + } +} diff --git a/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.py b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.py new file mode 100644 index 00000000..eec68a33 --- /dev/null +++ b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.py @@ -0,0 +1,39 @@ +class Solution: + def canBeIncreasing(self, nums): + n = len(nums) + idx = -1 + + # Find first distortion + for i in range(n - 1): + if nums[i] >= nums[i + 1]: + idx = i + break + + flag = True + for i in range(idx + 1, n - 1): + if nums[i] >= nums[i + 1]: + flag = False + break + + if (idx == 0 or idx == n - 1) and flag: + return True + if idx - 1 >= 0 and idx + 1 < n and nums[idx - 1] < nums[idx + 1] and flag: + return True + + # Check from the end + for i in range(n - 1, 0, -1): + if nums[i] <= nums[i - 1]: + idx = i + break + + flag = True + for i in range(idx - 1, 0, -1): + if nums[i] <= nums[i - 1]: + flag = False + break + + if (idx == 0 or idx == n - 1) and flag: + return True + if idx - 1 >= 0 and idx + 1 < n and nums[idx - 1] >= nums[idx + 1]: + return False + return flag diff --git a/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.py2 b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.py2 new file mode 100644 index 00000000..1efb04f5 --- /dev/null +++ b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.py2 @@ -0,0 +1,43 @@ +class Solution(object): + def canBeIncreasing(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + n = len(nums) + idx = -1 + + # Find first distortion + for i in range(n - 1): + if nums[i] >= nums[i + 1]: + idx = i + break + + flag = True + for i in range(idx + 1, n - 1): + if nums[i] >= nums[i + 1]: + flag = False + break + + if (idx == 0 or idx == n - 1) and flag: + return True + if idx - 1 >= 0 and idx + 1 < n and nums[idx - 1] < nums[idx + 1] and flag: + return True + + # Check from the end + for i in range(n - 1, 0, -1): + if nums[i] <= nums[i - 1]: + idx = i + break + + flag = True + for i in range(idx - 1, 0, -1): + if nums[i] <= nums[i - 1]: + flag = False + break + + if (idx == 0 or idx == n - 1) and flag: + return True + if idx - 1 >= 0 and idx + 1 < n and nums[idx - 1] >= nums[idx + 1]: + return False + return flag diff --git a/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.rb b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.rb new file mode 100644 index 00000000..cc57771b --- /dev/null +++ b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.rb @@ -0,0 +1,45 @@ +# @param {Integer[]} nums +# @return {Boolean} +def can_be_increasing(nums) + n = nums.length + idx = -1 + + # Find first distortion + (0...n-1).each do |i| + if nums[i] >= nums[i + 1] + idx = i + break + end + end + + flag = true + ((idx + 1)...(n - 1)).each do |i| + if nums[i] >= nums[i + 1] + flag = false + break + end + end + + return true if (idx == 0 || idx == n - 1) && flag + return true if idx - 1 >= 0 && idx + 1 < n && nums[idx - 1] < nums[idx + 1] && flag + + # Check from the end + (n - 1).downto(1) do |i| + if nums[i] <= nums[i - 1] + idx = i + break + end + end + + flag = true + (idx - 1).downto(1) do |i| + if nums[i] <= nums[i - 1] + flag = false + break + end + end + + return true if (idx == 0 || idx == n - 1) && flag + return false if idx - 1 >= 0 && idx + 1 < n && nums[idx - 1] >= nums[idx + 1] + flag +end diff --git a/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.rs b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.rs new file mode 100644 index 00000000..1d3e6e6f --- /dev/null +++ b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.rs @@ -0,0 +1,55 @@ +impl Solution { + pub fn can_be_increasing(nums: Vec) -> bool { + let n = nums.len(); + if n <= 2 { return true; } + let mut removed = false; + let mut prev = nums[0]; + for i in 1..n { + if prev >= nums[i] { + if removed { return false; } + removed = true; + if i == 1 || nums[i - 2] < nums[i] { prev = nums[i]; } + } else { prev = nums[i]; } + } + return true; + /* + let mut idx = -1i32; + + for i in 0..n - 1 { + if nums[i] >= nums[i + 1] { + idx = i as i32; + break; + } + } + + let mut flag = true; + for i in (idx + 1) as usize..n - 1 { + if nums[i] >= nums[i + 1] { + flag = false; + break; + } + } + + if (idx == 0 || idx as usize == n - 1) && flag { return true; } + if idx - 1 >= 0 && idx + 1 < n as i32 && nums[(idx - 1) as usize] < nums[(idx + 1) as usize] && flag { return true; } + + for i in (0..n - 1).rev() { + if nums[i + 1] <= nums[i] { + idx = i as i32; + break; + } + } + + flag = true; + for i in (0..idx as usize - 1).rev() { + if nums[i + 1] <= nums[i] { + flag = false; + break; + } + } + + if (idx == 0 || idx as usize == n - 1) && flag { return true; } + if idx - 1 >= 0 && idx + 1 < n as i32 && nums[(idx - 1) as usize] >= nums[(idx + 1) as usize] { return false; } + return flag; */ + } +} diff --git a/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.swift b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.swift new file mode 100644 index 00000000..b85eecf9 --- /dev/null +++ b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.swift @@ -0,0 +1,43 @@ +class Solution { + func canBeIncreasing(_ nums: [Int]) -> Bool { + let n = nums.count + var idx = -1 + + for i in 0..<(n - 1) { + if nums[i] >= nums[i + 1] { + idx = i + break + } + } + + var flag = true + for i in (idx + 1)..<(n - 1) { + if nums[i] >= nums[i + 1] { + flag = false + break + } + } + + if (idx == 0 || idx == n - 1) && flag { return true } + if idx - 1 >= 0 && idx + 1 < n && nums[idx - 1] < nums[idx + 1] && flag { return true } + + for i in stride(from: n - 1, through: 1, by: -1) { + if nums[i] <= nums[i - 1] { + idx = i + break + } + } + + flag = true + for i in stride(from: idx - 1, through: 1, by: -1) { + if nums[i] <= nums[i - 1] { + flag = false + break + } + } + + if (idx == 0 || idx == n - 1) && flag { return true } + if idx - 1 >= 0 && idx + 1 < n && nums[idx - 1] >= nums[idx + 1] { return false } + return flag + } +} diff --git a/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.ts b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.ts new file mode 100644 index 00000000..2852610b --- /dev/null +++ b/tests/1501-2000/1909. remove-one-element-to-make-the-array-strictly-increasing/sol.ts @@ -0,0 +1,43 @@ +function canBeIncreasing(nums: number[]): boolean { + const n = nums.length; + let idx = -1; + + for (let i = 0; i < n - 1; i++) { + if (nums[i] >= nums[i + 1]) { + idx = i; + break; + } + } + + let flag = true; + for (let i = idx + 1; i < n - 1; i++) { + if (nums[i] >= nums[i + 1]) { + flag = false; + break; + } + } + + if ((idx === 0 || idx === n - 1) && flag) return true; + if (idx - 1 >= 0 && idx + 1 < n && nums[idx - 1] < nums[idx + 1] && flag) + return true; + + for (let i = n - 1; i > 0; i--) { + if (nums[i] <= nums[i - 1]) { + idx = i; + break; + } + } + + flag = true; + for (let i = idx - 1; i > 0; i--) { + if (nums[i] <= nums[i - 1]) { + flag = false; + break; + } + } + + if ((idx === 0 || idx === n - 1) && flag) return true; + if (idx - 1 >= 0 && idx + 1 < n && nums[idx - 1] >= nums[idx + 1]) + return false; + return flag; +} diff --git a/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/manifest.yaml b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/manifest.yaml new file mode 100644 index 00000000..b7eb49cf --- /dev/null +++ b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/manifest.yaml @@ -0,0 +1,256 @@ +entry: + id: 1910 + title: remove-all-occurrences-of-a-substring + params: + s: + type: string + part: + type: string + call: + cpp: "Solution().removeOccurrences({s}, {part})" + rust: "Solution::remove_occurrences({s}, {part})" + python3: "Solution().removeOccurrences({s}, {part})" + python2: "Solution().removeOccurrences({s}, {part})" + ruby: "remove_occurrences({s}, {part})" + java: "new Solution().removeOccurrences({s}, {part})" + csharp: "new Solution().RemoveOccurrences({s}, {part})" + kotlin: "Solution().removeOccurrences({s}, {part})" + go: "removeOccurrences({s}, {part})" + dart: "Solution().removeOccurrences({s}, {part})" + swift: "Solution().removeOccurrences({s}, {part})" + typescript: "removeOccurrences({s}, {part})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().removeOccurrences(s, part, {result})" + checker: | + class Checker: + def removeOccurrences(self, s, part, result): + stack = [] + m = len(part) + for ch in s: + stack.append(ch) + if len(stack) >= m and ''.join(stack[-m:]) == part: + del stack[-m:] + return result == ''.join(stack) +seed: 1910 +tests: + - name: example-one + in: + s: "daabcbaabcbc" + part: "abc" + out: "dab" + - name: example-two + in: + s: "axxxxyyyyb" + part: "xy" + out: "ab" + - name: no-occurrence + in: + s: "hello" + part: "z" + out: "hello" + - name: exact-match + in: + s: "abc" + part: "abc" + out: "" + - name: part-longer + in: + s: "ab" + part: "abc" + out: "ab" + - name: repeated-single + in: + s: "aaaaaa" + part: "a" + out: "" + - name: repeated-pair + in: + s: "abababab" + part: "ab" + out: "" + - name: overlap-aba + in: + s: "ababa" + part: "aba" + out: "ba" + - name: overlap-aa + in: + s: "aaaaa" + part: "aa" + out: "a" + - name: cascade-after-removal + in: + s: "aabcbc" + part: "abc" + out: "" + - name: cascade-prefix + in: + s: "abcab" + part: "cab" + out: "ab" + - name: cascade-suffix + in: + s: "bcabc" + part: "bca" + out: "bc" + - name: repeated-word + in: + s: "foobarfoobar" + part: "foobar" + out: "" + - name: internal-occurrence + in: + s: "mississippi" + part: "issi" + out: "mssippi" + - name: repeated-letters-part + in: + s: "baaaab" + part: "aaa" + out: "bab" + - name: alternating-no-match + in: + s: "abababa" + part: "abaaba" + out: "abababa" + - name: removal-joins-match + in: + s: "xabcabcx" + part: "abc" + out: "xx" + - name: removal-joins-part + in: + s: "abcaabc" + part: "abc" + out: "a" + - name: one-character-suffix + in: + s: "zzaz" + part: "z" + out: "a" + - name: one-character-middle + in: + s: "banana" + part: "n" + out: "baaa" + - name: all-same-long-part + in: + s: "aaaaaaaa" + part: "aaaa" + out: "" + - name: all-same-nondivisible + in: + s: "aaaaaaaaa" + part: "aaaa" + out: "a" + - name: prefix-preserved + in: + s: "zzabcabc" + part: "abc" + out: "zz" + - name: suffix-preserved + in: + s: "abcabczz" + part: "abc" + out: "zz" + - name: case-lowercase-only + in: + s: "aAaAa" + part: "Aa" + out: "a" + - name: long-part-single + in: + s: "abcdefghijklmnopqrst" + part: "klmnop" + out: "abcdefghijqrst" + - name: near-match + in: + s: "abacaba" + part: "ababa" + out: "abacaba" + - name: nested-looking + in: + s: "abcxbcabc" + part: "bc" + out: "axa" + - name: chain-of-three + in: + s: "cabacaba" + part: "aba" + out: "cc" + - name: empty-result-cascade + in: + s: "aabbccabcc" + part: "abcc" + out: "aabbcc" + - name: stress-repeated + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + part: "aaaaa" + out: "" + - name: stress-pattern + in: + s: "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc" + part: "abcabc" + out: "" + - name: stress-near-matches + in: + s: "abababababababababababababababababababababababababababababab" + part: "ababa" + out: "bbbbbbbbbb" + - name: generated-short + in: + s: + gen: "str" + len: 40 + alphabet: "abc" + part: + gen: "str" + len: 4 + alphabet: "abc" + - name: generated-medium + in: + s: + gen: "str" + len: 250 + alphabet: "abcd" + part: + gen: "str" + len: 7 + alphabet: "abcd" + - name: generated-large + in: + s: + gen: "str" + len: 1000 + alphabet: "ab" + part: + gen: "str" + len: 31 + alphabet: "ab" + - name: generated-large-small-part + in: + s: + gen: "str" + len: 1000 + alphabet: "abc" + part: + gen: "str" + len: 2 + alphabet: "abc" + - name: generated-max-part + in: + s: + gen: "str" + len: 1000 + alphabet: "abcde" + part: + gen: "str" + len: 1000 + alphabet: "abcde" diff --git a/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.cpp b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.cpp new file mode 100644 index 00000000..1012824b --- /dev/null +++ b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + string removeOccurrences(string s, string part) { + string result_stack; + int target_length = part.length(); + char target_end_char = part.back(); + + for (char current_char : s) { + result_stack.push_back(current_char); + + if (current_char == target_end_char && result_stack.length() >= target_length) { + if (result_stack.substr(result_stack.length() - target_length) == part) { + result_stack.erase(result_stack.length() - target_length, target_length); + } + } + } + + return result_stack; + } +}; diff --git a/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.cs b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.cs new file mode 100644 index 00000000..a251c25d --- /dev/null +++ b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.cs @@ -0,0 +1,19 @@ +public class Solution { + public string RemoveOccurrences(string s, string part) { + var result_stack = new System.Text.StringBuilder(); + int target_length = part.Length; + char target_end_char = part[target_length - 1]; + + foreach (char current_char in s) { + result_stack.Append(current_char); + + if (current_char == target_end_char && result_stack.Length >= target_length) { + if (result_stack.ToString(result_stack.Length - target_length, target_length) == part) { + result_stack.Length -= target_length; + } + } + } + + return result_stack.ToString(); + } +} diff --git a/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.dart b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.dart new file mode 100644 index 00000000..dd8cbccb --- /dev/null +++ b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.dart @@ -0,0 +1,19 @@ +class Solution { + String removeOccurrences(String s, String part) { + List result_stack = []; + int target_length = part.length; + String target_end_char = part[target_length - 1]; + + for (String current_char in s.split('')) { + result_stack.add(current_char); + + if (current_char == target_end_char && result_stack.length >= target_length) { + if (result_stack.sublist(result_stack.length - target_length).join() == part) { + result_stack.removeRange(result_stack.length - target_length, result_stack.length); + } + } + } + + return result_stack.join(); + } +} diff --git a/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.go b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.go new file mode 100644 index 00000000..93e9e995 --- /dev/null +++ b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.go @@ -0,0 +1,17 @@ +func removeOccurrences(s string, part string) string { + result_stack := []rune{} + target_length := len(part) + target_end_char := rune(part[target_length-1]) + + for _, current_char := range s { + result_stack = append(result_stack, current_char) + + if current_char == target_end_char && len(result_stack) >= target_length { + if string(result_stack[len(result_stack)-target_length:]) == part { + result_stack = result_stack[:len(result_stack)-target_length] + } + } + } + + return string(result_stack) +} diff --git a/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.java b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.java new file mode 100644 index 00000000..17ff5a2d --- /dev/null +++ b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.java @@ -0,0 +1,19 @@ +class Solution { + public String removeOccurrences(String s, String part) { + StringBuilder result_stack = new StringBuilder(); + int target_length = part.length(); + char target_end_char = part.charAt(target_length - 1); + + for (char current_char : s.toCharArray()) { + result_stack.append(current_char); + + if (current_char == target_end_char && result_stack.length() >= target_length) { + if (result_stack.substring(result_stack.length() - target_length).equals(part)) { + result_stack.delete(result_stack.length() - target_length, result_stack.length()); + } + } + } + + return result_stack.toString(); + } +} diff --git a/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.kt b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.kt new file mode 100644 index 00000000..6c74b954 --- /dev/null +++ b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.kt @@ -0,0 +1,19 @@ +class Solution { + fun removeOccurrences(s: String, part: String): String { + val result_stack = StringBuilder() + val target_length = part.length + val target_end_char = part.last() + + for (current_char in s) { + result_stack.append(current_char) + + if (current_char == target_end_char && result_stack.length >= target_length) { + if (result_stack.substring(result_stack.length - target_length) == part) { + result_stack.delete(result_stack.length - target_length, result_stack.length) + } + } + } + + return result_stack.toString() + } +} diff --git a/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.py b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.py new file mode 100644 index 00000000..6d07a43f --- /dev/null +++ b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.py @@ -0,0 +1,14 @@ +class Solution: + def removeOccurrences(self, s: str, part: str) -> str: + result_stack = [] + target_length = len(part) + target_end_char = part[-1] + + for current_char in s: + result_stack.append(current_char) + + if current_char == target_end_char and len(result_stack) >= target_length: + if "".join(result_stack[-target_length:]) == part: + del result_stack[-target_length:] + + return "".join(result_stack) diff --git a/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.py2 b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.py2 new file mode 100644 index 00000000..d1b3df49 --- /dev/null +++ b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.py2 @@ -0,0 +1,19 @@ +class Solution(object): + def removeOccurrences(self, s, part): + """ + :type s: str + :type part: str + :rtype: str + """ + result_stack = [] + target_length = len(part) + target_end_char = part[-1] + + for current_char in s: + result_stack.append(current_char) + + if current_char == target_end_char and len(result_stack) >= target_length: + if "".join(result_stack[-target_length:]) == part: + del result_stack[-target_length:] + + return "".join(result_stack) diff --git a/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.rb b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.rb new file mode 100644 index 00000000..ef25ca68 --- /dev/null +++ b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.rb @@ -0,0 +1,20 @@ +# @param {String} s +# @param {String} part +# @return {String} +def remove_occurrences(s, part) + result_stack = [] + target_length = part.length + target_end_char = part[-1] + + s.each_char do |current_char| + result_stack << current_char + + if current_char == target_end_char && result_stack.length >= target_length + if result_stack[-target_length..-1].join == part + result_stack.slice!(-target_length..-1) + end + end + end + + result_stack.join +end diff --git a/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.rs b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.rs new file mode 100644 index 00000000..8cf3131c --- /dev/null +++ b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn remove_occurrences(s: String, part: String) -> String { + let mut result_stack: Vec = Vec::new(); + let target_length = part.len(); + let target_end_char = part.chars().last().unwrap(); + + for current_char in s.chars() { + result_stack.push(current_char); + + if current_char == target_end_char && result_stack.len() >= target_length { + let start = result_stack.len() - target_length; + if result_stack[start..].iter().collect::() == part { + result_stack.truncate(start); + } + } + } + + result_stack.into_iter().collect() + } +} diff --git a/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.swift b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.swift new file mode 100644 index 00000000..b7896501 --- /dev/null +++ b/tests/1501-2000/1910. remove-all-occurrences-of-a-substring/sol.swift @@ -0,0 +1,19 @@ +class Solution { + func removeOccurrences(_ s: String, _ part: String) -> String { + var result_stack: [Character] = [] + let target_length = part.count + let target_end_char = part.last! + + for current_char in s { + result_stack.append(current_char) + + if current_char == target_end_char && result_stack.count >= target_length { + if String(result_stack[(result_stack.count - target_length)..= target_length + ) { + if ( + result_stack.slice(result_stack.length - target_length).join("") === + part + ) { + result_stack.splice(result_stack.length - target_length, target_length); + } + } + } + + return result_stack.join(""); +} diff --git a/tests/1501-2000/1911. maximum-alternating-subsequence-sum/manifest.yaml b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/manifest.yaml new file mode 100644 index 00000000..43a759a5 --- /dev/null +++ b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/manifest.yaml @@ -0,0 +1,262 @@ +entry: + id: 1911 + title: "maximum-alternating-subsequence-sum" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().maxAlternatingSum({nums})" + rust: "Solution::max_alternating_sum({nums})" + python3: "Solution().maxAlternatingSum({nums})" + python2: "Solution().maxAlternatingSum({nums})" + ruby: "max_alternating_sum({nums})" + java: "new Solution().maxAlternatingSum({nums})" + csharp: "new Solution().MaxAlternatingSum({nums})" + kotlin: "Solution().maxAlternatingSum({nums})" + go: "maxAlternatingSum({nums})" + dart: "Solution().maxAlternatingSum({nums})" + swift: "Solution().maxAlternatingSum({nums})" + typescript: "maxAlternatingSum({nums})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().maxAlternatingSum(nums, {result})" + checker: | + class Checker: + def maxAlternatingSum(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + add = 0 + subtract = 0 + for value in nums: + add, subtract = max(add, subtract + value), max(subtract, add - value) + return result == add + +seed: 1911 + +tests: + - name: "example_one" + in: + nums: [4, 2, 5, 3] + out: 7 + - name: "example_two" + in: + nums: [5, 6, 7, 8] + out: 8 + - name: "example_three" + in: + nums: [6, 2, 1, 2, 4, 5] + out: 10 + - name: "single_minimum" + in: + nums: [1] + out: 1 + - name: "single_maximum" + in: + nums: [100000] + out: 100000 + - name: "two_increasing" + in: + nums: [1, 2] + out: 2 + - name: "two_decreasing" + in: + nums: [2, 1] + out: 2 + - name: "equal_pair" + in: + nums: [7, 7] + out: 7 + - name: "three_increasing" + in: + nums: [1, 2, 3] + out: 3 + - name: "three_decreasing" + in: + nums: [9, 5, 1] + out: 9 + - name: "alternating_peaks" + in: + nums: [10, 1, 10, 1, 10] + out: 28 + - name: "all_equal" + in: + nums: [13, 13, 13, 13, 13, 13] + out: 13 + - name: "strictly_increasing" + in: + nums: [1, 2, 3, 4, 5, 6, 7] + out: 7 + - name: "strictly_decreasing" + in: + nums: [20, 18, 16, 14, 12, 10] + out: 20 + - name: "small_peak_valley" + in: + nums: [3, 1, 4] + out: 6 + - name: "skip_negative_effect" + in: + nums: [8, 9, 2, 6] + out: 13 + - name: "late_peak" + in: + nums: [1, 1, 1, 100] + out: 100 + - name: "early_pair_then_peak" + in: + nums: [9, 1, 2, 20] + out: 28 + - name: "many_small_values" + in: + nums: [2, 1, 2, 1, 2, 1, 2, 1] + out: 5 + - name: "large_alternating" + in: + nums: [100000, 1, 99999, 2, 99998, 3] + out: 299994 + - name: "large_equal_values" + in: + nums: [100000, 100000, 100000, 100000] + out: 100000 + - name: "interleaved_choices" + in: + nums: [12, 5, 8, 20, 3, 15] + out: 39 + - name: "two_local_peaks" + in: + nums: [4, 3, 8, 2, 7] + out: 14 + - name: "best_single_late" + in: + nums: [2, 3, 4, 5, 90, 1] + out: 90 + - name: "best_pair_late" + in: + nums: [2, 1, 40, 3] + out: 41 + - name: "short_wave" + in: + nums: [5, 1, 4, 1, 3] + out: 10 + - name: "long_wave" + in: + nums: [9, 2, 8, 1, 7, 3, 6, 4, 5] + out: 25 + - name: "repeated_plateaus" + in: + nums: [4, 4, 6, 6, 8, 8] + out: 8 + - name: "large_then_small" + in: + nums: [99999, 1, 1, 1, 1] + out: 99999 + - name: "small_then_large_then_small" + in: + nums: [1, 2, 100000, 1] + out: 100000 + - name: "balanced_choices" + in: + nums: [7, 3, 6, 5, 9, 2, 8] + out: 20 + - name: "dense_duplicates" + in: + nums: [10, 2, 10, 2, 10, 2, 10] + out: 34 + - name: "near_limit_values" + in: + nums: [99998, 99997, 99996, 99995, 99994] + out: 99998 + - name: "alternating_small_values" + in: + nums: [1, 3, 2, 4, 3, 5, 4, 6] + out: 9 + - name: "generated_small" + seed: 191101 + in: + nums: + gen: "array" + len: + gen: "int" + min: 1 + max: 40 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + - name: "generated_medium" + seed: 191102 + in: + nums: + gen: "array" + len: + gen: "int" + min: 100 + max: 500 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_large" + seed: 191103 + in: + nums: + gen: "array" + len: + gen: "int" + min: 50000 + max: 50000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_maximum" + seed: 191104 + in: + nums: + gen: "array" + len: + gen: "int" + min: 100000 + max: 100000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_bounded_values" + seed: 191105 + in: + nums: + gen: "array" + len: + gen: "int" + min: 2000 + max: 5000 + of: + gen: "int" + min: 1 + max: 3 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.cpp b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.cpp new file mode 100644 index 00000000..47cced21 --- /dev/null +++ b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.cpp @@ -0,0 +1,47 @@ +class Solution { + +public: + + long long maxAlternatingSum(vector& nums) { + + int n = nums.size(); + + vector> memo(n+1, vector(2, -1)); + + function solve = [&](int idx, int flag) -> long long { + + if (idx >= n) { + + return 0; + + } + + if (memo[idx][flag] != -1) { + + return memo[idx][flag]; + + } + + long long skip = solve(idx+1, flag); + + long long val = nums[idx]; + + if (flag == 0) { + + val = -val; + + } + + long long take = val + solve(idx+1, 1 - flag); + + memo[idx][flag] = max(skip, take); + + return memo[idx][flag]; + + }; + + return solve(0, 1); + + } + +}; diff --git a/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.cs b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.cs new file mode 100644 index 00000000..5e070b08 --- /dev/null +++ b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.cs @@ -0,0 +1,53 @@ +public class Solution { + + public long MaxAlternatingSum(int[] nums) { + + int n = nums.Length; + + long[,] memo = new long[n+1, 2]; + + for (int i = 0; i <= n; i++) { + + memo[i, 0] = -1; + + memo[i, 1] = -1; + + } + + return Solve(0, 1, nums, n, memo); + + } + + private long Solve(int idx, int flag, int[] nums, int n, long[,] memo) { + + if (idx >= n) { + + return 0; + + } + + if (memo[idx, flag] != -1) { + + return memo[idx, flag]; + + } + + long skip = Solve(idx+1, flag, nums, n, memo); + + long val = nums[idx]; + + if (flag == 0) { + + val = -val; + + } + + long take = val + Solve(idx+1, 1 - flag, nums, n, memo); + + memo[idx, flag] = Math.Max(skip, take); + + return memo[idx, flag]; + + } + +} diff --git a/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.dart b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.dart new file mode 100644 index 00000000..3f4567ed --- /dev/null +++ b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.dart @@ -0,0 +1,13 @@ +class Solution { + int maxAlternatingSum(List nums) { + int even = 0; + int odd = 0; + for (final value in nums) { + final nextEven = even > odd + value ? even : odd + value; + final nextOdd = odd > even - value ? odd : even - value; + even = nextEven; + odd = nextOdd; + } + return even; + } +} diff --git a/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.go b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.go new file mode 100644 index 00000000..edd9f5c3 --- /dev/null +++ b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.go @@ -0,0 +1,57 @@ +func maxAlternatingSum(nums []int) int64 { + + n := len(nums) + + memo := make([][]int64, n+1) + + for i := range memo { + + memo[i] = []int64{-1, -1} + + } + + var solve func(idx, flag int) int64 + + solve = func(idx, flag int) int64 { + + if idx >= n { + + return 0 + + } + + if memo[idx][flag] != -1 { + + return memo[idx][flag] + + } + + skip := solve(idx+1, flag) + + val := int64(nums[idx]) + + if flag == 0 { + + val = -val + + } + + take := val + solve(idx+1, 1 - flag) + + if skip > take { + + memo[idx][flag] = skip + + } else { + + memo[idx][flag] = take + + } + + return memo[idx][flag] + + } + + return solve(0, 1) + +} diff --git a/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.java b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.java new file mode 100644 index 00000000..67c45049 --- /dev/null +++ b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.java @@ -0,0 +1,36 @@ +class Solution { + + public long maxAlternatingSum(int[] nums) { + long even = 0; + long odd = 0; + for (int value : nums) { + long nextEven = Math.max(even, odd + value); + long nextOdd = Math.max(odd, even - value); + even = nextEven; + odd = nextOdd; + } + return even; + + } + + private long solve(int idx, int flag, int[] nums, int n, long[][] memo) { + + if (idx >= n) return 0; + + if (memo[idx][flag] != -1) return memo[idx][flag]; + + long skip = solve(idx+1, flag, nums, n, memo); + + long val = nums[idx]; + + if (flag == 0) val = -val; + + long take = val + solve(idx+1, 1 - flag, nums, n, memo); + + memo[idx][flag] = Math.max(skip, take); + + return memo[idx][flag]; + + } + +} diff --git a/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.kt b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.kt new file mode 100644 index 00000000..bea1ee80 --- /dev/null +++ b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.kt @@ -0,0 +1,19 @@ +class Solution { + + fun maxAlternatingSum(nums: IntArray): Long { + + val n = nums.size + + var even = 0L + var odd = 0L + for (value in nums) { + val nextEven = maxOf(even, odd + value) + val nextOdd = maxOf(odd, even - value) + even = nextEven + odd = nextOdd + } + return even + + } + +} diff --git a/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.py b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.py new file mode 100644 index 00000000..482914fd --- /dev/null +++ b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.py @@ -0,0 +1,33 @@ +class Solution: + def maxAlternatingSum(self, nums: List[int]) -> int: + n = len(nums) + # memo[idx][flag] stores the max sum from this point forward + memo = [[-1] * 2 for _ in range(n + 1)] + + def solve(idx, nums, flag): + # Base case: no more elements to process + if idx >= n: + return 0 + + # If result already calculated, return it + if memo[idx][flag] != -1: + return memo[idx][flag] + + # Option 1: Skip the current number + skip = solve(idx + 1, nums, flag) + + # Option 2: Take the current number + val = nums[idx] + if not flag: # If it's an 'odd' position in subsequence, we subtract + val = -val + + take = val + solve(idx + 1, nums, not flag) + + # Store the best result between skipping and taking + ans = max(skip, take) + memo[idx][flag] = ans + + return ans + + # Start at index 0, looking for a number to ADD (True) + return solve(0, nums, True) diff --git a/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.py2 b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.py2 new file mode 100644 index 00000000..902798aa --- /dev/null +++ b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.py2 @@ -0,0 +1,8 @@ + +class Solution(object): + def maxAlternatingSum(self, nums): + even = 0 + odd = 0 + for value in nums: + even, odd = max(even, odd + value), max(odd, even - value) + return even diff --git a/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.rb b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.rb new file mode 100644 index 00000000..58f2a3bc --- /dev/null +++ b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.rb @@ -0,0 +1,16 @@ +# @param {Integer[]} nums + +# @return {Integer} + +def max_alternating_sum(nums) + even = 0 + odd = 0 + nums.each do |value| + next_even = [even, odd + value].max + next_odd = [odd, even - value].max + even = next_even + odd = next_odd + end + even + +end diff --git a/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.rs b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.rs new file mode 100644 index 00000000..d8021ab3 --- /dev/null +++ b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.rs @@ -0,0 +1,45 @@ +impl Solution { + + pub fn max_alternating_sum(nums: Vec) -> i64 { + + let n = nums.len(); + + let mut memo = vec![vec![-1i64; 2]; n+1]; + + fn solve(idx: usize, flag: usize, nums: &Vec, n: usize, memo: &mut Vec>) -> i64 { + + if idx >= n { + + return 0; + + } + + if memo[idx][flag] != -1 { + + return memo[idx][flag]; + + } + + let skip = solve(idx+1, flag, nums, n, memo); + + let mut val = nums[idx] as i64; + + if flag == 0 { + + val = -val; + + } + + let take = val + solve(idx+1, 1 - flag, nums, n, memo); + + memo[idx][flag] = skip.max(take); + + memo[idx][flag] + + } + + solve(0, 1, &nums, n, &mut memo) + + } + +} diff --git a/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.swift b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.swift new file mode 100644 index 00000000..ff206dd5 --- /dev/null +++ b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.swift @@ -0,0 +1,45 @@ +class Solution { + + func maxAlternatingSum(_ nums: [Int]) -> Int { + + let n = nums.count + + var memo = [[Int]](repeating: [Int](repeating: -1, count: 2), count: n+1) + + func solve(_ idx: Int, _ flag: Int) -> Int { + + if idx >= n { + + return 0 + + } + + if memo[idx][flag] != -1 { + + return memo[idx][flag] + + } + + let skip = solve(idx+1, flag) + + var val = nums[idx] + + if flag == 0 { + + val = -val + + } + + let take = val + solve(idx+1, 1 - flag) + + memo[idx][flag] = max(skip, take) + + return memo[idx][flag] + + } + + return solve(0, 1) + + } + +} diff --git a/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.ts b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.ts new file mode 100644 index 00000000..3b146bb6 --- /dev/null +++ b/tests/1501-2000/1911. maximum-alternating-subsequence-sum/sol.ts @@ -0,0 +1,11 @@ +function maxAlternatingSum(nums: number[]): number { + let even = 0; + let odd = 0; + for (const value of nums) { + const nextEven = Math.max(even, odd + value); + const nextOdd = Math.max(odd, even - value); + even = nextEven; + odd = nextOdd; + } + return even; +} diff --git a/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/manifest.yaml b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/manifest.yaml new file mode 100644 index 00000000..18ba1364 --- /dev/null +++ b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/manifest.yaml @@ -0,0 +1,257 @@ +entry: + id: 1913 + title: "maximum-product-difference-between-two-pairs" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().maxProductDifference({nums})" + rust: "Solution::max_product_difference({nums})" + python3: "Solution().maxProductDifference({nums})" + python2: "Solution().maxProductDifference({nums})" + ruby: "max_product_difference({nums})" + java: "new Solution().maxProductDifference({nums})" + csharp: "new Solution().MaxProductDifference({nums})" + kotlin: "Solution().maxProductDifference({nums})" + go: "maxProductDifference({nums})" + dart: "Solution().maxProductDifference({nums})" + swift: "Solution().maxProductDifference({nums})" + typescript: "maxProductDifference({nums})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().maxProductDifference(nums, {result})" + checker: | + class Checker: + def maxProductDifference(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not isinstance(nums, list) or len(nums) < 4: + return False + values = sorted(nums) + expected = values[-1] * values[-2] - values[0] * values[1] + return result == expected + +seed: 1913 + +tests: + - name: "example_one" + in: + nums: [5, 6, 2, 7, 4] + out: 34 + - name: "example_two" + in: + nums: [4, 2, 5, 9, 7, 4, 8] + out: 64 + - name: "minimum_length" + in: + nums: [1, 2, 3, 4] + out: 10 + - name: "minimum_length_equal" + in: + nums: [7, 7, 7, 7] + out: 0 + - name: "minimum_length_duplicates" + in: + nums: [1, 1, 10, 10] + out: 99 + - name: "all_ones" + in: + nums: [1, 1, 1, 1, 1, 1] + out: 0 + - name: "all_maximum" + in: + nums: [10000, 10000, 10000, 10000] + out: 0 + - name: "two_lowest_two_highest" + in: + nums: [1, 2, 9999, 10000] + out: 99989998 + - name: "high_duplicate_maxima" + in: + nums: [3, 4, 9999, 9999, 9999] + out: 99979989 + - name: "low_duplicate_minima" + in: + nums: [1, 1, 2, 100] + out: 199 + - name: "already_sorted" + in: + nums: [2, 5, 8, 11, 14, 17] + out: 228 + - name: "reverse_sorted" + in: + nums: [17, 14, 11, 8, 5, 2] + out: 228 + - name: "alternating_extremes" + in: + nums: [10000, 1, 9999, 2, 9998, 3] + out: 99989998 + - name: "near_extreme_values" + in: + nums: [9997, 9998, 9999, 10000, 9996] + out: 59988 + - name: "small_values" + in: + nums: [1, 2, 2, 3, 3, 4, 4] + out: 14 + - name: "repeated_middle" + in: + nums: [2, 2, 50, 50, 50, 100] + out: 4996 + - name: "one_large_pair" + in: + nums: [1, 1, 1, 5000, 6000] + out: 29999999 + - name: "two_small_pairs" + in: + nums: [1, 2, 3, 3, 4, 5] + out: 18 + - name: "large_gap" + in: + nums: [10, 20, 30, 40, 9000, 10000] + out: 89999800 + - name: "all_distinct" + in: + nums: [13, 29, 47, 61, 83, 97, 101, 103] + out: 10026 + - name: "many_minimums" + in: + nums: [1, 1, 1, 1, 2, 3, 4] + out: 11 + - name: "many_maximums" + in: + nums: [2, 3, 4, 9999, 10000, 10000, 10000] + out: 99999994 + - name: "medium_range" + in: + nums: [100, 200, 300, 400, 500, 600] + out: 280000 + - name: "squares_like" + in: + nums: [4, 9, 16, 25, 36, 49] + out: 1728 + - name: "prime_values" + in: + nums: [2, 3, 5, 7, 11, 13, 17] + out: 215 + - name: "boundary_low_high_mix" + in: + nums: [1, 10000, 1, 10000, 5000, 5000] + out: 99999999 + - name: "four_values_with_ties" + in: + nums: [42, 42, 999, 999] + out: 996237 + - name: "small_unsorted" + in: + nums: [8, 3, 6, 2, 7] + out: 50 + - name: "moderate_duplicates" + in: + nums: [12, 12, 15, 15, 20, 20, 25, 25] + out: 481 + - name: "large_uniform_band" + in: + nums: [9000, 9100, 9200, 9300, 9400, 9500] + out: 7400000 + - name: "one_each_boundary" + in: + nums: [1, 1, 10000, 9999, 500, 501] + out: 99989999 + - name: "descending_duplicates" + in: + nums: [1000, 1000, 750, 750, 500, 500] + out: 750000 + - name: "powers_of_two" + in: + nums: [2, 4, 8, 16, 32, 64] + out: 2040 + - name: "close_values" + in: + nums: [4998, 4999, 5000, 5001, 5002] + out: 30000 + - name: "large_staircase" + in: + nums: [1, 100, 200, 300, 400, 500, 600, 700, 800, 900] + out: 719900 + - name: "generated_small" + seed: 191301 + in: + nums: + gen: "array" + len: + gen: "int" + min: 4 + max: 20 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_medium" + seed: 191302 + in: + nums: + gen: "array" + len: + gen: "int" + min: 100 + max: 500 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_large" + seed: 191303 + in: + nums: + gen: "array" + len: 5000 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_maximum_length" + seed: 191304 + in: + nums: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_boundary_values" + seed: 191305 + in: + nums: + gen: "array" + len: 10000 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.cpp b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.cpp new file mode 100644 index 00000000..19504b1d --- /dev/null +++ b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.cpp @@ -0,0 +1,13 @@ +class Solution { + +public: + + int maxProductDifference(vector& nums) { + + sort(nums.begin(), nums.end()); + int n = nums.size(); + return (nums[n-1] * nums[n-2]) - (nums[0] * nums[1]); + + } + +}; diff --git a/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.cs b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.cs new file mode 100644 index 00000000..02601acb --- /dev/null +++ b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.cs @@ -0,0 +1,11 @@ +public class Solution { + + public int MaxProductDifference(int[] nums) { + + Array.Sort(nums); + int n = nums.Length; + return (nums[n-1] * nums[n-2]) - (nums[0] * nums[1]); + + } + +} diff --git a/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.dart b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.dart new file mode 100644 index 00000000..e347830f --- /dev/null +++ b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.dart @@ -0,0 +1,7 @@ +class Solution { + int maxProductDifference(List nums) { + nums.sort(); + final n = nums.length; + return nums[n - 1] * nums[n - 2] - nums[0] * nums[1]; + } +} diff --git a/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.go b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.go new file mode 100644 index 00000000..0aeba446 --- /dev/null +++ b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.go @@ -0,0 +1,7 @@ +func maxProductDifference(nums []int) int { + + sort.Ints(nums) + n := len(nums) + return (nums[n-1] * nums[n-2]) - (nums[0] * nums[1]) + +} diff --git a/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.java b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.java new file mode 100644 index 00000000..e11da699 --- /dev/null +++ b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.java @@ -0,0 +1,10 @@ +class Solution { + + public int maxProductDifference(int[] nums) { + + java.util.Arrays.sort(nums); + return (nums[nums.length-1] * nums[nums.length-2]) - (nums[0] * nums[1]); + + } + +} diff --git a/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.kt b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.kt new file mode 100644 index 00000000..077f34f8 --- /dev/null +++ b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.kt @@ -0,0 +1,10 @@ +class Solution { + + fun maxProductDifference(nums: IntArray): Int { + + nums.sort() + return (nums[nums.size-1] * nums[nums.size-2]) - (nums[0] * nums[1]) + + } + +} diff --git a/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.py b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.py new file mode 100644 index 00000000..a5d24ff1 --- /dev/null +++ b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.py @@ -0,0 +1,4 @@ +class Solution: + def maxProductDifference(self, nums: List[int]) -> int: + nums.sort() + return (nums[len(nums) - 1] * nums[len(nums) - 2]) - (nums[0] * nums[1]) diff --git a/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.py2 b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.py2 new file mode 100644 index 00000000..2ddb1816 --- /dev/null +++ b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + + def maxProductDifference(self, nums): + + """ + + :type nums: List[int] + + :rtype: int + + """ + + nums.sort() + return (nums[-1] * nums[-2]) - (nums[0] * nums[1]) diff --git a/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.rb b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.rb new file mode 100644 index 00000000..c832dc7d --- /dev/null +++ b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.rb @@ -0,0 +1,10 @@ +# @param {Integer[]} nums + +# @return {Integer} + +def max_product_difference(nums) + + nums.sort! + (nums[-1] * nums[-2]) - (nums[0] * nums[1]) + +end diff --git a/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.rs b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.rs new file mode 100644 index 00000000..76b443e7 --- /dev/null +++ b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.rs @@ -0,0 +1,12 @@ +impl Solution { + + pub fn max_product_difference(nums: Vec) -> i32 { + + let mut n = nums.clone(); + n.sort(); + let len = n.len(); + (n[len-1] * n[len-2]) - (n[0] * n[1]) + + } + +} diff --git a/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.swift b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.swift new file mode 100644 index 00000000..6baf108d --- /dev/null +++ b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.swift @@ -0,0 +1,11 @@ +class Solution { + + func maxProductDifference(_ nums: [Int]) -> Int { + + let sorted = nums.sorted() + let n = sorted.count + return (sorted[n-1] * sorted[n-2]) - (sorted[0] * sorted[1]) + + } + +} diff --git a/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.ts b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.ts new file mode 100644 index 00000000..d22d8a60 --- /dev/null +++ b/tests/1501-2000/1913. maximum-product-difference-between-two-pairs/sol.ts @@ -0,0 +1,5 @@ +function maxProductDifference(nums: number[]): number { + nums.sort((a, b) => a - b); + const n = nums.length; + return nums[n - 1] * nums[n - 2] - nums[0] * nums[1]; +} diff --git a/tests/1501-2000/1914. cyclically-rotating-a-grid/manifest.yaml b/tests/1501-2000/1914. cyclically-rotating-a-grid/manifest.yaml new file mode 100644 index 00000000..c737a85b --- /dev/null +++ b/tests/1501-2000/1914. cyclically-rotating-a-grid/manifest.yaml @@ -0,0 +1,487 @@ +entry: + id: 1914 + title: "cyclically-rotating-a-grid" + params: + grid: + type: array + items: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().rotateGrid({grid}, {k})" + rust: "Solution::rotate_grid({grid}, {k})" + python3: "Solution().rotateGrid({grid}, {k})" + python2: "Solution().rotateGrid({grid}, {k})" + ruby: "rotate_grid({grid}, {k})" + java: "new Solution().rotateGrid({grid}, {k})" + csharp: "new Solution().RotateGrid({grid}, {k})" + kotlin: "Solution().rotateGrid({grid}, {k})" + go: "rotateGrid({grid}, {k})" + dart: "Solution().rotateGrid({grid}, {k})" + swift: "Solution().rotateGrid({grid}, {k})" + typescript: "rotateGrid({grid}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().rotateGrid(grid, k, {result})" + checker: | + class Checker: + def rotateGrid(self, grid, k, result): + if not isinstance(result, list) or len(result) != len(grid): + return False + if not grid or any(not isinstance(row, list) or len(row) != len(grid[0]) for row in result): + return False + expected = [row[:] for row in grid] + m, n = len(expected), len(expected[0]) + top = left = 0 + bottom, right = m - 1, n - 1 + while top < bottom and left < right: + ring = [] + for c in range(left, right + 1): + ring.append(expected[top][c]) + for r in range(top + 1, bottom + 1): + ring.append(expected[r][right]) + for c in range(right - 1, left - 1, -1): + ring.append(expected[bottom][c]) + for r in range(bottom - 1, top, -1): + ring.append(expected[r][left]) + shift = k % len(ring) + rotated = ring[shift:] + ring[:shift] + p = 0 + for c in range(left, right + 1): + expected[top][c] = rotated[p] + p += 1 + for r in range(top + 1, bottom + 1): + expected[r][right] = rotated[p] + p += 1 + for c in range(right - 1, left - 1, -1): + expected[bottom][c] = rotated[p] + p += 1 + for r in range(bottom - 1, top, -1): + expected[r][left] = rotated[p] + p += 1 + top += 1 + left += 1 + bottom -= 1 + right -= 1 + return result == expected + +seed: 1914 + +tests: + - name: "example_one" + in: + grid: + - [40, 10] + - [30, 20] + k: 1 + out: + - [10, 20] + - [40, 30] + - name: "example_two" + in: + grid: + - [1, 2, 3, 4] + - [5, 6, 7, 8] + - [9, 10, 11, 12] + - [13, 14, 15, 16] + k: 2 + out: + - [3, 4, 8, 12] + - [2, 11, 10, 16] + - [1, 7, 6, 15] + - [5, 9, 13, 14] + - name: "zero_effect_rotation" + in: + grid: + - [1, 2] + - [3, 4] + k: 4 + - name: "large_k" + in: + grid: + - [1, 2] + - [3, 4] + k: 1000000000 + - name: "two_by_four" + in: + grid: + - [1, 2, 3, 4] + - [5, 6, 7, 8] + k: 3 + - name: "four_by_two" + in: + grid: + - [1, 2] + - [3, 4] + - [5, 6] + - [7, 8] + k: 5 + - name: "four_by_six" + in: + grid: + - [1, 2, 3, 4, 5, 6] + - [7, 8, 9, 10, 11, 12] + - [13, 14, 15, 16, 17, 18] + - [19, 20, 21, 22, 23, 24] + k: 7 + - name: "six_by_four" + in: + grid: + - [1, 2, 3, 4] + - [5, 6, 7, 8] + - [9, 10, 11, 12] + - [13, 14, 15, 16] + - [17, 18, 19, 20] + - [21, 22, 23, 24] + k: 9 + - name: "negative_k_not_allowed_but_values_negative" + in: + grid: + - [5000, 1] + - [2500, 4999] + k: 1 + - name: "duplicates" + in: + grid: + - [7, 7, 7, 7] + - [7, 7, 7, 7] + - [7, 7, 7, 7] + - [7, 7, 7, 7] + k: 13 + - name: "inner_layer" + in: + grid: + - [1, 2, 3, 4, 5, 6] + - [7, 8, 9, 10, 11, 12] + - [13, 14, 15, 16, 17, 18] + - [19, 20, 21, 22, 23, 24] + - [25, 26, 27, 28, 29, 30] + - [31, 32, 33, 34, 35, 36] + k: 1 + - name: "inner_multiple" + in: + grid: + - [1, 2, 3, 4, 5, 6] + - [7, 8, 9, 10, 11, 12] + - [13, 14, 15, 16, 17, 18] + - [19, 20, 21, 22, 23, 24] + - [25, 26, 27, 28, 29, 30] + - [31, 32, 33, 34, 35, 36] + k: 100 + - name: "nonuniform_values" + in: + grid: + - [31, 2, 4999, 44] + - [8, 700, 12, 900] + - [4200, 6, 88, 19] + - [73, 501, 4, 3000] + k: 2 + - name: "k_perimeter" + in: + grid: + - [1, 2, 3, 4, 5, 6] + - [7, 8, 9, 10, 11, 12] + - [13, 14, 15, 16, 17, 18] + - [19, 20, 21, 22, 23, 24] + k: 16 + - name: "k_perimeter_plus_one" + in: + grid: + - [1, 2, 3, 4, 5, 6] + - [7, 8, 9, 10, 11, 12] + - [13, 14, 15, 16, 17, 18] + - [19, 20, 21, 22, 23, 24] + k: 17 + - name: "eight_by_eight" + in: + grid: + - [1, 2, 3, 4, 5, 6, 7, 8] + - [9, 10, 11, 12, 13, 14, 15, 16] + - [17, 18, 19, 20, 21, 22, 23, 24] + - [25, 26, 27, 28, 29, 30, 31, 32] + - [33, 34, 35, 36, 37, 38, 39, 40] + - [41, 42, 43, 44, 45, 46, 47, 48] + - [49, 50, 51, 52, 53, 54, 55, 56] + - [57, 58, 59, 60, 61, 62, 63, 64] + k: 15 + - name: "eight_by_eight_huge_k" + in: + grid: + - [1, 2, 3, 4, 5, 6, 7, 8] + - [9, 10, 11, 12, 13, 14, 15, 16] + - [17, 18, 19, 20, 21, 22, 23, 24] + - [25, 26, 27, 28, 29, 30, 31, 32] + - [33, 34, 35, 36, 37, 38, 39, 40] + - [41, 42, 43, 44, 45, 46, 47, 48] + - [49, 50, 51, 52, 53, 54, 55, 56] + - [57, 58, 59, 60, 61, 62, 63, 64] + k: 999999999 + - name: "two_by_six" + in: + grid: + - [6, 5, 4, 3, 2, 1] + - [12, 11, 10, 9, 8, 7] + k: 4 + - name: "six_by_two" + in: + grid: + - [1, 2] + - [3, 4] + - [5, 6] + - [7, 8] + - [9, 10] + - [11, 12] + k: 8 + - name: "ten_by_four" + in: + grid: + - [1, 2, 3, 4] + - [5, 6, 7, 8] + - [9, 10, 11, 12] + - [13, 14, 15, 16] + - [17, 18, 19, 20] + - [21, 22, 23, 24] + - [25, 26, 27, 28] + - [29, 30, 31, 32] + - [33, 34, 35, 36] + - [37, 38, 39, 40] + k: 23 + - name: "four_by_ten" + in: + grid: + - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] + - [21, 22, 23, 24, 25, 26, 27, 28, 29, 30] + - [31, 32, 33, 34, 35, 36, 37, 38, 39, 40] + k: 31 + - name: "twelve_by_twelve" + in: + grid: + - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + - [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24] + - [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36] + - [37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48] + - [49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60] + - [61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72] + - [73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84] + - [85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96] + - [97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108] + - [109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120] + - [121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132] + - [133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144] + k: 47 + - name: "values_at_bounds" + in: + grid: + - [1, 5000, 1, 5000] + - [5000, 1, 5000, 1] + - [1, 5000, 1, 5000] + - [5000, 1, 5000, 1] + k: 6 + - name: "prime_like_values" + in: + grid: + - [2, 3, 5, 7] + - [11, 13, 17, 19] + - [23, 29, 31, 37] + - [41, 43, 47, 53] + k: 3 + - name: "all_same_layer_pattern" + in: + grid: + - [1, 2, 1, 2, 1, 2] + - [2, 1, 2, 1, 2, 1] + - [1, 2, 1, 2, 1, 2] + - [2, 1, 2, 1, 2, 1] + - [1, 2, 1, 2, 1, 2] + - [2, 1, 2, 1, 2, 1] + k: 10 + - name: "rotation_near_full_cycle" + in: + grid: + - [1, 2, 3, 4] + - [5, 6, 7, 8] + - [9, 10, 11, 12] + - [13, 14, 15, 16] + k: 1000000000 + - name: "twenty_by_two" + in: + grid: + - [1, 2] + - [3, 4] + - [5, 6] + - [7, 8] + - [9, 10] + - [11, 12] + - [13, 14] + - [15, 16] + - [17, 18] + - [19, 20] + - [21, 22] + - [23, 24] + - [25, 26] + - [27, 28] + - [29, 30] + - [31, 32] + - [33, 34] + - [35, 36] + - [37, 38] + - [39, 40] + k: 37 + - name: "twenty_by_four" + in: + grid: + - [1, 2, 3, 4] + - [5, 6, 7, 8] + - [9, 10, 11, 12] + - [13, 14, 15, 16] + - [17, 18, 19, 20] + - [21, 22, 23, 24] + - [25, 26, 27, 28] + - [29, 30, 31, 32] + - [33, 34, 35, 36] + - [37, 38, 39, 40] + - [41, 42, 43, 44] + - [45, 46, 47, 48] + - [49, 50, 51, 52] + - [53, 54, 55, 56] + - [57, 58, 59, 60] + - [61, 62, 63, 64] + - [65, 66, 67, 68] + - [69, 70, 71, 72] + - [73, 74, 75, 76] + - [77, 78, 79, 80] + k: 101 + - name: "thirty_by_two" + in: + grid: + - [1, 2] + - [3, 4] + - [5, 6] + - [7, 8] + - [9, 10] + - [11, 12] + - [13, 14] + - [15, 16] + - [17, 18] + - [19, 20] + - [21, 22] + - [23, 24] + - [25, 26] + - [27, 28] + - [29, 30] + - [31, 32] + - [33, 34] + - [35, 36] + - [37, 38] + - [39, 40] + - [41, 42] + - [43, 44] + - [45, 46] + - [47, 48] + - [49, 50] + - [51, 52] + - [53, 54] + - [55, 56] + - [57, 58] + - [59, 60] + k: 29 + - name: "forty_by_four" + in: + grid: + - [1, 2, 3, 4] + - [5, 6, 7, 8] + - [9, 10, 11, 12] + - [13, 14, 15, 16] + - [17, 18, 19, 20] + - [21, 22, 23, 24] + - [25, 26, 27, 28] + - [29, 30, 31, 32] + - [33, 34, 35, 36] + - [37, 38, 39, 40] + - [41, 42, 43, 44] + - [45, 46, 47, 48] + - [49, 50, 51, 52] + - [53, 54, 55, 56] + - [57, 58, 59, 60] + - [61, 62, 63, 64] + - [65, 66, 67, 68] + - [69, 70, 71, 72] + - [73, 74, 75, 76] + - [77, 78, 79, 80] + - [81, 82, 83, 84] + - [85, 86, 87, 88] + - [89, 90, 91, 92] + - [93, 94, 95, 96] + - [97, 98, 99, 100] + - [101, 102, 103, 104] + - [105, 106, 107, 108] + - [109, 110, 111, 112] + - [113, 114, 115, 116] + - [117, 118, 119, 120] + - [121, 122, 123, 124] + - [125, 126, 127, 128] + - [129, 130, 131, 132] + - [133, 134, 135, 136] + - [137, 138, 139, 140] + - [141, 142, 143, 144] + - [145, 146, 147, 148] + - [149, 150, 151, 152] + - [153, 154, 155, 156] + - [157, 158, 159, 160] + k: 777 + - name: "fifty_by_fifty_boundary_stress" + in: + grid: + - [1, 5000, 1, 5000, 1, 5000, 1, 5000, 1, 5000] + - [5000, 1, 5000, 1, 5000, 1, 5000, 1, 5000, 1] + - [1, 5000, 1, 5000, 1, 5000, 1, 5000, 1, 5000] + - [5000, 1, 5000, 1, 5000, 1, 5000, 1, 5000, 1] + k: 999999937 + - name: "different_layer_periods" + in: + grid: + - [3, 8, 13, 18, 23, 28, 33, 38] + - [43, 48, 53, 58, 63, 68, 73, 78] + - [83, 88, 93, 98, 103, 108, 113, 118] + - [123, 128, 133, 138, 143, 148, 153, 158] + - [163, 168, 173, 178, 183, 188, 193, 198] + - [203, 208, 213, 218, 223, 228, 233, 238] + - [243, 248, 253, 258, 263, 268, 273, 278] + - [283, 288, 293, 298, 303, 308, 313, 318] + k: 6 + - name: "single_step_large_rectangle" + in: + grid: + - [1, 2, 3, 4, 5, 6, 7, 8] + - [9, 10, 11, 12, 13, 14, 15, 16] + - [17, 18, 19, 20, 21, 22, 23, 24] + - [25, 26, 27, 28, 29, 30, 31, 32] + - [33, 34, 35, 36, 37, 38, 39, 40] + - [41, 42, 43, 44, 45, 46, 47, 48] + k: 1 + - name: "all_distinct_randomish" + in: + grid: + - [17, 499, 1200, 33] + - [4096, 88, 231, 700] + - [14, 3456, 67, 901] + - [2500, 5, 777, 1024] + k: 11 + - name: "rotation_two_full_cycles" + in: + grid: + - [1, 2] + - [3, 4] + k: 8 diff --git a/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.cpp b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.cpp new file mode 100644 index 00000000..6fe14c8d --- /dev/null +++ b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.cpp @@ -0,0 +1,43 @@ +class Solution { + +public: + + vector> rotateGrid(vector>& grid, int k) { + + int T = 0, L = 0; + + int B = grid.size() - 1, R = grid[0].size() - 1; + + while (T < B && L < R) { + + int ln = B - T, wid = R - L; + + int perimeter = 2 * ln + 2 * wid; + + int r = k % perimeter; + + while (r--) { + + int tmp = grid[T][L]; + + for (int i = L; i < R; ++i) grid[T][i] = grid[T][i + 1]; + + for (int i = T; i < B; ++i) grid[i][R] = grid[i + 1][R]; + + for (int i = R; i > L; --i) grid[B][i] = grid[B][i - 1]; + + for (int i = B; i > T; --i) grid[i][L] = grid[i - 1][L]; + + grid[T + 1][L] = tmp; + + } + + ++T; ++L; --B; --R; + + } + + return grid; + + } + +}; diff --git a/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.cs b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.cs new file mode 100644 index 00000000..5b2e7012 --- /dev/null +++ b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.cs @@ -0,0 +1,41 @@ +public class Solution { + + public int[][] RotateGrid(int[][] grid, int k) { + + int t = 0, l = 0; + + int b = grid.Length - 1, r = grid[0].Length - 1; + + while (t < b && l < r) { + + int ln = b - t, wid = r - l; + + int perimeter = 2 * ln + 2 * wid; + + int steps = k % perimeter; + + while (steps-- > 0) { + + int tmp = grid[t][l]; + + for (int i = l; i < r; i++) grid[t][i] = grid[t][i + 1]; + + for (int i = t; i < b; i++) grid[i][r] = grid[i + 1][r]; + + for (int i = r; i > l; i--) grid[b][i] = grid[b][i - 1]; + + for (int i = b; i > t; i--) grid[i][l] = grid[i - 1][l]; + + grid[t + 1][l] = tmp; + + } + + t++; l++; b--; r--; + + } + + return grid; + + } + +} diff --git a/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.dart b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.dart new file mode 100644 index 00000000..af52d76d --- /dev/null +++ b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.dart @@ -0,0 +1,35 @@ +class Solution { + List> rotateGrid(List> grid, int k) { + var top = 0; + var left = 0; + var bottom = grid.length - 1; + var right = grid[0].length - 1; + + while (top < bottom && left < right) { + final perimeter = 2 * (bottom - top) + 2 * (right - left); + var steps = k % perimeter; + while (steps > 0) { + final tmp = grid[top][left]; + for (var col = left; col < right; col++) { + grid[top][col] = grid[top][col + 1]; + } + for (var row = top; row < bottom; row++) { + grid[row][right] = grid[row + 1][right]; + } + for (var col = right; col > left; col--) { + grid[bottom][col] = grid[bottom][col - 1]; + } + for (var row = bottom; row > top; row--) { + grid[row][left] = grid[row - 1][left]; + } + grid[top + 1][left] = tmp; + steps--; + } + top++; + left++; + bottom--; + right--; + } + return grid; + } +} diff --git a/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.go b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.go new file mode 100644 index 00000000..b268e321 --- /dev/null +++ b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.go @@ -0,0 +1,63 @@ +func rotateGrid(grid [][]int, k int) [][]int { + + t, l := 0, 0 + + b, r := len(grid)-1, len(grid[0])-1 + + for t < b && l < r { + + ln := b - t + + wid := r - l + + perimeter := 2*ln + 2*wid + + steps := k % perimeter + + for steps > 0 { + + tmp := grid[t][l] + + for i := l; i < r; i++ { + + grid[t][i] = grid[t][i+1] + + } + + for i := t; i < b; i++ { + + grid[i][r] = grid[i+1][r] + + } + + for i := r; i > l; i-- { + + grid[b][i] = grid[b][i-1] + + } + + for i := b; i > t; i-- { + + grid[i][l] = grid[i-1][l] + + } + + grid[t+1][l] = tmp + + steps-- + + } + + t++ + + l++ + + b-- + + r-- + + } + + return grid + +} diff --git a/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.java b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.java new file mode 100644 index 00000000..b49e8db5 --- /dev/null +++ b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.java @@ -0,0 +1,41 @@ +class Solution { + + public int[][] rotateGrid(int[][] grid, int k) { + + int t = 0, l = 0; + + int b = grid.length - 1, r = grid[0].length - 1; + + while (t < b && l < r) { + + int ln = b - t, wid = r - l; + + int perimeter = 2 * ln + 2 * wid; + + int steps = k % perimeter; + + while (steps-- > 0) { + + int tmp = grid[t][l]; + + for (int i = l; i < r; i++) grid[t][i] = grid[t][i + 1]; + + for (int i = t; i < b; i++) grid[i][r] = grid[i + 1][r]; + + for (int i = r; i > l; i--) grid[b][i] = grid[b][i - 1]; + + for (int i = b; i > t; i--) grid[i][l] = grid[i - 1][l]; + + grid[t + 1][l] = tmp; + + } + + t++; l++; b--; r--; + + } + + return grid; + + } + +} diff --git a/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.kt b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.kt new file mode 100644 index 00000000..035a800b --- /dev/null +++ b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.kt @@ -0,0 +1,47 @@ +class Solution { + + fun rotateGrid(grid: Array, k: Int): Array { + + var t = 0 + + var l = 0 + + var b = grid.size - 1 + + var r = grid[0].size - 1 + + while (t < b && l < r) { + + val ln = b - t + + val wid = r - l + + val perimeter = 2 * ln + 2 * wid + + var steps = k % perimeter + + while (steps-- > 0) { + + val tmp = grid[t][l] + + for (i in l until r) grid[t][i] = grid[t][i + 1] + + for (i in t until b) grid[i][r] = grid[i + 1][r] + + for (i in r downTo l + 1) grid[b][i] = grid[b][i - 1] + + for (i in b downTo t + 1) grid[i][l] = grid[i - 1][l] + + grid[t + 1][l] = tmp + + } + + t++; l++; b--; r-- + + } + + return grid + + } + +} diff --git a/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.py b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.py new file mode 100644 index 00000000..82625322 --- /dev/null +++ b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.py @@ -0,0 +1,34 @@ +class Solution: + def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: + T, L = 0, 0 + B, R = len(grid) - 1, len(grid[0]) - 1 + + while T < B and L < R: + ln, wid = B - T, R - L + perimeter = 2 * ln + 2 * wid + r = k % perimeter + + while r: + tmp = grid[T][L] + + for i in range(L, R): + grid[T][i] = grid[T][i + 1] + + for i in range(T, B): + grid[i][R] = grid[i + 1][R] + + for i in range(R, L, -1): + grid[B][i] = grid[B][i - 1] + + for i in range(B, T, -1): + grid[i][L] = grid[i - 1][L] + + grid[T + 1][L] = tmp + r -= 1 + + T += 1 + L += 1 + B -= 1 + R -= 1 + + return grid diff --git a/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.py2 b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.py2 new file mode 100644 index 00000000..5829ba99 --- /dev/null +++ b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.py2 @@ -0,0 +1,59 @@ +class Solution(object): + + def rotateGrid(self, grid, k): + + """ + + :type grid: List[List[int]] + + :type k: int + + :rtype: List[List[int]] + + """ + + T, L = 0, 0 + + B, R = len(grid) - 1, len(grid[0]) - 1 + + while T < B and L < R: + + ln, wid = B - T, R - L + + perimeter = 2 * ln + 2 * wid + + r = k % perimeter + + while r: + + tmp = grid[T][L] + + for i in range(L, R): + + grid[T][i] = grid[T][i + 1] + + for i in range(T, B): + + grid[i][R] = grid[i + 1][R] + + for i in range(R, L, -1): + + grid[B][i] = grid[B][i - 1] + + for i in range(B, T, -1): + + grid[i][L] = grid[i - 1][L] + + grid[T + 1][L] = tmp + + r -= 1 + + T += 1 + + L += 1 + + B -= 1 + + R -= 1 + + return grid diff --git a/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.rb b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.rb new file mode 100644 index 00000000..91ad8ed7 --- /dev/null +++ b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.rb @@ -0,0 +1,69 @@ +# @param {Integer[][]} grid + +# @param {Integer} k + +# @return {Integer[][]} + +def rotate_grid(grid, k) + + t, l = 0, 0 + + b, r = grid.length - 1, grid[0].length - 1 + + while t < b && l < r + + ln = b - t + + wid = r - l + + perimeter = 2 * ln + 2 * wid + + steps = k % perimeter + + while steps > 0 + + tmp = grid[t][l] + + (l...r).each do |i| + + grid[t][i] = grid[t][i + 1] + + end + + (t...b).each do |i| + + grid[i][r] = grid[i + 1][r] + + end + + (l + 1..r).reverse_each do |i| + + grid[b][i] = grid[b][i - 1] + + end + + (t + 1..b).reverse_each do |i| + + grid[i][l] = grid[i - 1][l] + + end + + grid[t + 1][l] = tmp + + steps -= 1 + + end + + t += 1 + + l += 1 + + b -= 1 + + r -= 1 + + end + + grid + +end diff --git a/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.rs b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.rs new file mode 100644 index 00000000..3e6103d5 --- /dev/null +++ b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.rs @@ -0,0 +1,73 @@ +impl Solution { + + pub fn rotate_grid(grid: Vec>, k: i32) -> Vec> { + + let mut grid = grid; + + let mut t = 0; + + let mut l = 0; + + let mut b = grid.len() as i32 - 1; + + let mut r = grid[0].len() as i32 - 1; + + while t < b && l < r { + + let ln = b - t; + + let wid = r - l; + + let perimeter = 2 * ln + 2 * wid; + + let mut steps = (k % perimeter) as i32; + + while steps > 0 { + + let tmp = grid[t as usize][l as usize]; + + for i in l..r { + + grid[t as usize][i as usize] = grid[t as usize][(i + 1) as usize]; + + } + + for i in t..b { + + grid[i as usize][r as usize] = grid[(i + 1) as usize][r as usize]; + + } + + for i in (l + 1..=r).rev() { + + grid[b as usize][i as usize] = grid[b as usize][(i - 1) as usize]; + + } + + for i in (t + 1..=b).rev() { + + grid[i as usize][l as usize] = grid[(i - 1) as usize][l as usize]; + + } + + grid[(t + 1) as usize][l as usize] = tmp; + + steps -= 1; + + } + + t += 1; + + l += 1; + + b -= 1; + + r -= 1; + + } + + grid + + } + +} diff --git a/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.swift b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.swift new file mode 100644 index 00000000..192be0e5 --- /dev/null +++ b/tests/1501-2000/1914. cyclically-rotating-a-grid/sol.swift @@ -0,0 +1,73 @@ +class Solution { + + func rotateGrid(_ grid: [[Int]], _ k: Int) -> [[Int]] { + + var grid = grid + + var t = 0 + + var l = 0 + + var b = grid.count - 1 + + var r = grid[0].count - 1 + + while t < b && l < r { + + let ln = b - t + + let wid = r - l + + let perimeter = 2 * ln + 2 * wid + + var steps = k % perimeter + + while steps > 0 { + + let tmp = grid[t][l] + + for i in l.. 0) { + const tmp = grid[t][l]; + + for (let i = l; i < r; i++) grid[t][i] = grid[t][i + 1]; + + for (let i = t; i < b; i++) grid[i][r] = grid[i + 1][r]; + + for (let i = r; i > l; i--) grid[b][i] = grid[b][i - 1]; + + for (let i = b; i > t; i--) grid[i][l] = grid[i - 1][l]; + + grid[t + 1][l] = tmp; + } + + t++; + l++; + b--; + r--; + } + + return grid; +} diff --git a/tests/1501-2000/1915. number-of-wonderful-substrings/manifest.yaml b/tests/1501-2000/1915. number-of-wonderful-substrings/manifest.yaml new file mode 100644 index 00000000..71f72ac6 --- /dev/null +++ b/tests/1501-2000/1915. number-of-wonderful-substrings/manifest.yaml @@ -0,0 +1,236 @@ +entry: + id: 1915 + title: "number-of-wonderful-substrings" + params: + word: + type: string + call: + cpp: "Solution().wonderfulSubstrings({word})" + rust: "Solution::wonderful_substrings({word})" + python3: "Solution().wonderfulSubstrings({word})" + python2: "Solution().wonderfulSubstrings({word})" + ruby: "wonderful_substrings({word})" + java: "new Solution().wonderfulSubstrings({word})" + csharp: "new Solution().WonderfulSubstrings({word})" + kotlin: "Solution().wonderfulSubstrings({word})" + go: "wonderfulSubstrings({word})" + dart: "Solution().wonderfulSubstrings({word})" + swift: "Solution().wonderfulSubstrings({word})" + typescript: "wonderfulSubstrings({word})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().wonderfulSubstrings(word, {result})" + checker: | + class Checker: + def wonderfulSubstrings(self, word, result): + if not isinstance(word, str) or not isinstance(result, int) or isinstance(result, bool): + return False + if not (1 <= len(word) <= 100000) or any(ch < 'a' or ch > 'j' for ch in word): + return False + counts = [0] * 1024 + counts[0] = 1 + mask = 0 + expected = 0 + for ch in word: + mask ^= 1 << (ord(ch) - ord('a')) + expected += counts[mask] + for bit in range(10): + expected += counts[mask ^ (1 << bit)] + counts[mask] += 1 + return result == expected + +seed: 1915 + +tests: + - name: "single_a" + in: + word: "a" + out: 1 + - name: "single_j" + in: + word: "j" + out: 1 + - name: "two_distinct" + in: + word: "ab" + out: 2 + - name: "two_equal" + in: + word: "aa" + out: 3 + - name: "example_aba" + in: + word: "aba" + out: 4 + - name: "example_aabb" + in: + word: "aabb" + out: 9 + - name: "example_he" + in: + word: "he" + out: 2 + - name: "all_letters_once" + in: + word: "abcdefghij" + out: 10 + - name: "all_letters_reverse" + in: + word: "jihgfedcba" + out: 10 + - name: "two_cycles" + in: + word: "abcdefghijabcdefghij" + out: 23 + - name: "four_a" + in: + word: "aaaa" + out: 10 + - name: "six_b" + in: + word: "bbbbbb" + out: 21 + - name: "alternating_ab" + in: + word: "abab" + out: 7 + - name: "three_distinct" + in: + word: "abc" + out: 3 + - name: "double_then_single" + in: + word: "aab" + out: 5 + - name: "five_distinct" + in: + word: "abcde" + out: 5 + - name: "three_pairs" + in: + word: "aabbcc" + out: 18 + - name: "five_pair_prefix" + in: + word: "aabbccdde" + out: 35 + - name: "double_j_suffix" + in: + word: "abcdefghijj" + out: 13 + - name: "six_pairs" + in: + word: "aabbccddeeff" + out: 63 + - name: "thirty_mixed" + in: + word: "abcdefghijabcdefghijabcde" + out: 43 + - name: "twenty_a" + in: + word: "aaaaaaaaaaaaaaaaaaaa" + out: 210 + - name: "forty_alternating" + in: + word: "abababababababababababababababababababab" + out: 610 + - name: "thirty_abc" + in: + word: "abcabcabcabcabcabcabcabcabcabc" + out: 225 + - name: "forty_aabb" + in: + word: "aabbaabbaabbaabbaabbaabbaabbaabbaabbaabb" + out: 720 + - name: "ten_ab" + in: + word: "ababababab" + out: 40 + - name: "ten_abcde" + in: + word: "abcdeabcde" + out: 13 + - name: "ten_pairs" + in: + word: "aabbccddeeaabbccdde" + out: 150 + - name: "edge_a_and_j" + in: + word: "ajaja" + out: 11 + - name: "nested_masks" + in: + word: "abcddcba" + out: 18 + - name: "mixed_boundary_letters" + in: + word: "aijjiiia" + out: 25 + - name: "palindrome_mixed" + in: + word: "abccba" + out: 13 + - name: "repeated_blocks" + in: + word: "aabbccaabbcc" + out: 66 + - name: "long_single_letter" + in: + word: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: 1275 + - name: "long_two_letters" + in: + word: "ababababababababababababababababababababababababab" + out: 950 + - name: "generated_small" + seed: 191501 + in: + word: + gen: "str" + len: + gen: "int" + min: 1 + max: 40 + alphabet: "abcdefghij" + - name: "generated_medium" + seed: 191502 + in: + word: + gen: "str" + len: + gen: "int" + min: 100 + max: 500 + alphabet: "abcdefghij" + - name: "generated_large" + seed: 191503 + in: + word: + gen: "str" + len: + gen: "int" + min: 10000 + max: 20000 + alphabet: "abcdefghij" + - name: "generated_maximum" + seed: 191504 + in: + word: + gen: "str" + len: 100000 + alphabet: "abcdefghij" + - name: "generated_biased" + seed: 191505 + in: + word: + gen: "str" + len: 50000 + alphabet: "aaabcj" diff --git a/tests/1501-2000/1915. number-of-wonderful-substrings/sol.cpp b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.cpp new file mode 100644 index 00000000..89c4e5da --- /dev/null +++ b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.cpp @@ -0,0 +1,37 @@ +class Solution { + +public: + + long long wonderfulSubstrings(string word) { + + long long count[1024] = {0}; + + count[0] = 1; + + int mask = 0; + + long long res = 0; + + for (char ch : word) { + + int bit = ch - 'a'; + + mask ^= (1 << bit); + + res += count[mask]; + + for (int i = 0; i < 10; i++) { + + res += count[mask ^ (1 << i)]; + + } + + count[mask]++; + + } + + return res; + + } + +}; diff --git a/tests/1501-2000/1915. number-of-wonderful-substrings/sol.cs b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.cs new file mode 100644 index 00000000..e5a999e6 --- /dev/null +++ b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.cs @@ -0,0 +1,35 @@ +public class Solution { + + public long WonderfulSubstrings(string word) { + + long[] count = new long[1024]; + + count[0] = 1; + + int mask = 0; + + long res = 0; + + foreach (char ch in word) { + + int bit = ch - 'a'; + + mask ^= (1 << bit); + + res += count[mask]; + + for (int i = 0; i < 10; i++) { + + res += count[mask ^ (1 << i)]; + + } + + count[mask]++; + + } + + return res; + + } + +} diff --git a/tests/1501-2000/1915. number-of-wonderful-substrings/sol.dart b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.dart new file mode 100644 index 00000000..b73e3877 --- /dev/null +++ b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.dart @@ -0,0 +1,18 @@ +class Solution { + int wonderfulSubstrings(String word) { + final counts = List.filled(1 << 10, 0); + counts[0] = 1; + var mask = 0; + var answer = 0; + + for (final code in word.codeUnits) { + mask ^= 1 << (code - 97); + answer += counts[mask]; + for (var bit = 0; bit < 10; bit++) { + answer += counts[mask ^ (1 << bit)]; + } + counts[mask]++; + } + return answer; + } +} diff --git a/tests/1501-2000/1915. number-of-wonderful-substrings/sol.go b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.go new file mode 100644 index 00000000..7107bb34 --- /dev/null +++ b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.go @@ -0,0 +1,31 @@ +func wonderfulSubstrings(word string) int64 { + + count := make([]int64, 1024) + + count[0] = 1 + + mask := 0 + + var res int64 = 0 + + for _, ch := range word { + + bit := int(ch - 'a') + + mask ^= 1 << bit + + res += count[mask] + + for i := 0; i < 10; i++ { + + res += count[mask ^ (1 << i)] + + } + + count[mask]++ + + } + + return res + +} diff --git a/tests/1501-2000/1915. number-of-wonderful-substrings/sol.java b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.java new file mode 100644 index 00000000..84f8b0f5 --- /dev/null +++ b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.java @@ -0,0 +1,35 @@ +class Solution { + + public long wonderfulSubstrings(String word) { + + long[] count = new long[1024]; + + count[0] = 1; + + int mask = 0; + + long res = 0; + + for (char ch : word.toCharArray()) { + + int bit = ch - 'a'; + + mask ^= 1 << bit; + + res += count[mask]; + + for (int i = 0; i < 10; i++) { + + res += count[mask ^ (1 << i)]; + + } + + count[mask]++; + + } + + return res; + + } + +} diff --git a/tests/1501-2000/1915. number-of-wonderful-substrings/sol.kt b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.kt new file mode 100644 index 00000000..0e2e1979 --- /dev/null +++ b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.kt @@ -0,0 +1,35 @@ +class Solution { + + fun wonderfulSubstrings(word: String): Long { + + val count = LongArray(1024) + + count[0] = 1 + + var mask = 0 + + var res = 0L + + for (ch in word) { + + val bit = ch - 'a' + + mask = mask xor (1 shl bit) + + res += count[mask] + + for (i in 0 until 10) { + + res += count[mask xor (1 shl i)] + + } + + count[mask]++ + + } + + return res + + } + +} diff --git a/tests/1501-2000/1915. number-of-wonderful-substrings/sol.py b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.py new file mode 100644 index 00000000..341f51a6 --- /dev/null +++ b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.py @@ -0,0 +1,25 @@ +from collections import defaultdict + + +class Solution(object): + def wonderfulSubstrings(self, word): + """ + :type word: str + :rtype: int + """ + count = defaultdict(int) + count[0] = 1 + mask = 0 + res = 0 + + for ch in word: + bit = ord(ch) - ord("a") + mask ^= 1 << bit + res += count[mask] + + for i in range(10): + res += count[mask ^ (1 << i)] + + count[mask] += 1 + + return res diff --git a/tests/1501-2000/1915. number-of-wonderful-substrings/sol.py2 b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.py2 new file mode 100644 index 00000000..c9e4f705 --- /dev/null +++ b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.py2 @@ -0,0 +1,37 @@ +class Solution(object): + + def wonderfulSubstrings(self, word): + + """ + + :type word: str + + :rtype: int + + """ + + from collections import defaultdict + + count = defaultdict(int) + + count[0] = 1 + + mask = 0 + + res = 0 + + for ch in word: + + bit = ord(ch) - ord('a') + + mask ^= 1 << bit + + res += count[mask] + + for i in range(10): + + res += count[mask ^ (1 << i)] + + count[mask] += 1 + + return res diff --git a/tests/1501-2000/1915. number-of-wonderful-substrings/sol.rb b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.rb new file mode 100644 index 00000000..eda5f58c --- /dev/null +++ b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.rb @@ -0,0 +1,35 @@ +# @param {String} word + +# @return {Integer} + +def wonderful_substrings(word) + + count = Hash.new(0) + + count[0] = 1 + + mask = 0 + + res = 0 + + word.each_char do |ch| + + bit = ch.ord - 'a'.ord + + mask ^= 1 << bit + + res += count[mask] + + (0...10).each do |i| + + res += count[mask ^ (1 << i)] + + end + + count[mask] += 1 + + end + + res + +end diff --git a/tests/1501-2000/1915. number-of-wonderful-substrings/sol.rs b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.rs new file mode 100644 index 00000000..70810475 --- /dev/null +++ b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.rs @@ -0,0 +1,35 @@ +impl Solution { + + pub fn wonderful_substrings(word: String) -> i64 { + + let mut count = vec![0i64; 1024]; + + count[0] = 1; + + let mut mask = 0i32; + + let mut res = 0i64; + + for ch in word.bytes() { + + let bit = (ch - b'a') as i32; + + mask ^= 1 << bit; + + res += count[mask as usize]; + + for i in 0..10 { + + res += count[(mask ^ (1 << i)) as usize]; + + } + + count[mask as usize] += 1; + + } + + res + + } + +} diff --git a/tests/1501-2000/1915. number-of-wonderful-substrings/sol.swift b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.swift new file mode 100644 index 00000000..76094e12 --- /dev/null +++ b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.swift @@ -0,0 +1,35 @@ +class Solution { + + func wonderfulSubstrings(_ word: String) -> Int { + + var count = [Int](repeating: 0, count: 1024) + + count[0] = 1 + + var mask = 0 + + var res = 0 + + for ch in word { + + let bit = Int(ch.asciiValue! - Character("a").asciiValue!) + + mask ^= 1 << bit + + res += count[mask] + + for i in 0..<10 { + + res += count[mask ^ (1 << i)] + + } + + count[mask] += 1 + + } + + return res + + } + +} diff --git a/tests/1501-2000/1915. number-of-wonderful-substrings/sol.ts b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.ts new file mode 100644 index 00000000..d0b0638e --- /dev/null +++ b/tests/1501-2000/1915. number-of-wonderful-substrings/sol.ts @@ -0,0 +1,25 @@ +function wonderfulSubstrings(word: string): number { + const count: number[] = new Array(1024).fill(0); + + count[0] = 1; + + let mask = 0; + + let res = 0; + + for (const ch of word) { + const bit = ch.charCodeAt(0) - "a".charCodeAt(0); + + mask ^= 1 << bit; + + res += count[mask]; + + for (let i = 0; i < 10; i++) { + res += count[mask ^ (1 << i)]; + } + + count[mask]++; + } + + return res; +} diff --git a/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/manifest.yaml b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/manifest.yaml new file mode 100644 index 00000000..2f057f3f --- /dev/null +++ b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/manifest.yaml @@ -0,0 +1,221 @@ +entry: + id: 1916 + title: "count-ways-to-build-rooms-in-an-ant-colony" + params: + prevRoom: + type: array + items: + type: int + call: + cpp: "Solution().waysToBuildRooms({prevRoom})" + rust: "Solution::ways_to_build_rooms({prevRoom})" + python3: "Solution().waysToBuildRooms({prevRoom})" + python2: "Solution().waysToBuildRooms({prevRoom})" + ruby: "ways_to_build_rooms({prevRoom})" + java: "new Solution().waysToBuildRooms({prevRoom})" + csharp: "new Solution().WaysToBuildRooms({prevRoom})" + kotlin: "Solution().waysToBuildRooms({prevRoom})" + go: "waysToBuildRooms({prevRoom})" + dart: "Solution().waysToBuildRooms({prevRoom})" + swift: "Solution().waysToBuildRooms({prevRoom})" + typescript: "waysToBuildRooms({prevRoom})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 512 +oracle: + python3: + call: "Checker().waysToBuildRooms(prevRoom, {result})" + checker: | + class Checker: + MOD = 1000000007 + + def waysToBuildRooms(self, prevRoom, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + n = len(prevRoom) + if n < 2 or n > 100000 or prevRoom[0] != -1: + return False + children = [[] for _ in range(n)] + for i in range(1, n): + p = prevRoom[i] + if not isinstance(p, int) or p < 0 or p >= n: + return False + children[p].append(i) + fact = [1] * (n + 1) + for i in range(1, n + 1): + fact[i] = fact[i - 1] * i % self.MOD + invfact = [1] * (n + 1) + invfact[n] = pow(fact[n], self.MOD - 2, self.MOD) + for i in range(n, 0, -1): + invfact[i - 1] = invfact[i] * i % self.MOD + size = [0] * n + ways = [1] * n + order = [0] + for v in order: + order.extend(children[v]) + if len(order) != n: + return False + for v in reversed(order): + total = 0 + w = 1 + for u in children[v]: + c = size[u] + w = w * fact[total + c] % self.MOD + w = w * invfact[total] % self.MOD + w = w * invfact[c] % self.MOD + w = w * ways[u] % self.MOD + total += c + size[v] = total + 1 + ways[v] = w + return result == ways[0] +seed: 1916 +tests: + - name: chain-3 + in: + prevRoom: [-1, 0, 1] + - name: chain-5 + in: + prevRoom: [-1, 0, 1, 2, 3] + - name: star-3 + in: + prevRoom: [-1, 0, 0] + - name: star-6 + in: + prevRoom: [-1, 0, 0, 0, 0, 0] + - name: example-two + in: + prevRoom: [-1, 0, 0, 1, 2] + - name: balanced-7 + in: + prevRoom: [-1, 0, 0, 1, 1, 2, 2] + - name: balanced-15 + in: + prevRoom: [-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6] + - name: broom + in: + prevRoom: [-1, 0, 0, 0, 0, 1, 1, 1, 2, 2] + - name: two-branches + in: + prevRoom: [-1, 0, 0, 1, 2, 3, 4, 5, 6] + - name: uneven-left + in: + prevRoom: [-1, 0, 0, 1, 1, 1, 2, 2, 3, 4] + - name: uneven-right + in: + prevRoom: [-1, 0, 0, 0, 1, 2, 2, 3, 3, 3] + - name: root-and-three + in: + prevRoom: [-1, 0, 0, 0] + - name: root-and-four + in: + prevRoom: [-1, 0, 0, 0, 0] + - name: deep-tail-after-star + in: + prevRoom: [-1, 0, 0, 0, 0, 4, 5, 6, 7, 8] + - name: alternating-parent + in: + prevRoom: [-1, 0, 0, 1, 0, 2, 1, 3, 2, 4, 3, 5] + - name: shallow-wide + in: + prevRoom: [-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: root-two-subtrees + in: + prevRoom: [-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4] + - name: comb-left + in: + prevRoom: [-1, 0, 1, 1, 3, 3, 5, 5, 7, 7, 9] + - name: comb-right + in: + prevRoom: [-1, 0, 0, 2, 2, 4, 4, 6, 6, 8, 8] + - name: four-level + in: + prevRoom: [-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7] + - name: dense-early + in: + prevRoom: [-1, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3] + - name: dense-late + in: + prevRoom: [-1, 0, 1, 2, 0, 1, 2, 3, 4, 5, 6, 7] + - name: five-leaves-one-chain + in: + prevRoom: [-1, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5] + - name: split-three + in: + prevRoom: [-1, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5] + - name: near-complete-heap + in: + prevRoom: [-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6] + - name: parent-reuse + in: + prevRoom: [-1, 0, 0, 1, 0, 1, 0, 2, 1, 2, 0, 3, 3, 4, 4] + - name: zigzag-parents + in: + prevRoom: [-1, 0, 1, 0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5, 7] + - name: eight-root-children + in: + prevRoom: [-1, 0, 0, 0, 0, 0, 0, 0, 0] + - name: eight-chain + in: + prevRoom: [-1, 0, 1, 2, 3, 4, 5, 6, 7] + - name: mixed-branching + in: + prevRoom: [-1, 0, 0, 1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 8] + - name: mixed-branching-2 + in: + prevRoom: [-1, 0, 0, 0, 1, 2, 2, 3, 3, 4, 5, 5, 6, 7, 7] + - name: ten-balanced-ish + in: + prevRoom: [-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 7, 8, 8] + - name: root-with-long-and-short + in: + prevRoom: [-1, 0, 0, 1, 2, 3, 4, 5, 6, 0, 9, 10, 0] + - name: structured-20 + in: + prevRoom: [-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9] + - name: stress-static-100 + in: + prevRoom: + [ + -1, + 0, + 0, + 1, + 1, + 2, + 2, + 3, + 3, + 4, + 4, + 5, + 5, + 6, + 6, + 7, + 7, + 8, + 8, + 9, + 9, + 10, + 10, + 11, + 11, + 12, + 12, + 13, + 13, + 14, + 14, + 15, + 15, + 16, + 16, + 17, + 17, + 18, + 18, + 19, + ] diff --git a/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.cpp b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.cpp new file mode 100644 index 00000000..853e1df3 --- /dev/null +++ b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.cpp @@ -0,0 +1,91 @@ +class Solution { + +public: + + int waysToBuildRooms(vector& prevRoom) { + + int n = prevRoom.size(); + + vector> tree(n); + + for (int i = 1; i < n; i++) { + + tree[prevRoom[i]].push_back(i); + + } + + long long MOD = 1e9 + 7; + + vector fact(n+1), invFact(n+1); + + fact[0] = 1; + + for (int i = 1; i <= n; i++) fact[i] = fact[i-1] * i % MOD; + + invFact[n] = powMod(fact[n], MOD-2, MOD); + + for (int i = n; i > 0; i--) invFact[i-1] = invFact[i] * i % MOD; + + vector ways(n); + + vector size(n); + + function dfs = [&](int node) { + + ways[node] = 1; + + size[node] = 1; + + for (int child : tree[node]) { + + dfs(child); + + int oldSize = size[node]; + + size[node] += size[child]; + + ways[node] = ways[node] * comb(size[node]-1, oldSize-1, fact, invFact, MOD) % MOD; + + ways[node] = ways[node] * ways[child] % MOD; + + } + + }; + + dfs(0); + + return ways[0]; + + } + +private: + + long long powMod(long long a, long long b, long long mod) { + + long long res = 1; + + a %= mod; + + while (b > 0) { + + if (b & 1) res = res * a % mod; + + a = a * a % mod; + + b >>= 1; + + } + + return res; + + } + + long long comb(int n, int k, vector& fact, vector& invFact, long long mod) { + + if (k < 0 || k > n) return 0; + + return fact[n] * invFact[k] % mod * invFact[n-k] % mod; + + } + +}; diff --git a/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.cs b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.cs new file mode 100644 index 00000000..9d4fe99f --- /dev/null +++ b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.cs @@ -0,0 +1,87 @@ +public class Solution { + + public int WaysToBuildRooms(int[] prevRoom) { + + int n = prevRoom.Length; + + var tree = new List[n]; + + for (int i = 0; i < n; i++) tree[i] = new List(); + + for (int i = 1; i < n; i++) tree[prevRoom[i]].Add(i); + + long MOD = 1_000_000_007; + + long[] fact = new long[n+1]; + + long[] invFact = new long[n+1]; + + fact[0] = 1; + + for (int i = 1; i <= n; i++) fact[i] = fact[i-1] * i % MOD; + + invFact[n] = PowMod(fact[n], MOD-2, MOD); + + for (int i = n; i > 0; i--) invFact[i-1] = invFact[i] * i % MOD; + + long[] ways = new long[n]; + + int[] size = new int[n]; + + Dfs(0, tree, ways, size, fact, invFact, MOD); + + return (int)ways[0]; + + } + + private void Dfs(int node, List[] tree, long[] ways, int[] size, long[] fact, long[] invFact, long MOD) { + + ways[node] = 1; + + size[node] = 1; + + foreach (int child in tree[node]) { + + Dfs(child, tree, ways, size, fact, invFact, MOD); + + int oldSize = size[node]; + + size[node] += size[child]; + + ways[node] = ways[node] * Comb(size[node]-1, oldSize-1, fact, invFact, MOD) % MOD; + + ways[node] = ways[node] * ways[child] % MOD; + + } + + } + + private long Comb(int n, int k, long[] fact, long[] invFact, long MOD) { + + if (k < 0 || k > n) return 0; + + return fact[n] * invFact[k] % MOD * invFact[n-k] % MOD; + + } + + private long PowMod(long a, long b, long MOD) { + + long res = 1; + + a %= MOD; + + while (b > 0) { + + if ((b & 1) == 1) res = res * a % MOD; + + a = a * a % MOD; + + b >>= 1; + + } + + return res; + + } + +} diff --git a/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.dart b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.dart new file mode 100644 index 00000000..4ded79fc --- /dev/null +++ b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.dart @@ -0,0 +1,48 @@ +class Solution { + static const int _mod = 1000000007; + + int waysToBuildRooms(List prevRoom) { + final n = prevRoom.length; + final children = List.generate(n, (_) => []); + for (var room = 1; room < n; room++) { + children[prevRoom[room]].add(room); + } + + final factorial = List.filled(n + 1, 1); + final inverseFactorial = List.filled(n + 1, 1); + for (var i = 1; i <= n; i++) { + factorial[i] = (factorial[i - 1] * i) % _mod; + } + inverseFactorial[n] = _pow(factorial[n], _mod - 2); + for (var i = n; i > 0; i--) { + inverseFactorial[i - 1] = (inverseFactorial[i] * i) % _mod; + } + + final order = [0]; + for (var i = 0; i < order.length; i++) { + order.addAll(children[order[i]]); + } + final size = List.filled(n, 1); + final ways = List.filled(n, 1); + for (var index = order.length - 1; index >= 0; index--) { + final node = order[index]; + for (final child in children[node]) { + ways[node] = (ways[node] * ways[child]) % _mod; + ways[node] = (ways[node] * inverseFactorial[size[child]]) % _mod; + size[node] += size[child]; + } + ways[node] = (ways[node] * factorial[size[node] - 1]) % _mod; + } + return ways[0]; + } + + int _pow(int base, int exponent) { + var result = 1; + while (exponent > 0) { + if ((exponent & 1) != 0) result = (result * base) % _mod; + base = (base * base) % _mod; + exponent >>= 1; + } + return result; + } +} diff --git a/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.go b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.go new file mode 100644 index 00000000..bd9c810c --- /dev/null +++ b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.go @@ -0,0 +1,53 @@ +func waysToBuildRooms(prevRoom []int) int { + const MOD = 1000000007 + n := len(prevRoom) + tree := make([][]int, n) + for i := 1; i < n; i++ { + tree[prevRoom[i]] = append(tree[prevRoom[i]], i) + } + fact := make([]int64, n+1) + invFact := make([]int64, n+1) + fact[0] = 1 + for i := 1; i <= n; i++ { + fact[i] = fact[i-1] * int64(i) % MOD + } + invFact[n] = powMod(fact[n], int64(MOD-2), int64(MOD)) + for i := n; i > 0; i-- { + invFact[i-1] = invFact[i] * int64(i) % MOD + } + ways := make([]int64, n) + size := make([]int, n) + var dfs func(int) + dfs = func(node int) { + ways[node] = 1 + size[node] = 1 + for _, child := range tree[node] { + dfs(child) + oldSize := size[node] + size[node] += size[child] + ways[node] = ways[node] * comb(int64(size[node]-1), int64(oldSize-1), fact, invFact, int64(MOD)) % MOD + ways[node] = ways[node] * ways[child] % MOD + } + } + dfs(0) + return int(ways[0]) +} + +func comb(n, k int64, fact, invFact []int64, mod int64) int64 { + if k < 0 || k > n { + return 0 + } + return fact[n] * invFact[k] % mod * invFact[n-k] % mod +} + +func powMod(a, b, mod int64) int64 { + res := int64(1) + for b > 0 { + if b&1 == 1 { + res = res * a % mod + } + a = a * a % mod + b >>= 1 + } + return res +} diff --git a/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.java b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.java new file mode 100644 index 00000000..e3f51f4d --- /dev/null +++ b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.java @@ -0,0 +1,86 @@ +@SuppressWarnings("unchecked") +class Solution { + + public int waysToBuildRooms(int[] prevRoom) { + + int n = prevRoom.length; + + List[] tree = new List[n]; + + for (int i = 0; i < n; i++) tree[i] = new ArrayList<>(); + + for (int i = 1; i < n; i++) tree[prevRoom[i]].add(i); + + long[] fact = new long[n + 1]; + + long[] invFact = new long[n + 1]; + + int MOD = 1_000_000_007; + + fact[0] = 1; + + for (int i = 1; i <= n; i++) fact[i] = fact[i - 1] * i % MOD; + + invFact[n] = pow(fact[n], MOD - 2, MOD); + + for (int i = n; i > 0; i--) invFact[i - 1] = invFact[i] * i % MOD; + + long[] ways = new long[n]; + + int[] size = new int[n]; + + dfs(0, tree, ways, size, fact, invFact, MOD); + + return (int) ways[0]; + + } + + private void dfs(int node, List[] tree, long[] ways, int[] size, long[] fact, long[] invFact, int MOD) { + + ways[node] = 1; + + size[node] = 1; + + for (int child : tree[node]) { + + dfs(child, tree, ways, size, fact, invFact, MOD); + + int oldSize = size[node]; + + size[node] += size[child]; + + ways[node] = ways[node] * comb(size[node] - 1, oldSize - 1, fact, invFact, MOD) % MOD; + + ways[node] = ways[node] * ways[child] % MOD; + + } + + } + + private long comb(int n, int k, long[] fact, long[] invFact, int MOD) { + + if (k < 0 || k > n) return 0; + + return fact[n] * invFact[k] % MOD * invFact[n - k] % MOD; + + } + + private long pow(long a, long b, int MOD) { + + long res = 1; + + while (b > 0) { + + if ((b & 1) == 1) res = res * a % MOD; + + a = a * a % MOD; + + b >>= 1; + + } + + return res; + + } + +} diff --git a/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.kt b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.kt new file mode 100644 index 00000000..2e02057f --- /dev/null +++ b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.kt @@ -0,0 +1,91 @@ +class Solution { + + fun waysToBuildRooms(prevRoom: IntArray): Int { + + val MOD = 1_000_000_007 + + val n = prevRoom.size + + val tree = Array(n) { mutableListOf() } + + for (i in 1 until n) { + + tree[prevRoom[i]].add(i) + + } + + val fact = LongArray(n + 1) + + val invFact = LongArray(n + 1) + + fact[0] = 1 + + for (i in 1..n) fact[i] = fact[i - 1] * i % MOD + + invFact[n] = powMod(fact[n], (MOD - 2).toLong(), MOD.toLong()).toInt().toLong() // actually simpler to compute directly + + for (i in n downTo 1) invFact[i - 1] = invFact[i] * i % MOD + + val ways = LongArray(n) + + val size = IntArray(n) + + fun dfs(node: Int) { + + ways[node] = 1 + + size[node] = 1 + + for (child in tree[node]) { + + dfs(child) + + val oldSize = size[node] + + size[node] += size[child] + + ways[node] = ways[node] * comb(size[node] - 1, oldSize - 1, fact, invFact, MOD) % MOD + + ways[node] = ways[node] * ways[child] % MOD + + } + + } + + dfs(0) + + return ways[0].toInt() + + } + + private fun comb(n: Int, k: Int, fact: LongArray, invFact: LongArray, mod: Int): Long { + + if (k < 0 || k > n) return 0 + + return fact[n] * invFact[k] % mod * invFact[n - k] % mod + + } + + private fun powMod(a: Long, b: Long, mod: Long): Long { + + var res = 1L + + var base = a % mod + + var exp = b + + while (exp > 0) { + + if ((exp and 1L) == 1L) res = res * base % mod + + base = base * base % mod + + exp = exp shr 1 + + } + + return res + + } + +} diff --git a/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.py b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.py new file mode 100644 index 00000000..d88819d8 --- /dev/null +++ b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.py @@ -0,0 +1,21 @@ +from math import comb + + +class Solution: + def waysToBuildRooms(self, prevRoom: List[int]) -> int: + tree = defaultdict(list) + for i, x in enumerate(prevRoom): + tree[x].append(i) + + def fn(n): + """Return number of nodes and ways to build sub-tree.""" + if not tree[n]: + return 1, 1 # leaf + c, m = 0, 1 + for nn in tree[n]: + cc, mm = fn(nn) + c += cc + m = (m * comb(c, cc) * mm) % 1_000_000_007 + return c + 1, m + + return fn(0)[1] diff --git a/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.py2 b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.py2 new file mode 100644 index 00000000..561b7ea5 --- /dev/null +++ b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.py2 @@ -0,0 +1,56 @@ +class Solution(object): + + def waysToBuildRooms(self, prevRoom): + + """ + + :type prevRoom: List[int] + + :rtype: int + + """ + + from collections import defaultdict + + def comb(n, k): + if k < 0 or k > n: + return 0 + k = min(k, n - k) + value = 1 + for i in range(1, k + 1): + value = value * (n - k + i) // i + return value + + MOD = 1000000007 + + tree = defaultdict(list) + + for i, p in enumerate(prevRoom): + + if p >= 0: + + tree[p].append(i) + + def dfs(node): + + if not tree[node]: + + return 1, 1 + + total_size = 0 + + ways = 1 + + for child in tree[node]: + + child_size, child_ways = dfs(child) + + total_size += child_size + + ways = ways * comb(total_size, child_size) % MOD + + ways = ways * child_ways % MOD + + return total_size + 1, ways + + return dfs(0)[1] diff --git a/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.rb b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.rb new file mode 100644 index 00000000..c2317f73 --- /dev/null +++ b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.rb @@ -0,0 +1,79 @@ +# @param {Integer[]} prev_room + +# @return {Integer} + +def ways_to_build_rooms(prev_room) + + mod = 1_000_000_007 + + tree = Hash.new { |h, k| h[k] = [] } + + prev_room.each_with_index do |p, i| + + tree[p] << i if p >= 0 + + end + + fact = [1] * (prev_room.length + 1) + + (1..prev_room.length).each { |i| fact[i] = fact[i-1] * i % mod } + + inv_fact = [1] * (prev_room.length + 1) + + inv_fact[prev_room.length] = pow_mod(fact[prev_room.length], mod-2, mod) + + (prev_room.length-1).downto(0) { |i| inv_fact[i] = inv_fact[i+1] * (i+1) % mod } + + dfs = lambda do |node| + + size = 1 + + ways = 1 + + tree[node].each do |child| + + child_size, child_ways = dfs.call(child) + + total = size + child_size - 1 + + ways = ways * comb(total, child_size, fact, inv_fact, mod) % mod + + ways = ways * child_ways % mod + + size += child_size + + end + + [size, ways] + + end + + dfs.call(0)[1] + +end + +def pow_mod(a, b, mod) + + res = 1 + + while b > 0 + + res = res * a % mod if b.odd? + + a = a * a % mod + + b >>= 1 + + end + + res + +end + +def comb(n, k, fact, inv_fact, mod) + + return 0 if k < 0 || k > n + + fact[n] * inv_fact[k] % mod * inv_fact[n-k] % mod + +end diff --git a/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.rs b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.rs new file mode 100644 index 00000000..f2a56027 --- /dev/null +++ b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.rs @@ -0,0 +1,99 @@ +impl Solution { + + pub fn ways_to_build_rooms(prev_room: Vec) -> i32 { + + let n = prev_room.len(); + + let mut tree = vec![vec![]; n]; + + for i in 1..n { + + tree[prev_room[i] as usize].push(i); + + } + + let mod_val = 1_000_000_007i64; + + let mut fact = vec![1i64; n+1]; + + let mut inv_fact = vec![1i64; n+1]; + + for i in 1..=n { + + fact[i] = fact[i-1] * i as i64 % mod_val; + + } + + inv_fact[n] = Self::pow_mod(fact[n], mod_val - 2, mod_val); + + for i in (1..=n).rev() { + + inv_fact[i-1] = inv_fact[i] * i as i64 % mod_val; + + } + + let mut ways = vec![0i64; n]; + + let mut size = vec![0usize; n]; + + Self::dfs(0, &tree, &mut ways, &mut size, &fact, &inv_fact, mod_val); + + ways[0] as i32 + + } + + fn dfs(node: usize, tree: &Vec>, ways: &mut Vec, size: &mut Vec, fact: &Vec, inv_fact: &Vec, mod_val: i64) { + + ways[node] = 1; + + size[node] = 1; + + for &child in &tree[node] { + + Self::dfs(child, tree, ways, size, fact, inv_fact, mod_val); + + let old_size = size[node]; + + size[node] += size[child]; + + ways[node] = ways[node] * Self::comb(size[node] as i64 - 1, (old_size-1) as i64, fact, inv_fact, mod_val) % mod_val; + + ways[node] = ways[node] * ways[child] % mod_val; + + } + + } + + fn comb(n: i64, k: i64, fact: &Vec, inv_fact: &Vec, mod_val: i64) -> i64 { + + if k < 0 || k > n { return 0; } + + fact[n as usize] * inv_fact[k as usize] % mod_val * inv_fact[(n-k) as usize] % mod_val + + } + + fn pow_mod(mut a: i64, mut b: i64, mod_val: i64) -> i64 { + + let mut res = 1i64; + + a %= mod_val; + + while b > 0 { + + if b & 1 == 1 { + + res = res * a % mod_val; + + } + + a = a * a % mod_val; + + b >>= 1; + + } + + res + + } + +} diff --git a/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.swift b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.swift new file mode 100644 index 00000000..db6f1238 --- /dev/null +++ b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.swift @@ -0,0 +1,101 @@ +class Solution { + + func waysToBuildRooms(_ prevRoom: [Int]) -> Int { + + let MOD = 1_000_000_007 + + let n = prevRoom.count + + var tree = Array(repeating: [Int](), count: n) + + for i in 1.. Int64 { + + if k < 0 || k > n { return 0 } + + return fact[Int(n)] * invFact[Int(k)] % mod * invFact[Int(n-k)] % mod + + } + + private func powMod(_ a: Int64, _ b: Int64, _ mod: Int64) -> Int64 { + + var res: Int64 = 1 + + var base = a % mod + + var exp = b + + while exp > 0 { + + if exp & 1 == 1 { + + res = res * base % mod + + } + + base = base * base % mod + + exp >>= 1 + + } + + return res + + } + +} diff --git a/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.ts b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.ts new file mode 100644 index 00000000..20f60c93 --- /dev/null +++ b/tests/1501-2000/1916. count-ways-to-build-rooms-in-an-ant-colony/sol.ts @@ -0,0 +1,52 @@ +function waysToBuildRooms(prevRoom: number[]): number { + const MOD = 1_000_000_007; + const n = prevRoom.length; + const tree: number[][] = Array.from({ length: n }, () => []); + for (let i = 1; i < n; i++) { + tree[prevRoom[i]].push(i); + } + const mod = BigInt(MOD); + const fact: bigint[] = new Array(n + 1).fill(1n); + const invFact: bigint[] = new Array(n + 1).fill(1n); + for (let i = 1; i <= n; i++) fact[i] = (fact[i - 1] * BigInt(i)) % mod; + invFact[n] = powMod(fact[n], BigInt(MOD - 2), mod); + for (let i = n; i > 0; i--) invFact[i - 1] = (invFact[i] * BigInt(i)) % mod; + const ways: bigint[] = new Array(n).fill(0n); + const size: number[] = new Array(n).fill(0); + function dfs(node: number) { + ways[node] = 1n; + size[node] = 1; + for (const child of tree[node]) { + dfs(child); + const oldSize = size[node]; + size[node] += size[child]; + ways[node] = + (ways[node] * comb(size[node] - 1, oldSize - 1, fact, invFact, mod)) % + mod; + ways[node] = (ways[node] * ways[child]) % mod; + } + } + dfs(0); + return Number(ways[0]); +} +function comb( + n: number, + k: number, + fact: bigint[], + invFact: bigint[], + mod: bigint, +): bigint { + if (k < 0 || k > n) return 0n; + return (((fact[n] * invFact[k]) % mod) * invFact[n - k]) % mod; +} +function powMod(a: bigint, b: bigint, mod: bigint): bigint { + let res = 1n; + let base = a % mod; + let exp = b; + while (exp > 0) { + if (exp % 2n === 1n) res = (res * base) % mod; + base = (base * base) % mod; + exp /= 2n; + } + return res; +} diff --git a/tests/1501-2000/1920. build-array-from-permutation/manifest.yaml b/tests/1501-2000/1920. build-array-from-permutation/manifest.yaml new file mode 100644 index 00000000..d84b1d5d --- /dev/null +++ b/tests/1501-2000/1920. build-array-from-permutation/manifest.yaml @@ -0,0 +1,389 @@ +entry: + id: 1920 + title: "build-array-from-permutation" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().buildArray({nums})" + rust: "Solution::build_array({nums})" + python3: "Solution().buildArray({nums})" + python2: "Solution().buildArray({nums})" + ruby: "build_array({nums})" + java: "new Solution().buildArray({nums})" + csharp: "new Solution().BuildArray({nums})" + kotlin: "Solution().buildArray({nums})" + go: "buildArray({nums})" + dart: "Solution().buildArray({nums})" + swift: "Solution().buildArray({nums})" + typescript: "buildArray({nums})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().buildArray(nums, {result})" + checker: | + class Checker: + def buildArray(self, nums, result): + return isinstance(result, list) and result == [nums[nums[i]] for i in range(len(nums))] + +seed: 1920 + +tests: + - name: single + in: + nums: [0] + out: [0] + - name: two-identity + in: + nums: [0, 1] + out: [0, 1] + - name: two-swap + in: + nums: [1, 0] + out: [0, 1] + - name: example-one + in: + nums: [0, 2, 1, 5, 3, 4] + out: [0, 1, 2, 4, 5, 3] + - name: example-two + in: + nums: [5, 0, 1, 2, 3, 4] + out: [4, 5, 0, 1, 2, 3] + - name: identity-three + in: + nums: [0, 1, 2] + out: [0, 1, 2] + - name: reverse-three + in: + nums: [2, 1, 0] + out: [0, 1, 2] + - name: cycle-three + in: + nums: [1, 2, 0] + out: [2, 0, 1] + - name: cycle-three-reverse + in: + nums: [2, 0, 1] + out: [1, 2, 0] + - name: identity-four + in: + nums: [0, 1, 2, 3] + out: [0, 1, 2, 3] + - name: swap-pairs-four + in: + nums: [1, 0, 3, 2] + out: [0, 1, 2, 3] + - name: cycle-four + in: + nums: [1, 2, 3, 0] + out: [2, 3, 0, 1] + - name: mixed-four + in: + nums: [2, 0, 3, 1] + out: [3, 2, 1, 0] + - name: identity-five + in: + nums: [0, 1, 2, 3, 4] + out: [0, 1, 2, 3, 4] + - name: cycle-five + in: + nums: [1, 2, 3, 4, 0] + out: [2, 3, 4, 0, 1] + - name: reverse-five + in: + nums: [4, 3, 2, 1, 0] + out: [0, 1, 2, 3, 4] + - name: mixed-five + in: + nums: [2, 4, 1, 0, 3] + out: [1, 3, 4, 2, 0] + - name: identity-six + in: + nums: [0, 1, 2, 3, 4, 5] + out: [0, 1, 2, 3, 4, 5] + - name: cycle-six + in: + nums: [1, 2, 3, 4, 5, 0] + out: [2, 3, 4, 5, 0, 1] + - name: mixed-six + in: + nums: [3, 0, 5, 2, 1, 4] + out: [2, 3, 4, 5, 0, 1] + - name: identity-seven + in: + nums: [0, 1, 2, 3, 4, 5, 6] + out: [0, 1, 2, 3, 4, 5, 6] + - name: mixed-seven + in: + nums: [6, 0, 5, 1, 4, 2, 3] + out: [3, 6, 2, 0, 4, 5, 1] + - name: cycle-seven + in: + nums: [1, 2, 3, 4, 5, 6, 0] + out: [2, 3, 4, 5, 6, 0, 1] + - name: identity-eight + in: + nums: [0, 1, 2, 3, 4, 5, 6, 7] + out: [0, 1, 2, 3, 4, 5, 6, 7] + - name: pairs-eight + in: + nums: [1, 0, 3, 2, 5, 4, 7, 6] + out: [0, 1, 2, 3, 4, 5, 6, 7] + - name: mixed-eight + in: + nums: [4, 7, 2, 0, 6, 1, 5, 3] + out: [6, 3, 2, 4, 5, 7, 1, 0] + - name: cycle-nine + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 0] + out: [2, 3, 4, 5, 6, 7, 8, 0, 1] + - name: mixed-nine + in: + nums: [8, 3, 1, 7, 0, 6, 4, 2, 5] + out: [5, 7, 3, 2, 8, 4, 0, 1, 6] + - name: identity-ten + in: + nums: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + - name: reverse-ten + in: + nums: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] + out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + - name: mixed-ten + in: + nums: [2, 8, 5, 1, 9, 0, 7, 3, 6, 4] + out: [5, 6, 0, 8, 4, 2, 3, 1, 7, 9] + - name: cycle-twenty + in: + nums: + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0] + out: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 1] + - name: mixed-twelve + in: + nums: [7, 2, 11, 0, 9, 4, 1, 10, 6, 3, 8, 5] + out: [10, 11, 5, 7, 3, 9, 2, 8, 1, 0, 6, 4] + - name: large-identity + in: + nums: + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + ] + out: + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + ] + - name: large-cycle + in: + nums: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 0, + ] + out: + [ + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 0, + 1, + ] diff --git a/tests/1501-2000/1920. build-array-from-permutation/sol.cpp b/tests/1501-2000/1920. build-array-from-permutation/sol.cpp new file mode 100644 index 00000000..54fda310 --- /dev/null +++ b/tests/1501-2000/1920. build-array-from-permutation/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + vector buildArray(vector& nums) { + for (int i = 0; i < nums.size(); i++) { + nums[i] += (1024 * (nums[nums[i]] % 1024)); + } + + for (int i = 0; i < nums.size(); i++) { + nums[i] /= 1024; + } + + return nums; + } +}; diff --git a/tests/1501-2000/1920. build-array-from-permutation/sol.cs b/tests/1501-2000/1920. build-array-from-permutation/sol.cs new file mode 100644 index 00000000..ea47b857 --- /dev/null +++ b/tests/1501-2000/1920. build-array-from-permutation/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public int[] BuildArray(int[] nums) { + for (int i = 0; i < nums.Length; i++) { + nums[i] += (1024 * (nums[nums[i]] % 1024)); + } + + for (int i = 0; i < nums.Length; i++) { + nums[i] /= 1024; + } + + return nums; + } +} diff --git a/tests/1501-2000/1920. build-array-from-permutation/sol.dart b/tests/1501-2000/1920. build-array-from-permutation/sol.dart new file mode 100644 index 00000000..bbb7a6c2 --- /dev/null +++ b/tests/1501-2000/1920. build-array-from-permutation/sol.dart @@ -0,0 +1,13 @@ +class Solution { + List buildArray(List nums) { + for (int i = 0; i < nums.length; i++) { + nums[i] += (1024 * (nums[nums[i]] % 1024)); + } + + for (int i = 0; i < nums.length; i++) { + nums[i] ~/= 1024; + } + + return nums; + } +} diff --git a/tests/1501-2000/1920. build-array-from-permutation/sol.go b/tests/1501-2000/1920. build-array-from-permutation/sol.go new file mode 100644 index 00000000..04c15b16 --- /dev/null +++ b/tests/1501-2000/1920. build-array-from-permutation/sol.go @@ -0,0 +1,11 @@ +func buildArray(nums []int) []int { + for i := 0; i < len(nums); i++ { + nums[i] += (1024 * (nums[nums[i]] % 1024)) + } + + for i := 0; i < len(nums); i++ { + nums[i] /= 1024 + } + + return nums +} diff --git a/tests/1501-2000/1920. build-array-from-permutation/sol.java b/tests/1501-2000/1920. build-array-from-permutation/sol.java new file mode 100644 index 00000000..b5a1bee7 --- /dev/null +++ b/tests/1501-2000/1920. build-array-from-permutation/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int[] buildArray(int[] nums) { + for (int i = 0; i < nums.length; i++) { + nums[i] += (1024 * (nums[nums[i]] % 1024)); + } + + for (int i = 0; i < nums.length; i++) { + nums[i] /= 1024; + } + + return nums; + } +} diff --git a/tests/1501-2000/1920. build-array-from-permutation/sol.kt b/tests/1501-2000/1920. build-array-from-permutation/sol.kt new file mode 100644 index 00000000..b42559e1 --- /dev/null +++ b/tests/1501-2000/1920. build-array-from-permutation/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun buildArray(nums: IntArray): IntArray { + for (i in nums.indices) { + nums[i] += (1024 * (nums[nums[i]] % 1024)) + } + + for (i in nums.indices) { + nums[i] /= 1024 + } + + return nums + } +} diff --git a/tests/1501-2000/1920. build-array-from-permutation/sol.py b/tests/1501-2000/1920. build-array-from-permutation/sol.py new file mode 100644 index 00000000..4174cc6c --- /dev/null +++ b/tests/1501-2000/1920. build-array-from-permutation/sol.py @@ -0,0 +1,9 @@ +class Solution(object): + def buildArray(self, nums): + for i in range(len(nums)): + nums[i] += 1024 * (nums[nums[i]] % 1024) + + for i in range(len(nums)): + nums[i] //= 1024 + + return nums diff --git a/tests/1501-2000/1920. build-array-from-permutation/sol.py2 b/tests/1501-2000/1920. build-array-from-permutation/sol.py2 new file mode 100644 index 00000000..c15ad78e --- /dev/null +++ b/tests/1501-2000/1920. build-array-from-permutation/sol.py2 @@ -0,0 +1,13 @@ +class Solution(object): + def buildArray(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + for i in range(len(nums)): + nums[i] += (1024 * (nums[nums[i]] % 1024)) + + for i in range(len(nums)): + nums[i] //= 1024 + + return nums diff --git a/tests/1501-2000/1920. build-array-from-permutation/sol.rb b/tests/1501-2000/1920. build-array-from-permutation/sol.rb new file mode 100644 index 00000000..c69e2b55 --- /dev/null +++ b/tests/1501-2000/1920. build-array-from-permutation/sol.rb @@ -0,0 +1,13 @@ +# @param {Integer[]} nums +# @return {Integer[]} +def build_array(nums) + for i in 0...nums.length + nums[i] += (1024 * (nums[nums[i]] % 1024)) + end + + for i in 0...nums.length + nums[i] /= 1024 + end + + nums +end diff --git a/tests/1501-2000/1920. build-array-from-permutation/sol.rs b/tests/1501-2000/1920. build-array-from-permutation/sol.rs new file mode 100644 index 00000000..9e4cfb81 --- /dev/null +++ b/tests/1501-2000/1920. build-array-from-permutation/sol.rs @@ -0,0 +1,14 @@ +impl Solution { + pub fn build_array(nums: Vec) -> Vec { + let mut nums = nums; + for i in 0..nums.len() { + nums[i] += (1024 * (nums[nums[i] as usize] % 1024)); + } + + for i in 0..nums.len() { + nums[i] /= 1024; + } + + nums + } +} diff --git a/tests/1501-2000/1920. build-array-from-permutation/sol.swift b/tests/1501-2000/1920. build-array-from-permutation/sol.swift new file mode 100644 index 00000000..e3a80203 --- /dev/null +++ b/tests/1501-2000/1920. build-array-from-permutation/sol.swift @@ -0,0 +1,14 @@ +class Solution { + func buildArray(_ nums: [Int]) -> [Int] { + var nums = nums + for i in 0..& dist, vector& speed) { + vector arrival; + for (int i = 0; i < dist.size(); i++) { + arrival.push_back((dist[i] + speed[i] - 1) / speed[i]); + } + sort(arrival.begin(), arrival.end()); + for (int minute = 0; minute < arrival.size(); minute++) { + if (arrival[minute] <= minute) { + return minute; + } + } + return arrival.size(); + } +}; diff --git a/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.cs b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.cs new file mode 100644 index 00000000..378f08e8 --- /dev/null +++ b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public int EliminateMaximum(int[] dist, int[] speed) { + int n = dist.Length; + int[] arrival = new int[n]; + for (int i = 0; i < n; i++) { + arrival[i] = (dist[i] + speed[i] - 1) / speed[i]; + } + Array.Sort(arrival); + for (int minute = 0; minute < n; minute++) { + if (arrival[minute] <= minute) { + return minute; + } + } + return n; + } +} diff --git a/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.dart b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.dart new file mode 100644 index 00000000..7a173604 --- /dev/null +++ b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.dart @@ -0,0 +1,15 @@ +class Solution { + int eliminateMaximum(List dist, List speed) { + List arrival = []; + for (int i = 0; i < dist.length; i++) { + arrival.add((dist[i] + speed[i] - 1) ~/ speed[i]); + } + arrival.sort(); + for (int minute = 0; minute < arrival.length; minute++) { + if (arrival[minute] <= minute) { + return minute; + } + } + return arrival.length; + } +} diff --git a/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.go b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.go new file mode 100644 index 00000000..dff4bfe1 --- /dev/null +++ b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.go @@ -0,0 +1,13 @@ +func eliminateMaximum(dist []int, speed []int) int { + arrival := make([]int, len(dist)) + for i := 0; i < len(dist); i++ { + arrival[i] = (dist[i] + speed[i] - 1) / speed[i] + } + sort.Ints(arrival) + for minute, time := range arrival { + if time <= minute { + return minute + } + } + return len(arrival) +} diff --git a/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.java b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.java new file mode 100644 index 00000000..fcc261d7 --- /dev/null +++ b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.java @@ -0,0 +1,16 @@ +class Solution { + public int eliminateMaximum(int[] dist, int[] speed) { + int n = dist.length; + int[] arrival = new int[n]; + for (int i = 0; i < n; i++) { + arrival[i] = (dist[i] + speed[i] - 1) / speed[i]; + } + Arrays.sort(arrival); + for (int minute = 0; minute < n; minute++) { + if (arrival[minute] <= minute) { + return minute; + } + } + return n; + } +} diff --git a/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.kt b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.kt new file mode 100644 index 00000000..433d92fb --- /dev/null +++ b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.kt @@ -0,0 +1,12 @@ +class Solution { + fun eliminateMaximum(dist: IntArray, speed: IntArray): Int { + val arrival = IntArray(dist.size) { i -> (dist[i] + speed[i] - 1) / speed[i] } + arrival.sort() + for (minute in arrival.indices) { + if (arrival[minute] <= minute) { + return minute + } + } + return arrival.size + } +} diff --git a/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.py b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.py new file mode 100644 index 00000000..9181f67d --- /dev/null +++ b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.py @@ -0,0 +1,17 @@ +from typing import List + + +class Solution: + def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int: + arrival = [] + + for d, s in zip(dist, speed): + arrival.append((d + s - 1) // s) + + arrival.sort() + + for minute, time in enumerate(arrival): + if time <= minute: + return minute + + return len(arrival) diff --git a/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.py2 b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.py2 new file mode 100644 index 00000000..e6473341 --- /dev/null +++ b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def eliminateMaximum(self, dist, speed): + """ + :type dist: List[int] + :type speed: List[int] + :rtype: int + """ + arrival = [] + for d, s in zip(dist, speed): + arrival.append((d + s - 1) // s) + arrival.sort() + for minute, time in enumerate(arrival): + if time <= minute: + return minute + return len(arrival) diff --git a/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.rb b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.rb new file mode 100644 index 00000000..3aaa3d17 --- /dev/null +++ b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[]} dist +# @param {Integer[]} speed +# @return {Integer} +def eliminate_maximum(dist, speed) + arrival = [] + dist.each_with_index do |d, i| + arrival << (d + speed[i] - 1) / speed[i] + end + arrival.sort! + arrival.each_with_index do |time, minute| + return minute if time <= minute + end + arrival.length +end diff --git a/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.rs b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.rs new file mode 100644 index 00000000..0a73cd58 --- /dev/null +++ b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn eliminate_maximum(dist: Vec, speed: Vec) -> i32 { + let mut arrival: Vec = Vec::new(); + for i in 0..dist.len() { + arrival.push((dist[i] + speed[i] - 1) / speed[i]); + } + arrival.sort(); + for (minute, &time) in arrival.iter().enumerate() { + if time <= minute as i32 { + return minute as i32; + } + } + arrival.len() as i32 + } +} diff --git a/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.swift b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.swift new file mode 100644 index 00000000..9fe423c8 --- /dev/null +++ b/tests/1501-2000/1921. eliminate-maximum-number-of-monsters/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func eliminateMaximum(_ dist: [Int], _ speed: [Int]) -> Int { + var arrival = [Int]() + for i in 0.. a - b); + for (let minute = 0; minute < arrival.length; minute++) { + if (arrival[minute] <= minute) { + return minute; + } + } + return arrival.length; +} diff --git a/tests/1501-2000/1922. count-good-numbers/manifest.yaml b/tests/1501-2000/1922. count-good-numbers/manifest.yaml new file mode 100644 index 00000000..08aa7625 --- /dev/null +++ b/tests/1501-2000/1922. count-good-numbers/manifest.yaml @@ -0,0 +1,219 @@ +entry: + id: 1922 + title: "count-good-numbers" + params: + n: + type: long + call: + cpp: "Solution().countGoodNumbers({n})" + rust: "Solution::count_good_numbers({n})" + python3: "Solution().countGoodNumbers({n})" + python2: "Solution().countGoodNumbers({n})" + ruby: "count_good_numbers({n})" + java: "new Solution().countGoodNumbers({n})" + csharp: "new Solution().CountGoodNumbers({n})" + kotlin: "Solution().countGoodNumbers({n})" + go: "countGoodNumbers({n})" + dart: "Solution().countGoodNumbers({n})" + swift: "Solution().countGoodNumbers({n})" + typescript: "countGoodNumbers({n})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().countGoodNumbers(n, {result})" + checker: | + class Checker: + def countGoodNumbers(self, n, result): + if not isinstance(n, int) or not (1 <= n <= 10**15): + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + mod = 10**9 + 7 + expected = (pow(5, (n + 1) // 2, mod) * pow(4, n // 2, mod)) % mod + return result == expected + +seed: 1922 + +tests: + - name: "n_1" + in: + n: 1 + out: 5 + - name: "n_2" + in: + n: 2 + out: 20 + - name: "n_3" + in: + n: 3 + out: 100 + - name: "n_4_example" + in: + n: 4 + out: 400 + - name: "n_5" + in: + n: 5 + out: 2000 + - name: "n_6" + in: + n: 6 + out: 8000 + - name: "n_7" + in: + n: 7 + out: 40000 + - name: "n_8" + in: + n: 8 + out: 160000 + - name: "n_9" + in: + n: 9 + out: 800000 + - name: "n_10" + in: + n: 10 + out: 3200000 + - name: "n_11" + in: + n: 11 + out: 16000000 + - name: "n_12" + in: + n: 12 + out: 64000000 + - name: "n_13" + in: + n: 13 + out: 320000000 + - name: "n_14_modulo" + in: + n: 14 + out: 279999993 + - name: "n_15_modulo" + in: + n: 15 + out: 399999958 + - name: "n_16" + in: + n: 16 + out: 599999825 + - name: "n_17" + in: + n: 17 + out: 999999111 + - name: "n_18" + in: + n: 18 + out: 999996423 + - name: "n_19" + in: + n: 19 + out: 999982087 + - name: "n_20" + in: + n: 20 + out: 999928327 + - name: "n_25" + in: + n: 25 + out: 856640007 + - name: "n_30" + in: + n: 30 + out: 624001610 + - name: "n_31" + in: + n: 31 + out: 120008029 + - name: "n_32" + in: + n: 32 + out: 480032116 + - name: "n_40" + in: + n: 40 + out: 138022365 + - name: "n_50_example" + in: + n: 50 + out: 564908303 + - name: "n_64_power_boundary" + in: + n: 64 + out: 778421646 + - name: "n_75" + in: + n: 75 + out: 248816778 + - name: "n_100" + in: + n: 100 + out: 564490093 + - name: "n_101_odd" + in: + n: 101 + out: 822450451 + - name: "n_128_power_boundary" + in: + n: 128 + out: 719767538 + - name: "n_256_power_boundary" + in: + n: 256 + out: 132124309 + - name: "n_500" + in: + n: 500 + out: 315782032 + - name: "n_999_odd" + in: + n: 999 + out: 759005252 + - name: "n_1000" + in: + n: 1000 + out: 36020987 + - name: "generated_small" + seed: 19221 + in: + n: + gen: "int" + min: 1 + max: 100 + - name: "generated_medium" + seed: 19222 + in: + n: + gen: "int" + min: 1001 + max: 1000000 + - name: "generated_large" + seed: 19223 + in: + n: + gen: "int" + min: 1000000000 + max: 1000000000000 + - name: "generated_near_limit_even" + seed: 19224 + in: + n: + gen: "int" + min: 999999999999000 + max: 1000000000000000 + - name: "generated_near_limit_mixed" + seed: 19225 + in: + n: + gen: "int" + min: 999999999999900 + max: 1000000000000000 diff --git a/tests/1501-2000/1922. count-good-numbers/sol.cpp b/tests/1501-2000/1922. count-good-numbers/sol.cpp new file mode 100644 index 00000000..00aa98f7 --- /dev/null +++ b/tests/1501-2000/1922. count-good-numbers/sol.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int countGoodNumbers(long long n) { + const long long MOD = 1000000007; + long long evenPositions = (n + 1) / 2; + long long oddPositions = n / 2; + + long long evenWays = chakraPower(5, evenPositions, MOD); + long long oddWays = chakraPower(4, oddPositions, MOD); + + return (evenWays * oddWays) % MOD; + } + + long long chakraPower(long long base, long long power, long long mod) { + long long result = 1; + long long b = base % mod; + long long p = power; + while (p > 0) { + if (p % 2 == 1) { + result = (result * b) % mod; + } + b = (b * b) % mod; + p /= 2; + } + return result; + } +}; diff --git a/tests/1501-2000/1922. count-good-numbers/sol.cs b/tests/1501-2000/1922. count-good-numbers/sol.cs new file mode 100644 index 00000000..978f0888 --- /dev/null +++ b/tests/1501-2000/1922. count-good-numbers/sol.cs @@ -0,0 +1,27 @@ +public class Solution { + private const int MOD = 1000000007; + + public int CountGoodNumbers(long n) { + long evenPositions = (n + 1) / 2; + long oddPositions = n / 2; + + long evenWays = ChakraPower(5, evenPositions); + long oddWays = ChakraPower(4, oddPositions); + + return (int)((evenWays * oddWays) % MOD); + } + + private long ChakraPower(long baseNum, long power) { + long result = 1; + long b = baseNum % MOD; + long p = power; + while (p > 0) { + if (p % 2 == 1) { + result = (result * b) % MOD; + } + b = (b * b) % MOD; + p /= 2; + } + return result; + } +} diff --git a/tests/1501-2000/1922. count-good-numbers/sol.dart b/tests/1501-2000/1922. count-good-numbers/sol.dart new file mode 100644 index 00000000..cd6f4b37 --- /dev/null +++ b/tests/1501-2000/1922. count-good-numbers/sol.dart @@ -0,0 +1,26 @@ +class Solution { + int countGoodNumbers(int n) { + const int mod = 1000000007; + int evenPositions = (n + 1) ~/ 2; + int oddPositions = n ~/ 2; + + int evenWays = chakraPower(5, evenPositions, mod); + int oddWays = chakraPower(4, oddPositions, mod); + + return (evenWays * oddWays) % mod; + } + + int chakraPower(int base, int power, int mod) { + int result = 1; + int b = base % mod; + int p = power; + while (p > 0) { + if (p % 2 == 1) { + result = (result * b) % mod; + } + b = (b * b) % mod; + p ~/= 2; + } + return result; + } +} diff --git a/tests/1501-2000/1922. count-good-numbers/sol.go b/tests/1501-2000/1922. count-good-numbers/sol.go new file mode 100644 index 00000000..6e9b7e88 --- /dev/null +++ b/tests/1501-2000/1922. count-good-numbers/sol.go @@ -0,0 +1,24 @@ +func countGoodNumbers(n int64) int { + const mod int64 = 1000000007 + evenPositions := (n + 1) / 2 + oddPositions := n / 2 + + evenWays := chakraPower(5, evenPositions, mod) + oddWays := chakraPower(4, oddPositions, mod) + + return int((evenWays * oddWays) % mod) +} + +func chakraPower(base, power, mod int64) int64 { + result := int64(1) + b := base % mod + p := power + for p > 0 { + if p%2 == 1 { + result = (result * b) % mod + } + b = (b * b) % mod + p /= 2 + } + return result +} diff --git a/tests/1501-2000/1922. count-good-numbers/sol.java b/tests/1501-2000/1922. count-good-numbers/sol.java new file mode 100644 index 00000000..3d080430 --- /dev/null +++ b/tests/1501-2000/1922. count-good-numbers/sol.java @@ -0,0 +1,26 @@ +class Solution { + private static final int MOD = 1_000_000_007; + + public int countGoodNumbers(long n) { + long evenPositions = (n + 1) / 2; + long oddPositions = n / 2; + + long evenWays = chakraPower(5, evenPositions); + long oddWays = chakraPower(4, oddPositions); + + return (int)((evenWays * oddWays) % MOD); + } + + private long chakraPower(long base, long power) { + long result = 1; + base %= MOD; + while (power > 0) { + if (power % 2 == 1) { + result = (result * base) % MOD; + } + base = (base * base) % MOD; + power /= 2; + } + return result; + } +} diff --git a/tests/1501-2000/1922. count-good-numbers/sol.kt b/tests/1501-2000/1922. count-good-numbers/sol.kt new file mode 100644 index 00000000..0552db5a --- /dev/null +++ b/tests/1501-2000/1922. count-good-numbers/sol.kt @@ -0,0 +1,26 @@ +class Solution { + fun countGoodNumbers(n: Long): Int { + val mod = 1_000_000_007L + val evenPositions = (n + 1) / 2 + val oddPositions = n / 2 + + val evenWays = chakraPower(5, evenPositions, mod) + val oddWays = chakraPower(4, oddPositions, mod) + + return ((evenWays * oddWays) % mod).toInt() + } + + private fun chakraPower(base: Long, power: Long, mod: Long): Long { + var result = 1L + var b = base % mod + var p = power + while (p > 0) { + if (p % 2 == 1L) { + result = (result * b) % mod + } + b = (b * b) % mod + p /= 2 + } + return result + } +} diff --git a/tests/1501-2000/1922. count-good-numbers/sol.py b/tests/1501-2000/1922. count-good-numbers/sol.py new file mode 100644 index 00000000..0e0cadb2 --- /dev/null +++ b/tests/1501-2000/1922. count-good-numbers/sol.py @@ -0,0 +1,24 @@ +class Solution: + MOD = 10**9 + 7 + + def countGoodNumbers(self, n: int) -> int: + chakra_length = n + even_positions = (chakra_length + 1) // 2 + odd_positions = chakra_length // 2 + + even_ways = self.chakra_power(5, even_positions) + odd_ways = self.chakra_power(4, odd_positions) + + return (even_ways * odd_ways) % self.MOD + + def chakra_power(self, base, power): + result = 1 + base %= self.MOD + + while power > 0: + if power % 2 == 1: + result = (result * base) % self.MOD + base = (base * base) % self.MOD + power //= 2 + + return result diff --git a/tests/1501-2000/1922. count-good-numbers/sol.py2 b/tests/1501-2000/1922. count-good-numbers/sol.py2 new file mode 100644 index 00000000..912d0d64 --- /dev/null +++ b/tests/1501-2000/1922. count-good-numbers/sol.py2 @@ -0,0 +1,24 @@ +class Solution(object): + def countGoodNumbers(self, n): + """ + :type n: int + :rtype: int + """ + MOD = 10**9 + 7 + even_positions = (n + 1) // 2 + odd_positions = n // 2 + + even_ways = self.chakra_power(5, even_positions) + odd_ways = self.chakra_power(4, odd_positions) + + return (even_ways * odd_ways) % MOD + + def chakra_power(self, base, power): + result = 1 + base %= (10**9 + 7) + while power > 0: + if power % 2 == 1: + result = (result * base) % (10**9 + 7) + base = (base * base) % (10**9 + 7) + power //= 2 + return result diff --git a/tests/1501-2000/1922. count-good-numbers/sol.rb b/tests/1501-2000/1922. count-good-numbers/sol.rb new file mode 100644 index 00000000..5c96752d --- /dev/null +++ b/tests/1501-2000/1922. count-good-numbers/sol.rb @@ -0,0 +1,25 @@ +# @param {Integer} n +# @return {Integer} +def count_good_numbers(n) + mod = 10**9 + 7 + even_positions = (n + 1) / 2 + odd_positions = n / 2 + + even_ways = chakra_power(5, even_positions, mod) + odd_ways = chakra_power(4, odd_positions, mod) + + (even_ways * odd_ways) % mod +end + +def chakra_power(base, power, mod) + result = 1 + base %= mod + while power > 0 + if power % 2 == 1 + result = (result * base) % mod + end + base = (base * base) % mod + power /= 2 + end + result +end diff --git a/tests/1501-2000/1922. count-good-numbers/sol.rs b/tests/1501-2000/1922. count-good-numbers/sol.rs new file mode 100644 index 00000000..1e2f3c45 --- /dev/null +++ b/tests/1501-2000/1922. count-good-numbers/sol.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn count_good_numbers(n: i64) -> i32 { + const MOD: i64 = 1_000_000_007; + let even_positions = (n + 1) / 2; + let odd_positions = n / 2; + + let even_ways = Self::chakra_power(5, even_positions, MOD); + let odd_ways = Self::chakra_power(4, odd_positions, MOD); + + ((even_ways * odd_ways) % MOD) as i32 + } + + fn chakra_power(base: i64, power: i64, modulus: i64) -> i64 { + let mut result = 1; + let mut b = base % modulus; + let mut p = power; + while p > 0 { + if p % 2 == 1 { + result = (result * b) % modulus; + } + b = (b * b) % modulus; + p /= 2; + } + result + } +} diff --git a/tests/1501-2000/1922. count-good-numbers/sol.swift b/tests/1501-2000/1922. count-good-numbers/sol.swift new file mode 100644 index 00000000..39f07087 --- /dev/null +++ b/tests/1501-2000/1922. count-good-numbers/sol.swift @@ -0,0 +1,26 @@ +class Solution { + func countGoodNumbers(_ n: Int) -> Int { + let mod = 1_000_000_007 + let evenPositions = (n + 1) / 2 + let oddPositions = n / 2 + + let evenWays = chakraPower(5, evenPositions, mod) + let oddWays = chakraPower(4, oddPositions, mod) + + return (evenWays * oddWays) % mod + } + + func chakraPower(_ base: Int, _ power: Int, _ mod: Int) -> Int { + var result = 1 + var b = base % mod + var p = power + while p > 0 { + if p % 2 == 1 { + result = (result * b) % mod + } + b = (b * b) % mod + p /= 2 + } + return result + } +} diff --git a/tests/1501-2000/1922. count-good-numbers/sol.ts b/tests/1501-2000/1922. count-good-numbers/sol.ts new file mode 100644 index 00000000..89687eb7 --- /dev/null +++ b/tests/1501-2000/1922. count-good-numbers/sol.ts @@ -0,0 +1,24 @@ +function countGoodNumbers(n: number): number { + const mod = 1000000007; + const evenPositions = Math.floor((n + 1) / 2); + const oddPositions = Math.floor(n / 2); + + const evenWays = chakraPower(5, evenPositions, mod); + const oddWays = chakraPower(4, oddPositions, mod); + + return Number((BigInt(evenWays) * BigInt(oddWays)) % BigInt(mod)); +} + +function chakraPower(base: number, power: number, mod: number): number { + let result = 1n; + let b = BigInt(base) % BigInt(mod); + let p = BigInt(power); + while (p > 0) { + if (p % 2n === 1n) { + result = (result * b) % BigInt(mod); + } + b = (b * b) % BigInt(mod); + p /= 2n; + } + return Number(result); +} diff --git a/tests/1501-2000/1923. longest-common-subpath/manifest.yaml b/tests/1501-2000/1923. longest-common-subpath/manifest.yaml new file mode 100644 index 00000000..186d7134 --- /dev/null +++ b/tests/1501-2000/1923. longest-common-subpath/manifest.yaml @@ -0,0 +1,337 @@ +entry: + id: 1923 + title: "Longest Common Subpath" + params: + n: + type: int + paths: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().longestCommonSubpath({n}, {paths})" + rust: "Solution::longest_common_subpath({n}, {paths})" + python3: "Solution().longestCommonSubpath({n}, {paths})" + python2: "Solution().longestCommonSubpath({n}, {paths})" + ruby: "longest_common_subpath({n}, {paths})" + java: "new Solution().longestCommonSubpath({n}, {paths})" + csharp: "new Solution().LongestCommonSubpath({n}, {paths})" + kotlin: "Solution().longestCommonSubpath({n}, {paths})" + go: "longestCommonSubpath({n}, {paths})" + dart: "Solution().longestCommonSubpath({n}, {paths})" + swift: "Solution().longestCommonSubpath({n}, {paths})" + typescript: "longestCommonSubpath({n}, {paths})" + +judge: + type: "exact" + +limits: + time_ms: 5000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().check(n, paths, {result})" + checker: | + class Checker: + def check(self, n, paths, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not paths: + return result == 0 + shortest = min(paths, key=len) + expected = 0 + for length in range(1, len(shortest) + 1): + found = False + for start in range(len(shortest) - length + 1): + part = shortest[start:start + length] + if all(any(path[i:i + length] == part for i in range(len(path) - length + 1)) for path in paths): + found = True + break + if found: + expected = length + return result == expected + +seed: 1923 + +tests: + - name: example-one + in: + n: 5 + paths: + - [0, 1, 2, 3, 4] + - [2, 3, 4] + - [4, 0, 1, 2, 3] + out: 2 + - name: example-two + in: + n: 3 + paths: + - [0] + - [1] + - [2] + out: 0 + - name: example-three + in: + n: 5 + paths: + - [0, 1, 2, 3, 4] + - [4, 3, 2, 1, 0] + out: 1 + - name: identical-singletons + in: + n: 7 + paths: + - [6] + - [6] + out: 1 + - name: identical-long + in: + n: 20 + paths: + - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + out: 10 + - name: no-overlap + in: + n: 10 + paths: + - [0, 1, 2] + - [3, 4, 5] + - [6, 7, 8] + out: 0 + - name: one-common-at-end + in: + n: 10 + paths: + - [0, 1, 7] + - [2, 3, 7] + - [4, 5, 7] + out: 1 + - name: common-prefix + in: + n: 20 + paths: + - [1, 2, 3, 4] + - [1, 2, 3, 8] + - [1, 2, 3, 9] + out: 3 + - name: common-suffix + in: + n: 20 + paths: + - [4, 1, 2, 3] + - [8, 1, 2, 3] + - [9, 1, 2, 3] + out: 3 + - name: common-middle + in: + n: 30 + paths: + - [8, 9, 1, 2, 3, 4] + - [7, 1, 2, 3, 4, 6] + - [5, 1, 2, 3, 4, 0] + out: 4 + - name: repeated-pattern + in: + n: 10 + paths: + - [1, 2, 1, 2, 1] + - [3, 1, 2, 1, 4] + - [1, 2, 1, 5] + out: 3 + - name: overlap-not-enough + in: + n: 10 + paths: + - [1, 2, 3, 4] + - [0, 2, 3, 5] + - [2, 3, 6, 7] + out: 2 + - name: three-paths-length-two + in: + n: 8 + paths: + - [0, 1, 2] + - [4, 0, 1] + - [0, 1, 7] + out: 2 + - name: four-paths + in: + n: 12 + paths: + - [2, 3, 4, 5] + - [0, 2, 3, 4, 8] + - [7, 2, 3, 4, 9] + - [10, 2, 3, 4, 11] + out: 3 + - name: shortest-limits-answer + in: + n: 20 + paths: + - [6, 7] + - [1, 6, 7, 8] + - [6, 7, 9, 10] + out: 2 + - name: answer-zero-after-long-prefix + in: + n: 20 + paths: + - [1, 2, 3, 4] + - [1, 2, 3, 5] + - [1, 2, 6, 7] + out: 2 + - name: alternating-city-values + in: + n: 6 + paths: + - [0, 1, 0, 1, 0] + - [2, 0, 1, 0, 3] + - [0, 1, 0, 4] + out: 3 + - name: large-city-labels + in: + n: 100000 + paths: + - [99999, 99998, 50000, 49999] + - [1, 99999, 99998, 50000] + - [99998, 50000, 49999, 2] + out: 2 + - name: disjoint-large-labels + in: + n: 100000 + paths: + - [99999, 99998] + - [99997, 99996] + - [99995, 99994] + out: 0 + - name: common-seven + in: + n: 30 + paths: + - [10, 11, 12, 13, 14, 15, 16, 2] + - [1, 10, 11, 12, 13, 14, 15, 16] + - [16, 10, 11, 12, 13, 14, 15, 16, 3] + out: 7 + - name: shifted-common-block + in: + n: 30 + paths: + - [0, 4, 5, 6, 7, 8, 9] + - [3, 4, 5, 6, 7, 8, 9, 2] + - [4, 5, 6, 7, 8, 9] + out: 6 + - name: common-block-broken-at-one + in: + n: 30 + paths: + - [4, 5, 6, 7, 8] + - [0, 4, 5, 6, 7, 9] + - [4, 5, 6, 8, 7] + out: 3 + - name: many-friends + in: + n: 20 + paths: + - [1, 2, 3, 4] + - [0, 1, 2, 3, 9] + - [8, 1, 2, 3, 7] + - [6, 1, 2, 3, 5] + - [1, 2, 3] + out: 3 + - name: singleton-among-long + in: + n: 20 + paths: + - [4] + - [0, 1, 4, 2, 3] + - [7, 4, 8] + out: 1 + - name: all-cities-unique + in: + n: 50 + paths: + - [1, 2, 3, 4, 5] + - [6, 7, 8, 9, 10] + out: 0 + - name: reverse-common-single + in: + n: 10 + paths: + - [1, 2, 3, 4] + - [4, 3, 2, 1] + - [0, 2, 3, 5] + out: 1 + - name: common-two-in-long-paths + in: + n: 40 + paths: + - [1, 7, 8, 9, 10, 2] + - [3, 7, 8, 6, 10, 4] + - [7, 8, 5, 9, 10] + out: 2 + - name: common-ten + in: + n: 30 + paths: + - [5, 6, 7, 8, 9, 10, 11, 12, 13, 14] + - [0, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 1] + out: 10 + - name: repeated-single-common + in: + n: 5 + paths: + - [0, 1, 0, 1] + - [2, 1, 2, 3] + - [1, 4, 1] + out: 1 + - name: common-middle-three + in: + n: 25 + paths: + - [2, 3, 4, 5, 6] + - [8, 3, 4, 5, 9] + - [3, 4, 5, 7] + out: 3 + - name: two-paths-identical-small + in: + n: 4 + paths: + - [0, 1, 2] + - [0, 1, 2] + out: 3 + - name: two-paths-overlap-one + in: + n: 4 + paths: + - [0, 1] + - [1, 2] + out: 1 + - name: common-block-at-tail + in: + n: 30 + paths: + - [0, 1, 2, 8, 9, 10] + - [3, 4, 8, 9, 10] + - [5, 6, 7, 8, 9, 10] + out: 3 + - name: all-two-city-common + in: + n: 10 + paths: + - [1, 2, 3] + - [4, 1, 2] + - [1, 2, 5] + - [6, 1, 2, 7] + out: 2 + - name: common-block-with-extra-prefixes + in: + n: 50 + paths: + - [20, 21, 22, 23, 24, 25, 26] + - [1, 20, 21, 22, 23, 24, 25, 26, 2] + - [20, 21, 22, 23, 24, 25, 26, 3] + out: 7 diff --git a/tests/1501-2000/1923. longest-common-subpath/sol.cpp b/tests/1501-2000/1923. longest-common-subpath/sol.cpp new file mode 100644 index 00000000..9b6117dd --- /dev/null +++ b/tests/1501-2000/1923. longest-common-subpath/sol.cpp @@ -0,0 +1,100 @@ +class Solution { +public: + int longestCommonSubpath(int n, vector>& paths) { + vector combined; + vector path_origin; + for (int i = 0; i < paths.size(); i++) { + for (int v : paths[i]) { + combined.push_back(v); + path_origin.push_back(i); + } + combined.push_back(-(i + 1)); + path_origin.push_back(i); + } + int N = combined.size(); + int M = paths.size(); + vector S = combined; + vector P_ID = path_origin; + + vector rank(N); + { + vector temp = S; + sort(temp.begin(), temp.end()); + temp.erase(unique(temp.begin(), temp.end()), temp.end()); + for (int i = 0; i < N; i++) { + rank[i] = lower_bound(temp.begin(), temp.end(), S[i]) - temp.begin(); + } + } + + int k = 1; + while (k < N) { + vector key(N); + for (int i = 0; i < N; i++) { + long long first = rank[i]; + long long second = (i + k < N) ? rank[i + k] + 1 : 0; + key[i] = (first << 32) | second; + } + vector sorted_key = key; + sort(sorted_key.begin(), sorted_key.end()); + sorted_key.erase(unique(sorted_key.begin(), sorted_key.end()), sorted_key.end()); + for (int i = 0; i < N; i++) { + rank[i] = lower_bound(sorted_key.begin(), sorted_key.end(), key[i]) - sorted_key.begin(); + } + if (k >= N) break; + k *= 2; + } + + vector sa(N); + for (int i = 0; i < N; i++) { + sa[rank[i]] = i; + } + + vector lcp(N, 0); + vector inv_sa = rank; + int h = 0; + for (int i = 0; i < N; i++) { + if (inv_sa[i] > 0) { + int j = sa[inv_sa[i] - 1]; + while (i + h < N && j + h < N && S[i + h] == S[j + h]) { + h++; + } + lcp[inv_sa[i]] = h; + if (h > 0) h--; + } + } + + int ans = 0; + int left = 0; + vector count(M, 0); + int distinct_paths = 0; + deque min_q; + + for (int right = 0; right < N; right++) { + int p_id = P_ID[sa[right]]; + if (p_id >= 0) { + if (count[p_id] == 0) distinct_paths++; + count[p_id]++; + } + while (!min_q.empty() && lcp[min_q.back()] >= lcp[right]) { + min_q.pop_back(); + } + min_q.push_back(right); + + while (distinct_paths == M) { + while (!min_q.empty() && min_q.front() <= left) { + min_q.pop_front(); + } + if (!min_q.empty()) { + ans = max(ans, lcp[min_q.front()]); + } + int out_id = P_ID[sa[left]]; + if (out_id >= 0) { + count[out_id]--; + if (count[out_id] == 0) distinct_paths--; + } + left++; + } + } + return ans; + } +}; diff --git a/tests/1501-2000/1923. longest-common-subpath/sol.cs b/tests/1501-2000/1923. longest-common-subpath/sol.cs new file mode 100644 index 00000000..59bffdee --- /dev/null +++ b/tests/1501-2000/1923. longest-common-subpath/sol.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; + +public class Solution { + public int LongestCommonSubpath(int n, int[][] paths) { + List combined = new List(); + List pathOrigin = new List(); + for (int i = 0; i < paths.Length; i++) { + foreach (int v in paths[i]) { + combined.Add(v); + pathOrigin.Add(i); + } + combined.Add(-(i+1)); + pathOrigin.Add(i); + } + int N = combined.Count; + int M = paths.Length; + int[] S = combined.ToArray(); + int[] P = pathOrigin.ToArray(); + + int[] rank = new int[N]; + { + int[] temp = (int[])S.Clone(); + Array.Sort(temp); + for (int i = 0; i < N; i++) { + rank[i] = Array.BinarySearch(temp, S[i]); + } + } + + int k = 1; + while (k < N) { + long[] keys = new long[N]; + for (int i = 0; i < N; i++) { + long first = rank[i]; + long second = (i+k < N) ? rank[i+k] + 1L : 0L; + keys[i] = (first << 32) | second; + } + long[] sorted = (long[])keys.Clone(); + Array.Sort(sorted); + for (int i = 0; i < N; i++) { + rank[i] = Array.BinarySearch(sorted, keys[i]); + } + if (k >= N) break; + k *= 2; + } + + int[] sa = new int[N]; + for (int i = 0; i < N; i++) { + sa[rank[i]] = i; + } + + int[] lcp = new int[N]; + int[] inv = (int[])rank.Clone(); + int h = 0; + for (int i = 0; i < N; i++) { + if (inv[i] > 0) { + int j = sa[inv[i]-1]; + while (i+h < N && j+h < N && S[i+h] == S[j+h]) { + h++; + } + lcp[inv[i]] = h; + if (h > 0) h--; + } + } + + int ans = 0; + int left = 0; + int[] count = new int[M]; + int distinct = 0; + var minQ = new LinkedList(); + for (int right = 0; right < N; right++) { + int p = P[sa[right]]; + if (p >= 0) { + if (count[p] == 0) distinct++; + count[p]++; + } + while (minQ.Count > 0 && lcp[minQ.Last.Value] >= lcp[right]) { + minQ.RemoveLast(); + } + minQ.AddLast(right); + + while (distinct == M) { + while (minQ.Count > 0 && minQ.First.Value <= left) { + minQ.RemoveFirst(); + } + if (minQ.Count > 0) { + ans = Math.Max(ans, lcp[minQ.First.Value]); + } + int outIdx = P[sa[left]]; + if (outIdx >= 0) { + count[outIdx]--; + if (count[outIdx] == 0) distinct--; + } + left++; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1923. longest-common-subpath/sol.dart b/tests/1501-2000/1923. longest-common-subpath/sol.dart new file mode 100644 index 00000000..2f6dd030 --- /dev/null +++ b/tests/1501-2000/1923. longest-common-subpath/sol.dart @@ -0,0 +1,98 @@ +import 'dart:collection'; + +class Solution { + int longestCommonSubpath(int n, List> paths) { + List combined = []; + List pathOrigin = []; + for (int i = 0; i < paths.length; i++) { + for (int v in paths[i]) { + combined.add(v); + pathOrigin.add(i); + } + combined.add(-(i+1)); + pathOrigin.add(i); + } + int N = combined.length; + int M = paths.length; + List S = combined; + List P = pathOrigin; + + // rank compression + List rank = List.filled(N, 0); + { + List temp = List.from(S)..sort(); + for (int i = 0; i < N; i++) { + rank[i] = temp.indexOf(S[i]); + } + } + + int k = 1; + while (k < N) { + List keys = List.filled(N, 0); + for (int i = 0; i < N; i++) { + int first = rank[i]; + int second = (i+k < N) ? rank[i+k] + 1 : 0; + // combine into single int (fits in 64-bit, but Dart int is 64-bit) + keys[i] = (first << 32) | second; + } + List sorted = List.from(keys)..sort(); + for (int i = 0; i < N; i++) { + rank[i] = sorted.indexOf(keys[i]); + } + if (k >= N) break; + k *= 2; + } + + List sa = List.filled(N, 0); + for (int i = 0; i < N; i++) { + sa[rank[i]] = i; + } + + List lcp = List.filled(N, 0); + List inv = List.from(rank); + int h = 0; + for (int i = 0; i < N; i++) { + if (inv[i] > 0) { + int j = sa[inv[i]-1]; + while (i+h < N && j+h < N && S[i+h] == S[j+h]) { + h++; + } + lcp[inv[i]] = h; + if (h > 0) h--; + } + } + + int ans = 0; + int left = 0; + List count = List.filled(M, 0); + int distinct = 0; + Queue minQ = Queue(); + for (int right = 0; right < N; right++) { + int p = P[sa[right]]; + if (p >= 0) { + if (count[p] == 0) distinct++; + count[p]++; + } + while (minQ.isNotEmpty && lcp[minQ.last] >= lcp[right]) { + minQ.removeLast(); + } + minQ.addLast(right); + + while (distinct == M) { + while (minQ.isNotEmpty && minQ.first <= left) { + minQ.removeFirst(); + } + if (minQ.isNotEmpty) { + ans = ans > lcp[minQ.first] ? ans : lcp[minQ.first]; + } + int out = P[sa[left]]; + if (out >= 0) { + count[out]--; + if (count[out] == 0) distinct--; + } + left++; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1923. longest-common-subpath/sol.go b/tests/1501-2000/1923. longest-common-subpath/sol.go new file mode 100644 index 00000000..187a5cfe --- /dev/null +++ b/tests/1501-2000/1923. longest-common-subpath/sol.go @@ -0,0 +1,109 @@ +func longestCommonSubpath(n int, paths [][]int) int { + var combined []int + var pathOrigin []int + for i, p := range paths { + for _, v := range p { + combined = append(combined, v) + pathOrigin = append(pathOrigin, i) + } + combined = append(combined, -(i+1)) + pathOrigin = append(pathOrigin, i) + } + N := len(combined) + M := len(paths) + + // rank compression + rank := make([]int, N) + { + temp := make([]int, N) + copy(temp, combined) + sort.Ints(temp) + for i := range combined { + rank[i] = sort.SearchInts(temp, combined[i]) + } + } + + k := 1 + for k < N { + key := make([]uint64, N) + for i := 0; i < N; i++ { + first := uint64(rank[i]) + second := uint64(0) + if i+k < N { + second = uint64(rank[i+k]) + 1 + } + key[i] = (first << 32) | second + } + sortedKey := make([]uint64, N) + copy(sortedKey, key) + sort.Slice(sortedKey, func(i, j int) bool { return sortedKey[i] < sortedKey[j] }) + for i := 0; i < N; i++ { + rank[i] = sort.Search(N, func(j int) bool { return sortedKey[j] >= key[i] }) + } + if k >= N { + break + } + k *= 2 + } + + sa := make([]int, N) + for i, r := range rank { + sa[r] = i + } + + lcp := make([]int, N) + inv := make([]int, N) + copy(inv, rank) + h := 0 + for i := 0; i < N; i++ { + if inv[i] > 0 { + j := sa[inv[i]-1] + for i+h < N && j+h < N && combined[i+h] == combined[j+h] { + h++ + } + lcp[inv[i]] = h + if h > 0 { + h-- + } + } + } + + ans := 0 + left := 0 + count := make([]int, M) + distinct := 0 + minQ := []int{} + for right := 0; right < N; right++ { + p := pathOrigin[sa[right]] + if p >= 0 { + if count[p] == 0 { + distinct++ + } + count[p]++ + } + for len(minQ) > 0 && lcp[minQ[len(minQ)-1]] >= lcp[right] { + minQ = minQ[:len(minQ)-1] + } + minQ = append(minQ, right) + + for distinct == M { + for len(minQ) > 0 && minQ[0] <= left { + minQ = minQ[1:] + } + if len(minQ) > 0 { + if lcp[minQ[0]] > ans { + ans = lcp[minQ[0]] + } + } + out := pathOrigin[sa[left]] + if out >= 0 { + count[out]-- + if count[out] == 0 { + distinct-- + } + } + left++ + } + } + return ans +} diff --git a/tests/1501-2000/1923. longest-common-subpath/sol.java b/tests/1501-2000/1923. longest-common-subpath/sol.java new file mode 100644 index 00000000..950b4ce0 --- /dev/null +++ b/tests/1501-2000/1923. longest-common-subpath/sol.java @@ -0,0 +1,103 @@ +import java.util.*; + +class Solution { + public int longestCommonSubpath(int n, int[][] paths) { + List combined = new ArrayList<>(); + List pathOrigin = new ArrayList<>(); + for (int i = 0; i < paths.length; i++) { + for (int v : paths[i]) { + combined.add(v); + pathOrigin.add(i); + } + combined.add(-(i+1)); + pathOrigin.add(i); + } + int N = combined.size(); + int M = paths.length; + int[] S = new int[N]; + int[] P = new int[N]; + for (int i = 0; i < N; i++) { + S[i] = combined.get(i); + P[i] = pathOrigin.get(i); + } + + // rank compression + int[] rank = new int[N]; + { + int[] temp = S.clone(); + Arrays.sort(temp); + for (int i = 0; i < N; i++) { + rank[i] = Arrays.binarySearch(temp, S[i]); + } + } + + int k = 1; + while (k < N) { + long[] keys = new long[N]; + for (int i = 0; i < N; i++) { + long first = rank[i]; + long second = (i+k < N) ? rank[i+k] + 1L : 0L; + keys[i] = (first << 32) | second; + } + long[] sorted = keys.clone(); + Arrays.sort(sorted); + for (int i = 0; i < N; i++) { + rank[i] = Arrays.binarySearch(sorted, keys[i]); + } + if (k >= N) break; + k *= 2; + } + + int[] sa = new int[N]; + for (int i = 0; i < N; i++) { + sa[rank[i]] = i; + } + + int[] lcp = new int[N]; + int[] inv = rank.clone(); + int h = 0; + for (int i = 0; i < N; i++) { + if (inv[i] > 0) { + int j = sa[inv[i]-1]; + while (i+h < N && j+h < N && S[i+h] == S[j+h]) { + h++; + } + lcp[inv[i]] = h; + if (h > 0) h--; + } + } + + int ans = 0; + int left = 0; + int[] count = new int[M]; + int distinct = 0; + Deque minQ = new ArrayDeque<>(); + for (int right = 0; right < N; right++) { + int p = P[sa[right]]; + if (p >= 0) { + if (count[p] == 0) distinct++; + count[p]++; + } + while (!minQ.isEmpty() && lcp[minQ.peekLast()] >= lcp[right]) { + minQ.pollLast(); + } + minQ.offerLast(right); + + while (distinct == M) { + while (!minQ.isEmpty() && minQ.peekFirst() <= left) { + minQ.pollFirst(); + } + if (!minQ.isEmpty()) { + ans = Math.max(ans, lcp[minQ.peekFirst()]); + } + int out = P[sa[left]]; + if (out >= 0) { + count[out]--; + if (count[out] == 0) distinct--; + } + left++; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1923. longest-common-subpath/sol.kt b/tests/1501-2000/1923. longest-common-subpath/sol.kt new file mode 100644 index 00000000..2f27bfbe --- /dev/null +++ b/tests/1501-2000/1923. longest-common-subpath/sol.kt @@ -0,0 +1,97 @@ +class Solution { + fun longestCommonSubpath(n: Int, paths: Array): Int { + val combined = mutableListOf() + val pathOrigin = mutableListOf() + for ((i, p) in paths.withIndex()) { + for (v in p) { + combined.add(v) + pathOrigin.add(i) + } + combined.add(-(i+1)) + pathOrigin.add(i) + } + val N = combined.size + val M = paths.size + val S = combined.toIntArray() + val P = pathOrigin.toIntArray() + + // rank compression + val rank = IntArray(N) + run { + val temp = S.copyOf() + temp.sort() + for (i in 0 until N) { + rank[i] = temp.binarySearch(S[i]) + } + } + + var k = 1 + while (k < N) { + val keys = LongArray(N) + for (i in 0 until N) { + val first = rank[i].toLong() + val second = if (i+k < N) rank[i+k].toLong() + 1L else 0L + keys[i] = (first shl 32) or second + } + val sorted = keys.copyOf() + sorted.sort() + for (i in 0 until N) { + rank[i] = sorted.binarySearch(keys[i]) + } + if (k >= N) break + k *= 2 + } + + val sa = IntArray(N) + for (i in 0 until N) { + sa[rank[i]] = i + } + + val lcp = IntArray(N) + val inv = rank.copyOf() + var h = 0 + for (i in 0 until N) { + if (inv[i] > 0) { + val j = sa[inv[i]-1] + while (i+h < N && j+h < N && S[i+h] == S[j+h]) { + h++ + } + lcp[inv[i]] = h + if (h > 0) h-- + } + } + + var ans = 0 + var left = 0 + val count = IntArray(M) + var distinct = 0 + val minQ = ArrayDeque() + for (right in 0 until N) { + val p = P[sa[right]] + if (p >= 0) { + if (count[p] == 0) distinct++ + count[p]++ + } + while (!minQ.isEmpty() && lcp[minQ.last()] >= lcp[right]) { + minQ.removeLast() + } + minQ.addLast(right) + + while (distinct == M) { + while (!minQ.isEmpty() && minQ.first() <= left) { + minQ.removeFirst() + } + if (!minQ.isEmpty()) { + ans = maxOf(ans, lcp[minQ.first()]) + } + val out = P[sa[left]] + if (out >= 0) { + count[out]-- + if (count[out] == 0) distinct-- + } + left++ + } + } + return ans + } +} diff --git a/tests/1501-2000/1923. longest-common-subpath/sol.py b/tests/1501-2000/1923. longest-common-subpath/sol.py new file mode 100644 index 00000000..81c0e96a --- /dev/null +++ b/tests/1501-2000/1923. longest-common-subpath/sol.py @@ -0,0 +1,95 @@ +import numpy as np +from typing import List + + +class Solution: + def longestCommonSubpath(self, n: int, paths: List[List[int]]) -> int: + # 1. Padding & Field Concatenation + combined = [] + path_origin = [] + for i, p in enumerate(paths): + combined.extend(p) + combined.append(-(i + 1)) + path_origin.extend([i] * (len(p) + 1)) + + S = np.array(combined, dtype=np.int32) + P_ID = np.array(path_origin, dtype=np.int32) + N = len(S) + M = len(paths) + + # 2. Vectorized Suffix Array (Rank Doubling) + # We transform the suffix sort into a "Key-Packing" problem + _, rank = np.unique(S, return_inverse=True) + + k = 1 + while k < N: + # Shift the rank field to create the 'Second Half' of the key + first_half = rank.astype(np.int64) + second_half = np.zeros(N, dtype=np.int64) + second_half[:-k] = rank[k:] + 1 # +1 to distinguish from 'no suffix' + + # Pack two 32-bit ranks into one 64-bit key for a single C-sort + combined_key = (first_half << 32) | second_half + _, rank = np.unique(combined_key, return_inverse=True) + + if k >= N: + break + k *= 2 + + sa = np.empty(N, dtype=np.int32) + sa[rank] = np.arange(N) + + # 3. Vectorized LCP (Kasai's Invariant) + # While Kasai is inherently serial, we can speed up the string + # comparisons using NumPy's slice-equality checks + lcp = np.zeros(N, dtype=np.int32) + inv_sa = rank + h = 0 + for i in range(N): + if inv_sa[i] > 0: + j = sa[inv_sa[i] - 1] + # The only serial part: incrementing h + while i + h < N and j + h < N and S[i + h] == S[j + h]: + h += 1 + lcp[inv_sa[i]] = h + if h > 0: + h -= 1 + + # 4. Maximizing Mutual Information (Sliding Window) + # We use a two-pointer approach but keep the LCP comparisons vectorized + ans = 0 + left = 0 + count = np.zeros(M, dtype=np.int32) + distinct_paths = 0 + + # Deque for Monotonic Queue (Minimum LCP in window) + from collections import deque + + min_q = deque() + + for right in range(N): + p_id = P_ID[sa[right]] + if p_id >= 0: + if count[p_id] == 0: + distinct_paths += 1 + count[p_id] += 1 + + while min_q and lcp[min_q[-1]] >= lcp[right]: + min_q.pop() + min_q.append(right) + + while distinct_paths == M: + while min_q and min_q[0] <= left: + min_q.popleft() + + if min_q: + ans = max(ans, lcp[min_q[0]]) + + out_id = P_ID[sa[left]] + if out_id >= 0: + count[out_id] -= 1 + if count[out_id] == 0: + distinct_paths -= 1 + left += 1 + + return int(ans) diff --git a/tests/1501-2000/1923. longest-common-subpath/sol.py2 b/tests/1501-2000/1923. longest-common-subpath/sol.py2 new file mode 100644 index 00000000..7a880a76 --- /dev/null +++ b/tests/1501-2000/1923. longest-common-subpath/sol.py2 @@ -0,0 +1,82 @@ +class Solution(object): + def longestCommonSubpath(self, n, paths): + """ + :type n: int + :type paths: List[List[int]] + :rtype: int + """ + combined = [] + path_origin = [] + for i, p in enumerate(paths): + for v in p: + combined.append(v) + path_origin.append(i) + combined.append(-(i+1)) + path_origin.append(i) + N = len(combined) + M = len(paths) + + # rank compression + rank = [0]*N + temp = sorted(combined) + for i in range(N): + rank[i] = temp.index(combined[i]) + + k = 1 + while k < N: + keys = [0]*N + for i in range(N): + first = rank[i] + second = rank[i+k] + 1 if i+k < N else 0 + keys[i] = (first << 32) | second + sorted_keys = sorted(keys) + for i in range(N): + rank[i] = sorted_keys.index(keys[i]) + if k >= N: + break + k *= 2 + + sa = [0]*N + for i in range(N): + sa[rank[i]] = i + + lcp = [0]*N + inv = rank + h = 0 + for i in range(N): + if inv[i] > 0: + j = sa[inv[i]-1] + while i+h < N and j+h < N and combined[i+h] == combined[j+h]: + h += 1 + lcp[inv[i]] = h + if h > 0: + h -= 1 + + ans = 0 + left = 0 + count = [0]*M + distinct = 0 + from collections import deque + min_q = deque() + for right in range(N): + p = path_origin[sa[right]] + if p >= 0: + if count[p] == 0: + distinct += 1 + count[p] += 1 + while min_q and lcp[min_q[-1]] >= lcp[right]: + min_q.pop() + min_q.append(right) + + while distinct == M: + while min_q and min_q[0] <= left: + min_q.popleft() + if min_q: + ans = max(ans, lcp[min_q[0]]) + out = path_origin[sa[left]] + if out >= 0: + count[out] -= 1 + if count[out] == 0: + distinct -= 1 + left += 1 + return ans diff --git a/tests/1501-2000/1923. longest-common-subpath/sol.rb b/tests/1501-2000/1923. longest-common-subpath/sol.rb new file mode 100644 index 00000000..8c868330 --- /dev/null +++ b/tests/1501-2000/1923. longest-common-subpath/sol.rb @@ -0,0 +1,90 @@ +# @param {Integer} n +# @param {Integer[][]} paths +# @return {Integer} +def longest_common_subpath(n, paths) + combined = [] + path_origin = [] + paths.each_with_index do |p, i| + p.each do |v| + combined << v + path_origin << i + end + combined << -(i+1) + path_origin << i + end + n = combined.size + m = paths.size + + # rank compression + rank = [] + temp = combined.sort + combined.each do |x| + rank << temp.index(x) + end + + k = 1 + while k < n + keys = [] + (0...n).each do |i| + first = rank[i] + second = (i+k < n) ? rank[i+k] + 1 : 0 + keys << ((first << 32) | second) + end + sorted = keys.sort + (0...n).each do |i| + rank[i] = sorted.index(keys[i]) + end + break if k >= n + k *= 2 + end + + sa = Array.new(n, 0) + (0...n).each do |i| + sa[rank[i]] = i + end + + lcp = Array.new(n, 0) + inv = rank.dup + h = 0 + (0...n).each do |i| + if inv[i] > 0 + j = sa[inv[i]-1] + while i+h < n && j+h < n && combined[i+h] == combined[j+h] + h += 1 + end + lcp[inv[i]] = h + h -= 1 if h > 0 + end + end + + ans = 0 + left = 0 + count = Array.new(m, 0) + distinct = 0 + min_q = [] + (0...n).each do |right| + p = path_origin[sa[right]] + if p >= 0 + count[p] += 1 + distinct += 1 if count[p] == 1 + end + while !min_q.empty? && lcp[min_q.last] >= lcp[right] + min_q.pop + end + min_q << right + + while distinct == m + while !min_q.empty? && min_q.first <= left + min_q.shift + end + ans = [ans, lcp[min_q.first]].max unless min_q.empty? + out = path_origin[sa[left]] + if out >= 0 + count[out] -= 1 + distinct -= 1 if count[out] == 0 + end + left += 1 + end + end + ans +end diff --git a/tests/1501-2000/1923. longest-common-subpath/sol.rs b/tests/1501-2000/1923. longest-common-subpath/sol.rs new file mode 100644 index 00000000..eda8fdd0 --- /dev/null +++ b/tests/1501-2000/1923. longest-common-subpath/sol.rs @@ -0,0 +1,103 @@ +impl Solution { + pub fn longest_common_subpath(n: i32, paths: Vec>) -> i32 { + let mut combined = Vec::new(); + let mut path_origin = Vec::new(); + for (i, p) in paths.iter().enumerate() { + for &v in p { + combined.push(v); + path_origin.push(i as i32); + } + combined.push(-(i as i32 + 1)); + path_origin.push(i as i32); + } + let n_total = combined.len(); + let m = paths.len(); + + let mut rank: Vec = combined.iter().map(|&x| { + // coordinate compression + let mut temp: Vec = combined.clone(); + temp.sort(); + temp.dedup(); + temp.iter().position(|&y| y == x).unwrap() as i32 + }).collect(); + + let mut k = 1; + while k < n_total { + let mut keys: Vec = Vec::new(); + for i in 0..n_total { + let first = rank[i] as u64; + let second = if i + k < n_total { rank[i + k] as u64 + 1 } else { 0 }; + keys.push((first << 32) | second); + } + let mut sorted = keys.clone(); + sorted.sort(); + sorted.dedup(); + for i in 0..n_total { + rank[i] = sorted.iter().position(|&x| x == keys[i]).unwrap() as i32; + } + if k >= n_total { break; } + k *= 2; + } + + let mut sa = vec![0usize; n_total]; + for (i, &r) in rank.iter().enumerate() { + sa[r as usize] = i; + } + + let mut lcp = vec![0i32; n_total]; + let inv_sa = rank.clone(); + let mut h = 0usize; + for i in 0..n_total { + if inv_sa[i] > 0 { + let j = sa[inv_sa[i] as usize - 1]; + while i + h < n_total && j + h < n_total && combined[i + h] == combined[j + h] { + h += 1; + } + lcp[inv_sa[i] as usize] = h as i32; + if h > 0 { h -= 1; } + } + } + + let mut ans = 0; + let mut left = 0; + let mut count = vec![0i32; m]; + let mut distinct = 0; + let mut min_q: VecDeque = VecDeque::new(); + + for right in 0..n_total { + let p = path_origin[sa[right]]; + if p >= 0 { + if count[p as usize] == 0 { distinct += 1; } + count[p as usize] += 1; + } + while let Some(&back) = min_q.back() { + if lcp[back] >= lcp[right] { + min_q.pop_back(); + } else { + break; + } + } + min_q.push_back(right); + + while distinct == m { + while let Some(&front) = min_q.front() { + if front <= left { + min_q.pop_front(); + } else { + break; + } + } + if let Some(&front) = min_q.front() { + ans = ans.max(lcp[front]); + } + let out = path_origin[sa[left]]; + if out >= 0 { + count[out as usize] -= 1; + if count[out as usize] == 0 { distinct -= 1; } + } + left += 1; + } + } + ans + } +} diff --git a/tests/1501-2000/1923. longest-common-subpath/sol.swift b/tests/1501-2000/1923. longest-common-subpath/sol.swift new file mode 100644 index 00000000..80f7d0d8 --- /dev/null +++ b/tests/1501-2000/1923. longest-common-subpath/sol.swift @@ -0,0 +1,95 @@ +class Solution { + func longestCommonSubpath(_ n: Int, _ paths: [[Int]]) -> Int { + var combined: [Int] = [] + var pathOrigin: [Int] = [] + for (i, p) in paths.enumerated() { + for v in p { + combined.append(v) + pathOrigin.append(i) + } + combined.append(-(i+1)) + pathOrigin.append(i) + } + let N = combined.count + let M = paths.count + let S = combined + let P = pathOrigin + + // rank compression + var rank = [Int](repeating: 0, count: N) + do { + let temp = S.sorted() + for i in 0..= N { break } + k *= 2 + } + + var sa = [Int](repeating: 0, count: N) + for i in 0.. 0 { + let j = sa[inv[i]-1] + while i+h < N && j+h < N && S[i+h] == S[j+h] { + h += 1 + } + lcp[inv[i]] = h + if h > 0 { h -= 1 } + } + } + + var ans = 0 + var left = 0 + var count = [Int](repeating: 0, count: M) + var distinct = 0 + var minQ: [Int] = [] + for right in 0..= 0 { + if count[p] == 0 { distinct += 1 } + count[p] += 1 + } + while !minQ.isEmpty && lcp[minQ.last!] >= lcp[right] { + minQ.removeLast() + } + minQ.append(right) + + while distinct == M { + while !minQ.isEmpty && minQ.first! <= left { + minQ.removeFirst() + } + if !minQ.isEmpty { + ans = max(ans, lcp[minQ.first!]) + } + let out = P[sa[left]] + if out >= 0 { + count[out] -= 1 + if count[out] == 0 { distinct -= 1 } + } + left += 1 + } + } + return ans + } +} diff --git a/tests/1501-2000/1923. longest-common-subpath/sol.ts b/tests/1501-2000/1923. longest-common-subpath/sol.ts new file mode 100644 index 00000000..cc90918b --- /dev/null +++ b/tests/1501-2000/1923. longest-common-subpath/sol.ts @@ -0,0 +1,95 @@ +function longestCommonSubpath(n: number, paths: number[][]): number { + const combined: number[] = []; + const pathOrigin: number[] = []; + for (let i = 0; i < paths.length; i++) { + for (const v of paths[i]) { + combined.push(v); + pathOrigin.push(i); + } + combined.push(-(i + 1)); + pathOrigin.push(i); + } + const N = combined.length; + const M = paths.length; + const S = combined; + const P = pathOrigin; + + // rank compression + const rank: number[] = new Array(N); + { + const temp = [...S].sort((a, b) => a - b); + for (let i = 0; i < N; i++) { + rank[i] = temp.indexOf(S[i]); + } + } + + let k = 1; + while (k < N) { + const keys: number[] = new Array(N); + for (let i = 0; i < N; i++) { + const first = rank[i]; + const second = i + k < N ? rank[i + k] + 1 : 0; + // JS number is 64-bit double, but bitwise ops use 32-bit. Use BigInt? + // Instead use string key or combine as tuple. We'll use tuple of two numbers. + keys[i] = first * 1000000 + second; // approximate unique key + } + const sortedKeys = [...keys].sort((a, b) => a - b); + for (let i = 0; i < N; i++) { + rank[i] = sortedKeys.indexOf(keys[i]); + } + if (k >= N) break; + k *= 2; + } + + const sa: number[] = new Array(N); + for (let i = 0; i < N; i++) { + sa[rank[i]] = i; + } + + const lcp: number[] = new Array(N).fill(0); + const inv = rank; + let h = 0; + for (let i = 0; i < N; i++) { + if (inv[i] > 0) { + const j = sa[inv[i] - 1]; + while (i + h < N && j + h < N && S[i + h] === S[j + h]) { + h++; + } + lcp[inv[i]] = h; + if (h > 0) h--; + } + } + + let ans = 0; + let left = 0; + const count: number[] = new Array(M).fill(0); + let distinct = 0; + const minQ: number[] = []; + for (let right = 0; right < N; right++) { + const p = P[sa[right]]; + if (p >= 0) { + if (count[p] === 0) distinct++; + count[p]++; + } + while (minQ.length > 0 && lcp[minQ[minQ.length - 1]] >= lcp[right]) { + minQ.pop(); + } + minQ.push(right); + + while (distinct === M) { + while (minQ.length > 0 && minQ[0] <= left) { + minQ.shift(); + } + if (minQ.length > 0) { + ans = Math.max(ans, lcp[minQ[0]]); + } + const out = P[sa[left]]; + if (out >= 0) { + count[out]--; + if (count[out] === 0) distinct--; + } + left++; + } + } + return ans; +} diff --git a/tests/1501-2000/1925. count-square-sum-triples/manifest.yaml b/tests/1501-2000/1925. count-square-sum-triples/manifest.yaml new file mode 100644 index 00000000..9ca66db3 --- /dev/null +++ b/tests/1501-2000/1925. count-square-sum-triples/manifest.yaml @@ -0,0 +1,200 @@ +entry: + id: 1925 + title: "count-square-sum-triples" + params: + n: + type: int + call: + cpp: "Solution().countTriples({n})" + rust: "Solution::count_triples({n})" + python3: "Solution().countTriples({n})" + python2: "Solution().countTriples({n})" + ruby: "count_triples({n})" + java: "new Solution().countTriples({n})" + csharp: "new Solution().CountTriples({n})" + kotlin: "Solution().countTriples({n})" + go: "countTriples({n})" + dart: "Solution().countTriples({n})" + swift: "Solution().countTriples({n})" + typescript: "countTriples({n})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().countTriples(n, {result})" + checker: | + from math import gcd, isqrt + + class Checker: + def countTriples(self, n, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + expected = 0 + for a in range(1, n + 1): + for b in range(1, n + 1): + c = isqrt(a * a + b * b) + if c <= n and c * c == a * a + b * b: + expected += 1 + return result == expected + +seed: 1925 + +tests: + - name: "minimum" + in: + n: 1 + out: 0 + - name: "below-first-triple" + in: + n: 4 + out: 0 + - name: "first-triple" + in: + n: 5 + out: 2 + - name: "six" + in: + n: 6 + out: 2 + - name: "seven" + in: + n: 7 + out: 2 + - name: "eight" + in: + n: 8 + out: 2 + - name: "nine" + in: + n: 9 + out: 2 + - name: "example-two" + in: + n: 10 + out: 4 + - name: "eleven" + in: + n: 11 + out: 4 + - name: "twelve" + in: + n: 12 + out: 4 + - name: "fifteen" + in: + n: 15 + out: 8 + - name: "sixteen" + in: + n: 16 + out: 8 + - name: "twenty" + in: + n: 20 + out: 12 + - name: "twenty-four" + in: + n: 24 + out: 12 + - name: "twenty-five" + in: + n: 25 + out: 16 + - name: "thirty" + in: + n: 30 + out: 22 + - name: "thirty-five" + in: + n: 35 + out: 26 + - name: "forty" + in: + n: 40 + out: 32 + - name: "forty-five" + in: + n: 45 + out: 36 + - name: "fifty" + in: + n: 50 + out: 40 + - name: "sixty" + in: + n: 60 + out: 52 + - name: "seventy-five" + in: + n: 75 + out: 74 + - name: "eighty" + in: + n: 80 + out: 78 + - name: "ninety" + in: + n: 90 + out: 94 + - name: "one-hundred" + in: + n: 100 + out: 104 + - name: "one-ten" + in: + n: 110 + out: 118 + - name: "one-twenty" + in: + n: 120 + out: 132 + - name: "one-twenty-five" + in: + n: 125 + out: 142 + - name: "one-twenty-eight" + in: + n: 128 + out: 142 + - name: "one-forty" + in: + n: 140 + out: 158 + - name: "one-fifty" + in: + n: 150 + out: 178 + - name: "one-sixty" + in: + n: 160 + out: 190 + - name: "one-seventy-five" + in: + n: 175 + out: 214 + - name: "two-hundred" + in: + n: 200 + out: 254 + - name: "two-twenty-five" + in: + n: 225 + out: 296 + - name: "two-forty" + in: + n: 240 + out: 314 + - name: "two-forty-nine" + in: + n: 249 + out: 324 + - name: "maximum" + in: + n: 250 + out: 330 diff --git a/tests/1501-2000/1925. count-square-sum-triples/sol.cpp b/tests/1501-2000/1925. count-square-sum-triples/sol.cpp new file mode 100644 index 00000000..c72de319 --- /dev/null +++ b/tests/1501-2000/1925. count-square-sum-triples/sol.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int countTriples(int n) { + int cnt = 0; + int nsqrt = (int) sqrt(n); + for (int s = 2; s <= nsqrt; s++) { + int start = (s & 1) + 1; + for (int t = start; t < s; t += 2) { + if (gcd(s, t) != 1) continue; + int c = s * s + t * t; + if (c > n) break; + int k = n / c; + cnt += 2 * k; + } + } + return cnt; + } +private: + int gcd(int a, int b) { + while (b != 0) { + int temp = b; + b = a % b; + a = temp; + } + return a; + } +}; diff --git a/tests/1501-2000/1925. count-square-sum-triples/sol.cs b/tests/1501-2000/1925. count-square-sum-triples/sol.cs new file mode 100644 index 00000000..6db70eb9 --- /dev/null +++ b/tests/1501-2000/1925. count-square-sum-triples/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public int CountTriples(int n) { + int cnt = 0; + int nsqrt = (int) Math.Sqrt(n); + for (int s = 2; s <= nsqrt; s++) { + int start = (s & 1) + 1; + for (int t = start; t < s; t += 2) { + if (Gcd(s, t) != 1) continue; + int c = s * s + t * t; + if (c > n) break; + int k = n / c; + cnt += 2 * k; + } + } + return cnt; + } + private int Gcd(int a, int b) { + while (b != 0) { + int temp = b; + b = a % b; + a = temp; + } + return a; + } +} diff --git a/tests/1501-2000/1925. count-square-sum-triples/sol.dart b/tests/1501-2000/1925. count-square-sum-triples/sol.dart new file mode 100644 index 00000000..f265b012 --- /dev/null +++ b/tests/1501-2000/1925. count-square-sum-triples/sol.dart @@ -0,0 +1,25 @@ +class Solution { + int countTriples(int n) { + int cnt = 0; + int nsqrt = sqrt(n).toInt(); + for (int s = 2; s <= nsqrt; s++) { + int start = (s & 1) + 1; + for (int t = start; t < s; t += 2) { + if (gcd(s, t) != 1) continue; + int c = s * s + t * t; + if (c > n) break; + int k = n ~/ c; + cnt += 2 * k; + } + } + return cnt; + } + int gcd(int a, int b) { + while (b != 0) { + int temp = b; + b = a % b; + a = temp; + } + return a; + } +} diff --git a/tests/1501-2000/1925. count-square-sum-triples/sol.go b/tests/1501-2000/1925. count-square-sum-triples/sol.go new file mode 100644 index 00000000..308f6e7c --- /dev/null +++ b/tests/1501-2000/1925. count-square-sum-triples/sol.go @@ -0,0 +1,26 @@ +func countTriples(n int) int { + cnt := 0 + nsqrt := int(math.Sqrt(float64(n))) + for s := 2; s <= nsqrt; s++ { + start := (s & 1) + 1 + for t := start; t < s; t += 2 { + if gcd(s, t) != 1 { + continue + } + c := s*s + t*t + if c > n { + break + } + k := n / c + cnt += 2 * k + } + } + return cnt +} + +func gcd(a, b int) int { + for b != 0 { + a, b = b, a % b + } + return a +} diff --git a/tests/1501-2000/1925. count-square-sum-triples/sol.java b/tests/1501-2000/1925. count-square-sum-triples/sol.java new file mode 100644 index 00000000..aa7b9869 --- /dev/null +++ b/tests/1501-2000/1925. count-square-sum-triples/sol.java @@ -0,0 +1,25 @@ +class Solution { + public int countTriples(int n) { + int cnt = 0; + int nsqrt = (int) Math.sqrt(n); + for (int s = 2; s <= nsqrt; s++) { + int start = (s & 1) + 1; + for (int t = start; t < s; t += 2) { + if (gcd(s, t) != 1) continue; + int c = s * s + t * t; + if (c > n) break; + int k = n / c; + cnt += 2 * k; + } + } + return cnt; + } + private int gcd(int a, int b) { + while (b != 0) { + int temp = b; + b = a % b; + a = temp; + } + return a; + } +} diff --git a/tests/1501-2000/1925. count-square-sum-triples/sol.kt b/tests/1501-2000/1925. count-square-sum-triples/sol.kt new file mode 100644 index 00000000..911afce9 --- /dev/null +++ b/tests/1501-2000/1925. count-square-sum-triples/sol.kt @@ -0,0 +1,29 @@ +class Solution { + fun countTriples(n: Int): Int { + var cnt = 0 + val nsqrt = Math.sqrt(n.toDouble()).toInt() + for (s in 2..nsqrt) { + val start = (s and 1) + 1 + var t = start + while (t < s) { + if (gcd(s, t) != 1) { t += 2; continue } + val c = s * s + t * t + if (c > n) break + val k = n / c + cnt += 2 * k + t += 2 + } + } + return cnt + } + private fun gcd(a: Int, b: Int): Int { + var x = a + var y = b + while (y != 0) { + val temp = y + y = x % y + x = temp + } + return x + } +} diff --git a/tests/1501-2000/1925. count-square-sum-triples/sol.py b/tests/1501-2000/1925. count-square-sum-triples/sol.py new file mode 100644 index 00000000..07941e01 --- /dev/null +++ b/tests/1501-2000/1925. count-square-sum-triples/sol.py @@ -0,0 +1,17 @@ +from math import gcd, isqrt + + +class Solution: + def countTriples(self, n: int) -> int: + cnt = 0 + nsqrt = isqrt(n) + for s in range(2, nsqrt + 1): + for t in range((s & 1) + 1, s, 2): + if gcd(s, t) != 1: + continue + c = s * s + t * t + if c > n: + break + k = n // c + cnt += 2 * k + return cnt diff --git a/tests/1501-2000/1925. count-square-sum-triples/sol.py2 b/tests/1501-2000/1925. count-square-sum-triples/sol.py2 new file mode 100644 index 00000000..3bac2ff3 --- /dev/null +++ b/tests/1501-2000/1925. count-square-sum-triples/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def countTriples(self, n): + """ + :type n: int + :rtype: int + """ + cnt = 0 + nsqrt = int(n ** 0.5) + for s in range(2, nsqrt + 1): + for t in range((s & 1) + 1, s, 2): + a, b = s, t + while b: + a, b = b, a % b + if a != 1: + continue + c = s * s + t * t + if c > n: + break + k = n // c + cnt += 2 * k + return cnt diff --git a/tests/1501-2000/1925. count-square-sum-triples/sol.rb b/tests/1501-2000/1925. count-square-sum-triples/sol.rb new file mode 100644 index 00000000..36e51910 --- /dev/null +++ b/tests/1501-2000/1925. count-square-sum-triples/sol.rb @@ -0,0 +1,21 @@ +# @param {Integer} n +# @return {Integer} +def count_triples(n) + cnt = 0 + nsqrt = Math.sqrt(n).to_i + (2..nsqrt).each do |s| + start_t = (s & 1) + 1 + (start_t...s).step(2).each do |t| + a, b = s, t + while b != 0 + a, b = b, a % b + end + next if a != 1 + c = s * s + t * t + break if c > n + k = n / c + cnt += 2 * k + end + end + cnt +end diff --git a/tests/1501-2000/1925. count-square-sum-triples/sol.rs b/tests/1501-2000/1925. count-square-sum-triples/sol.rs new file mode 100644 index 00000000..562a88d1 --- /dev/null +++ b/tests/1501-2000/1925. count-square-sum-triples/sol.rs @@ -0,0 +1,34 @@ +impl Solution { + pub fn count_triples(n: i32) -> i32 { + let mut cnt = 0; + let nsqrt = (n as f64).sqrt() as i32; + for s in 2..=nsqrt { + let start = (s & 1) + 1; + let mut t = start; + while t < s { + if gcd(s, t) != 1 { + t += 2; + continue; + } + let c = s * s + t * t; + if c > n { + break; + } + let k = n / c; + cnt += 2 * k; + t += 2; + } + } + cnt + } +} +fn gcd(a: i32, b: i32) -> i32 { + let mut x = a; + let mut y = b; + while y != 0 { + let temp = y; + y = x % y; + x = temp; + } + x +} diff --git a/tests/1501-2000/1925. count-square-sum-triples/sol.swift b/tests/1501-2000/1925. count-square-sum-triples/sol.swift new file mode 100644 index 00000000..552b8566 --- /dev/null +++ b/tests/1501-2000/1925. count-square-sum-triples/sol.swift @@ -0,0 +1,33 @@ +class Solution { + func countTriples(_ n: Int) -> Int { + var cnt = 0 + let nsqrt = Int(Double(n).squareRoot()) + if nsqrt < 2 { return 0 } + for s in 2...nsqrt { + let start = (s & 1) + 1 + var t = start + while t < s { + if gcd(s, t) != 1 { + t += 2 + continue + } + let c = s * s + t * t + if c > n { break } + let k = n / c + cnt += 2 * k + t += 2 + } + } + return cnt + } + private func gcd(_ a: Int, _ b: Int) -> Int { + var x = a + var y = b + while y != 0 { + let temp = y + y = x % y + x = temp + } + return x + } +} diff --git a/tests/1501-2000/1925. count-square-sum-triples/sol.ts b/tests/1501-2000/1925. count-square-sum-triples/sol.ts new file mode 100644 index 00000000..f301b9d4 --- /dev/null +++ b/tests/1501-2000/1925. count-square-sum-triples/sol.ts @@ -0,0 +1,23 @@ +function countTriples(n: number): number { + let cnt = 0; + const nsqrt = Math.floor(Math.sqrt(n)); + for (let s = 2; s <= nsqrt; s++) { + const start = (s & 1) + 1; + for (let t = start; t < s; t += 2) { + if (gcd(s, t) !== 1) continue; + const c = s * s + t * t; + if (c > n) break; + const k = Math.floor(n / c); + cnt += 2 * k; + } + } + return cnt; +} +function gcd(a: number, b: number): number { + while (b !== 0) { + const temp = b; + b = a % b; + a = temp; + } + return a; +} diff --git a/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/manifest.yaml b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/manifest.yaml new file mode 100644 index 00000000..0ebca369 --- /dev/null +++ b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/manifest.yaml @@ -0,0 +1,378 @@ +entry: + id: 1926 + title: "nearest-exit-from-entrance-in-maze" + params: + maze: + type: array + items: + type: array + items: + type: char + entrance: + type: array + items: + type: int + call: + cpp: "Solution().nearestExit({maze}, {entrance})" + rust: "Solution::nearest_exit({maze}, {entrance})" + python3: "Solution().nearestExit({maze}, {entrance})" + python2: "Solution().nearestExit({maze}, {entrance})" + ruby: "nearest_exit({maze}, {entrance})" + java: "new Solution().nearestExit({maze}, {entrance})" + csharp: "new Solution().NearestExit({maze}, {entrance})" + kotlin: "Solution().nearestExit({maze}, {entrance})" + go: "nearestExit({maze}, {entrance})" + dart: "Solution().nearestExit({maze}, {entrance})" + swift: "Solution().nearestExit({maze}, {entrance})" + typescript: "nearestExit({maze}, {entrance})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().nearestExit(maze, entrance, {result})" + checker: | + from collections import deque + + class Checker: + def nearestExit(self, maze, entrance, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + rows = len(maze) + cols = len(maze[0]) + start = (entrance[0], entrance[1]) + queue = deque([(start[0], start[1], 0)]) + seen = {start} + while queue: + r, c, distance = queue.popleft() + for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)): + nr, nc = r + dr, c + dc + if nr < 0 or nr >= rows or nc < 0 or nc >= cols: + continue + if (nr, nc) in seen or maze[nr][nc] != '.': + continue + if nr == 0 or nr == rows - 1 or nc == 0 or nc == cols - 1: + return result == distance + 1 + seen.add((nr, nc)) + queue.append((nr, nc, distance + 1)) + return result == -1 + +seed: 1926 + +tests: + - name: "example-one" + in: + maze: + - ["+", "+", ".", "+"] + - [".", ".", ".", "+"] + - ["+", "+", "+", "."] + entrance: [1, 2] + out: 1 + - name: "example-two" + in: + maze: + - ["+", "+", "+"] + - [".", ".", "."] + - ["+", "+", "+"] + entrance: [1, 0] + out: 2 + - name: "example-three" + in: + maze: + - [".", "+"] + entrance: [0, 0] + out: -1 + - name: "one-by-two-entrance-border" + in: + maze: + - [".", "."] + entrance: [0, 0] + out: 1 + - name: "one-by-three-middle" + in: + maze: + - ["+", ".", "."] + entrance: [0, 1] + out: 1 + - name: "one-by-three-blocked" + in: + maze: + - ["+", ".", "+"] + entrance: [0, 1] + out: -1 + - name: "two-by-two-from-corner" + in: + maze: + - [".", "+"] + - [".", "."] + entrance: [0, 0] + out: 1 + - name: "two-by-two-isolated" + in: + maze: + - [".", "+"] + - ["+", "+"] + entrance: [0, 0] + out: -1 + - name: "entrance-border-not-counted" + in: + maze: + - [".", ".", "."] + - ["+", "+", "."] + - ["+", "+", "."] + entrance: [0, 0] + out: 1 + - name: "nearest-up" + in: + maze: + - ["+", ".", "+"] + - ["+", ".", "+"] + - ["+", ".", "+"] + entrance: [2, 1] + out: 2 + - name: "nearest-down" + in: + maze: + - ["+", ".", "+"] + - ["+", ".", "+"] + - ["+", ".", "+"] + entrance: [0, 1] + out: 2 + - name: "nearest-left" + in: + maze: + - [".", ".", ".", "+"] + - ["+", "+", ".", "+"] + - ["+", "+", ".", "+"] + entrance: [0, 2] + out: 1 + - name: "nearest-right" + in: + maze: + - ["+", ".", ".", "."] + - ["+", ".", "+", "+"] + - ["+", ".", "+", "+"] + entrance: [0, 1] + out: 1 + - name: "straight-three" + in: + maze: + - ["+", "+", "+", "+", "+"] + - [".", ".", ".", ".", "."] + - ["+", "+", "+", "+", "+"] + entrance: [1, 2] + out: 2 + - name: "straight-four-to-left" + in: + maze: + - ["+", "+", "+", "+", "+", "+"] + - [".", ".", ".", ".", ".", "+"] + - ["+", "+", "+", "+", "+", "+"] + entrance: [1, 4] + out: 4 + - name: "straight-four-to-right" + in: + maze: + - ["+", "+", "+", "+", "+", "+"] + - ["+", ".", ".", ".", ".", "."] + - ["+", "+", "+", "+", "+", "+"] + entrance: [1, 1] + out: 4 + - name: "detour-around-wall" + in: + maze: + - ["+", ".", "+", ".", "+"] + - [".", ".", ".", ".", "."] + - ["+", "+", "+", "+", "+"] + entrance: [1, 2] + out: 2 + - name: "blocked-center" + in: + maze: + - ["+", ".", "+", ".", "+"] + - ["+", ".", "+", ".", "+"] + - ["+", ".", "+", ".", "+"] + - ["+", "+", "+", "+", "+"] + entrance: [1, 1] + out: 1 + - name: "long-zigzag" + in: + maze: + - ["+", ".", ".", ".", "+", "+"] + - ["+", "+", "+", ".", "+", "+"] + - ["+", "+", ".", ".", ".", "+"] + - ["+", "+", ".", "+", "+", "+"] + - ["+", ".", ".", "+", "+", "+"] + entrance: [3, 2] + out: 1 + - name: "enclosed-pocket" + in: + maze: + - ["+", "+", "+", "+", "+"] + - ["+", ".", ".", ".", "+"] + - ["+", ".", ".", ".", "+"] + - ["+", "+", "+", "+", "+"] + entrance: [2, 2] + out: -1 + - name: "open-square" + in: + maze: + - [".", ".", ".", "."] + - [".", ".", ".", "."] + - [".", ".", ".", "."] + - [".", ".", ".", "."] + entrance: [1, 1] + out: 1 + - name: "open-square-center" + in: + maze: + - [".", ".", ".", ".", "."] + - [".", ".", ".", ".", "."] + - [".", ".", ".", ".", "."] + - [".", ".", ".", ".", "."] + - [".", ".", ".", ".", "."] + entrance: [2, 2] + out: 2 + - name: "single-open-cell" + in: + maze: + - ["+"] + entrance: [0, 0] + out: -1 + - name: "single-cell-open" + in: + maze: + - ["."] + entrance: [0, 0] + out: -1 + - name: "three-by-three-ring" + in: + maze: + - [".", ".", "."] + - [".", "+", "."] + - [".", ".", "."] + entrance: [1, 1] + out: 1 + - name: "three-by-three-corridor" + in: + maze: + - ["+", ".", "+"] + - [".", ".", "."] + - ["+", ".", "+"] + entrance: [1, 1] + out: 1 + - name: "no-exit-inner-component" + in: + maze: + - ["+", "+", "+", "+", "+", "+"] + - ["+", ".", ".", ".", ".", "+"] + - ["+", ".", "+", "+", ".", "+"] + - ["+", ".", ".", ".", ".", "+"] + - ["+", "+", "+", "+", "+", "+"] + entrance: [1, 1] + out: -1 + - name: "border-exit-behind-detour" + in: + maze: + - ["+", "+", ".", "+", "+"] + - ["+", ".", ".", ".", "+"] + - ["+", ".", "+", ".", "+"] + - [".", ".", "+", ".", "+"] + - ["+", "+", "+", ".", "+"] + entrance: [1, 2] + out: 1 + - name: "wide-maze" + in: + maze: + - ["+", ".", ".", ".", ".", ".", "+", "."] + - ["+", "+", "+", "+", ".", "+", "+", "."] + - [".", ".", ".", ".", ".", "+", ".", "."] + entrance: [1, 4] + out: 1 + - name: "deep-nine-by-nine" + in: + maze: + - ["+", "+", "+", "+", "+", "+", "+", "+", "+"] + - ["+", ".", ".", ".", ".", ".", ".", ".", "+"] + - ["+", ".", "+", "+", "+", "+", "+", ".", "+"] + - ["+", ".", "+", ".", ".", ".", "+", ".", "+"] + - ["+", ".", "+", ".", "+", ".", "+", ".", "+"] + - ["+", ".", "+", ".", ".", ".", "+", ".", "+"] + - ["+", ".", "+", "+", "+", "+", "+", ".", "+"] + - ["+", ".", ".", ".", ".", ".", ".", ".", "+"] + - ["+", "+", "+", "+", "+", "+", "+", "+", "+"] + entrance: [4, 3] + out: -1 + - name: "many-exits-near" + in: + maze: + - [".", ".", ".", ".", "."] + - [".", "+", "+", "+", "."] + - [".", "+", ".", "+", "."] + - [".", "+", ".", "+", "."] + - [".", ".", ".", ".", "."] + entrance: [2, 2] + out: 2 + - name: "large-open-eight" + in: + maze: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + entrance: [3, 3] + out: 3 + - name: "large-open-edge-entrance" + in: + maze: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + entrance: [0, 4] + out: 1 + - name: "long-horizontal-corridor" + in: + maze: + - ["+", ".", ".", ".", ".", ".", ".", ".", ".", ".", "+"] + - ["+", "+", "+", "+", "+", ".", "+", "+", "+", "+", "+"] + - ["+", "+", "+", "+", "+", ".", "+", "+", "+", "+", "+"] + entrance: [2, 5] + out: 2 + - name: "large-enclosed" + in: + maze: + - ["+", "+", "+", "+", "+", "+", "+", "+", "+", "+"] + - ["+", ".", ".", ".", ".", ".", ".", ".", ".", "+"] + - ["+", ".", "+", "+", "+", "+", "+", "+", ".", "+"] + - ["+", ".", "+", ".", ".", ".", "+", "+", ".", "+"] + - ["+", ".", "+", ".", "+", ".", "+", "+", ".", "+"] + - ["+", ".", "+", ".", ".", ".", "+", "+", ".", "+"] + - ["+", ".", "+", "+", "+", "+", "+", "+", ".", "+"] + - ["+", ".", ".", ".", ".", ".", ".", ".", ".", "+"] + - ["+", "+", "+", "+", "+", "+", "+", "+", "+", "+"] + entrance: [4, 3] + out: -1 + - name: "final-corner-exit" + in: + maze: + - ["+", "+", "+", "+", "."] + - ["+", ".", ".", ".", "."] + - ["+", ".", "+", "+", "+"] + - ["+", ".", ".", ".", "+"] + - [".", "+", "+", "+", "+"] + entrance: [1, 1] + out: 3 diff --git a/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.cpp b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.cpp new file mode 100644 index 00000000..a5071d29 --- /dev/null +++ b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int nearestExit(vector>& maze, vector& entrance) { + int n = maze.size(), m = maze[0].size(); + vector> visited(n, vector(m, false)); + queue> q; + q.push({entrance[0], entrance[1], 0}); + visited[entrance[0]][entrance[1]] = true; + int dirs[4][2] = {{-1,0},{1,0},{0,-1},{0,1}}; + + while(!q.empty()) { + auto [r, c, dist] = q.front(); q.pop(); + for(auto& d : dirs) { + int nr = r + d[0], nc = c + d[1]; + if(nr >= 0 && nc >= 0 && nr < n && nc < m && !visited[nr][nc] && maze[nr][nc] == '.') { + visited[nr][nc] = true; + if(nr == 0 || nc == 0 || nr == n-1 || nc == m-1) return dist+1; + q.push({nr, nc, dist+1}); + } + } + } + return -1; + } +}; diff --git a/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.cs b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.cs new file mode 100644 index 00000000..107e3f0d --- /dev/null +++ b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.cs @@ -0,0 +1,23 @@ +public class Solution { + public int NearestExit(char[][] maze, int[] entrance) { + int n = maze.Length, m = maze[0].Length; + bool[,] visited = new bool[n,m]; + Queue<(int,int,int)> q = new Queue<(int,int,int)>(); + q.Enqueue((entrance[0], entrance[1], 0)); + visited[entrance[0], entrance[1]] = true; + int[][] dirs = new int[][] { new int[]{-1,0}, new int[]{1,0}, new int[]{0,-1}, new int[]{0,1} }; + + while(q.Count > 0) { + var (r, c, dist) = q.Dequeue(); + foreach(var d in dirs) { + int nr = r + d[0], nc = c + d[1]; + if(nr >= 0 && nc >= 0 && nr < n && nc < m && !visited[nr,nc] && maze[nr][nc] == '.') { + visited[nr,nc] = true; + if(nr == 0 || nc == 0 || nr == n-1 || nc == m-1) return dist+1; + q.Enqueue((nr, nc, dist+1)); + } + } + } + return -1; + } +} diff --git a/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.dart b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.dart new file mode 100644 index 00000000..1d923215 --- /dev/null +++ b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.dart @@ -0,0 +1,24 @@ +class Solution { + int nearestExit(List> maze, List entrance) { + int n = maze.length, m = maze[0].length; + List> visited = List.generate(n, (_) => List.filled(m, false)); + Queue> q = Queue(); + q.add([entrance[0], entrance[1], 0]); + visited[entrance[0]][entrance[1]] = true; + List> dirs = [[-1,0],[1,0],[0,-1],[0,1]]; + + while(q.isNotEmpty) { + var cell = q.removeFirst(); + int r = cell[0], c = cell[1], dist = cell[2]; + for(var d in dirs) { + int nr = r + d[0], nc = c + d[1]; + if(nr >= 0 && nc >= 0 && nr < n && nc < m && !visited[nr][nc] && maze[nr][nc] == ".") { + visited[nr][nc] = true; + if(nr == 0 || nc == 0 || nr == n-1 || nc == m-1) return dist+1; + q.add([nr, nc, dist+1]); + } + } + } + return -1; + } +} diff --git a/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.go b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.go new file mode 100644 index 00000000..f490c7d4 --- /dev/null +++ b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.go @@ -0,0 +1,29 @@ +func nearestExit(maze [][]byte, entrance []int) int { + n := len(maze) + m := len(maze[0]) + visited := make([][]bool, n) + for i := range visited { + visited[i] = make([]bool, m) + } + type cell struct { r, c, dist int } + q := []cell{{entrance[0], entrance[1], 0}} + visited[entrance[0]][entrance[1]] = true + dirs := [][]int{{-1,0},{1,0},{0,-1},{0,1}} + + for len(q) > 0 { + cur := q[0] + q = q[1:] + for _, d := range dirs { + nr := cur.r + d[0] + nc := cur.c + d[1] + if nr >= 0 && nc >= 0 && nr < n && nc < m && !visited[nr][nc] && maze[nr][nc] == '.' { + visited[nr][nc] = true + if nr == 0 || nc == 0 || nr == n-1 || nc == m-1 { + return cur.dist + 1 + } + q = append(q, cell{nr, nc, cur.dist+1}) + } + } + } + return -1 +} diff --git a/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.java b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.java new file mode 100644 index 00000000..d01bd60d --- /dev/null +++ b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.java @@ -0,0 +1,24 @@ +class Solution { + public int nearestExit(char[][] maze, int[] entrance) { + int n = maze.length, m = maze[0].length; + boolean[][] visited = new boolean[n][m]; + Queue q = new LinkedList<>(); + q.add(new int[]{entrance[0], entrance[1], 0}); + visited[entrance[0]][entrance[1]] = true; + int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}}; + + while(!q.isEmpty()) { + int[] cell = q.poll(); + int r = cell[0], c = cell[1], dist = cell[2]; + for(int[] d : dirs) { + int nr = r + d[0], nc = c + d[1]; + if(nr >= 0 && nc >= 0 && nr < n && nc < m && !visited[nr][nc] && maze[nr][nc] == '.') { + visited[nr][nc] = true; + if(nr == 0 || nc == 0 || nr == n-1 || nc == m-1) return dist+1; + q.add(new int[]{nr, nc, dist+1}); + } + } + } + return -1; + } +} diff --git a/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.kt b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.kt new file mode 100644 index 00000000..5f7c0876 --- /dev/null +++ b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun nearestExit(maze: Array, entrance: IntArray): Int { + val n = maze.size + val m = maze[0].size + val visited = Array(n) { BooleanArray(m) } + val q = ArrayDeque>() + q.add(Triple(entrance[0], entrance[1], 0)) + visited[entrance[0]][entrance[1]] = true + val dirs = arrayOf(intArrayOf(-1,0), intArrayOf(1,0), intArrayOf(0,-1), intArrayOf(0,1)) + + while(q.isNotEmpty()) { + val (r, c, dist) = q.removeFirst() + for(d in dirs) { + val nr = r + d[0] + val nc = c + d[1] + if(nr >= 0 && nc >= 0 && nr < n && nc < m && !visited[nr][nc] && maze[nr][nc] == '.') { + visited[nr][nc] = true + if(nr == 0 || nc == 0 || nr == n-1 || nc == m-1) return dist+1 + q.add(Triple(nr, nc, dist+1)) + } + } + } + return -1 + } +} diff --git a/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.py b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.py new file mode 100644 index 00000000..1d905c24 --- /dev/null +++ b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.py @@ -0,0 +1,45 @@ +class Solution: + def validCell(self, r, c, n, m): + if r < 0 or c < 0 or r >= n or c >= m: + return False + return True + + def validEdgeCell(self, r, c, n, m): + if r == 0 or c == 0 or r == n - 1 or c == m - 1: + return True + return False + + def __init__(self): + self.directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] + + def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: + n = len(maze) + m = len(maze[0]) + + visited = [[False for _ in range(m)] for _ in range(n)] + + que = deque() + que.append((entrance[0], entrance[1], 0)) + + visited[entrance[0]][entrance[1]] = True + + while que: + r, c, dist = que.popleft() + + for row, col in self.directions: + nRow = row + r + nCol = col + c + + if ( + self.validCell(nRow, nCol, n, m) + and not visited[nRow][nCol] + and maze[nRow][nCol] == "." + ): + visited[nRow][nCol] = True + + if self.validEdgeCell(nRow, nCol, n, m): + return dist + 1 + + que.append((nRow, nCol, dist + 1)) + + return -1 diff --git a/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.py2 b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.py2 new file mode 100644 index 00000000..00f41bdb --- /dev/null +++ b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.py2 @@ -0,0 +1,26 @@ +class Solution(object): + def nearestExit(self, maze, entrance): + """ + :type maze: List[List[str]] + :type entrance: List[int] + :rtype: int + """ + from collections import deque + n = len(maze) + m = len(maze[0]) + visited = [[False for _ in range(m)] for _ in range(n)] + q = deque() + q.append((entrance[0], entrance[1], 0)) + visited[entrance[0]][entrance[1]] = True + dirs = [(-1,0),(1,0),(0,-1),(0,1)] + + while q: + r, c, dist = q.popleft() + for dr, dc in dirs: + nr, nc = r+dr, c+dc + if 0 <= nr < n and 0 <= nc < m and not visited[nr][nc] and maze[nr][nc] == '.': + visited[nr][nc] = True + if nr == 0 or nc == 0 or nr == n-1 or nc == m-1: + return dist+1 + q.append((nr, nc, dist+1)) + return -1 diff --git a/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.rb b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.rb new file mode 100644 index 00000000..80a985cf --- /dev/null +++ b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.rb @@ -0,0 +1,23 @@ +def nearest_exit(maze, entrance) + n = maze.length + m = maze[0].length + visited = Array.new(n) { Array.new(m, false) } + q = [[entrance[0], entrance[1], 0]] + visited[entrance[0]][entrance[1]] = true + dirs = [[-1,0],[1,0],[0,-1],[0,1]] + + until q.empty? + r, c, dist = q.shift + dirs.each do |dr, dc| + nr, nc = r+dr, c+dc + if nr >= 0 && nc >= 0 && nr < n && nc < m && !visited[nr][nc] && maze[nr][nc] == "." + visited[nr][nc] = true + if nr == 0 || nc == 0 || nr == n-1 || nc == m-1 + return dist+1 + end + q << [nr, nc, dist+1] + end + end + end + -1 +end diff --git a/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.rs b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.rs new file mode 100644 index 00000000..a41fedd8 --- /dev/null +++ b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn nearest_exit(maze: Vec>, entrance: Vec) -> i32 { + let n = maze.len() as i32; + let m = maze[0].len() as i32; + let mut visited = vec![vec![false; m as usize]; n as usize]; + let mut q = std::collections::VecDeque::new(); + q.push_back((entrance[0], entrance[1], 0)); + visited[entrance[0] as usize][entrance[1] as usize] = true; + let dirs = [(-1,0),(1,0),(0,-1),(0,1)]; + + while let Some((r, c, dist)) = q.pop_front() { + for (dr, dc) in dirs.iter() { + let nr = r + dr; + let nc = c + dc; + if nr >= 0 && nc >= 0 && nr < n && nc < m && !visited[nr as usize][nc as usize] && maze[nr as usize][nc as usize] == '.' { + visited[nr as usize][nc as usize] = true; + if nr == 0 || nc == 0 || nr == n-1 || nc == m-1 { + return dist + 1; + } + q.push_back((nr, nc, dist+1)); + } + } + } + -1 + } +} diff --git a/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.swift b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.swift new file mode 100644 index 00000000..1a29dbc3 --- /dev/null +++ b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.swift @@ -0,0 +1,27 @@ +class Solution { + func nearestExit(_ maze: [[Character]], _ entrance: [Int]) -> Int { + let n = maze.count + let m = maze[0].count + var visited = Array(repeating: Array(repeating: false, count: m), count: n) + var q = [(Int, Int, Int)]() + q.append((entrance[0], entrance[1], 0)) + visited[entrance[0]][entrance[1]] = true + let dirs = [(-1,0),(1,0),(0,-1),(0,1)] + + while !q.isEmpty { + let (r, c, dist) = q.removeFirst() + for (dr, dc) in dirs { + let nr = r + dr + let nc = c + dc + if nr >= 0 && nc >= 0 && nr < n && nc < m && !visited[nr][nc] && maze[nr][nc] == "." { + visited[nr][nc] = true + if nr == 0 || nc == 0 || nr == n-1 || nc == m-1 { + return dist + 1 + } + q.append((nr, nc, dist+1)) + } + } + } + return -1 + } +} diff --git a/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.ts b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.ts new file mode 100644 index 00000000..3e5c6abf --- /dev/null +++ b/tests/1501-2000/1926. nearest-exit-from-entrance-in-maze/sol.ts @@ -0,0 +1,35 @@ +function nearestExit(maze: string[][], entrance: number[]): number { + const n = maze.length, + m = maze[0].length; + const visited = Array.from({ length: n }, () => Array(m).fill(false)); + const q: [number, number, number][] = [[entrance[0], entrance[1], 0]]; + visited[entrance[0]][entrance[1]] = true; + const dirs = [ + [-1, 0], + [1, 0], + [0, -1], + [0, 1], + ]; + + while (q.length > 0) { + const [r, c, dist] = q.shift()!; + for (const [dr, dc] of dirs) { + const nr = r + dr, + nc = c + dc; + if ( + nr >= 0 && + nc >= 0 && + nr < n && + nc < m && + !visited[nr][nc] && + maze[nr][nc] === "." + ) { + visited[nr][nc] = true; + if (nr === 0 || nc === 0 || nr === n - 1 || nc === m - 1) + return dist + 1; + q.push([nr, nc, dist + 1]); + } + } + } + return -1; +} diff --git a/tests/1501-2000/1927. sum-game/manifest.yaml b/tests/1501-2000/1927. sum-game/manifest.yaml new file mode 100644 index 00000000..e9e2c69c --- /dev/null +++ b/tests/1501-2000/1927. sum-game/manifest.yaml @@ -0,0 +1,209 @@ +entry: + id: 1927 + title: "sum-game" + params: + num: + type: string + call: + cpp: "Solution().sumGame({num})" + rust: "Solution::sum_game({num})" + python3: "Solution().sumGame({num})" + python2: "Solution().sumGame({num})" + ruby: "sum_game({num})" + java: "new Solution().sumGame({num})" + csharp: "new Solution().SumGame({num})" + kotlin: "Solution().sumGame({num})" + go: "sumGame({num})" + dart: "Solution().sumGame({num})" + swift: "Solution().sumGame({num})" + typescript: "sumGame({num})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().sumGame(num, {result})" + checker: | + class Checker: + def sumGame(self, num, result): + if not isinstance(num, str) or len(num) < 2 or len(num) % 2 != 0: + return False + if any(ch != '?' and not ('0' <= ch <= '9') for ch in num): + return False + if not isinstance(result, bool): + return False + half = len(num) // 2 + left = sum(int(ch) for ch in num[:half] if ch != '?') + right = sum(int(ch) for ch in num[half:] if ch != '?') + q_left = num[:half].count('?') + q_right = num[half:].count('?') + return result == ((left - right) * 2 != (q_right - q_left) * 9) + +seed: 1927 + +tests: + - name: "example_equal" + in: + num: "5023" + out: false + - name: "example_one_question_pair" + in: + num: "25??" + out: true + - name: "example_balanced_questions" + in: + num: "?3295???" + out: false + - name: "minimum_equal" + in: + num: "00" + out: false + - name: "minimum_unequal" + in: + num: "09" + out: true + - name: "minimum_questions_left" + in: + num: "?0" + out: true + - name: "minimum_questions_right" + in: + num: "0?" + out: true + - name: "all_questions_two" + in: + num: "??" + out: false + - name: "all_questions_four" + in: + num: "????" + out: false + - name: "all_questions_six" + in: + num: "??????" + out: false + - name: "left_question_right_fixed" + in: + num: "?999" + out: true + - name: "right_question_left_fixed" + in: + num: "999?" + out: true + - name: "equal_fixed_halves" + in: + num: "123321" + out: false + - name: "unequal_fixed_halves" + in: + num: "123456" + out: true + - name: "same_question_count_nonzero_gap" + in: + num: "1?2?" + out: true + - name: "same_question_count_zero_gap" + in: + num: "1?1?" + out: false + - name: "two_left_questions" + in: + num: "??90" + out: false + - name: "two_right_questions" + in: + num: "90??" + out: false + - name: "two_each_questions" + in: + num: "??00" + out: true + - name: "question_spacing" + in: + num: "?1?2" + out: true + - name: "max_left_digits" + in: + num: "99990000" + out: true + - name: "max_right_digits" + in: + num: "00009999" + out: true + - name: "zero_vs_nines" + in: + num: "00009999" + out: true + - name: "alternating_digits" + in: + num: "09090909" + out: false + - name: "alternating_unequal" + in: + num: "09090999" + out: true + - name: "four_left_questions" + in: + num: "????9999" + out: true + - name: "four_right_questions" + in: + num: "9999????" + out: true + - name: "balanced_question_counts" + in: + num: "??99??99" + out: false + - name: "balanced_counts_gap_one" + in: + num: "??99??98" + out: true + - name: "long_equal_fixed" + in: + num: "12345678901234567890123456789012345678901234567890" + out: true + - name: "long_unequal_fixed" + in: + num: "12345678901234567890123456789012345678901234567899" + out: true + - name: "long_questions_balanced" + in: + num: "?????00000?????00000" + out: false + - name: "long_questions_left_heavy" + in: + num: "??????????0000000000" + out: true + - name: "long_questions_right_heavy" + in: + num: "0000000000??????????" + out: true + - name: "large_max_digits_equal" + in: + num: "999999999999999999999999999999999999999999999999999999999999" + out: false + - name: "large_zero_max_imbalance" + in: + num: "000000000000000000000000000000999999999999999999999999999999" + out: true + - name: "question_and_digit_mix_left" + in: + num: "?9?8?7?60000" + out: true + - name: "question_and_digit_mix_right" + in: + num: "0000?9?8?7?6" + out: true + - name: "near_cancellation" + in: + num: "?123456789?123456789" + out: false + - name: "near_cancellation_shifted" + in: + num: "?123456789?123456788" + out: true diff --git a/tests/1501-2000/1927. sum-game/sol.cpp b/tests/1501-2000/1927. sum-game/sol.cpp new file mode 100644 index 00000000..2a9358f3 --- /dev/null +++ b/tests/1501-2000/1927. sum-game/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + bool sumGame(string num) { + int n = num.size(); + int half = n / 2; + int sumLeft = 0, sumRight = 0; + int qLeft = 0, qRight = 0; + + for (int i = 0; i < half; i++) { + if (num[i] == '?') qLeft++; + else sumLeft += num[i] - '0'; + } + + for (int i = half; i < n; i++) { + if (num[i] == '?') qRight++; + else sumRight += num[i] - '0'; + } + + return (sumLeft - sumRight) * 2 != (qRight - qLeft) * 9; + } +}; diff --git a/tests/1501-2000/1927. sum-game/sol.cs b/tests/1501-2000/1927. sum-game/sol.cs new file mode 100644 index 00000000..964d765a --- /dev/null +++ b/tests/1501-2000/1927. sum-game/sol.cs @@ -0,0 +1,20 @@ +public class Solution { + public bool SumGame(string num) { + int n = num.Length; + int half = n / 2; + int sumLeft = 0, sumRight = 0; + int qLeft = 0, qRight = 0; + + for (int i = 0; i < half; i++) { + if (num[i] == '?') qLeft++; + else sumLeft += num[i] - '0'; + } + + for (int i = half; i < n; i++) { + if (num[i] == '?') qRight++; + else sumRight += num[i] - '0'; + } + + return (sumLeft - sumRight) * 2 != (qRight - qLeft) * 9; + } +} diff --git a/tests/1501-2000/1927. sum-game/sol.dart b/tests/1501-2000/1927. sum-game/sol.dart new file mode 100644 index 00000000..37f9a7ea --- /dev/null +++ b/tests/1501-2000/1927. sum-game/sol.dart @@ -0,0 +1,26 @@ +class Solution { + bool sumGame(String num) { + int n = num.length; + int half = n ~/ 2; + int sumLeft = 0, sumRight = 0; + int qLeft = 0, qRight = 0; + + for (int i = 0; i < half; i++) { + if (num[i] == '?') { + qLeft++; + } else { + sumLeft += int.parse(num[i]); + } + } + + for (int i = half; i < n; i++) { + if (num[i] == '?') { + qRight++; + } else { + sumRight += int.parse(num[i]); + } + } + + return (sumLeft - sumRight) * 2 != (qRight - qLeft) * 9; + } +} diff --git a/tests/1501-2000/1927. sum-game/sol.go b/tests/1501-2000/1927. sum-game/sol.go new file mode 100644 index 00000000..0121f6e6 --- /dev/null +++ b/tests/1501-2000/1927. sum-game/sol.go @@ -0,0 +1,24 @@ +func sumGame(num string) bool { + n := len(num) + half := n / 2 + sumLeft, sumRight := 0, 0 + qLeft, qRight := 0, 0 + + for i := 0; i < half; i++ { + if num[i] == '?' { + qLeft++ + } else { + sumLeft += int(num[i] - '0') + } + } + + for i := half; i < n; i++ { + if num[i] == '?' { + qRight++ + } else { + sumRight += int(num[i] - '0') + } + } + + return (sumLeft - sumRight) * 2 != (qRight - qLeft) * 9 +} diff --git a/tests/1501-2000/1927. sum-game/sol.java b/tests/1501-2000/1927. sum-game/sol.java new file mode 100644 index 00000000..36b8e4c6 --- /dev/null +++ b/tests/1501-2000/1927. sum-game/sol.java @@ -0,0 +1,22 @@ +class Solution { + public boolean sumGame(String num) { + int n = num.length(); + int half = n / 2; + int sumLeft = 0, sumRight = 0; + int qLeft = 0, qRight = 0; + + for (int i = 0; i < half; i++) { + char c = num.charAt(i); + if (c == '?') qLeft++; + else sumLeft += c - '0'; + } + + for (int i = half; i < n; i++) { + char c = num.charAt(i); + if (c == '?') qRight++; + else sumRight += c - '0'; + } + + return (sumLeft - sumRight) * 2 != (qRight - qLeft) * 9; + } +} diff --git a/tests/1501-2000/1927. sum-game/sol.kt b/tests/1501-2000/1927. sum-game/sol.kt new file mode 100644 index 00000000..463e0480 --- /dev/null +++ b/tests/1501-2000/1927. sum-game/sol.kt @@ -0,0 +1,24 @@ +class Solution { + fun sumGame(num: String): Boolean { + val n = num.length + val half = n / 2 + var sumLeft = 0 + var sumRight = 0 + var qLeft = 0 + var qRight = 0 + + for (i in 0 until half) { + val c = num[i] + if (c == '?') qLeft++ + else sumLeft += c - '0' + } + + for (i in half until n) { + val c = num[i] + if (c == '?') qRight++ + else sumRight += c - '0' + } + + return (sumLeft - sumRight) * 2 != (qRight - qLeft) * 9 + } +} diff --git a/tests/1501-2000/1927. sum-game/sol.py b/tests/1501-2000/1927. sum-game/sol.py new file mode 100644 index 00000000..24e76e10 --- /dev/null +++ b/tests/1501-2000/1927. sum-game/sol.py @@ -0,0 +1,24 @@ +class Solution(object): + def sumGame(self, num): + """ + :type num: str + :rtype: bool + """ + n = len(num) + half = n // 2 + sum_left = sum_right = 0 + q_left = q_right = 0 + + for i in range(half): + if num[i] == "?": + q_left += 1 + else: + sum_left += int(num[i]) + + for i in range(half, n): + if num[i] == "?": + q_right += 1 + else: + sum_right += int(num[i]) + + return (sum_left - sum_right) * 2 != (q_right - q_left) * 9 diff --git a/tests/1501-2000/1927. sum-game/sol.py2 b/tests/1501-2000/1927. sum-game/sol.py2 new file mode 100644 index 00000000..58bdfb26 --- /dev/null +++ b/tests/1501-2000/1927. sum-game/sol.py2 @@ -0,0 +1,24 @@ +class Solution(object): + def sumGame(self, num): + """ + :type num: str + :rtype: bool + """ + n = len(num) + half = n // 2 + sum_left = sum_right = 0 + q_left = q_right = 0 + + for i in range(half): + if num[i] == '?': + q_left += 1 + else: + sum_left += int(num[i]) + + for i in range(half, n): + if num[i] == '?': + q_right += 1 + else: + sum_right += int(num[i]) + + return (sum_left - sum_right) * 2 != (q_right - q_left) * 9 diff --git a/tests/1501-2000/1927. sum-game/sol.rb b/tests/1501-2000/1927. sum-game/sol.rb new file mode 100644 index 00000000..d0ae3db6 --- /dev/null +++ b/tests/1501-2000/1927. sum-game/sol.rb @@ -0,0 +1,28 @@ +# @param {String} num +# @return {Boolean} +def sum_game(num) + n = num.length + half = n / 2 + sum_left = 0 + sum_right = 0 + q_left = 0 + q_right = 0 + + (0...half).each do |i| + if num[i] == '?' + q_left += 1 + else + sum_left += num[i].to_i + end + end + + (half...n).each do |i| + if num[i] == '?' + q_right += 1 + else + sum_right += num[i].to_i + end + end + + (sum_left - sum_right) * 2 != (q_right - q_left) * 9 +end diff --git a/tests/1501-2000/1927. sum-game/sol.rs b/tests/1501-2000/1927. sum-game/sol.rs new file mode 100644 index 00000000..0c3ab898 --- /dev/null +++ b/tests/1501-2000/1927. sum-game/sol.rs @@ -0,0 +1,29 @@ +impl Solution { + pub fn sum_game(num: String) -> bool { + let n = num.len(); + let half = n / 2; + let chars: Vec = num.chars().collect(); + let mut sum_left = 0i32; + let mut sum_right = 0i32; + let mut q_left = 0i32; + let mut q_right = 0i32; + + for i in 0..half { + if chars[i] == '?' { + q_left += 1; + } else { + sum_left += chars[i] as i32 - '0' as i32; + } + } + + for i in half..n { + if chars[i] == '?' { + q_right += 1; + } else { + sum_right += chars[i] as i32 - '0' as i32; + } + } + + (sum_left - sum_right) * 2 != (q_right - q_left) * 9 + } +} diff --git a/tests/1501-2000/1927. sum-game/sol.swift b/tests/1501-2000/1927. sum-game/sol.swift new file mode 100644 index 00000000..c25c4be8 --- /dev/null +++ b/tests/1501-2000/1927. sum-game/sol.swift @@ -0,0 +1,27 @@ +class Solution { + func sumGame(_ num: String) -> Bool { + let chars = Array(num) + let n = chars.count + let half = n / 2 + var sumLeft = 0, sumRight = 0 + var qLeft = 0, qRight = 0 + + for i in 0..>& edges, vector& passingFees) { + int n = passingFees.size(); + vector>> graph(n); + for (auto& e : edges) { + graph[e[0]].push_back({e[1], e[2]}); + graph[e[1]].push_back({e[0], e[2]}); + } + vector times(n, maxTime + 1); + vector costs(n, INT_MAX); + times[0] = 0; + costs[0] = passingFees[0]; + // priority queue: min cost, then min time + priority_queue, vector>, greater>> pq; + pq.push({passingFees[0], 0, 0}); + while (!pq.empty()) { + auto [cost, time, city] = pq.top(); pq.pop(); + if (city == n - 1) return cost; + for (auto& [nxt, t] : graph[city]) { + int nt = time + t; + if (nt > maxTime) continue; + int nc = cost + passingFees[nxt]; + if (nc < costs[nxt] || nt < times[nxt]) { + costs[nxt] = nc; + times[nxt] = nt; + pq.push({nc, nt, nxt}); + } + } + } + return -1; + } +}; diff --git a/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.cs b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.cs new file mode 100644 index 00000000..c84de2ec --- /dev/null +++ b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.cs @@ -0,0 +1,37 @@ +public class Solution { + public int MinCost(int maxTime, int[][] edges, int[] passingFees) { + int n = passingFees.Length; + var graph = new List<(int,int)>[n]; + for (int i = 0; i < n; i++) graph[i] = new List<(int,int)>(); + foreach (var e in edges) { + graph[e[0]].Add((e[1], e[2])); + graph[e[1]].Add((e[0], e[2])); + } + int[] times = new int[n]; + int[] costs = new int[n]; + Array.Fill(times, maxTime + 1); + Array.Fill(costs, int.MaxValue); + times[0] = 0; + costs[0] = passingFees[0]; + var pq = new SortedSet<(int cost, int time, int city)>(); + pq.Add((passingFees[0], 0, 0)); + while (pq.Count > 0) { + var cur = pq.Min; + pq.Remove(cur); + int cost = cur.cost, time = cur.time, city = cur.city; + if (city == n - 1) return cost; + foreach (var nb in graph[city]) { + int nxt = nb.Item1, t = nb.Item2; + int nt = time + t; + if (nt > maxTime) continue; + int nc = cost + passingFees[nxt]; + if (nc < costs[nxt] || nt < times[nxt]) { + costs[nxt] = nc; + times[nxt] = nt; + pq.Add((nc, nt, nxt)); + } + } + } + return -1; + } +} diff --git a/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.dart b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.dart new file mode 100644 index 00000000..355d0ed7 --- /dev/null +++ b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.dart @@ -0,0 +1,40 @@ +class Solution { + int minCost(int maxTime, List> edges, List passingFees) { + int n = passingFees.length; + List>> graph = List.generate(n, (_) => []); + for (var e in edges) { + graph[e[0]].add([e[1], e[2]]); + graph[e[1]].add([e[0], e[2]]); + } + List times = List.filled(n, maxTime + 1); + List costs = List.filled(n, 1 << 31 - 1); // large + times[0] = 0; + costs[0] = passingFees[0]; + // simple priority queue using list and sort + List> pq = [[passingFees[0], 0, 0]]; + while (pq.isNotEmpty) { + // find min + int minIdx = 0; + for (int i = 1; i < pq.length; i++) { + if (pq[i][0] < pq[minIdx][0] || (pq[i][0] == pq[minIdx][0] && pq[i][1] < pq[minIdx][1])) { + minIdx = i; + } + } + var cur = pq.removeAt(minIdx); + int cost = cur[0], time = cur[1], city = cur[2]; + if (city == n - 1) return cost; + for (var nb in graph[city]) { + int nxt = nb[0], t = nb[1]; + int nt = time + t; + if (nt > maxTime) continue; + int nc = cost + passingFees[nxt]; + if (nc < costs[nxt] || nt < times[nxt]) { + costs[nxt] = nc; + times[nxt] = nt; + pq.add([nc, nt, nxt]); + } + } + } + return -1; + } +} diff --git a/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.go b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.go new file mode 100644 index 00000000..c7e92d05 --- /dev/null +++ b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.go @@ -0,0 +1,54 @@ +func minCost(maxTime int, edges [][]int, passingFees []int) int { + n := len(passingFees) + graph := make([][]int, n) + for i := range graph { + graph[i] = make([]int, 0) + } + // adjacency list: store pairs as [next, time]? Need better structure + // using map from node to slice of [next, time] + adj := make([][][2]int, n) + for _, e := range edges { + u, v, t := e[0], e[1], e[2] + adj[u] = append(adj[u], [2]int{v, t}) + adj[v] = append(adj[v], [2]int{u, t}) + } + times := make([]int, n) + costs := make([]int, n) + for i := range times { + times[i] = maxTime + 1 + costs[i] = int(^uint(0) >> 1) // max int + } + times[0] = 0 + costs[0] = passingFees[0] + // priority queue as slice, need custom heap, but for simplicity use sort each time? + // Given constraints small, we can use simple slice and sort + type item struct {cost, time, city int} + pq := []item{{passingFees[0], 0, 0}} + for len(pq) > 0 { + // find min + minIdx := 0 + for i := 1; i < len(pq); i++ { + if pq[i].cost < pq[minIdx].cost || (pq[i].cost == pq[minIdx].cost && pq[i].time < pq[minIdx].time) { + minIdx = i + } + } + cur := pq[minIdx] + pq = append(pq[:minIdx], pq[minIdx+1:]...) + cost, time, city := cur.cost, cur.time, cur.city + if city == n-1 { + return cost + } + for _, nb := range adj[city] { + nxt, t := nb[0], nb[1] + nt := time + t + if nt > maxTime { continue } + nc := cost + passingFees[nxt] + if nc < costs[nxt] || nt < times[nxt] { + costs[nxt] = nc + times[nxt] = nt + pq = append(pq, item{nc, nt, nxt}) + } + } + } + return -1 +} diff --git a/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.java b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.java new file mode 100644 index 00000000..46c1ec54 --- /dev/null +++ b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.java @@ -0,0 +1,37 @@ +@SuppressWarnings("unchecked") +class Solution { + public int minCost(int maxTime, int[][] edges, int[] passingFees) { + int n = passingFees.length; + List[] graph = new ArrayList[n]; + for (int i = 0; i < n; i++) graph[i] = new ArrayList<>(); + for (int[] e : edges) { + graph[e[0]].add(new int[]{e[1], e[2]}); + graph[e[1]].add(new int[]{e[0], e[2]}); + } + int[] times = new int[n]; + int[] costs = new int[n]; + Arrays.fill(times, maxTime + 1); + Arrays.fill(costs, Integer.MAX_VALUE); + times[0] = 0; + costs[0] = passingFees[0]; + PriorityQueue pq = new PriorityQueue<>((a,b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]); + pq.offer(new int[]{passingFees[0], 0, 0}); + while (!pq.isEmpty()) { + int[] cur = pq.poll(); + int cost = cur[0], time = cur[1], city = cur[2]; + if (city == n - 1) return cost; + for (int[] nb : graph[city]) { + int nxt = nb[0], t = nb[1]; + int nt = time + t; + if (nt > maxTime) continue; + int nc = cost + passingFees[nxt]; + if (nc < costs[nxt] || nt < times[nxt]) { + costs[nxt] = nc; + times[nxt] = nt; + pq.offer(new int[]{nc, nt, nxt}); + } + } + } + return -1; + } +} diff --git a/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.kt b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.kt new file mode 100644 index 00000000..4e535c8d --- /dev/null +++ b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.kt @@ -0,0 +1,31 @@ +class Solution { + fun minCost(maxTime: Int, edges: Array, passingFees: IntArray): Int { + val n = passingFees.size + val graph = Array(n) { mutableListOf>() } + for (e in edges) { + graph[e[0]].add(e[1] to e[2]) + graph[e[1]].add(e[0] to e[2]) + } + val times = IntArray(n) { maxTime + 1 } + val costs = IntArray(n) { Int.MAX_VALUE } + times[0] = 0 + costs[0] = passingFees[0] + val pq = java.util.PriorityQueue>(compareBy({ it.first }, { it.second })) + pq.add(Triple(passingFees[0], 0, 0)) + while (pq.isNotEmpty()) { + val (cost, time, city) = pq.poll() + if (city == n - 1) return cost + for ((nxt, t) in graph[city]) { + val nt = time + t + if (nt > maxTime) continue + val nc = cost + passingFees[nxt] + if (nc < costs[nxt] || nt < times[nxt]) { + costs[nxt] = nc + times[nxt] = nt + pq.add(Triple(nc, nt, nxt)) + } + } + } + return -1 + } +} diff --git a/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.py b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.py new file mode 100644 index 00000000..9598a7e5 --- /dev/null +++ b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.py @@ -0,0 +1,60 @@ +import heapq +from collections import defaultdict +from typing import List + + +class Solution: + def minCost( + self, maxTime: int, edges: List[List[int]], passingFees: List[int] + ) -> int: + # Number of cities + n = len(passingFees) + + # Create a graph to store cities and the time required to travel between them + graph = defaultdict(list) + + # Fill the graph with the roads (edges) + for u, v, time in edges: + graph[u].append((v, time)) + graph[v].append((u, time)) + + # Initialize cost array: costs[i] will hold the minimum cost to reach city i + costs = [float("inf")] * n + # Initialize time array: times[i] will hold the minimum time to reach city i + times = [maxTime + 1] * n + # Starting at city 0 with its passing fee + times[0] = 0 + costs[0] = passingFees[0] + + # Min-heap (priority queue) to always expand the node with the least cost and time + queue = [ + (passingFees[0], 0, 0) + ] # (current total cost, current time, current city) + + while queue: + # Pop the city with the smallest cost and time from the priority queue + curr_cost, curr_time, curr_city = heapq.heappop(queue) + + # If we have reached the destination city (city n - 1), return the cost + if curr_city == n - 1: + return curr_cost + + # Explore all the neighboring cities (neighbors and the time to reach them) + for next_city, travel_time in graph[curr_city]: + # If traveling to the next city exceeds the maxTime, skip this path + if curr_time + travel_time > maxTime: + continue + + # Calculate the new time and cost after moving to the next city + new_time = curr_time + travel_time + new_cost = curr_cost + passingFees[next_city] + + # If we find a cheaper way to reach next_city, update the cost and time + if new_cost < costs[next_city] or new_time < times[next_city]: + costs[next_city] = new_cost + times[next_city] = new_time + # Push the updated city state into the priority queue + heapq.heappush(queue, (new_cost, new_time, next_city)) + + # If we cannot reach the destination city within the allowed time, return -1 + return -1 diff --git a/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.py2 b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.py2 new file mode 100644 index 00000000..bc79803b --- /dev/null +++ b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.py2 @@ -0,0 +1,33 @@ +class Solution(object): + def minCost(self, maxTime, edges, passingFees): + """ + :type maxTime: int + :type edges: List[List[int]] + :type passingFees: List[int] + :rtype: int + """ + import heapq + n = len(passingFees) + graph = [[] for _ in range(n)] + for u, v, t in edges: + graph[u].append((v, t)) + graph[v].append((u, t)) + times = [maxTime + 1] * n + costs = [float('inf')] * n + times[0] = 0 + costs[0] = passingFees[0] + pq = [(passingFees[0], 0, 0)] + while pq: + cost, time, city = heapq.heappop(pq) + if city == n - 1: + return cost + for nxt, t in graph[city]: + nt = time + t + if nt > maxTime: + continue + nc = cost + passingFees[nxt] + if nc < costs[nxt] or nt < times[nxt]: + costs[nxt] = nc + times[nxt] = nt + heapq.heappush(pq, (nc, nt, nxt)) + return -1 diff --git a/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.rb b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.rb new file mode 100644 index 00000000..51fd807e --- /dev/null +++ b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.rb @@ -0,0 +1,31 @@ +def min_cost(max_time, edges, passing_fees) + n = passing_fees.size + graph = Array.new(n) { [] } + edges.each do |u, v, t| + graph[u] << [v, t] + graph[v] << [u, t] + end + times = Array.new(n, max_time + 1) + costs = Array.new(n, Float::INFINITY) + times[0] = 0 + costs[0] = passing_fees[0] + pq = [[passing_fees[0], 0, 0]] + until pq.empty? + cost, time, city = pq.shift + if city == n - 1 + return cost + end + graph[city].each do |nxt, t| + nt = time + t + next if nt > max_time + nc = cost + passing_fees[nxt] + if nc < costs[nxt] or nt < times[nxt] + costs[nxt] = nc + times[nxt] = nt + pq << [nc, nt, nxt] + pq.sort_by! { |arr| [arr[0], arr[1]] } + end + end + end + -1 +end diff --git a/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.rs b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.rs new file mode 100644 index 00000000..c9e81416 --- /dev/null +++ b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.rs @@ -0,0 +1,48 @@ +impl Solution { + pub fn min_cost(max_time: i32, edges: Vec>, passing_fees: Vec) -> i32 { + let n = passing_fees.len(); + let mut graph = vec![Vec::new(); n]; + for e in &edges { + let u = e[0] as usize; + let v = e[1] as usize; + let t = e[2]; + graph[u].push((v, t)); + graph[v].push((u, t)); + } + let mut times = vec![max_time + 1; n]; + let mut costs = vec![i32::MAX; n]; + times[0] = 0; + costs[0] = passing_fees[0]; + // Use BinaryHeap with custom ordering (cost, time) + use std::collections::BinaryHeap; + use std::cmp::Reverse; + #[derive(Eq, PartialEq)] + struct Item { cost: i32, time: i32, city: usize } + impl Ord for Item { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + (other.cost, other.time).cmp(&(self.cost, self.time)) + } + } + impl PartialOrd for Item { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } + } + let mut pq = BinaryHeap::new(); + pq.push(Item { cost: passing_fees[0], time: 0, city: 0 }); + while let Some(Item { cost, time, city }) = pq.pop() { + if city == n - 1 { return cost; } + for &(nxt, t) in &graph[city] { + let nt = time + t; + if nt > max_time { continue; } + let nc = cost + passing_fees[nxt]; + if nc < costs[nxt] || nt < times[nxt] { + costs[nxt] = nc; + times[nxt] = nt; + pq.push(Item { cost: nc, time: nt, city: nxt }); + } + } + } + -1 + } +} diff --git a/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.swift b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.swift new file mode 100644 index 00000000..f1a1daa0 --- /dev/null +++ b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.swift @@ -0,0 +1,38 @@ +class Solution { + func minCost(_ maxTime: Int, _ edges: [[Int]], _ passingFees: [Int]) -> Int { + let n = passingFees.count + var graph = Array(repeating: [(Int, Int)](), count: n) + for e in edges { + graph[e[0]].append((e[1], e[2])) + graph[e[1]].append((e[0], e[2])) + } + var times = Array(repeating: maxTime + 1, count: n) + var costs = Array(repeating: Int.max, count: n) + times[0] = 0 + costs[0] = passingFees[0] + var pq = [(passingFees[0], 0, 0)] + while !pq.isEmpty { + // find min + var minIdx = 0 + for i in 1.. maxTime { continue } + let nc = cost + passingFees[nxt] + if nc < costs[nxt] || nt < times[nxt] { + costs[nxt] = nc + times[nxt] = nt + pq.append((nc, nt, nxt)) + } + } + } + return -1 + } +} diff --git a/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.ts b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.ts new file mode 100644 index 00000000..f36cdba8 --- /dev/null +++ b/tests/1501-2000/1928. minimum-cost-to-reach-destination-in-time/sol.ts @@ -0,0 +1,46 @@ +function minCost( + maxTime: number, + edges: number[][], + passingFees: number[], +): number { + const n = passingFees.length; + const graph: Array> = Array.from( + { length: n }, + () => [], + ); + for (const [u, v, t] of edges) { + graph[u].push([v, t]); + graph[v].push([u, t]); + } + const times = new Array(n).fill(maxTime + 1); + const costs = new Array(n).fill(Infinity); + times[0] = 0; + costs[0] = passingFees[0]; + // Use simple array as priority queue (sort each time) + const pq: Array<[number, number, number]> = [[passingFees[0], 0, 0]]; + while (pq.length) { + // find min + let minIdx = 0; + for (let i = 1; i < pq.length; i++) { + if ( + pq[i][0] < pq[minIdx][0] || + (pq[i][0] === pq[minIdx][0] && pq[i][1] < pq[minIdx][1]) + ) { + minIdx = i; + } + } + const [cost, time, city] = pq.splice(minIdx, 1)[0]; + if (city === n - 1) return cost; + for (const [nxt, t] of graph[city]) { + const nt = time + t; + if (nt > maxTime) continue; + const nc = cost + passingFees[nxt]; + if (nc < costs[nxt] || nt < times[nxt]) { + costs[nxt] = nc; + times[nxt] = nt; + pq.push([nc, nt, nxt]); + } + } + } + return -1; +} diff --git a/tests/1501-2000/1929. concatenation-of-array/manifest.yaml b/tests/1501-2000/1929. concatenation-of-array/manifest.yaml new file mode 100644 index 00000000..f833ccc6 --- /dev/null +++ b/tests/1501-2000/1929. concatenation-of-array/manifest.yaml @@ -0,0 +1,886 @@ +entry: + id: 1929 + title: "concatenation-of-array" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().getConcatenation({nums})" + rust: "Solution::get_concatenation({nums})" + python3: "Solution().getConcatenation({nums})" + python2: "Solution().getConcatenation({nums})" + ruby: "get_concatenation({nums})" + java: "new Solution().getConcatenation({nums})" + csharp: "new Solution().GetConcatenation({nums})" + kotlin: "Solution().getConcatenation({nums})" + go: "getConcatenation({nums})" + dart: "Solution().getConcatenation({nums})" + swift: "Solution().getConcatenation({nums})" + typescript: "getConcatenation({nums})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().getConcatenation(nums, {result})" + checker: | + class Checker: + def getConcatenation(self, nums, result): + if not isinstance(nums, list) or not isinstance(result, list): + return False + if len(nums) < 1 or len(nums) > 1000: + return False + if any(not isinstance(x, int) or isinstance(x, bool) or x < 1 or x > 1000 for x in nums): + return False + return result == nums + nums + +seed: 1929 + +tests: + - name: "example_one" + in: + nums: [1, 2, 1] + out: [1, 2, 1, 1, 2, 1] + - name: "example_two" + in: + nums: [1, 3, 2, 1] + out: [1, 3, 2, 1, 1, 3, 2, 1] + - name: "single_minimum" + in: + nums: [1] + out: [1, 1] + - name: "single_maximum" + in: + nums: [1000] + out: [1000, 1000] + - name: "two_distinct" + in: + nums: [1, 1000] + out: [1, 1000, 1, 1000] + - name: "two_equal" + in: + nums: [7, 7] + out: [7, 7, 7, 7] + - name: "ascending_small" + in: + nums: [1, 2, 3, 4, 5] + out: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] + - name: "descending_small" + in: + nums: [5, 4, 3, 2, 1] + out: [5, 4, 3, 2, 1, 5, 4, 3, 2, 1] + - name: "all_minimum" + in: + nums: [1, 1, 1, 1, 1, 1] + out: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: "all_maximum" + in: + nums: [1000, 1000, 1000, 1000] + out: [1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000] + - name: "alternating_extremes" + in: + nums: [1, 1000, 1, 1000, 1] + out: [1, 1000, 1, 1000, 1, 1, 1000, 1, 1000, 1] + - name: "repeated_cycle" + in: + nums: [2, 4, 2, 4, 2, 4, 2] + out: [2, 4, 2, 4, 2, 4, 2, 2, 4, 2, 4, 2, 4, 2] + - name: "mixed_small" + in: + nums: [9, 1, 8, 2, 7, 3, 6, 4, 5] + out: [9, 1, 8, 2, 7, 3, 6, 4, 5, 9, 1, 8, 2, 7, 3, 6, 4, 5] + - name: "powers_and_gaps" + in: + nums: [1, 2, 4, 8, 16, 32, 64, 128] + out: [1, 2, 4, 8, 16, 32, 64, 128, 1, 2, 4, 8, 16, 32, 64, 128] + - name: "large_values_mixed" + in: + nums: [999, 1000, 998, 997, 1, 500, 1000, 2, 999, 3] + out: + [ + 999, + 1000, + 998, + 997, + 1, + 500, + 1000, + 2, + 999, + 3, + 999, + 1000, + 998, + 997, + 1, + 500, + 1000, + 2, + 999, + 3, + ] + - name: "length_eleven" + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + - name: "length_twelve_duplicates" + in: + nums: [12, 12, 3, 3, 12, 3, 12, 3, 12, 3, 12, 3] + out: + [ + 12, + 12, + 3, + 3, + 12, + 3, + 12, + 3, + 12, + 3, + 12, + 3, + 12, + 12, + 3, + 3, + 12, + 3, + 12, + 3, + 12, + 3, + 12, + 3, + ] + - name: "length_fifteen" + in: + nums: [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + out: + [ + 15, + 14, + 13, + 12, + 11, + 10, + 9, + 8, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + 15, + 14, + 13, + 12, + 11, + 10, + 9, + 8, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + ] + - name: "length_twenty" + in: + nums: + [ + 1, + 1000, + 2, + 999, + 3, + 998, + 4, + 997, + 5, + 996, + 6, + 995, + 7, + 994, + 8, + 993, + 9, + 992, + 10, + 991, + ] + out: + [ + 1, + 1000, + 2, + 999, + 3, + 998, + 4, + 997, + 5, + 996, + 6, + 995, + 7, + 994, + 8, + 993, + 9, + 992, + 10, + 991, + 1, + 1000, + 2, + 999, + 3, + 998, + 4, + 997, + 5, + 996, + 6, + 995, + 7, + 994, + 8, + 993, + 9, + 992, + 10, + 991, + ] + - name: "length_twenty_five" + in: + nums: + [ + 25, + 1, + 25, + 2, + 25, + 3, + 25, + 4, + 25, + 5, + 25, + 6, + 25, + 7, + 25, + 8, + 25, + 9, + 25, + 10, + 25, + 11, + 25, + 12, + 25, + ] + out: + [ + 25, + 1, + 25, + 2, + 25, + 3, + 25, + 4, + 25, + 5, + 25, + 6, + 25, + 7, + 25, + 8, + 25, + 9, + 25, + 10, + 25, + 11, + 25, + 12, + 25, + 25, + 1, + 25, + 2, + 25, + 3, + 25, + 4, + 25, + 5, + 25, + 6, + 25, + 7, + 25, + 8, + 25, + 9, + 25, + 10, + 25, + 11, + 25, + 12, + 25, + ] + - name: "length_thirty_one" + in: + nums: + [ + 1, + 4, + 9, + 16, + 25, + 36, + 49, + 64, + 81, + 100, + 121, + 144, + 169, + 196, + 225, + 256, + 289, + 324, + 361, + 400, + 441, + 484, + 529, + 576, + 625, + 676, + 729, + 784, + 841, + 900, + 961, + ] + out: + [ + 1, + 4, + 9, + 16, + 25, + 36, + 49, + 64, + 81, + 100, + 121, + 144, + 169, + 196, + 225, + 256, + 289, + 324, + 361, + 400, + 441, + 484, + 529, + 576, + 625, + 676, + 729, + 784, + 841, + 900, + 961, + 1, + 4, + 9, + 16, + 25, + 36, + 49, + 64, + 81, + 100, + 121, + 144, + 169, + 196, + 225, + 256, + 289, + 324, + 361, + 400, + 441, + 484, + 529, + 576, + 625, + 676, + 729, + 784, + 841, + 900, + 961, + ] + - name: "length_forty_mixed" + in: + nums: + [ + 1, + 1000, + 2, + 999, + 3, + 998, + 4, + 997, + 5, + 996, + 6, + 995, + 7, + 994, + 8, + 993, + 9, + 992, + 10, + 991, + 11, + 990, + 12, + 989, + 13, + 988, + 14, + 987, + 15, + 986, + 16, + 985, + 17, + 984, + 18, + 983, + 19, + 982, + 20, + 981, + ] + out: + [ + 1, + 1000, + 2, + 999, + 3, + 998, + 4, + 997, + 5, + 996, + 6, + 995, + 7, + 994, + 8, + 993, + 9, + 992, + 10, + 991, + 11, + 990, + 12, + 989, + 13, + 988, + 14, + 987, + 15, + 986, + 16, + 985, + 17, + 984, + 18, + 983, + 19, + 982, + 20, + 981, + 1, + 1000, + 2, + 999, + 3, + 998, + 4, + 997, + 5, + 996, + 6, + 995, + 7, + 994, + 8, + 993, + 9, + 992, + 10, + 991, + 11, + 990, + 12, + 989, + 13, + 988, + 14, + 987, + 15, + 986, + 16, + 985, + 17, + 984, + 18, + 983, + 19, + 982, + 20, + 981, + ] + - name: "three_minimum" + in: + nums: [1, 1, 1] + out: [1, 1, 1, 1, 1, 1] + - name: "three_maximum" + in: + nums: [1000, 1000, 1000] + out: [1000, 1000, 1000, 1000, 1000, 1000] + - name: "alternating_short" + in: + nums: [1, 1000, 2, 999, 3, 998] + out: [1, 1000, 2, 999, 3, 998, 1, 1000, 2, 999, 3, 998] + - name: "palindromic_values" + in: + nums: [4, 8, 15, 16, 23, 42, 23, 16, 15, 8, 4] + out: + [ + 4, + 8, + 15, + 16, + 23, + 42, + 23, + 16, + 15, + 8, + 4, + 4, + 8, + 15, + 16, + 23, + 42, + 23, + 16, + 15, + 8, + 4, + ] + - name: "zeros_not_allowed_but_one_is" + in: + nums: [1, 10, 100, 1000] + out: [1, 10, 100, 1000, 1, 10, 100, 1000] + - name: "prime_values" + in: + nums: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + out: + [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + - name: "uniform_middle" + in: + nums: [500, 500, 500, 500, 500, 500, 500, 500, 500] + out: + [ + 500, + 500, + 500, + 500, + 500, + 500, + 500, + 500, + 500, + 500, + 500, + 500, + 500, + 500, + 500, + 500, + 500, + 500, + ] + - name: "length_fifty" + in: + nums: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + ] + out: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + ] + - name: "generated_small" + seed: 192901 + in: + nums: + gen: "array" + len: + gen: "int" + min: 1 + max: 20 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_medium" + seed: 192902 + in: + nums: + gen: "array" + len: + gen: "int" + min: 50 + max: 200 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_boundary_values" + seed: 192903 + in: + nums: + gen: "array" + len: + gen: "int" + min: 100 + max: 300 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_large" + seed: 192904 + in: + nums: + gen: "array" + len: + gen: "int" + min: 800 + max: 1000 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_maximum" + seed: 192905 + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1929. concatenation-of-array/sol.cpp b/tests/1501-2000/1929. concatenation-of-array/sol.cpp new file mode 100644 index 00000000..956dc847 --- /dev/null +++ b/tests/1501-2000/1929. concatenation-of-array/sol.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + vector getConcatenation(vector& nums) { + int n = nums.size(); + vector ans(2 * n, 0); + for (int i = 0; i < 2 * n; i++) { + ans[i] = nums[i % n]; + } + return ans; + } +}; diff --git a/tests/1501-2000/1929. concatenation-of-array/sol.cs b/tests/1501-2000/1929. concatenation-of-array/sol.cs new file mode 100644 index 00000000..e845d9ec --- /dev/null +++ b/tests/1501-2000/1929. concatenation-of-array/sol.cs @@ -0,0 +1,10 @@ +public class Solution { + public int[] GetConcatenation(int[] nums) { + int n = nums.Length; + int[] ans = new int[2 * n]; + for (int i = 0; i < 2 * n; i++) { + ans[i] = nums[i % n]; + } + return ans; + } +} diff --git a/tests/1501-2000/1929. concatenation-of-array/sol.dart b/tests/1501-2000/1929. concatenation-of-array/sol.dart new file mode 100644 index 00000000..e4b67997 --- /dev/null +++ b/tests/1501-2000/1929. concatenation-of-array/sol.dart @@ -0,0 +1,10 @@ +class Solution { + List getConcatenation(List nums) { + int n = nums.length; + List ans = List.filled(2 * n, 0); + for (int i = 0; i < 2 * n; i++) { + ans[i] = nums[i % n]; + } + return ans; + } +} diff --git a/tests/1501-2000/1929. concatenation-of-array/sol.go b/tests/1501-2000/1929. concatenation-of-array/sol.go new file mode 100644 index 00000000..7c09f333 --- /dev/null +++ b/tests/1501-2000/1929. concatenation-of-array/sol.go @@ -0,0 +1,8 @@ +func getConcatenation(nums []int) []int { + n := len(nums) + ans := make([]int, 2*n) + for i := 0; i < 2*n; i++ { + ans[i] = nums[i%n] + } + return ans +} diff --git a/tests/1501-2000/1929. concatenation-of-array/sol.java b/tests/1501-2000/1929. concatenation-of-array/sol.java new file mode 100644 index 00000000..222e63d3 --- /dev/null +++ b/tests/1501-2000/1929. concatenation-of-array/sol.java @@ -0,0 +1,10 @@ +class Solution { + public int[] getConcatenation(int[] nums) { + int n = nums.length; + int[] ans = new int[2 * n]; + for (int i = 0; i < 2 * n; i++) { + ans[i] = nums[i % n]; + } + return ans; + } +} diff --git a/tests/1501-2000/1929. concatenation-of-array/sol.kt b/tests/1501-2000/1929. concatenation-of-array/sol.kt new file mode 100644 index 00000000..02d2cfa4 --- /dev/null +++ b/tests/1501-2000/1929. concatenation-of-array/sol.kt @@ -0,0 +1,10 @@ +class Solution { + fun getConcatenation(nums: IntArray): IntArray { + val n = nums.size + val ans = IntArray(2 * n) + for (i in 0 until 2 * n) { + ans[i] = nums[i % n] + } + return ans + } +} diff --git a/tests/1501-2000/1929. concatenation-of-array/sol.py b/tests/1501-2000/1929. concatenation-of-array/sol.py new file mode 100644 index 00000000..43c18098 --- /dev/null +++ b/tests/1501-2000/1929. concatenation-of-array/sol.py @@ -0,0 +1,10 @@ +class Solution: + def getConcatenation(self, nums): + + n = len(nums) + ans = [0] * (2 * n) + + for i in range(2 * n): + ans[i] = nums[i % n] + + return ans diff --git a/tests/1501-2000/1929. concatenation-of-array/sol.py2 b/tests/1501-2000/1929. concatenation-of-array/sol.py2 new file mode 100644 index 00000000..f0518d4f --- /dev/null +++ b/tests/1501-2000/1929. concatenation-of-array/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def getConcatenation(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + n = len(nums) + ans = [0] * (2 * n) + for i in range(2 * n): + ans[i] = nums[i % n] + return ans diff --git a/tests/1501-2000/1929. concatenation-of-array/sol.rb b/tests/1501-2000/1929. concatenation-of-array/sol.rb new file mode 100644 index 00000000..9473d544 --- /dev/null +++ b/tests/1501-2000/1929. concatenation-of-array/sol.rb @@ -0,0 +1,10 @@ +# @param {Integer[]} nums +# @return {Integer[]} +def get_concatenation(nums) + n = nums.length + ans = Array.new(2 * n, 0) + for i in 0...(2 * n) + ans[i] = nums[i % n] + end + ans +end diff --git a/tests/1501-2000/1929. concatenation-of-array/sol.rs b/tests/1501-2000/1929. concatenation-of-array/sol.rs new file mode 100644 index 00000000..c6c04900 --- /dev/null +++ b/tests/1501-2000/1929. concatenation-of-array/sol.rs @@ -0,0 +1,10 @@ +impl Solution { + pub fn get_concatenation(nums: Vec) -> Vec { + let n = nums.len(); + let mut ans = vec![0; 2 * n]; + for i in 0..(2 * n) { + ans[i] = nums[i % n]; + } + ans + } +} diff --git a/tests/1501-2000/1929. concatenation-of-array/sol.swift b/tests/1501-2000/1929. concatenation-of-array/sol.swift new file mode 100644 index 00000000..867fba8e --- /dev/null +++ b/tests/1501-2000/1929. concatenation-of-array/sol.swift @@ -0,0 +1,10 @@ +class Solution { + func getConcatenation(_ nums: [Int]) -> [Int] { + let n = nums.count + var ans = [Int](repeating: 0, count: 2 * n) + for i in 0..<(2 * n) { + ans[i] = nums[i % n] + } + return ans + } +} diff --git a/tests/1501-2000/1929. concatenation-of-array/sol.ts b/tests/1501-2000/1929. concatenation-of-array/sol.ts new file mode 100644 index 00000000..01fe5a76 --- /dev/null +++ b/tests/1501-2000/1929. concatenation-of-array/sol.ts @@ -0,0 +1,8 @@ +function getConcatenation(nums: number[]): number[] { + const n = nums.length; + const ans: number[] = new Array(2 * n).fill(0); + for (let i = 0; i < 2 * n; i++) { + ans[i] = nums[i % n]; + } + return ans; +} diff --git a/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/manifest.yaml b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/manifest.yaml new file mode 100644 index 00000000..fb71f491 --- /dev/null +++ b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/manifest.yaml @@ -0,0 +1,305 @@ +entry: + id: 1930 + title: "unique-length-3-palindromic-subsequences" + params: + s: + type: string + call: + cpp: "Solution().countPalindromicSubsequence({s})" + rust: "Solution::count_palindromic_subsequence({s})" + python3: "Solution().countPalindromicSubsequence({s})" + python2: "Solution().countPalindromicSubsequence({s})" + ruby: "count_palindromic_subsequence({s})" + java: "new Solution().countPalindromicSubsequence({s})" + csharp: "new Solution().CountPalindromicSubsequence({s})" + kotlin: "Solution().countPalindromicSubsequence({s})" + go: "countPalindromicSubsequence({s})" + dart: "Solution().countPalindromicSubsequence({s})" + swift: "Solution().countPalindromicSubsequence({s})" + typescript: "countPalindromicSubsequence({s})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().countPalindromicSubsequence(s, {result})" + checker: | + class Checker: + def countPalindromicSubsequence(self, s, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + first = {} + last = {} + for i, ch in enumerate(s): + first.setdefault(ch, i) + last[ch] = i + expected = 0 + for ch, left in first.items(): + right = last[ch] + if right - left > 1: + expected += len(set(s[left + 1:right])) + return result == expected + +seed: 1930 + +tests: + - name: example-one + in: + s: "aabca" + out: 3 + judge: + type: "exact" + - name: example-two + in: + s: "adc" + out: 0 + judge: + type: "exact" + - name: example-three + in: + s: "bbcbaba" + out: 4 + judge: + type: "exact" + - name: minimum-all-equal + in: + s: "aaa" + out: 1 + judge: + type: "exact" + - name: minimum-distinct + in: + s: "abc" + out: 0 + judge: + type: "exact" + - name: four-equal + in: + s: "aaaa" + out: 1 + judge: + type: "exact" + - name: one-pair-at-end + in: + s: "aba" + out: 1 + judge: + type: "exact" + - name: no-middle-character + in: + s: "abb" + out: 0 + judge: + type: "exact" + - name: separated-pair + in: + s: "abca" + out: 2 + judge: + type: "exact" + - name: nested-palindromes + in: + s: "abacaba" + out: 5 + judge: + type: "exact" + - name: all-alphabet-once + in: + s: "abcdefghijklmnopqrstuvwxyz" + out: 0 + judge: + type: "exact" + - name: long-single-letter + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: 1 + judge: + type: "exact" + - name: repeated-endpoints + in: + s: "aabaa" + out: 2 + judge: + type: "exact" + - name: reverse-blocks + in: + s: "abccba" + out: 3 + judge: + type: "exact" + - name: two-copies-alphabet + in: + s: "abcabc" + out: 6 + judge: + type: "exact" + - name: one-letter-alphabet + in: + s: "zzzz" + out: 1 + judge: + type: "exact" + - name: partial-middle + in: + s: "abac" + out: 1 + judge: + type: "exact" + - name: disjoint-pairs + in: + s: "aabbcc" + out: 0 + judge: + type: "exact" + - name: two-alphabet-runs + in: + s: "abcdeabcde" + out: 20 + judge: + type: "exact" + - name: adjacent-pairs-only + in: + s: "aabbccddeeff" + out: 0 + judge: + type: "exact" + - name: twenty-five-distinct-with-repeat + in: + s: "abcdefghijklmnopqrstuvwxyza" + out: 25 + judge: + type: "exact" + - name: three-runs + in: + s: "aaabbbccc" + out: 3 + judge: + type: "exact" + - name: alternating-two + in: + s: "ababababab" + out: 4 + judge: + type: "exact" + - name: alternating-three + in: + s: "abcabcabcabcabc" + out: 9 + judge: + type: "exact" + - name: repeated-end-after-middle + in: + s: "aabbccaa" + out: 3 + judge: + type: "exact" + - name: symmetric-five + in: + s: "xayax" + out: 3 + judge: + type: "exact" + - name: distinct-middle-window + in: + s: "mnopqmn" + out: 8 + judge: + type: "exact" + - name: interleaved-six + in: + s: "azbycxa" + out: 5 + judge: + type: "exact" + - name: full-palindrome + in: + s: "abcdedcba" + out: 10 + judge: + type: "exact" + - name: duplicate-three-runs + in: + s: "aaabbbccc" + out: 3 + judge: + type: "exact" + - name: mirrored-six + in: + s: "aabbaa" + out: 2 + judge: + type: "exact" + - name: offset-mirror + in: + s: "abccbaab" + out: 6 + judge: + type: "exact" + - name: all-letters-twice + in: + s: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" + out: 650 + judge: + type: "exact" + - name: dense-four-symbols + in: + s: "abcdabcdabcdabcd" + out: 16 + judge: + type: "exact" + - name: sparse-endpoints + in: + s: "aabcdefghijklmnopqrstuvwxyza" + out: 26 + judge: + type: "exact" + - name: generator-random-small + in: + s: + gen: "str" + len: 100 + alphabet: "abcde" + judge: + type: "exact" + seed: 193001 + - name: generator-random-medium + in: + s: + gen: "str" + len: 1000 + alphabet: "abcdefgh" + judge: + type: "exact" + seed: 193002 + - name: generator-full-alphabet + in: + s: + gen: "str" + len: 10000 + alphabet: "abcdefghijklmnopqrstuvwxyz" + judge: + type: "exact" + seed: 193003 + - name: generator-large-binary + in: + s: + gen: "str" + len: 50000 + alphabet: "ab" + judge: + type: "exact" + seed: 193004 + - name: generator-maximum-alphabet + in: + s: + gen: "str" + len: 100000 + alphabet: "abcdefghijklmnopqrstuvwxyz" + judge: + type: "exact" + seed: 193005 diff --git a/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.cpp b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.cpp new file mode 100644 index 00000000..b26bad42 --- /dev/null +++ b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int countPalindromicSubsequence(string s) { + int n = s.length(); + vector first(26, -1); + vector last(26, -1); + + for (int i = 0; i < n; i++) { + int c = s[i] - 'a'; + if (first[c] == -1) first[c] = i; + last[c] = i; + } + + int ans = 0; + for (int c = 0; c < 26; c++) { + if (first[c] != -1 && last[c] - first[c] > 1) { + int mask = 0; + for (int i = first[c] + 1; i < last[c]; i++) { + mask |= 1 << (s[i] - 'a'); + } + ans += __builtin_popcount(mask); + } + } + return ans; + } +}; diff --git a/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.cs b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.cs new file mode 100644 index 00000000..d1853c3f --- /dev/null +++ b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.cs @@ -0,0 +1,35 @@ +public class Solution { + public int CountPalindromicSubsequence(string s) { + int n = s.Length; + int[] first = new int[26]; + int[] last = new int[26]; + for (int i = 0; i < 26; i++) { + first[i] = -1; + last[i] = -1; + } + + for (int i = 0; i < n; i++) { + int c = s[i] - 'a'; + if (first[c] == -1) first[c] = i; + last[c] = i; + } + + int ans = 0; + for (int c = 0; c < 26; c++) { + if (first[c] != -1 && last[c] - first[c] > 1) { + int mask = 0; + for (int i = first[c] + 1; i < last[c]; i++) { + mask |= 1 << (s[i] - 'a'); + } + int bits = 0; + uint value = (uint)mask; + while (value != 0) { + value &= value - 1; + bits++; + } + ans += bits; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.dart b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.dart new file mode 100644 index 00000000..8ee02846 --- /dev/null +++ b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.dart @@ -0,0 +1,25 @@ +class Solution { + int countPalindromicSubsequence(String s) { + int n = s.length; + List first = List.filled(26, -1); + List last = List.filled(26, -1); + + for (int i = 0; i < n; i++) { + int c = s.codeUnitAt(i) - 97; + if (first[c] == -1) first[c] = i; + last[c] = i; + } + + int ans = 0; + for (int c = 0; c < 26; c++) { + if (first[c] != -1 && last[c] - first[c] > 1) { + int mask = 0; + for (int i = first[c] + 1; i < last[c]; i++) { + mask |= 1 << (s.codeUnitAt(i) - 97); + } + ans += mask.toRadixString(2).split('1').length - 1; + } + } + return ans; + } +} diff --git a/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.go b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.go new file mode 100644 index 00000000..77b82f6e --- /dev/null +++ b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.go @@ -0,0 +1,29 @@ +func countPalindromicSubsequence(s string) int { + n := len(s) + first := make([]int, 26) + last := make([]int, 26) + for i := 0; i < 26; i++ { + first[i] = -1 + last[i] = -1 + } + + for i := 0; i < n; i++ { + c := int(s[i] - 'a') + if first[c] == -1 { + first[c] = i + } + last[c] = i + } + + ans := 0 + for c := 0; c < 26; c++ { + if first[c] != -1 && last[c]-first[c] > 1 { + mask := 0 + for i := first[c] + 1; i < last[c]; i++ { + mask |= 1 << int(s[i]-'a') + } + ans += bits.OnesCount(uint(mask)) + } + } + return ans +} diff --git a/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.java b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.java new file mode 100644 index 00000000..29e00116 --- /dev/null +++ b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.java @@ -0,0 +1,29 @@ +class Solution { + public int countPalindromicSubsequence(String s) { + int n = s.length(); + int[] first = new int[26]; + int[] last = new int[26]; + for (int i = 0; i < 26; i++) { + first[i] = -1; + last[i] = -1; + } + + for (int i = 0; i < n; i++) { + int c = s.charAt(i) - 'a'; + if (first[c] == -1) first[c] = i; + last[c] = i; + } + + int ans = 0; + for (int c = 0; c < 26; c++) { + if (first[c] != -1 && last[c] - first[c] > 1) { + int mask = 0; + for (int i = first[c] + 1; i < last[c]; i++) { + mask |= 1 << (s.charAt(i) - 'a'); + } + ans += Integer.bitCount(mask); + } + } + return ans; + } +} diff --git a/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.kt b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.kt new file mode 100644 index 00000000..f8921950 --- /dev/null +++ b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun countPalindromicSubsequence(s: String): Int { + val n = s.length + val first = IntArray(26) { -1 } + val last = IntArray(26) { -1 } + + for (i in 0 until n) { + val c = s[i] - 'a' + if (first[c] == -1) first[c] = i + last[c] = i + } + + var ans = 0 + for (c in 0 until 26) { + if (first[c] != -1 && last[c] - first[c] > 1) { + var mask = 0 + for (i in first[c] + 1 until last[c]) { + mask = mask or (1 shl (s[i] - 'a')) + } + ans += Integer.bitCount(mask) + } + } + return ans + } +} diff --git a/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.py b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.py new file mode 100644 index 00000000..e6f0a81d --- /dev/null +++ b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.py @@ -0,0 +1,21 @@ +class Solution: + def countPalindromicSubsequence(self, s: str) -> int: + n = len(s) + first = [-1] * 26 + last = [-1] * 26 + + for i, ch in enumerate(s): + c = ord(ch) - ord("a") + if first[c] == -1: + first[c] = i + last[c] = i + + ans = 0 + for c in range(26): + if first[c] != -1 and last[c] - first[c] > 1: + mask = 0 + for i in range(first[c] + 1, last[c]): + mask |= 1 << (ord(s[i]) - ord("a")) + ans += bin(mask).count("1") + + return ans diff --git a/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.py2 b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.py2 new file mode 100644 index 00000000..deb5e382 --- /dev/null +++ b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.py2 @@ -0,0 +1,25 @@ +class Solution(object): + def countPalindromicSubsequence(self, s): + """ + :type s: str + :rtype: int + """ + n = len(s) + first = [-1] * 26 + last = [-1] * 26 + + for i, ch in enumerate(s): + c = ord(ch) - ord('a') + if first[c] == -1: + first[c] = i + last[c] = i + + ans = 0 + for c in range(26): + if first[c] != -1 and last[c] - first[c] > 1: + mask = 0 + for i in range(first[c] + 1, last[c]): + mask |= 1 << (ord(s[i]) - ord('a')) + ans += bin(mask).count("1") + + return ans diff --git a/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.rb b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.rb new file mode 100644 index 00000000..c8bcf8f9 --- /dev/null +++ b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.rb @@ -0,0 +1,26 @@ +# @param {String} s +# @return {Integer} +def count_palindromic_subsequence(s) + n = s.length + first = Array.new(26, -1) + last = Array.new(26, -1) + + s.each_char.with_index do |ch, i| + c = ch.ord - 'a'.ord + first[c] = i if first[c] == -1 + last[c] = i + end + + ans = 0 + (0...26).each do |c| + if first[c] != -1 && last[c] - first[c] > 1 + mask = 0 + (first[c] + 1...last[c]).each do |i| + mask |= 1 << (s[i].ord - 'a'.ord) + end + ans += mask.to_s(2).count('1') + end + end + + ans +end diff --git a/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.rs b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.rs new file mode 100644 index 00000000..c73d912b --- /dev/null +++ b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.rs @@ -0,0 +1,28 @@ +impl Solution { + pub fn count_palindromic_subsequence(s: String) -> i32 { + let chars: Vec = s.chars().collect(); + let n = chars.len(); + let mut first = vec![-1; 26]; + let mut last = vec![-1; 26]; + + for i in 0..n { + let c = (chars[i] as u8 - b'a') as usize; + if first[c] == -1 { + first[c] = i as i32; + } + last[c] = i as i32; + } + + let mut ans = 0; + for c in 0..26 { + if first[c] != -1 && last[c] - first[c] > 1 { + let mut mask = 0u32; + for i in (first[c] as usize + 1)..(last[c] as usize) { + mask |= 1 << (chars[i] as u8 - b'a'); + } + ans += mask.count_ones() as i32; + } + } + ans + } +} diff --git a/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.swift b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.swift new file mode 100644 index 00000000..765b022e --- /dev/null +++ b/tests/1501-2000/1930. unique-length-3-palindromic-subsequences/sol.swift @@ -0,0 +1,28 @@ +class Solution { + func countPalindromicSubsequence(_ s: String) -> Int { + let chars = Array(s) + let n = chars.count + var first = [Int](repeating: -1, count: 26) + var last = [Int](repeating: -1, count: 26) + + for i in 0.. 1 { + var mask = 0 + for i in (first[c]+1).. 1) { + let mask = 0; + for (let i = first[c] + 1; i < last[c]; i++) { + mask |= 1 << (s.charCodeAt(i) - 97); + } + ans += mask.toString(2).split("1").length - 1; + } + } + return ans; +} diff --git a/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/manifest.yaml b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/manifest.yaml new file mode 100644 index 00000000..0e9c0ebc --- /dev/null +++ b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/manifest.yaml @@ -0,0 +1,295 @@ +entry: + id: 1931 + title: "painting-a-grid-with-three-different-colors" + params: + m: + type: int + n: + type: int + call: + cpp: "Solution().colorTheGrid({m}, {n})" + rust: "Solution::color_the_grid({m}, {n})" + python3: "Solution().colorTheGrid({m}, {n})" + python2: "Solution().colorTheGrid({m}, {n})" + ruby: "color_the_grid({m}, {n})" + java: "new Solution().colorTheGrid({m}, {n})" + csharp: "new Solution().ColorTheGrid({m}, {n})" + kotlin: "Solution().colorTheGrid({m}, {n})" + go: "colorTheGrid({m}, {n})" + dart: "Solution().colorTheGrid({m}, {n})" + swift: "Solution().colorTheGrid({m}, {n})" + typescript: "colorTheGrid({m}, {n})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().colorTheGrid(m, n, {result})" + checker: | + class Checker: + MOD = 1000000007 + + def colorTheGrid(self, m, n, result): + if not isinstance(m, int) or not isinstance(n, int): + return False + if not (1 <= m <= 5 and 1 <= n <= 1000): + return False + if not isinstance(result, int) or not (0 <= result < self.MOD): + return False + rows = [] + for mask in range(3 ** m): + x = mask + row = [] + ok = True + for i in range(m): + row.append(x % 3) + x //= 3 + if i and row[i] == row[i - 1]: + ok = False + if ok: + rows.append(tuple(row)) + ways = [1] * len(rows) + for _ in range(1, n): + nxt = [] + for current in rows: + total = 0 + for previous, count in zip(rows, ways): + if all(a != b for a, b in zip(previous, current)): + total += count + nxt.append(total % self.MOD) + ways = nxt + return sum(ways) % self.MOD == result + +seed: 1931 + +tests: + - name: "one_by_one" + in: + m: 1 + n: 1 + out: 3 + - name: "one_by_two" + in: + m: 1 + n: 2 + out: 6 + - name: "one_by_three" + in: + m: 1 + n: 3 + out: 12 + - name: "one_by_ten" + in: + m: 1 + n: 10 + out: 1536 + - name: "one_by_max_columns" + in: + m: 1 + n: 1000 + out: 32634808 + - name: "two_by_one" + in: + m: 2 + n: 1 + out: 6 + - name: "two_by_two" + in: + m: 2 + n: 2 + out: 18 + - name: "two_by_three" + in: + m: 2 + n: 3 + out: 54 + - name: "two_by_ten" + in: + m: 2 + n: 10 + out: 118098 + - name: "two_by_max_columns" + in: + m: 2 + n: 1000 + out: 113776386 + - name: "three_by_one" + in: + m: 3 + n: 1 + out: 12 + - name: "three_by_two" + in: + m: 3 + n: 2 + out: 54 + - name: "three_by_three" + in: + m: 3 + n: 3 + out: 246 + - name: "three_by_five" + in: + m: 3 + n: 5 + out: 5118 + - name: "three_by_ten" + in: + m: 3 + n: 10 + out: 10107954 + - name: "three_by_hundred" + in: + m: 3 + n: 100 + out: 905790447 + - name: "three_by_max_columns" + in: + m: 3 + n: 1000 + out: 650420578 + - name: "four_by_one" + in: + m: 4 + n: 1 + out: 24 + - name: "four_by_two" + in: + m: 4 + n: 2 + out: 162 + - name: "four_by_three" + in: + m: 4 + n: 3 + out: 1122 + - name: "four_by_five" + in: + m: 4 + n: 5 + out: 54450 + - name: "four_by_ten" + in: + m: 4 + n: 10 + out: 896895828 + - name: "four_by_fifty" + in: + m: 4 + n: 50 + out: 101279711 + - name: "four_by_max_columns" + in: + m: 4 + n: 1000 + out: 281273229 + - name: "five_by_one" + in: + m: 5 + n: 1 + out: 48 + - name: "five_by_two" + in: + m: 5 + n: 2 + out: 486 + - name: "five_by_three" + in: + m: 5 + n: 3 + out: 5118 + - name: "example_five_by_five" + in: + m: 5 + n: 5 + out: 580986 + - name: "five_by_ten" + in: + m: 5 + n: 10 + out: 796884854 + - name: "five_by_twenty" + in: + m: 5 + n: 20 + out: 679216699 + - name: "five_by_hundred" + in: + m: 5 + n: 100 + out: 714933866 + - name: "five_by_five_hundred" + in: + m: 5 + n: 500 + out: 859596253 + - name: "five_by_999" + in: + m: 5 + n: 999 + out: 719222548 + - name: "five_by_max_columns" + in: + m: 5 + n: 1000 + out: 408208448 + - name: "generated_small" + seed: 193101 + in: + m: + gen: "int" + min: 1 + max: 5 + n: + gen: "int" + min: 1 + max: 20 + - name: "generated_medium" + seed: 193102 + in: + m: + gen: "int" + min: 2 + max: 5 + n: + gen: "int" + min: 20 + max: 200 + - name: "generated_wide" + seed: 193103 + in: + m: + gen: "int" + min: 1 + max: 3 + n: + gen: "int" + min: 800 + max: 1000 + - name: "generated_tall" + seed: 193104 + in: + m: + gen: "int" + min: 4 + max: 5 + n: + gen: "int" + min: 400 + max: 1000 + - name: "generated_boundary" + seed: 193105 + in: + m: + gen: "int" + min: 1 + max: 5 + n: + gen: "int" + min: 990 + max: 1000 diff --git a/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.cpp b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.cpp new file mode 100644 index 00000000..e52dcff2 --- /dev/null +++ b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + int colorTheGrid(int m, int n) { + const int MOD = 1000000007; + long long total = 1; + for (int i = 0; i < m; i++) total *= 3; + vector good; + vector> pattern(total, vector(m)); + for (int i = 0; i < total; i++) { + int val = i; + bool valid = true; + for (int k = 0; k < m; k++) { + pattern[i][k] = val % 3; + val /= 3; + } + for (int k = 1; k < m; k++) { + if (pattern[i][k] == pattern[i][k-1]) { + valid = false; + break; + } + } + if (valid) good.push_back(i); + } + vector> compatible(good.size()); + for (int i = 0; i < (int)good.size(); i++) { + for (int j = 0; j < (int)good.size(); j++) { + bool ok = true; + for (int k = 0; k < m; k++) { + if (pattern[good[i]][k] == pattern[good[j]][k]) { + ok = false; + break; + } + } + if (ok) compatible[i].push_back(j); + } + } + vector dp(good.size(), 1), next(good.size()); + for (int col = 2; col <= n; col++) { + fill(next.begin(), next.end(), 0); + for (int i = 0; i < (int)good.size(); i++) { + long long totalWays = 0; + for (int j : compatible[i]) { + totalWays += dp[j]; + } + next[i] = totalWays % MOD; + } + dp.swap(next); + } + long long ans = 0; + for (long long ways : dp) ans += ways; + return (int)(ans % MOD); + } +}; diff --git a/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.cs b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.cs new file mode 100644 index 00000000..77514c12 --- /dev/null +++ b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.cs @@ -0,0 +1,52 @@ +public class Solution { + public int ColorTheGrid(int m, int n) { + const int MOD = 1000000007; + long total = 1; + for (int i = 0; i < m; i++) total *= 3; + long[,] dp = new long[n+1, total]; + int[,] rowValid = new int[total, total]; + List good = new List(); + int[,] pattern = new int[total, m]; + for (int i = 0; i < total; i++) { + int val = i; + bool valid = true; + for (int k = 0; k < m; k++) { + pattern[i,k] = val % 3; + val /= 3; + } + for (int k = 1; k < m; k++) { + if (pattern[i,k] == pattern[i,k-1]) { + valid = false; + break; + } + } + if (valid) good.Add(i); + } + foreach (int i in good) dp[1,i] = 1; + foreach (int i in good) { + foreach (int j in good) { + rowValid[i,j] = 1; + for (int k = 0; k < m; k++) { + if (pattern[i,k] == pattern[j,k]) { + rowValid[i,j] = 0; + break; + } + } + } + } + for (int col = 2; col <= n; col++) { + foreach (int i in good) { + long totalWays = 0; + foreach (int j in good) { + if (rowValid[i,j] == 1) { + totalWays += dp[col-1,j]; + } + } + dp[col,i] = totalWays % MOD; + } + } + long ans = 0; + foreach (int i in good) ans += dp[n,i]; + return (int)(ans % MOD); + } +} diff --git a/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.dart b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.dart new file mode 100644 index 00000000..1f0dcc64 --- /dev/null +++ b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.dart @@ -0,0 +1,60 @@ +class Solution { + int colorTheGrid(int m, int n) { + final mod = 1000000007; + int total = 1; + for (int i = 0; i < m; i++) { + total *= 3; + } + List> dp = List.generate(n + 1, (_) => List.filled(total, 0)); + List> rowValid = List.generate(total, (_) => List.filled(total, 0)); + List good = []; + List> pattern = List.generate(total, (_) => List.filled(m, 0)); + for (int i = 0; i < total; i++) { + int val = i; + bool valid = true; + for (int k = 0; k < m; k++) { + pattern[i][k] = val % 3; + val ~/= 3; + } + for (int k = 1; k < m; k++) { + if (pattern[i][k] == pattern[i][k - 1]) { + valid = false; + break; + } + } + if (valid) { + good.add(i); + } + } + for (int i in good) { + dp[1][i] = 1; + } + for (int i in good) { + for (int j in good) { + rowValid[i][j] = 1; + for (int k = 0; k < m; k++) { + if (pattern[i][k] == pattern[j][k]) { + rowValid[i][j] = 0; + break; + } + } + } + } + for (int col = 2; col <= n; col++) { + for (int i in good) { + int totalWays = 0; + for (int j in good) { + if (rowValid[i][j] == 1) { + totalWays += dp[col - 1][j]; + } + } + dp[col][i] = totalWays % mod; + } + } + int ans = 0; + for (int i in good) { + ans += dp[n][i]; + } + return ans % mod; + } +} diff --git a/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.go b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.go new file mode 100644 index 00000000..0f42eda4 --- /dev/null +++ b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.go @@ -0,0 +1,63 @@ +func colorTheGrid(m int, n int) int { + mod := 1000000007 + total := 1 + for i := 0; i < m; i++ { + total *= 3 + } + dp := make([][]int, n+1) + for i := range dp { + dp[i] = make([]int, total) + } + rowValid := make([][]int, total) + for i := range rowValid { + rowValid[i] = make([]int, total) + } + good := []int{} + pattern := make([][]int, total) + for i := 0; i < total; i++ { + pattern[i] = make([]int, m) + val := i + valid := 1 + for k := 0; k < m; k++ { + pattern[i][k] = val % 3 + val /= 3 + } + for k := 1; k < m; k++ { + if pattern[i][k] == pattern[i][k-1] { + valid = 0 + } + } + if valid == 1 { + good = append(good, i) + } + } + for _, i := range good { + dp[1][i] = 1 + } + for _, i := range good { + for _, j := range good { + rowValid[i][j] = 1 + for k := 0; k < m; k++ { + if pattern[i][k] == pattern[j][k] { + rowValid[i][j] = 0 + } + } + } + } + for col := 2; col <= n; col++ { + for _, i := range good { + totalWays := 0 + for _, j := range good { + if rowValid[i][j] == 1 { + totalWays += dp[col-1][j] + } + } + dp[col][i] = totalWays % mod + } + } + ans := 0 + for _, i := range good { + ans += dp[n][i] + } + return ans % mod +} diff --git a/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.java b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.java new file mode 100644 index 00000000..2f551cd3 --- /dev/null +++ b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.java @@ -0,0 +1,52 @@ +class Solution { + public int colorTheGrid(int m, int n) { + int mod = 1000000007; + int total = 1; + for (int i = 0; i < m; i++) total *= 3; + int[][] dp = new int[n+1][total]; + int[][] rowValid = new int[total][total]; + java.util.List good = new java.util.ArrayList<>(); + int[][] pattern = new int[total][m]; + for (int i = 0; i < total; i++) { + int val = i; + boolean valid = true; + for (int k = 0; k < m; k++) { + pattern[i][k] = val % 3; + val /= 3; + } + for (int k = 1; k < m; k++) { + if (pattern[i][k] == pattern[i][k-1]) { + valid = false; + break; + } + } + if (valid) good.add(i); + } + for (int i : good) dp[1][i] = 1; + for (int i : good) { + for (int j : good) { + rowValid[i][j] = 1; + for (int k = 0; k < m; k++) { + if (pattern[i][k] == pattern[j][k]) { + rowValid[i][j] = 0; + break; + } + } + } + } + for (int col = 2; col <= n; col++) { + for (int i : good) { + long totalWays = 0; + for (int j : good) { + if (rowValid[i][j] == 1) { + totalWays += dp[col-1][j]; + } + } + dp[col][i] = (int)(totalWays % mod); + } + } + long ans = 0; + for (int i : good) ans += dp[n][i]; + return (int)(ans % mod); + } +} diff --git a/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.kt b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.kt new file mode 100644 index 00000000..72d2013f --- /dev/null +++ b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.kt @@ -0,0 +1,52 @@ +class Solution { + fun colorTheGrid(m: Int, n: Int): Int { + val mod = 1000000007 + var total = 1 + repeat(m) { total *= 3 } + val dp = Array(n+1) { IntArray(total) } + val rowValid = Array(total) { IntArray(total) } + val good = mutableListOf() + val pattern = Array(total) { IntArray(m) } + for (i in 0 until total) { + var value = i + var valid = true + for (k in 0 until m) { + pattern[i][k] = value % 3 + value /= 3 + } + for (k in 1 until m) { + if (pattern[i][k] == pattern[i][k-1]) { + valid = false + break + } + } + if (valid) good.add(i) + } + for (i in good) dp[1][i] = 1 + for (i in good) { + for (j in good) { + rowValid[i][j] = 1 + for (k in 0 until m) { + if (pattern[i][k] == pattern[j][k]) { + rowValid[i][j] = 0 + break + } + } + } + } + for (col in 2..n) { + for (i in good) { + var totalWays = 0L + for (j in good) { + if (rowValid[i][j] == 1) { + totalWays += dp[col-1][j] + } + } + dp[col][i] = (totalWays % mod).toInt() + } + } + var ans = 0L + for (i in good) ans += dp[n][i] + return (ans % mod).toInt() + } +} diff --git a/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.py b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.py new file mode 100644 index 00000000..1fad13c7 --- /dev/null +++ b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.py @@ -0,0 +1,36 @@ +class Solution(object): + def colorTheGrid(self, m, n): + mod = 10**9 + 7 + total = 1 + for _ in range(m): + total *= 3 + dp = [[0] * total for _ in range(n + 1)] + rowValid = [[0] * total for _ in range(total)] + good = [] + pattern = [[] for _ in range(total)] + for i in range(total): + val, valid = i, 1 + for _ in range(m): + pattern[i].append(val % 3) + val //= 3 + for j in range(1, m): + if pattern[i][j] == pattern[i][j - 1]: + valid = 0 + if valid: + good.append(i) + for i in good: + dp[1][i] = 1 + for i in good: + for j in good: + rowValid[i][j] = 1 + for k in range(m): + if pattern[i][k] == pattern[j][k]: + rowValid[i][j] = 0 + for col in range(2, n + 1): + for i in good: + total_ways = 0 + for j in good: + if rowValid[i][j]: + total_ways += dp[col - 1][j] + dp[col][i] = total_ways % mod + return sum(dp[n]) % mod diff --git a/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.py2 b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.py2 new file mode 100644 index 00000000..8d96c7d6 --- /dev/null +++ b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.py2 @@ -0,0 +1,41 @@ +class Solution(object): + def colorTheGrid(self, m, n): + """ + :type m: int + :type n: int + :rtype: int + """ + mod = 10**9+7 + total = 1 + for _ in range(m): + total *= 3 + dp = [[0]*total for _ in range(n+1)] + rowValid = [[0]*total for _ in range(total)] + good = [] + pattern = [[] for _ in range(total)] + for i in range(total): + val, valid = i, 1 + for _ in range(m): + pattern[i].append(val % 3) + val //= 3 + for j in range(1, m): + if pattern[i][j] == pattern[i][j-1]: + valid = 0 + if valid: + good.append(i) + for i in good: + dp[1][i] = 1 + for i in good: + for j in good: + rowValid[i][j] = 1 + for k in range(m): + if pattern[i][k] == pattern[j][k]: + rowValid[i][j] = 0 + for col in range(2, n+1): + for i in good: + total_ways = 0 + for j in good: + if rowValid[i][j]: + total_ways += dp[col-1][j] + dp[col][i] = total_ways % mod + return sum(dp[n]) % mod diff --git a/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.rb b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.rb new file mode 100644 index 00000000..12add8bc --- /dev/null +++ b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.rb @@ -0,0 +1,49 @@ +# @param {Integer} m +# @param {Integer} n +# @return {Integer} +def color_the_grid(m, n) + mod = 10**9+7 + total = 1 + m.times { total *= 3 } + dp = Array.new(n+1) { Array.new(total, 0) } + rowValid = Array.new(total) { Array.new(total, 0) } + good = [] + pattern = Array.new(total) { [] } + (0...total).each do |i| + val = i + valid = 1 + m.times do + pattern[i] << val % 3 + val /= 3 + end + (1...m).each do |j| + if pattern[i][j] == pattern[i][j-1] + valid = 0 + end + end + good << i if valid == 1 + end + good.each { |i| dp[1][i] = 1 } + good.each do |i| + good.each do |j| + rowValid[i][j] = 1 + (0...m).each do |k| + if pattern[i][k] == pattern[j][k] + rowValid[i][j] = 0 + end + end + end + end + (2..n).each do |col| + good.each do |i| + total_ways = 0 + good.each do |j| + if rowValid[i][j] == 1 + total_ways += dp[col-1][j] + end + end + dp[col][i] = total_ways % mod + end + end + dp[n].sum % mod +end diff --git a/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.rs b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.rs new file mode 100644 index 00000000..6d8e9f38 --- /dev/null +++ b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.rs @@ -0,0 +1,62 @@ +impl Solution { + pub fn color_the_grid(m: i32, n: i32) -> i32 { + let modulus: i64 = 1000000007; + let m = m as usize; + let n = n as usize; + let mut total = 1; + for _ in 0..m { + total *= 3; + } + let mut dp = vec![vec![0i64; total]; n+1]; + let mut row_valid = vec![vec![0i32; total]; total]; + let mut good: Vec = Vec::new(); + let mut pattern = vec![vec![0i32; m]; total]; + for i in 0..total { + let mut val = i; + let mut valid = 1; + for k in 0..m { + pattern[i][k] = (val % 3) as i32; + val /= 3; + } + for k in 1..m { + if pattern[i][k] == pattern[i][k-1] { + valid = 0; + break; + } + } + if valid == 1 { + good.push(i); + } + } + for &i in &good { + dp[1][i] = 1; + } + for &i in &good { + for &j in &good { + row_valid[i][j] = 1; + for k in 0..m { + if pattern[i][k] == pattern[j][k] { + row_valid[i][j] = 0; + break; + } + } + } + } + for col in 2..=n { + for &i in &good { + let mut total_ways: i64 = 0; + for &j in &good { + if row_valid[i][j] == 1 { + total_ways += dp[col-1][j]; + } + } + dp[col][i] = total_ways % modulus; + } + } + let mut ans: i64 = 0; + for &i in &good { + ans += dp[n][i]; + } + (ans % modulus) as i32 + } +} diff --git a/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.swift b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.swift new file mode 100644 index 00000000..2188adbd --- /dev/null +++ b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.swift @@ -0,0 +1,60 @@ +class Solution { + func colorTheGrid(_ m: Int, _ n: Int) -> Int { + let mod = 1000000007 + var total = 1 + for _ in 0..= 2 { + for col in 2...n { + for i in good { + var totalWays = 0 + for j in good { + if rowValid[i][j] == 1 { + totalWays += dp[col-1][j] + } + } + dp[col][i] = totalWays % mod + } + } + } + var ans = 0 + for i in good { + ans += dp[n][i] + } + return ans % mod + } +} diff --git a/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.ts b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.ts new file mode 100644 index 00000000..ea7e5f01 --- /dev/null +++ b/tests/1501-2000/1931. painting-a-grid-with-three-different-colors/sol.ts @@ -0,0 +1,56 @@ +function colorTheGrid(m: number, n: number): number { + const mod = 1000000007; + let total = 1; + for (let i = 0; i < m; i++) total *= 3; + const dp: number[][] = Array.from({ length: n + 1 }, () => + Array(total).fill(0), + ); + const rowValid: number[][] = Array.from({ length: total }, () => + Array(total).fill(0), + ); + const good: number[] = []; + const pattern: number[][] = Array.from({ length: total }, () => + Array(m).fill(0), + ); + for (let i = 0; i < total; i++) { + let val = i; + let valid = 1; + for (let k = 0; k < m; k++) { + pattern[i][k] = val % 3; + val = Math.floor(val / 3); + } + for (let k = 1; k < m; k++) { + if (pattern[i][k] === pattern[i][k - 1]) { + valid = 0; + break; + } + } + if (valid === 1) good.push(i); + } + for (const i of good) dp[1][i] = 1; + for (const i of good) { + for (const j of good) { + rowValid[i][j] = 1; + for (let k = 0; k < m; k++) { + if (pattern[i][k] === pattern[j][k]) { + rowValid[i][j] = 0; + break; + } + } + } + } + for (let col = 2; col <= n; col++) { + for (const i of good) { + let totalWays = 0; + for (const j of good) { + if (rowValid[i][j] === 1) { + totalWays += dp[col - 1][j]; + } + } + dp[col][i] = totalWays % mod; + } + } + let ans = 0; + for (const i of good) ans += dp[n][i]; + return ans % mod; +} diff --git a/tests/1501-2000/1935. maximum-number-of-words-you-can-type/manifest.yaml b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/manifest.yaml new file mode 100644 index 00000000..4437b464 --- /dev/null +++ b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/manifest.yaml @@ -0,0 +1,236 @@ +entry: + id: 1935 + title: "maximum-number-of-words-you-can-type" + params: + broken: + type: string + text: + type: string + call: + cpp: "Solution().canBeTypedWords({text}, {broken})" + rust: "Solution::can_be_typed_words({text}, {broken})" + python3: "Solution().canBeTypedWords({text}, {broken})" + python2: "Solution().canBeTypedWords({text}, {broken})" + ruby: "can_be_typed_words({text}, {broken})" + java: "new Solution().canBeTypedWords({text}, {broken})" + csharp: "new Solution().CanBeTypedWords({text}, {broken})" + kotlin: "Solution().canBeTypedWords({text}, {broken})" + go: "canBeTypedWords({text}, {broken})" + dart: "Solution().canBeTypedWords({text}, {broken})" + swift: "Solution().canBeTypedWords({text}, {broken})" + typescript: "canBeTypedWords({text}, {broken})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().canBeTypedWords(text, broken, {result})" + checker: | + class Checker: + def canBeTypedWords(self, text, broken, result): + if not isinstance(text, str) or not isinstance(broken, str): + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + broken = set(broken) + expected = sum(1 for word in text.split(" ") if all(ch not in broken for ch in word)) + return result == expected + +seed: 1935 + +tests: + - name: "example_1" + in: + text: "hello world" + broken: "ad" + out: 1 + - name: "example_2" + in: + text: "leet code" + broken: "lt" + out: 1 + - name: "example_3" + in: + text: "leet code" + broken: "e" + out: 0 + - name: "empty_broken" + in: + text: "a bb ccc dddd" + broken: "" + out: 4 + - name: "all_letters_broken" + in: + text: "a bb ccc dddd" + broken: "abcdefghijklmnopqrstuvwxyz" + out: 0 + - name: "one_word_typable" + in: + text: "keyboard" + broken: "xz" + out: 1 + - name: "one_word_blocked" + in: + text: "keyboard" + broken: "b" + out: 0 + - name: "first_word_blocked" + in: + text: "bad cab dab" + broken: "b" + out: 0 + - name: "last_word_blocked" + in: + text: "ace bed dog" + broken: "g" + out: 2 + - name: "alternating_words" + in: + text: "aa bb cc dd ee" + broken: "bd" + out: 3 + - name: "single_character_words" + in: + text: "a b c d e" + broken: "bd" + out: 3 + - name: "repeated_broken_character" + in: + text: "aaaa aaab baaa" + broken: "a" + out: 0 + - name: "repeated_working_character" + in: + text: "bbbb bbb bb" + broken: "a" + out: 3 + - name: "mixed_case_patterns" + in: + text: "abc def ghi jkl" + broken: "cfj" + out: 1 + - name: "broken_only_unused" + in: + text: "abc def ghi" + broken: "jkl" + out: 3 + - name: "vowels_broken" + in: + text: "alpha beta crypt rhythm" + broken: "aeiou" + out: 2 + - name: "consonants_broken" + in: + text: "one two three four" + broken: "tn" + out: 1 + - name: "all_words_share_letter" + in: + text: "cat coat cart trace" + broken: "c" + out: 0 + - name: "long_words" + in: + text: "abcdefghij klmnopqrst uvwxyz" + broken: "fpz" + out: 0 + - name: "long_words_one_survives" + in: + text: "abcdefghij klmnopqrst uvwxy" + broken: "fpz" + out: 1 + - name: "spaces_separate_words" + in: + text: "ab cd ef gh" + broken: "x" + out: 4 + - name: "distinct_broken_letters" + in: + text: "hello help helium" + broken: "hp" + out: 0 + - name: "only_first_letter_broken" + in: + text: "apple banana cherry" + broken: "abc" + out: 0 + - name: "only_last_letter_broken" + in: + text: "apple banana cherry" + broken: "ey" + out: 1 + - name: "middle_letter_broken" + in: + text: "apple banana cherry" + broken: "p" + out: 2 + - name: "two_typable_two_blocked" + in: + text: "dog cat fish bird" + broken: "cf" + out: 2 + - name: "alphabet_words" + in: + text: "abc mno xyz" + broken: "d" + out: 3 + - name: "alphabet_words_blocked" + in: + text: "abc mno xyz" + broken: "mo" + out: 2 + - name: "empty_word_impossible_not_allowed" + in: + text: "z" + broken: "" + out: 1 + - name: "every_word_has_different_failure" + in: + text: "ab cd ef gh ij" + broken: "acegi" + out: 0 + - name: "single_word_length_ten_thousand_boundary" + in: + text: + gen: "str" + len: 10000 + alphabet: "a" + broken: "b" + out: 1 + - name: "single_word_length_nine_thousand" + in: + text: + gen: "str" + len: 9000 + alphabet: "z" + broken: "a" + out: 1 + - name: "single_word_blocked_large" + in: + text: + gen: "str" + len: 10000 + alphabet: "q" + broken: "q" + out: 0 + - name: "single_word_mixed_large" + in: + text: + gen: "str" + len: 7777 + alphabet: "ab" + broken: "c" + out: 1 + - name: "single_word_mixed_blocked_large" + in: + text: + gen: "str" + len: 8888 + alphabet: "abc" + broken: "c" + out: 0 diff --git a/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.cpp b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.cpp new file mode 100644 index 00000000..a5cda414 --- /dev/null +++ b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int canBeTypedWords(string text, string brokenLetters) { + vector b(26, false); + int res = 0; + + for (char c : brokenLetters) { + b[c - 'a'] = true; + } + + stringstream ss(text); + string w; + while (ss >> w) { + bool ok = true; + for (char c : w) { + if (b[c - 'a']) { + ok = false; + break; + } + } + if (ok) { + res++; + } + } + + return res; + } +}; diff --git a/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.cs b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.cs new file mode 100644 index 00000000..dc9ae63d --- /dev/null +++ b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public int CanBeTypedWords(string text, string brokenLetters) { + bool[] b = new bool[26]; + int res = 0; + + foreach (char c in brokenLetters) { + b[c - 'a'] = true; + } + + foreach (string w in text.Split(' ')) { + bool ok = true; + foreach (char c in w) { + if (b[c - 'a']) { + ok = false; + break; + } + } + if (ok) { + res++; + } + } + + return res; + } +} diff --git a/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.dart b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.dart new file mode 100644 index 00000000..be11e87e --- /dev/null +++ b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.dart @@ -0,0 +1,26 @@ +class Solution { + int canBeTypedWords(String text, String brokenLetters) { + List b = List.filled(26, false); + int res = 0; + + for (int i = 0; i < brokenLetters.length; i++) { + b[brokenLetters.codeUnitAt(i) - 97] = true; + } + + List words = text.split(' '); + for (String w in words) { + bool ok = true; + for (int i = 0; i < w.length; i++) { + if (b[w.codeUnitAt(i) - 97]) { + ok = false; + break; + } + } + if (ok) { + res++; + } + } + + return res; + } +} diff --git a/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.go b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.go new file mode 100644 index 00000000..5f9b4735 --- /dev/null +++ b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.go @@ -0,0 +1,24 @@ +func canBeTypedWords(text string, brokenLetters string) int { + b := make([]bool, 26) + res := 0 + + for _, c := range brokenLetters { + b[c-'a'] = true + } + + words := strings.Split(text, " ") + for _, w := range words { + ok := true + for _, c := range w { + if b[c-'a'] { + ok = false + break + } + } + if ok { + res++ + } + } + + return res +} diff --git a/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.java b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.java new file mode 100644 index 00000000..8c59098c --- /dev/null +++ b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.java @@ -0,0 +1,25 @@ +class Solution { + public int canBeTypedWords(String text, String brokenLetters) { + boolean[] b = new boolean[26]; + int res = 0; + + for (char c : brokenLetters.toCharArray()) { + b[c - 'a'] = true; + } + + for (String w : text.split(" ")) { + boolean ok = true; + for (char c : w.toCharArray()) { + if (b[c - 'a']) { + ok = false; + break; + } + } + if (ok) { + res++; + } + } + + return res; + } +} diff --git a/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.kt b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.kt new file mode 100644 index 00000000..3327b99b --- /dev/null +++ b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.kt @@ -0,0 +1,25 @@ +class Solution { + fun canBeTypedWords(text: String, brokenLetters: String): Int { + val b = BooleanArray(26) + var res = 0 + + for (c in brokenLetters) { + b[c - 'a'] = true + } + + for (w in text.split(" ")) { + var ok = true + for (c in w) { + if (b[c - 'a']) { + ok = false + break + } + } + if (ok) { + res++ + } + } + + return res + } +} diff --git a/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.py b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.py new file mode 100644 index 00000000..e4850e20 --- /dev/null +++ b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.py @@ -0,0 +1,20 @@ +class Solution: + def canBeTypedWords(self, text, brokenLetters): + broken = brokenLetters + b = [False] * 26 + res = 0 + + for c in broken: + b[ord(c) - 97] = True + + words = text.split() + for w in words: + ok = True + for c in w: + if b[ord(c) - 97]: + ok = False + break + if ok: + res = res + 1 + + return res diff --git a/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.py2 b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.py2 new file mode 100644 index 00000000..5f78a86e --- /dev/null +++ b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.py2 @@ -0,0 +1,24 @@ +class Solution(object): + def canBeTypedWords(self, text, brokenLetters): + """ + :type text: str + :type brokenLetters: str + :rtype: int + """ + b = [False]*26 + res = 0 + + for c in brokenLetters: + b[ord(c)-97] = True + + words = text.split() + for w in words: + ok = True + for c in w: + if b[ord(c)-97]: + ok = False + break + if ok: + res = res + 1 + + return res diff --git a/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.rb b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.rb new file mode 100644 index 00000000..31575d1a --- /dev/null +++ b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.rb @@ -0,0 +1,24 @@ +# @param {String} text +# @param {String} broken_letters +# @return {Integer} +def can_be_typed_words(text, broken_letters) + b = Array.new(26, false) + res = 0 + + broken_letters.each_char do |c| + b[c.ord - 97] = true + end + + text.split.each do |w| + ok = true + w.each_char do |c| + if b[c.ord - 97] + ok = false + break + end + end + res += 1 if ok + end + + res +end diff --git a/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.rs b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.rs new file mode 100644 index 00000000..b40702a5 --- /dev/null +++ b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn can_be_typed_words(text: String, broken_letters: String) -> i32 { + let mut b = vec![false; 26]; + let mut res = 0; + + for c in broken_letters.bytes() { + b[(c - 97) as usize] = true; + } + + for w in text.split(' ') { + let mut ok = true; + for c in w.bytes() { + if b[(c - 97) as usize] { + ok = false; + break; + } + } + if ok { + res += 1; + } + } + + res + } +} diff --git a/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.swift b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.swift new file mode 100644 index 00000000..15540d28 --- /dev/null +++ b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.swift @@ -0,0 +1,26 @@ +class Solution { + func canBeTypedWords(_ text: String, _ brokenLetters: String) -> Int { + var b = [Bool](repeating: false, count: 26) + var res = 0 + + for c in brokenLetters { + b[Int(c.asciiValue! - 97)] = true + } + + let words = text.split(separator: " ") + for w in words { + var ok = true + for c in w { + if b[Int(c.asciiValue! - 97)] { + ok = false + break + } + } + if ok { + res += 1 + } + } + + return res + } +} diff --git a/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.ts b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.ts new file mode 100644 index 00000000..9e935da5 --- /dev/null +++ b/tests/1501-2000/1935. maximum-number-of-words-you-can-type/sol.ts @@ -0,0 +1,24 @@ +function canBeTypedWords(text: string, brokenLetters: string): number { + const b: boolean[] = new Array(26).fill(false); + let res = 0; + + for (const c of brokenLetters) { + b[c.charCodeAt(0) - 97] = true; + } + + const words = text.split(" "); + for (const w of words) { + let ok = true; + for (const c of w) { + if (b[c.charCodeAt(0) - 97]) { + ok = false; + break; + } + } + if (ok) { + res++; + } + } + + return res; +} diff --git a/tests/1501-2000/1936. add-minimum-number-of-rungs/manifest.yaml b/tests/1501-2000/1936. add-minimum-number-of-rungs/manifest.yaml new file mode 100644 index 00000000..c39b5ebf --- /dev/null +++ b/tests/1501-2000/1936. add-minimum-number-of-rungs/manifest.yaml @@ -0,0 +1,314 @@ +entry: + id: 1936 + title: "add-minimum-number-of-rungs" + params: + rungs: + type: array + items: + type: int + dist: + type: int + call: + cpp: "Solution().addRungs({rungs}, {dist})" + rust: "Solution::add_rungs({rungs}, {dist})" + python3: "Solution().addRungs({rungs}, {dist})" + python2: "Solution().addRungs({rungs}, {dist})" + ruby: "add_rungs({rungs}, {dist})" + java: "new Solution().addRungs({rungs}, {dist})" + csharp: "new Solution().AddRungs({rungs}, {dist})" + kotlin: "Solution().addRungs({rungs}, {dist})" + go: "addRungs({rungs}, {dist})" + dart: "Solution().addRungs({rungs}, {dist})" + swift: "Solution().addRungs({rungs}, {dist})" + typescript: "addRungs({rungs}, {dist})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().addRungs(rungs, dist, {result})" + checker: | + class Checker: + def addRungs(self, rungs, dist, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + current = 0 + expected = 0 + for rung in rungs: + if rung - current > dist: + expected += (rung - current - 1) // dist + current = rung + return result == expected + +seed: 1936 + +tests: + - name: "example_one" + in: + rungs: [1, 3, 5, 10] + dist: 2 + out: 2 + - name: "example_two" + in: + rungs: [3, 6, 8, 10] + dist: 3 + out: 0 + - name: "example_three" + in: + rungs: [3, 4, 6, 7] + dist: 2 + out: 1 + - name: "single_reachable" + in: + rungs: [1] + dist: 1 + out: 0 + - name: "single_gap_one" + in: + rungs: [2] + dist: 1 + out: 1 + - name: "single_large_gap" + in: + rungs: [1000000000] + dist: 1 + out: 999999999 + - name: "exact_multiple_gap" + in: + rungs: [10] + dist: 5 + out: 1 + - name: "non_multiple_gap" + in: + rungs: [11] + dist: 5 + out: 2 + - name: "all_reachable" + in: + rungs: [2, 4, 6, 8, 10] + dist: 2 + out: 0 + - name: "gaps_each_need_one" + in: + rungs: [3, 6, 9, 12] + dist: 2 + out: 4 + - name: "mixed_gaps" + in: + rungs: [1, 10, 11, 25] + dist: 5 + out: 3 + - name: "large_dist" + in: + rungs: [1, 2, 100, 1000] + dist: 1000000000 + out: 0 + - name: "dist_one_consecutive" + in: + rungs: [1, 2, 3, 4, 5, 6] + dist: 1 + out: 0 + - name: "dist_one_sparse" + in: + rungs: [1, 3, 6, 10] + dist: 1 + out: 6 + - name: "dist_two_long" + in: + rungs: [2, 4, 6, 8, 10, 12, 14, 16] + dist: 2 + out: 0 + - name: "first_gap_only" + in: + rungs: [8, 9, 10] + dist: 3 + out: 2 + - name: "last_gap_only" + in: + rungs: [1, 2, 3, 10] + dist: 3 + out: 2 + - name: "two_huge_gaps" + in: + rungs: [100, 1000000000] + dist: 100 + out: 9999998 + - name: "near_limit_dist" + in: + rungs: [1, 999999999, 1000000000] + dist: 999999998 + out: 0 + - name: "alternating_small_gaps" + in: + rungs: [1, 5, 6, 10, 11, 15, 16] + dist: 3 + out: 3 + - name: "zero_additions_after_first" + in: + rungs: [4, 8, 12, 16, 20] + dist: 4 + out: 0 + - name: "remainder_zero" + in: + rungs: [7, 14, 21] + dist: 3 + out: 6 + - name: "remainder_one" + in: + rungs: [8, 16, 24] + dist: 3 + out: 6 + - name: "negative_not_allowed_boundary" + in: + rungs: [1, 1000000000] + dist: 2 + out: 499999999 + - name: "dense_then_gap" + in: + rungs: [1, 2, 3, 4, 5, 20] + dist: 4 + out: 3 + - name: "gap_then_dense" + in: + rungs: [10, 11, 12, 13, 14] + dist: 3 + out: 3 + - name: "many_rungs_dist_three" + in: + rungs: [3, 6, 9, 12, 15, 18, 21, 24, 27, 30] + dist: 3 + out: 0 + - name: "many_rungs_dist_four" + in: + rungs: [1, 5, 9, 13, 17, 21, 25] + dist: 4 + out: 0 + - name: "large_first_then_small" + in: + rungs: [50, 51, 52, 53, 54] + dist: 10 + out: 4 + - name: "large_values_small_dist" + in: + rungs: [999999990, 999999995, 1000000000] + dist: 2 + out: 499999998 + - name: "one_less_than_dist" + in: + rungs: [9, 18, 27] + dist: 10 + out: 0 + - name: "exactly_dist_from_floor" + in: + rungs: [10, 20, 30] + dist: 10 + out: 0 + - name: "strictly_increasing_irregular" + in: + rungs: [2, 7, 8, 19, 40] + dist: 6 + out: 4 + - name: "large_count_small_steps" + in: + rungs: [1, 4, 7, 10, 13, 16, 19, 22, 25] + dist: 2 + out: 8 + - name: "near_max_single" + in: + rungs: [999999999] + dist: 1000000000 + out: 0 + - name: "generated_small_strict" + seed: 101 + in: + rungs: + gen: "array" + len: + gen: "int" + min: 1 + max: 30 + of: + gen: "int" + min: 1 + max: 200 + distinct: true + sorted: true + dist: + gen: "int" + min: 1 + max: 30 + - name: "generated_medium_strict" + seed: 102 + in: + rungs: + gen: "array" + len: + gen: "int" + min: 20 + max: 100 + of: + gen: "int" + min: 1 + max: 10000 + distinct: true + sorted: true + dist: + gen: "int" + min: 1 + max: 500 + - name: "generated_large_sparse" + seed: 103 + in: + rungs: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: true + sorted: true + dist: + gen: "int" + min: 1 + max: 1000 + - name: "generated_large_dense" + seed: 104 + in: + rungs: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: true + sorted: true + dist: + gen: "int" + min: 100000 + max: 1000000000 + - name: "generated_max_values" + seed: 105 + in: + rungs: + gen: "array" + len: + gen: "int" + min: 50000 + max: 100000 + of: + gen: "int" + min: 900000000 + max: 1000000000 + distinct: true + sorted: true + dist: + gen: "int" + min: 1 + max: 1000000000 diff --git a/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.cpp b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.cpp new file mode 100644 index 00000000..f992a07e --- /dev/null +++ b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int addRungs(vector& rungs, int dist) { + int curr = 0; + int res = 0; + for (int rung : rungs) { + if (rung - curr > dist) { + res += (rung - curr - 1) / dist; + } + curr = rung; + } + return res; + } +}; diff --git a/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.cs b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.cs new file mode 100644 index 00000000..5b96a434 --- /dev/null +++ b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public int AddRungs(int[] rungs, int dist) { + int curr = 0; + int res = 0; + foreach (int rung in rungs) { + if (rung - curr > dist) { + res += (rung - curr - 1) / dist; + } + curr = rung; + } + return res; + } +} diff --git a/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.dart b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.dart new file mode 100644 index 00000000..3c2534d2 --- /dev/null +++ b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.dart @@ -0,0 +1,13 @@ +class Solution { + int addRungs(List rungs, int dist) { + int curr = 0; + int res = 0; + for (int rung in rungs) { + if (rung - curr > dist) { + res += (rung - curr - 1) ~/ dist; + } + curr = rung; + } + return res; + } +} diff --git a/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.go b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.go new file mode 100644 index 00000000..8b7a1e25 --- /dev/null +++ b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.go @@ -0,0 +1,11 @@ +func addRungs(rungs []int, dist int) int { + curr := 0 + res := 0 + for _, rung := range rungs { + if rung - curr > dist { + res += (rung - curr - 1) / dist + } + curr = rung + } + return res +} diff --git a/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.java b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.java new file mode 100644 index 00000000..88197d32 --- /dev/null +++ b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int addRungs(int[] rungs, int dist) { + int curr = 0; + int res = 0; + for (int rung : rungs) { + if (rung - curr > dist) { + res += (rung - curr - 1) / dist; + } + curr = rung; + } + return res; + } +} diff --git a/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.kt b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.kt new file mode 100644 index 00000000..1af1d42c --- /dev/null +++ b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun addRungs(rungs: IntArray, dist: Int): Int { + var curr = 0 + var res = 0 + for (rung in rungs) { + if (rung - curr > dist) { + res += (rung - curr - 1) / dist + } + curr = rung + } + return res + } +} diff --git a/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.py b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.py new file mode 100644 index 00000000..a7ad4923 --- /dev/null +++ b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.py @@ -0,0 +1,16 @@ +class Solution(object): + def addRungs(self, rungs, dist): + """ + :type rungs: List[int] + :type dist: int + :rtype: int + """ + curr = 0 + res = 0 + + for rung in rungs: + if rung - curr > dist: + res += (rung - curr - 1) // dist + curr = rung + + return res diff --git a/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.py2 b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.py2 new file mode 100644 index 00000000..c6c3b892 --- /dev/null +++ b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def addRungs(self, rungs, dist): + """ + :type rungs: List[int] + :type dist: int + :rtype: int + """ + curr = 0 + res = 0 + for rung in rungs: + if rung - curr > dist: + res += (rung - curr - 1) / dist + curr = rung + return res diff --git a/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.rb b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.rb new file mode 100644 index 00000000..72e7fb11 --- /dev/null +++ b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[]} rungs +# @param {Integer} dist +# @return {Integer} +def add_rungs(rungs, dist) + curr = 0 + res = 0 + rungs.each do |rung| + if rung - curr > dist + res += (rung - curr - 1) / dist + end + curr = rung + end + res +end diff --git a/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.rs b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.rs new file mode 100644 index 00000000..c27a4339 --- /dev/null +++ b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn add_rungs(rungs: Vec, dist: i32) -> i32 { + let mut curr = 0; + let mut res = 0; + for rung in rungs { + if rung - curr > dist { + res += (rung - curr - 1) / dist; + } + curr = rung; + } + res + } +} diff --git a/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.swift b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.swift new file mode 100644 index 00000000..d23d5b20 --- /dev/null +++ b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.swift @@ -0,0 +1,13 @@ +class Solution { + func addRungs(_ rungs: [Int], _ dist: Int) -> Int { + var curr = 0 + var res = 0 + for rung in rungs { + if rung - curr > dist { + res += (rung - curr - 1) / dist + } + curr = rung + } + return res + } +} diff --git a/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.ts b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.ts new file mode 100644 index 00000000..4dcd762d --- /dev/null +++ b/tests/1501-2000/1936. add-minimum-number-of-rungs/sol.ts @@ -0,0 +1,11 @@ +function addRungs(rungs: number[], dist: number): number { + let curr = 0; + let res = 0; + for (const rung of rungs) { + if (rung - curr > dist) { + res += Math.floor((rung - curr - 1) / dist); + } + curr = rung; + } + return res; +} diff --git a/tests/1501-2000/1937. maximum-number-of-points-with-cost/manifest.yaml b/tests/1501-2000/1937. maximum-number-of-points-with-cost/manifest.yaml new file mode 100644 index 00000000..9b02c900 --- /dev/null +++ b/tests/1501-2000/1937. maximum-number-of-points-with-cost/manifest.yaml @@ -0,0 +1,356 @@ +entry: + id: 1937 + title: "maximum-number-of-points-with-cost" + params: + points: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().maxPoints({points})" + rust: "Solution::max_points({points})" + python3: "Solution().maxPoints({points})" + python2: "Solution().maxPoints({points})" + ruby: "max_points({points})" + java: "new Solution().maxPoints({points})" + csharp: "new Solution().MaxPoints({points})" + kotlin: "Solution().maxPoints({points})" + go: "maxPoints({points})" + dart: "Solution().maxPoints({points})" + swift: "Solution().maxPoints({points})" + typescript: "maxPoints({points})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().maxPoints(points, {result})" + checker: | + class Checker: + def maxPoints(self, points, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not points or not points[0]: + return False + dp = list(points[0]) + for row in points[1:]: + left = [0] * len(dp) + right = [0] * len(dp) + left[0] = dp[0] + for c in range(1, len(dp)): + left[c] = max(left[c - 1], dp[c] + c) + right[-1] = dp[-1] - len(dp) + 1 + for c in range(len(dp) - 2, -1, -1): + right[c] = max(right[c + 1], dp[c] - c) + dp = [row[c] + max(left[c] - c, right[c] + c) for c in range(len(dp))] + return result == max(dp) + +seed: 1937 + +tests: + - name: "single_cell" + in: + points: + elemType: "int" + value: + - [5] + out: 5 + - name: "single_row_zeroes" + in: + points: + elemType: "int" + value: + - [0, 0, 0] + out: 0 + - name: "single_row_increasing" + in: + points: + elemType: "int" + value: + - [1, 2, 3] + out: 3 + - name: "single_row_decreasing" + in: + points: + elemType: "int" + value: + - [3, 2, 1] + out: 3 + - name: "one_column_growth" + in: + points: + elemType: "int" + value: + - [1] + - [2] + - [3] + out: 6 + - name: "one_column_jump" + in: + points: + elemType: "int" + value: + - [5] + - [0] + - [10] + out: 15 + - name: "example_two" + in: + points: + elemType: "int" + value: + - [1, 5] + - [2, 3] + - [4, 2] + out: 11 + - name: "example_one" + in: + points: + elemType: "int" + value: + - [1, 2, 3] + - [1, 5, 1] + - [3, 1, 1] + out: 9 + - name: "all_zero_two_by_two" + in: + points: + elemType: "int" + value: + - [0, 0] + - [0, 0] + out: 0 + - name: "opposite_corners" + in: + points: + elemType: "int" + value: + - [9, 0] + - [0, 9] + out: 17 + - name: "center_peak_first" + in: + points: + elemType: "int" + value: + - [10, 1, 1] + - [1, 10, 1] + out: 19 + - name: "center_peak_second" + in: + points: + elemType: "int" + value: + - [1, 10, 1] + - [1, 1, 10] + out: 19 + - name: "constant_rows" + in: + points: + elemType: "int" + value: + - [7, 7, 7] + - [7, 7, 7] + out: 14 + - name: "alternating_peaks" + in: + points: + elemType: "int" + value: + - [0, 5, 0] + - [5, 0, 5] + out: 9 + - name: "three_rows_mixed" + in: + points: + elemType: "int" + value: + - [2, 0, 4] + - [1, 3, 2] + - [5, 1, 0] + out: 10 + - name: "wide_two_rows" + in: + points: + elemType: "int" + value: + - [8, 1, 6, 2] + - [3, 9, 0, 4] + out: 16 + - name: "wide_three_rows" + in: + points: + elemType: "int" + value: + - [1, 4, 2, 8] + - [7, 0, 5, 3] + - [2, 9, 1, 6] + out: 20 + - name: "maximum_values_two_columns" + in: + points: + elemType: "int" + value: + - [100000, 0] + - [0, 100000] + out: 199999 + - name: "maximum_single_row" + in: + points: + elemType: "int" + value: + - [0, 100000, 0] + out: 100000 + - name: "maximum_constant" + in: + points: + elemType: "int" + value: + - [100000, 100000] + - [100000, 100000] + out: 200000 + - name: "four_rows_three_columns" + in: + points: + elemType: "int" + value: + - [4, 1, 7] + - [2, 8, 3] + - [9, 0, 6] + - [1, 5, 2] + out: 26 + - name: "reversed_two_rows" + in: + points: + elemType: "int" + value: + - [0, 1, 2, 3, 4] + - [4, 3, 2, 1, 0] + out: 4 + - name: "three_diagonal_peaks" + in: + points: + elemType: "int" + value: + - [5, 0, 0, 0, 5] + - [0, 5, 0, 5, 0] + - [0, 0, 5, 0, 0] + out: 13 + - name: "four_rows_two_columns" + in: + points: + elemType: "int" + value: + - [1, 3] + - [2, 4] + - [5, 0] + - [6, 1] + out: 17 + - name: "descending_rows" + in: + points: + elemType: "int" + value: + - [9, 8, 7] + - [6, 5, 4] + - [3, 2, 1] + out: 18 + - name: "identity_peaks" + in: + points: + elemType: "int" + value: + - [1, 0, 0] + - [0, 1, 0] + - [0, 0, 1] + out: 1 + - name: "constant_wide_rows" + in: + points: + elemType: "int" + value: + - [2, 2, 2, 2] + - [1, 1, 1, 1] + - [3, 3, 3, 3] + out: 6 + - name: "right_diagonal" + in: + points: + elemType: "int" + value: + - [0, 9, 0, 0] + - [0, 0, 9, 0] + - [0, 0, 0, 9] + out: 25 + - name: "wide_two_rows_mixed" + in: + points: + elemType: "int" + value: + - [6, 1, 4, 2, 8] + - [0, 7, 3, 9, 1] + out: 16 + - name: "four_rows_three_columns_alt" + in: + points: + elemType: "int" + value: + - [3, 0, 8] + - [5, 2, 1] + - [4, 9, 0] + - [7, 1, 6] + out: 25 + - name: "large_values_small_matrix" + in: + points: + elemType: "int" + value: + - [11, 12, 13] + - [14, 15, 16] + out: 29 + - name: "separated_large_peaks" + in: + points: + elemType: "int" + value: + - [20, 0, 0, 0] + - [0, 0, 0, 20] + - [0, 0, 20, 0] + out: 56 + - name: "exponential_values" + in: + points: + elemType: "int" + value: + - [1, 2, 4, 8] + - [16, 8, 4, 2] + - [3, 6, 12, 24] + out: 42 + - name: "three_large_diagonal_peaks" + in: + points: + elemType: "int" + value: + - [0, 0, 0] + - [100, 0, 0] + - [0, 100, 0] + - [0, 0, 100] + out: 298 + - name: "five_rows_mixed" + in: + points: + elemType: "int" + value: + - [7, 2, 9, 1] + - [4, 8, 0, 6] + - [3, 5, 11, 2] + - [10, 1, 4, 7] + - [0, 6, 3, 9] + out: 41 diff --git a/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.cpp b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.cpp new file mode 100644 index 00000000..0e8237f9 --- /dev/null +++ b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + long long maxPoints(vector>& points) { + int m = points.size(); + int n = points[0].size(); + + vector dp(points[0].begin(), points[0].end()); + + for (int r = 1; r < m; r++) { + vector left(n, 0); + vector right(n, 0); + + left[0] = dp[0]; + for (int c = 1; c < n; c++) { + left[c] = max(left[c-1], dp[c] + c); + } + + right[n-1] = dp[n-1] - (n-1); + for (int c = n-2; c >= 0; c--) { + right[c] = max(right[c+1], dp[c] - c); + } + + vector new_dp(n, 0); + for (int c = 0; c < n; c++) { + long long best = max(left[c] - c, right[c] + c); + new_dp[c] = points[r][c] + best; + } + dp = new_dp; + } + + return *max_element(dp.begin(), dp.end()); + } +}; diff --git a/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.cs b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.cs new file mode 100644 index 00000000..8cb1cbc4 --- /dev/null +++ b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.cs @@ -0,0 +1,33 @@ +public class Solution { + public long MaxPoints(int[][] points) { + int m = points.Length; + int n = points[0].Length; + + long[] dp = new long[n]; + for (int i = 0; i < n; i++) dp[i] = points[0][i]; + + for (int r = 1; r < m; r++) { + long[] left = new long[n]; + long[] right = new long[n]; + + left[0] = dp[0]; + for (int c = 1; c < n; c++) { + left[c] = Math.Max(left[c-1], dp[c] + c); + } + + right[n-1] = dp[n-1] - (n-1); + for (int c = n-2; c >= 0; c--) { + right[c] = Math.Max(right[c+1], dp[c] - c); + } + + long[] newDp = new long[n]; + for (int c = 0; c < n; c++) { + long best = Math.Max(left[c] - c, right[c] + c); + newDp[c] = points[r][c] + best; + } + dp = newDp; + } + + return dp.Max(); + } +} diff --git a/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.dart b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.dart new file mode 100644 index 00000000..fd342fe2 --- /dev/null +++ b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.dart @@ -0,0 +1,36 @@ +class Solution { + int maxPoints(List> points) { + int m = points.length; + int n = points[0].length; + + List dp = List.from(points[0]); + + for (int r = 1; r < m; r++) { + List left = List.filled(n, 0); + List right = List.filled(n, 0); + + left[0] = dp[0]; + for (int c = 1; c < n; c++) { + left[c] = max(left[c-1], dp[c] + c); + } + + right[n-1] = dp[n-1] - (n-1); + for (int c = n-2; c >= 0; c--) { + right[c] = max(right[c+1], dp[c] - c); + } + + List newDp = List.filled(n, 0); + for (int c = 0; c < n; c++) { + int best = max(left[c] - c, right[c] + c); + newDp[c] = points[r][c] + best; + } + dp = newDp; + } + + int maxVal = dp[0]; + for (int v in dp) { + if (v > maxVal) maxVal = v; + } + return maxVal; + } +} diff --git a/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.go b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.go new file mode 100644 index 00000000..c1ae048c --- /dev/null +++ b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.go @@ -0,0 +1,46 @@ +func maxPoints(points [][]int) int64 { + m := len(points) + n := len(points[0]) + + dp := make([]int64, n) + for i := 0; i < n; i++ { + dp[i] = int64(points[0][i]) + } + + for r := 1; r < m; r++ { + left := make([]int64, n) + right := make([]int64, n) + + left[0] = dp[0] + for c := 1; c < n; c++ { + left[c] = maxInt64(left[c-1], dp[c] + int64(c)) + } + + right[n-1] = dp[n-1] - int64(n-1) + for c := n-2; c >= 0; c-- { + right[c] = maxInt64(right[c+1], dp[c] - int64(c)) + } + + newDp := make([]int64, n) + for c := 0; c < n; c++ { + best := maxInt64(left[c] - int64(c), right[c] + int64(c)) + newDp[c] = int64(points[r][c]) + best + } + dp = newDp + } + + maxVal := dp[0] + for _, v := range dp { + if v > maxVal { + maxVal = v + } + } + return maxVal +} + +func maxInt64(a, b int64) int64 { + if a > b { + return a + } + return b +} diff --git a/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.java b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.java new file mode 100644 index 00000000..101ab468 --- /dev/null +++ b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.java @@ -0,0 +1,35 @@ +class Solution { + public long maxPoints(int[][] points) { + int m = points.length; + int n = points[0].length; + + long[] dp = new long[n]; + for (int i = 0; i < n; i++) dp[i] = points[0][i]; + + for (int r = 1; r < m; r++) { + long[] left = new long[n]; + long[] right = new long[n]; + + left[0] = dp[0]; + for (int c = 1; c < n; c++) { + left[c] = Math.max(left[c-1], dp[c] + c); + } + + right[n-1] = dp[n-1] - (n-1); + for (int c = n-2; c >= 0; c--) { + right[c] = Math.max(right[c+1], dp[c] - c); + } + + long[] newDp = new long[n]; + for (int c = 0; c < n; c++) { + long best = Math.max(left[c] - c, right[c] + c); + newDp[c] = points[r][c] + best; + } + dp = newDp; + } + + long max = Long.MIN_VALUE; + for (long v : dp) max = Math.max(max, v); + return max; + } +} diff --git a/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.kt b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.kt new file mode 100644 index 00000000..585cd8e5 --- /dev/null +++ b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.kt @@ -0,0 +1,32 @@ +class Solution { + fun maxPoints(points: Array): Long { + val m = points.size + val n = points[0].size + + var dp = LongArray(n) { points[0][it].toLong() } + + for (r in 1 until m) { + val left = LongArray(n) + val right = LongArray(n) + + left[0] = dp[0] + for (c in 1 until n) { + left[c] = maxOf(left[c-1], dp[c] + c) + } + + right[n-1] = dp[n-1] - (n-1) + for (c in n-2 downTo 0) { + right[c] = maxOf(right[c+1], dp[c] - c) + } + + val newDp = LongArray(n) + for (c in 0 until n) { + val best = maxOf(left[c] - c, right[c] + c) + newDp[c] = points[r][c] + best + } + dp = newDp + } + + return dp.max()!! + } +} diff --git a/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.py b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.py new file mode 100644 index 00000000..405175b2 --- /dev/null +++ b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.py @@ -0,0 +1,29 @@ +class Solution: + def maxPoints(self, points: List[List[int]]) -> int: + m = len(points) + n = len(points[0]) + + dp = points[0][:] + + for r in range(1, m): + left = [0] * n + right = [0] * n + + left[0] = dp[0] + for c in range(1, n): + left[c] = max(left[c - 1], dp[c] + c) + + right[n - 1] = dp[n - 1] - (n - 1) + for c in range(n - 2, -1, -1): + right[c] = max(right[c + 1], dp[c] - c) + + new_dp = [0] * n + + for c in range(n): + best = max(left[c] - c, right[c] + c) + + new_dp[c] = points[r][c] + best + + dp = new_dp + + return max(dp) diff --git a/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.py2 b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.py2 new file mode 100644 index 00000000..c3cb4ced --- /dev/null +++ b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.py2 @@ -0,0 +1,30 @@ +class Solution(object): + def maxPoints(self, points): + """ + :type points: List[List[int]] + :rtype: int + """ + m = len(points) + n = len(points[0]) + + dp = points[0][:] + + for r in range(1, m): + left = [0] * n + right = [0] * n + + left[0] = dp[0] + for c in range(1, n): + left[c] = max(left[c-1], dp[c] + c) + + right[n-1] = dp[n-1] - (n-1) + for c in range(n-2, -1, -1): + right[c] = max(right[c+1], dp[c] - c) + + new_dp = [0] * n + for c in range(n): + best = max(left[c] - c, right[c] + c) + new_dp[c] = points[r][c] + best + dp = new_dp + + return max(dp) diff --git a/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.rb b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.rb new file mode 100644 index 00000000..4cc42ee0 --- /dev/null +++ b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.rb @@ -0,0 +1,32 @@ +# @param {Integer[][]} points +# @return {Integer} +def max_points(points) + m = points.length + n = points[0].length + + dp = points[0].dup + + (1...m).each do |r| + left = Array.new(n, 0) + right = Array.new(n, 0) + + left[0] = dp[0] + (1...n).each do |c| + left[c] = [left[c-1], dp[c] + c].max + end + + right[n-1] = dp[n-1] - (n-1) + (n-2).downto(0) do |c| + right[c] = [right[c+1], dp[c] - c].max + end + + new_dp = Array.new(n, 0) + (0...n).each do |c| + best = [left[c] - c, right[c] + c].max + new_dp[c] = points[r][c] + best + end + dp = new_dp + end + + dp.max +end diff --git a/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.rs b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.rs new file mode 100644 index 00000000..19ec4982 --- /dev/null +++ b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.rs @@ -0,0 +1,32 @@ +impl Solution { + pub fn max_points(points: Vec>) -> i64 { + let m = points.len(); + let n = points[0].len(); + + let mut dp: Vec = points[0].iter().map(|&x| x as i64).collect(); + + for r in 1..m { + let mut left = vec![0i64; n]; + let mut right = vec![0i64; n]; + + left[0] = dp[0]; + for c in 1..n { + left[c] = left[c-1].max(dp[c] + c as i64); + } + + right[n-1] = dp[n-1] - (n-1) as i64; + for c in (0..n-1).rev() { + right[c] = right[c+1].max(dp[c] - c as i64); + } + + let mut new_dp = vec![0i64; n]; + for c in 0..n { + let best = (left[c] - c as i64).max(right[c] + c as i64); + new_dp[c] = points[r][c] as i64 + best; + } + dp = new_dp; + } + + *dp.iter().max().unwrap() + } +} diff --git a/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.swift b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.swift new file mode 100644 index 00000000..b97a4abb --- /dev/null +++ b/tests/1501-2000/1937. maximum-number-of-points-with-cost/sol.swift @@ -0,0 +1,32 @@ +class Solution { + func maxPoints(_ points: [[Int]]) -> Int { + let m = points.count + let n = points[0].count + + var dp = points[0] + + for r in 1..= 0; c--) { + right[c] = Math.max(right[c + 1], dp[c] - c); + } + + const newDp = new Array(n).fill(0); + for (let c = 0; c < n; c++) { + const best = Math.max(left[c] - c, right[c] + c); + newDp[c] = points[r][c] + best; + } + dp = newDp; + } + + return Math.max(...dp); +} diff --git a/tests/1501-2000/1938. maximum-genetic-difference-query/manifest.yaml b/tests/1501-2000/1938. maximum-genetic-difference-query/manifest.yaml new file mode 100644 index 00000000..f0eb82a5 --- /dev/null +++ b/tests/1501-2000/1938. maximum-genetic-difference-query/manifest.yaml @@ -0,0 +1,816 @@ +entry: + id: 1938 + title: maximum-genetic-difference-query + params: + parents: + type: array + items: + type: int + queries: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().maxGeneticDifference({parents}, {queries})" + rust: "Solution::max_genetic_difference({parents}, {queries})" + python3: "Solution().maxGeneticDifference({parents}, {queries})" + python2: "Solution().maxGeneticDifference({parents}, {queries})" + ruby: "max_genetic_difference({parents}, {queries})" + java: "new Solution().maxGeneticDifference({parents}, {queries})" + csharp: "new Solution().MaxGeneticDifference({parents}, {queries})" + kotlin: "Solution().maxGeneticDifference({parents}, {queries})" + go: "maxGeneticDifference({parents}, {queries})" + dart: "Solution().maxGeneticDifference({parents}, {queries})" + swift: "Solution().maxGeneticDifference({parents}, {queries})" + typescript: "maxGeneticDifference({parents}, {queries})" + +judge: + type: exact + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().check(parents, queries, {result})" + checker: | + class Checker: + def check(self, parents, queries, result): + if not isinstance(result, list) or len(result) != len(queries): + return False + for i, q in enumerate(queries): + if not isinstance(q, list) or len(q) != 2: + return False + node, value = q + if not isinstance(node, int) or not isinstance(value, int): + return False + best = -1 + seen = set() + while node != -1 and node not in seen: + seen.add(node) + best = max(best, value ^ node) + if node < 0 or node >= len(parents): + return False + node = parents[node] + if node != -1 or result[i] != best: + return False + return True + +seed: 1938 + +tests: + - name: example-one + in: + parents: [-1, 0, 1, 1] + queries: [[0, 2], [3, 2], [2, 5]] + out: [2, 3, 7] + - name: example-two + in: + parents: [3, 7, -1, 2, 0, 7, 0, 2] + queries: [[4, 6], [1, 15], [0, 5]] + out: [6, 14, 7] + - name: root-only-queries + in: + parents: [-1, 0, 0, 0, 0] + queries: [[0, 0], [0, 1], [0, 31], [0, 200000]] + out: [0, 1, 31, 200000] + - name: star + in: + parents: [-1, 0, 0, 0, 0, 0, 0] + queries: [[1, 0], [2, 7], [3, 8], [4, 15], [5, 16], [6, 200000]] + out: [1, 7, 11, 15, 21, 200006] + - name: chain + in: + parents: [-1, 0, 1, 2, 3, 4, 5, 6] + queries: [[7, 0], [7, 1], [7, 7], [7, 8], [4, 31]] + out: [7, 7, 7, 15, 31] + - name: balanced + in: + parents: [-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6] + queries: [[7, 0], [8, 15], [9, 31], [10, 63], [13, 127], [14, 200000]] + out: [7, 15, 31, 63, 127, 200014] + - name: nonzero-root + in: + parents: [2, 0, -1, 2, 3, 3] + queries: [[2, 0], [0, 7], [4, 8], [5, 15]] + out: [2, 7, 12, 13] + - name: repeated-nodes + in: + parents: [-1, 0, 1, 1, 2, 2, 4] + queries: [[6, 3], [6, 3], [1, 3], [6, 1024], [0, 1024]] + out: [7, 7, 3, 1030, 1024] + - name: duplicate-values + in: + parents: [-1, 0, 0, 1, 1, 2, 2, 5] + queries: [[3, 4], [4, 4], [7, 4], [7, 5], [6, 6]] + out: [7, 5, 6, 7, 6] + - name: high-bits + in: + parents: [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8] + queries: [[9, 131071], [8, 131072], [7, 200000], [5, 65535]] + out: [131071, 131080, 200007, 65535] + - name: singleton-branches + in: + parents: [-1, 0, 0, 2, 2, 4, 4, 6, 6] + queries: [[1, 10], [3, 10], [5, 10], [7, 10], [8, 10]] + out: [11, 10, 15, 14, 14] + - name: alternating + in: + parents: [-1, 0, 1, 0, 3, 4, 3, 6, 7, 6] + queries: [[2, 12], [5, 12], [8, 12], [9, 12], [9, 12345]] + out: [14, 15, 15, 15, 12351] + - name: all-nodes + in: + parents: [-1, 0, 0, 1, 1, 2, 2, 3, 4, 5] + queries: + [ + [0, 9], + [1, 9], + [2, 9], + [3, 9], + [4, 9], + [5, 9], + [6, 9], + [7, 9], + [8, 9], + [9, 9], + ] + out: [9, 9, 11, 10, 13, 12, 15, 14, 13, 12] + - name: wide-values + in: + parents: [-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + queries: [[11, 1023], [10, 1024], [9, 65536], [8, 131071]] + out: [1023, 1034, 65545, 131071] + - name: deep-branch + in: + parents: + [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18] + queries: [[19, 0], [19, 123], [15, 999], [10, 4095]] + out: [19, 127, 1007, 4095] + - name: mixed-components-tree-shape + in: + parents: [4, 4, 5, 5, -1, 7, 7, 8, 9, 4] + queries: [[0, 3], [1, 17], [2, 31], [3, 63], [6, 127], [9, 200000]] + out: [7, 21, 29, 60, 123, 200009] + - name: powers-of-two + in: + parents: [-1, 0, 1, 2, 3, 4, 5, 6] + queries: [[7, 1], [7, 2], [7, 4], [7, 8], [7, 16], [7, 128]] + out: [7, 7, 7, 15, 23, 135] + - name: many-queries + in: + parents: [-1, 0, 0, 1, 1, 2, 2] + queries: + [ + [3, 0], + [3, 1], + [3, 2], + [3, 3], + [4, 4], + [4, 5], + [5, 6], + [5, 7], + [6, 8], + [6, 9], + ] + out: [3, 2, 3, 3, 5, 5, 6, 7, 14, 15] + - name: n-32-chain + in: + parents: + [ + -1, + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + ] + queries: [[31, 0], [31, 1], [31, 63], [30, 1024]] + out: [31, 31, 63, 1054] + - name: n-32-star + in: + parents: + [ + -1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + queries: [[31, 0], [30, 63], [29, 127], [28, 1024]] + out: [31, 63, 127, 1052] + - name: n-64-balanced + in: + parents: + [ + -1, + 0, + 0, + 1, + 1, + 2, + 2, + 3, + 3, + 4, + 4, + 5, + 5, + 6, + 6, + 7, + 7, + 8, + 8, + 9, + 9, + 10, + 10, + 11, + 11, + 12, + 12, + 13, + 13, + 14, + 14, + 15, + 15, + 16, + 16, + 17, + 17, + 18, + 18, + 19, + 19, + 20, + 20, + 21, + 21, + 22, + 22, + 23, + 23, + 24, + 24, + 25, + 25, + 26, + 26, + 27, + 27, + 28, + 28, + 29, + 29, + 30, + 30, + ] + queries: [[31, 0], [47, 123], [62, 200000], [40, 65535]] + out: [31, 126, 200062, 65535] + - name: sparse-high-node + in: + parents: + [10, 10, 11, 11, 12, 12, 13, 13, 14, 14, -1, 10, 11, 12, 10, 14, 15] + queries: [[0, 5], [2, 6], [4, 7], [6, 8], [8, 9], [16, 200000]] + - name: low-values + in: + parents: [-1, 0, 1, 1, 3, 3, 5, 5, 7] + queries: [[8, 0], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5]] + out: [8, 9, 10, 11, 12, 13] + - name: query-order + in: + parents: [-1, 0, 0, 1, 2, 3, 4] + queries: [[6, 20], [0, 20], [5, 20], [2, 20], [4, 20], [1, 20]] + out: [22, 20, 23, 22, 22, 21] + - name: values-at-limit + in: + parents: [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + queries: [[11, 200000], [10, 199999], [9, 131072], [8, 131071]] + out: [200011, 199999, 131081, 131071] + - name: forked-depth + in: + parents: [-1, 0, 0, 1, 1, 2, 2, 3, 5, 6, 6, 7, 8, 9, 10, 11] + queries: [[12, 42], [13, 43], [14, 44], [15, 45], [4, 46]] + out: [47, 45, 46, 46, 47] + - name: repeated-root-and-leaves + in: + parents: [-1, 0, 0, 1, 1, 2, 2, 3, 3] + queries: [[0, 77], [0, 77], [8, 77], [8, 77], [4, 77], [4, 77]] + out: [77, 77, 78, 78, 77, 77] + - name: zigzag-tree + in: + parents: [-1, 0, 0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14] + queries: [[15, 255], [14, 254], [13, 253], [12, 252]] + out: [255, 254, 253, 253] + - name: n-100-chain + in: + parents: + [ + -1, + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + 63, + 64, + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + ] + queries: [[99, 0], [99, 200000], [50, 131071]] + out: [99, 200063, 131071] + - name: branching-100 + in: + parents: + [ + -1, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 2, + 2, + 2, + 2, + 3, + 3, + 3, + 3, + 4, + 4, + 4, + 4, + 5, + 5, + 5, + 5, + 6, + 6, + 6, + 6, + 7, + 7, + 7, + 7, + 8, + 8, + 8, + 8, + 9, + 9, + 9, + 9, + 10, + 10, + 10, + 10, + 11, + 11, + 11, + 11, + 12, + 12, + 12, + 12, + 13, + 13, + 13, + 13, + 14, + 14, + 14, + 14, + 15, + 15, + 15, + 15, + 16, + 16, + 16, + 16, + 17, + 17, + 17, + 17, + 18, + 18, + 18, + 18, + 19, + 19, + 19, + 19, + 20, + 20, + 20, + 20, + 21, + 21, + 21, + 21, + 22, + 22, + 22, + 22, + 23, + 23, + 23, + 23, + ] + queries: [[24, 0], [48, 12345], [72, 200000], [96, 65535]] + out: [24, 12347, 200017, 65535] + - name: alternating-bits + in: + parents: [-1, 0, 1, 0, 3, 4, 3, 6, 7, 6, 9, 10, 9, 12, 13, 12] + queries: [[15, 43690], [14, 21845], [13, 13107], [12, 52428]] + out: [43692, 21852, 13119, 52431] + - name: max-nodes-values + in: + parents: [-1, 0, 0, 1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + queries: [[15, 200000], [14, 199000], [13, 198000], [12, 197000]] + out: [200015, 199006, 198013, 197004] + - name: repeated-query-bulk + in: + parents: [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8] + queries: + [ + [9, 0], + [9, 0], + [9, 0], + [9, 1], + [9, 1], + [9, 2], + [9, 3], + [9, 4], + [9, 5], + [9, 6], + [9, 7], + [9, 8], + [9, 9], + ] + out: [9, 9, 9, 9, 9, 11, 11, 13, 13, 15, 15, 15, 15] + - name: large-root-branch + in: + parents: [-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + queries: [[1, 200000], [2, 199999], [3, 131072], [4, 65536], [15, 32768]] + out: [200001, 199999, 131075, 65540, 32783] + - name: near-limit-node-count + in: + parents: + [ + -1, + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + 63, + 64, + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + 99, + 100, + 101, + 102, + 103, + 104, + 105, + 106, + 107, + 108, + 109, + 110, + 111, + 112, + 113, + 114, + 115, + 116, + 117, + 118, + 119, + 120, + 121, + 122, + 123, + 124, + 125, + 126, + 127, + 128, + 129, + 130, + 131, + 132, + 133, + 134, + 135, + 136, + 137, + 138, + 139, + 140, + 141, + 142, + 143, + 144, + 145, + 146, + 147, + 148, + 149, + 150, + 151, + 152, + 153, + 154, + 155, + 156, + 157, + 158, + 159, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 174, + 175, + 176, + 177, + 178, + 179, + 180, + 181, + 182, + 183, + 184, + 185, + 186, + 187, + 188, + 189, + 190, + 191, + 192, + 193, + 194, + 195, + 196, + 197, + 198, + 199, + ] + queries: [[199, 0], [199, 200000], [150, 131071]] + out: [199, 200191, 131071] diff --git a/tests/1501-2000/1938. maximum-genetic-difference-query/sol.cpp b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.cpp new file mode 100644 index 00000000..de458e64 --- /dev/null +++ b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.cpp @@ -0,0 +1,71 @@ +class Solution { +public: + vector maxGeneticDifference(vector& parents, vector>& queries) { + int n = parents.size(); + vector> adj(n); + int root = 0; + for (int i = 0; i < n; i++) { + if (parents[i] == -1) root = i; + else adj[parents[i]].push_back(i); + } + + // Trie node + struct Node { + int count; + unordered_map child; + Node() : count(0) {} + }; + + Node* trie = new Node(); + + auto increase = [&](int num, int delta) { + Node* cur = trie; + for (int i = 17; i >= 0; i--) { + int bit = (num >> i) & 1; + if (cur->child.find(bit) == cur->child.end()) { + cur->child[bit] = new Node(); + } + cur = cur->child[bit]; + cur->count += delta; + } + }; + + auto findMax = [&](int num) { + Node* cur = trie; + int ans = 0; + for (int i = 17; i >= 0; i--) { + int bit = (num >> i) & 1; + int desired = 1 - bit; + if (cur->child.find(desired) != cur->child.end() && cur->child[desired]->count > 0) { + cur = cur->child[desired]; + ans |= (1 << i); + } else { + cur = cur->child[bit]; + } + } + return ans; + }; + + // group queries by node + unordered_map>> qmap; + for (int i = 0; i < queries.size(); i++) { + qmap[queries[i][0]].push_back({i, queries[i][1]}); + } + + vector ans(queries.size(), 0); + + function dfs = [&](int u) { + increase(u, 1); + for (auto& p : qmap[u]) { + ans[p.first] = findMax(p.second); + } + for (int v : adj[u]) { + dfs(v); + } + increase(u, -1); + }; + + dfs(root); + return ans; + } +}; diff --git a/tests/1501-2000/1938. maximum-genetic-difference-query/sol.cs b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.cs new file mode 100644 index 00000000..8d1fdc2f --- /dev/null +++ b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.cs @@ -0,0 +1,72 @@ +public class Solution { + private class TrieNode { + public int count; + public Dictionary child = new Dictionary(); + } + + private class BitTrie { + public TrieNode root = new TrieNode(); + + public void Increase(int number, int d) { + TrieNode cur = root; + for (int i = 17; i >= 0; i--) { + int bit = (number >> i) & 1; + if (!cur.child.ContainsKey(bit)) cur.child[bit] = new TrieNode(); + cur = cur.child[bit]; + cur.count += d; + } + } + + public int FindMax(int number) { + TrieNode cur = root; + int ans = 0; + for (int i = 17; i >= 0; i--) { + int bit = (number >> i) & 1; + int desired = 1 - bit; + if (cur.child.ContainsKey(desired) && cur.child[desired].count > 0) { + cur = cur.child[desired]; + ans |= (1 << i); + } else { + cur = cur.child[bit]; + } + } + return ans; + } + } + + public int[] MaxGeneticDifference(int[] parents, int[][] queries) { + int n = parents.Length; + List> adj = new List>(); + for (int i = 0; i < n; i++) adj.Add(new List()); + int root = 0; + for (int i = 0; i < n; i++) { + if (parents[i] == -1) root = i; + else adj[parents[i]].Add(i); + } + + BitTrie trie = new BitTrie(); + Dictionary> qmap = new Dictionary>(); + for (int i = 0; i < queries.Length; i++) { + int node = queries[i][0]; + int val = queries[i][1]; + if (!qmap.ContainsKey(node)) qmap[node] = new List<(int, int)>(); + qmap[node].Add((i, val)); + } + + int[] ans = new int[queries.Length]; + + void Dfs(int u) { + trie.Increase(u, 1); + if (qmap.ContainsKey(u)) { + foreach (var (idx, val) in qmap[u]) { + ans[idx] = trie.FindMax(val); + } + } + foreach (int v in adj[u]) Dfs(v); + trie.Increase(u, -1); + } + + Dfs(root); + return ans; + } +} diff --git a/tests/1501-2000/1938. maximum-genetic-difference-query/sol.dart b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.dart new file mode 100644 index 00000000..9836ccdf --- /dev/null +++ b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.dart @@ -0,0 +1,67 @@ +class TrieNode1938 { + int count = 0; + Map child = {}; +} + +class BitTrie1938 { + TrieNode1938 root = TrieNode1938(); + + void increase(int number, int delta) { + TrieNode1938 cur = root; + for (int i = 17; i >= 0; i--) { + int bit = (number >> i) & 1; + cur.child.putIfAbsent(bit, () => TrieNode1938()); + cur = cur.child[bit]!; + cur.count += delta; + } + } + + int findMax(int number) { + TrieNode1938 cur = root; + int answer = 0; + for (int i = 17; i >= 0; i--) { + int bit = (number >> i) & 1; + int desired = 1 - bit; + if (cur.child.containsKey(desired) && cur.child[desired]!.count > 0) { + cur = cur.child[desired]!; + answer |= 1 << i; + } else { + cur = cur.child[bit]!; + } + } + return answer; + } +} + +class Solution { + List maxGeneticDifference(List parents, List> queries) { + int n = parents.length; + List> children = List.generate(n, (_) => []); + int root = 0; + for (int i = 0; i < n; i++) { + if (parents[i] == -1) { + root = i; + } else { + children[parents[i]].add(i); + } + } + BitTrie1938 trie = BitTrie1938(); + Map>> grouped = {}; + for (int i = 0; i < queries.length; i++) { + grouped.putIfAbsent(queries[i][0], () => >[]).add([i, queries[i][1]]); + } + List answer = List.filled(queries.length, 0); + void dfs(int node) { + trie.increase(node, 1); + for (List query in grouped[node] ?? >[]) { + answer[query[0]] = trie.findMax(query[1]); + } + for (int child in children[node]) { + dfs(child); + } + trie.increase(node, -1); + } + dfs(root); + return answer; + } +} diff --git a/tests/1501-2000/1938. maximum-genetic-difference-query/sol.go b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.go new file mode 100644 index 00000000..10b824b2 --- /dev/null +++ b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.go @@ -0,0 +1,79 @@ +func maxGeneticDifference(parents []int, queries [][]int) []int { + n := len(parents) + children := make([][]int, n) + root := 0 + for node, parent := range parents { + if parent == -1 { + root = node + } else { + children[parent] = append(children[parent], node) + } + } + + type query struct { + index int + value int + } + byNode := make([][]query, n) + for index, item := range queries { + byNode[item[0]] = append(byNode[item[0]], query{index, item[1]}) + } + + type trieNode struct { + next [2]int + count int + } + trie := []trieNode{{}} + update := func(value, delta int) { + current := 0 + trie[current].count += delta + for bit := 17; bit >= 0; bit-- { + digit := (value >> bit) & 1 + if trie[current].next[digit] == 0 { + trie = append(trie, trieNode{}) + trie[current].next[digit] = len(trie) - 1 + } + current = trie[current].next[digit] + trie[current].count += delta + } + } + maximumXor := func(value int) int { + current, result := 0, 0 + for bit := 17; bit >= 0; bit-- { + digit := (value >> bit) & 1 + preferred := trie[current].next[1-digit] + if preferred != 0 && trie[preferred].count > 0 { + result |= 1 << bit + current = preferred + } else { + current = trie[current].next[digit] + } + } + return result + } + + answer := make([]int, len(queries)) + type frame struct { + node int + leaving bool + } + stack := []frame{{node: root}} + for len(stack) > 0 { + last := len(stack) - 1 + current := stack[last] + stack = stack[:last] + if current.leaving { + update(current.node, -1) + continue + } + update(current.node, 1) + for _, item := range byNode[current.node] { + answer[item.index] = maximumXor(item.value) + } + stack = append(stack, frame{node: current.node, leaving: true}) + for index := len(children[current.node]) - 1; index >= 0; index-- { + stack = append(stack, frame{node: children[current.node][index]}) + } + } + return answer +} diff --git a/tests/1501-2000/1938. maximum-genetic-difference-query/sol.java b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.java new file mode 100644 index 00000000..8e73fb78 --- /dev/null +++ b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.java @@ -0,0 +1,73 @@ +import java.util.*; + +class Solution { + class TrieNode { + int count = 0; + Map child = new HashMap<>(); + } + + class BitTrie { + TrieNode root = new TrieNode(); + + void increase(int number, int d) { + TrieNode cur = root; + for (int i = 17; i >= 0; i--) { + int bit = (number >> i) & 1; + cur.child.computeIfAbsent(bit, k -> new TrieNode()); + cur = cur.child.get(bit); + cur.count += d; + } + } + + int findMax(int number) { + TrieNode cur = root; + int ans = 0; + for (int i = 17; i >= 0; i--) { + int bit = (number >> i) & 1; + int desired = 1 - bit; + if (cur.child.containsKey(desired) && cur.child.get(desired).count > 0) { + cur = cur.child.get(desired); + ans |= (1 << i); + } else { + cur = cur.child.get(bit); + } + } + return ans; + } + } + + public int[] maxGeneticDifference(int[] parents, int[][] queries) { + int n = parents.length; + List> adj = new ArrayList<>(); + for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); + int root = 0; + for (int i = 0; i < n; i++) { + if (parents[i] == -1) root = i; + else adj.get(parents[i]).add(i); + } + + BitTrie trie = new BitTrie(); + Map> qmap = new HashMap<>(); + for (int i = 0; i < queries.length; i++) { + qmap.computeIfAbsent(queries[i][0], k -> new ArrayList<>()).add(new int[]{i, queries[i][1]}); + } + + int[] ans = new int[queries.length]; + + dfs(root, adj, trie, qmap, ans); + return ans; + } + + private void dfs(int u, List> adj, BitTrie trie, Map> qmap, int[] ans) { + trie.increase(u, 1); + if (qmap.containsKey(u)) { + for (int[] p : qmap.get(u)) { + ans[p[0]] = trie.findMax(p[1]); + } + } + for (int v : adj.get(u)) { + dfs(v, adj, trie, qmap, ans); + } + trie.increase(u, -1); + } +} diff --git a/tests/1501-2000/1938. maximum-genetic-difference-query/sol.kt b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.kt new file mode 100644 index 00000000..cc80f5c1 --- /dev/null +++ b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.kt @@ -0,0 +1,66 @@ +class Solution { + class TrieNode { + var count: Int = 0 + var child: MutableMap = HashMap() + } + + class BitTrie { + var root = TrieNode() + + fun increase(number: Int, d: Int) { + var cur = root + for (i in 17 downTo 0) { + val bit = (number shr i) and 1 + if (!cur.child.containsKey(bit)) cur.child[bit] = TrieNode() + cur = cur.child[bit]!! + cur.count += d + } + } + + fun findMax(number: Int): Int { + var cur = root + var ans = 0 + for (i in 17 downTo 0) { + val bit = (number shr i) and 1 + val desired = 1 - bit + if (cur.child.containsKey(desired) && cur.child[desired]!!.count > 0) { + cur = cur.child[desired]!! + ans = ans or (1 shl i) + } else { + cur = cur.child[bit]!! + } + } + return ans + } + } + + fun maxGeneticDifference(parents: IntArray, queries: Array): IntArray { + val n = parents.size + val adj = Array(n) { mutableListOf() } + var root = 0 + for (i in 0 until n) { + if (parents[i] == -1) root = i + else adj[parents[i]].add(i) + } + + val trie = BitTrie() + val qmap = HashMap>>() + queries.forEachIndexed { idx, q -> + qmap.getOrPut(q[0]) { mutableListOf() }.add(idx to q[1]) + } + + val ans = IntArray(queries.size) + + fun dfs(u: Int) { + trie.increase(u, 1) + qmap[u]?.forEach { (idx, value) -> + ans[idx] = trie.findMax(value) + } + for (v in adj[u]) dfs(v) + trie.increase(u, -1) + } + + dfs(root) + return ans + } +} diff --git a/tests/1501-2000/1938. maximum-genetic-difference-query/sol.py b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.py new file mode 100644 index 00000000..c8db0337 --- /dev/null +++ b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.py @@ -0,0 +1,80 @@ +class BitTrieNode: + def __init__(self): + self.count = 0 + self.child = {} + + +class BitTrie: + def __init__(self): + self.root = BitTrieNode() + + def increase(self, number, d): + cur = self.root + for i in range(17, -1, -1): + bit = (number >> i) & 1 + + if bit not in cur.child: + cur.child[bit] = BitTrieNode() + + cur = cur.child[bit] + cur.count += d + + def findMax(self, number): + + cur, ans = self.root, 0 + for i in range(17, -1, -1): + bit = (number >> i) & 1 + + if (1 - bit) in cur.child and cur.child[1 - bit].count > 0: + cur = cur.child[1 - bit] + ans |= 1 << i + + # elif bit in cur.child and cur.child[bit].count > 0: + # cur = cur.child[bit] + else: + cur = cur.child[bit] + + # else: + # return ans + + return ans + + +class Solution: + def maxGeneticDifference( + self, parents: List[int], queries: List[List[int]] + ) -> List[int]: + qs = queries + + lookup = defaultdict(list) + + T = BitTrie() + + start = 0 + + queries = defaultdict(list) + + for u, v in enumerate(parents): + lookup[v].append(u) + if v == -1: + start = u + + for index, (node, val) in enumerate(qs): + queries[node].append((index, val)) + + ans = [None] * len(qs) + + def dfs(u): + T.increase(u, 1) + + for index, val in queries[u]: + ans[index] = T.findMax(val) + + for v in lookup[u]: + dfs(v) + + T.increase(u, -1) + + dfs(start) + + return ans diff --git a/tests/1501-2000/1938. maximum-genetic-difference-query/sol.py2 b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.py2 new file mode 100644 index 00000000..4136073b --- /dev/null +++ b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.py2 @@ -0,0 +1,63 @@ +class Solution(object): + def maxGeneticDifference(self, parents, queries): + """ + :type parents: List[int] + :type queries: List[List[int]] + :rtype: List[int] + """ + class BitTrieNode: + def __init__(self): + self.count = 0 + self.child = {} + + class BitTrie: + def __init__(self): + self.root = BitTrieNode() + + def increase(self, number, d): + cur = self.root + for i in range(17, -1, -1): + bit = (number >> i) & 1 + if bit not in cur.child: + cur.child[bit] = BitTrieNode() + cur = cur.child[bit] + cur.count += d + + def findMax(self, number): + cur, ans = self.root, 0 + for i in range(17, -1, -1): + bit = (number >> i) & 1 + if (1 - bit) in cur.child and cur.child[1 - bit].count > 0: + cur = cur.child[1 - bit] + ans |= (1 << i) + else: + cur = cur.child[bit] + return ans + + n = len(parents) + adj = [[] for _ in range(n)] + root = 0 + for i, p in enumerate(parents): + if p == -1: + root = i + else: + adj[p].append(i) + + trie = BitTrie() + qmap = {} + for i, (node, val) in enumerate(queries): + qmap.setdefault(node, []).append((i, val)) + + ans = [0] * len(queries) + + def dfs(u): + trie.increase(u, 1) + if u in qmap: + for idx, val in qmap[u]: + ans[idx] = trie.findMax(val) + for v in adj[u]: + dfs(v) + trie.increase(u, -1) + + dfs(root) + return ans diff --git a/tests/1501-2000/1938. maximum-genetic-difference-query/sol.rb b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.rb new file mode 100644 index 00000000..244f8df3 --- /dev/null +++ b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.rb @@ -0,0 +1,72 @@ +class BitTrieNode1938 + attr_accessor :count, :child + def initialize + @count = 0 + @child = {} + end +end + +class BitTrie1938 + def initialize + @root = BitTrieNode1938.new + end + + def increase(number, d) + cur = @root + 17.downto(0) do |i| + bit = (number >> i) & 1 + cur.child[bit] ||= BitTrieNode1938.new + cur = cur.child[bit] + cur.count += d + end + end + + def find_max(number) + cur, ans = @root, 0 + 17.downto(0) do |i| + bit = (number >> i) & 1 + desired = 1 - bit + if cur.child.key?(desired) && cur.child[desired].count > 0 + cur = cur.child[desired] + ans |= (1 << i) + else + cur = cur.child[bit] + end + end + ans + end +end + +def max_genetic_difference(parents, queries) + + n = parents.length + adj = Array.new(n) { [] } + root = 0 + parents.each_with_index do |p, i| + if p == -1 + root = i + else + adj[p] << i + end + end + + trie = BitTrie1938.new + qmap = Hash.new { |h, k| h[k] = [] } + queries.each_with_index do |(node, val), idx| + qmap[node] << [idx, val] + end + + ans = Array.new(queries.length, 0) + + dfs = lambda do |u| + trie.increase(u, 1) + qmap[u].each do |idx, val| + ans[idx] = trie.find_max(val) + end if qmap.key?(u) + adj[u].each { |v| dfs.call(v) } + trie.increase(u, -1) + end + + dfs.call(root) + ans +end diff --git a/tests/1501-2000/1938. maximum-genetic-difference-query/sol.rs b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.rs new file mode 100644 index 00000000..9af2ad71 --- /dev/null +++ b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.rs @@ -0,0 +1,94 @@ +use std::collections::HashMap; + +struct TrieNode { + count: i32, + child: HashMap, +} + +struct Trie { + nodes: Vec, +} + +impl Trie { + fn new() -> Self { + Trie { nodes: vec![TrieNode { count: 0, child: HashMap::new() }] } + } + + fn increase(&mut self, num: i32, delta: i32) { + let mut cur = 0; + for i in (0..=17).rev() { + let bit = (num >> i) & 1; + let next = { + let node = &self.nodes[cur]; + if let Some(&n) = node.child.get(&bit) { + n + } else { + let new_node = TrieNode { count: 0, child: HashMap::new() }; + self.nodes.push(new_node); + let idx = self.nodes.len() - 1; + self.nodes[cur].child.insert(bit, idx); + idx + } + }; + cur = next; + self.nodes[cur].count += delta; + } + } + + fn find_max(&self, num: i32) -> i32 { + let mut cur = 0; + let mut ans = 0; + for i in (0..=17).rev() { + let bit = (num >> i) & 1; + let desired = 1 - bit; + if let Some(&n) = self.nodes[cur].child.get(&desired) { + if self.nodes[n].count > 0 { + cur = n; + ans |= (1 << i); + continue; + } + } + cur = self.nodes[cur].child[&bit]; + } + ans + } +} + +impl Solution { + pub fn max_genetic_difference(parents: Vec, queries: Vec>) -> Vec { + let n = parents.len(); + let mut adj = vec![Vec::new(); n]; + let mut root = 0; + for i in 0..n { + if parents[i] == -1 { + root = i; + } else { + adj[parents[i] as usize].push(i); + } + } + + let mut trie = Trie::new(); + let mut qmap: HashMap> = HashMap::new(); + for (i, q) in queries.iter().enumerate() { + qmap.entry(q[0]).or_insert(Vec::new()).push((i, q[1])); + } + + let mut ans = vec![0; queries.len()]; + + fn dfs(u: usize, adj: &Vec>, trie: &mut Trie, qmap: &HashMap>, ans: &mut Vec) { + trie.increase(u as i32, 1); + if let Some(queries) = qmap.get(&(u as i32)) { + for &(idx, val) in queries { + ans[idx] = trie.find_max(val); + } + } + for &v in &adj[u] { + dfs(v, adj, trie, qmap, ans); + } + trie.increase(u as i32, -1); + } + + dfs(root, &adj, &mut trie, &qmap, &mut ans); + ans + } +} diff --git a/tests/1501-2000/1938. maximum-genetic-difference-query/sol.swift b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.swift new file mode 100644 index 00000000..0fb5b4d9 --- /dev/null +++ b/tests/1501-2000/1938. maximum-genetic-difference-query/sol.swift @@ -0,0 +1,75 @@ +class Solution { + func maxGeneticDifference(_ parents: [Int], _ queries: [[Int]]) -> [Int] { + class TrieNode { + var count: Int = 0 + var child: [Int: TrieNode] = [:] + } + + class BitTrie { + var root = TrieNode() + + func increase(_ number: Int, _ d: Int) { + var cur = root + for i in stride(from: 17, through: 0, by: -1) { + let bit = (number >> i) & 1 + if cur.child[bit] == nil { + cur.child[bit] = TrieNode() + } + cur = cur.child[bit]! + cur.count += d + } + } + + func findMax(_ number: Int) -> Int { + var cur = root + var ans = 0 + for i in stride(from: 17, through: 0, by: -1) { + let bit = (number >> i) & 1 + let desired = 1 - bit + if let nxt = cur.child[desired], nxt.count > 0 { + cur = nxt + ans |= (1 << i) + } else { + cur = cur.child[bit]! + } + } + return ans + } + } + + let n = parents.count + var adj = Array(repeating: [Int](), count: n) + var root = 0 + for i in 0.. = new Map(); + } + + class BitTrie { + root: TrieNode = new TrieNode(); + + increase(number: number, d: number): void { + let cur = this.root; + for (let i = 17; i >= 0; i--) { + const bit = (number >> i) & 1; + if (!cur.child.has(bit)) cur.child.set(bit, new TrieNode()); + cur = cur.child.get(bit)!; + cur.count += d; + } + } + + findMax(number: number): number { + let cur = this.root; + let ans = 0; + for (let i = 17; i >= 0; i--) { + const bit = (number >> i) & 1; + const desired = 1 - bit; + if (cur.child.has(desired) && cur.child.get(desired)!.count > 0) { + cur = cur.child.get(desired)!; + ans |= 1 << i; + } else { + cur = cur.child.get(bit)!; + } + } + return ans; + } + } + + const n = parents.length; + const adj: number[][] = Array.from({ length: n }, () => []); + let root = 0; + parents.forEach((p, i) => { + if (p === -1) root = i; + else adj[p].push(i); + }); + + const trie = new BitTrie(); + const qmap = new Map(); + queries.forEach((q, i) => { + if (!qmap.has(q[0])) qmap.set(q[0], []); + qmap.get(q[0])!.push([i, q[1]]); + }); + + const ans: number[] = new Array(queries.length).fill(0); + + const dfs = (u: number) => { + trie.increase(u, 1); + if (qmap.has(u)) { + for (const [idx, val] of qmap.get(u)!) { + ans[idx] = trie.findMax(val); + } + } + for (const v of adj[u]) dfs(v); + trie.increase(u, -1); + }; + + dfs(root); + return ans; +} diff --git a/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/manifest.yaml b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/manifest.yaml new file mode 100644 index 00000000..b677512b --- /dev/null +++ b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/manifest.yaml @@ -0,0 +1,220 @@ +entry: + id: 1941 + title: "check-if-all-characters-have-equal-number-of-occurrences" + params: + s: + type: string + call: + cpp: "Solution().areOccurrencesEqual({s})" + rust: "Solution::are_occurrences_equal({s})" + python3: "Solution().areOccurrencesEqual({s})" + python2: "Solution().areOccurrencesEqual({s})" + ruby: "are_occurrences_equal({s})" + java: "new Solution().areOccurrencesEqual({s})" + csharp: "new Solution().AreOccurrencesEqual({s})" + kotlin: "Solution().areOccurrencesEqual({s})" + go: "areOccurrencesEqual({s})" + dart: "Solution().areOccurrencesEqual({s})" + swift: "Solution().areOccurrencesEqual({s})" + typescript: "areOccurrencesEqual({s})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().areOccurrencesEqual(s, {result})" + checker: | + from collections import Counter + + class Checker: + def areOccurrencesEqual(self, s, result): + if not isinstance(result, bool): + return False + counts = Counter(s).values() + expected = len(set(counts)) == 1 + return result == expected + +seed: 1941 + +tests: + - name: "example_balanced_three_chars" + in: + s: "abacbc" + out: true + - name: "example_unbalanced" + in: + s: "aaabb" + out: false + - name: "single_character" + in: + s: "z" + out: true + - name: "two_equal" + in: + s: "aa" + out: true + - name: "two_different" + in: + s: "ab" + out: true + - name: "three_distinct" + in: + s: "abc" + out: true + - name: "one_repeated_one_single" + in: + s: "aab" + out: false + - name: "three_equal_pairs" + in: + s: "aabbcc" + out: true + - name: "three_counts_two_three" + in: + s: "aabbbcc" + out: false + - name: "four_equal" + in: + s: "aaaabbbbccccdddd" + out: true + - name: "four_mixed" + in: + s: "aaaabbbbcccd" + out: false + - name: "alternating_two" + in: + s: "abababab" + out: true + - name: "alternating_three" + in: + s: "abcabcabc" + out: true + - name: "dominant_first" + in: + s: "aaaaabc" + out: false + - name: "all_same_long" + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaa" + out: true + - name: "case_single_extra" + in: + s: "aabbcccd" + out: false + - name: "letters_at_alphabet_edges" + in: + s: "aazz" + out: true + - name: "sparse_letters_equal" + in: + s: "azazbyby" + out: true + - name: "sparse_letters_unequal" + in: + s: "azazb" + out: false + - name: "frequency_one_with_many" + in: + s: "abcdefghijk" + out: true + - name: "frequency_one_with_duplicate" + in: + s: "abcdefghijklma" + out: false + - name: "seven_equal_blocks" + in: + s: "aaaaaaabbbbbbbcccccccdddddddeeeeeeefffffffggggggg" + out: true + - name: "seven_blocks_one_short" + in: + s: "aaaaaaabbbbbbbcccccccdddddddeeeeeeefffffffgggggg" + out: false + - name: "reordered_equal_blocks" + in: + s: "ccbbbaaaddd" + out: false + - name: "reordered_unequal_blocks" + in: + s: "ccbbbaaaddd" + out: false + - name: "twenty_six_once" + in: + s: "abcdefghijklmnopqrstuvwxyz" + out: true + - name: "twenty_six_with_extra" + in: + s: "abcdefghijklmnopqrstuvwxyza" + out: false + - name: "maximal_equal_fourty" + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + out: true + - name: "maximal_unequal_fourty" + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + out: false + - name: "three_chars_count_ten" + in: + s: "aaaaaaaaaabbbbbbbbbbcccccccccc" + out: true + - name: "three_chars_count_ten_minus_one" + in: + s: "aaaaaaaaaabbbbbbbbbbccccccccc" + out: false + - name: "mixed_runs_balanced" + in: + s: "abcddcba" + out: true + - name: "mixed_runs_unbalanced" + in: + s: "abcddcbaa" + out: false + - name: "gen_small" + seed: 194101 + in: + s: + gen: "str" + len: + gen: "int" + min: 1 + max: 20 + alphabet: "abcde" + - name: "gen_medium" + seed: 194102 + in: + s: + gen: "str" + len: + gen: "int" + min: 50 + max: 200 + alphabet: "abcdefgh" + - name: "gen_large" + seed: 194103 + in: + s: + gen: "str" + len: + gen: "int" + min: 500 + max: 1000 + alphabet: "abcdefghij" + - name: "gen_binary_stress" + seed: 194104 + in: + s: + gen: "str" + len: 1000 + alphabet: "ab" + - name: "gen_full_alphabet_stress" + seed: 194105 + in: + s: + gen: "str" + len: 1000 + alphabet: "abcdefghijklmnopqrstuvwxyz" diff --git a/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.cpp b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.cpp new file mode 100644 index 00000000..fde7e6e1 --- /dev/null +++ b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + bool areOccurrencesEqual(string s) { + unordered_map freq; + for (char c : s) { + freq[c]++; + } + unordered_set vals; + for (auto& [k, v] : freq) { + vals.insert(v); + } + return vals.size() == 1; + } +}; diff --git a/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.cs b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.cs new file mode 100644 index 00000000..833eb23c --- /dev/null +++ b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.cs @@ -0,0 +1,9 @@ +public class Solution { + public bool AreOccurrencesEqual(string s) { + var freq = new Dictionary(); + foreach (char c in s) { + freq[c] = freq.GetValueOrDefault(c) + 1; + } + return freq.Values.ToHashSet().Count == 1; + } +} diff --git a/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.dart b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.dart new file mode 100644 index 00000000..638e0189 --- /dev/null +++ b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.dart @@ -0,0 +1,10 @@ +class Solution { + bool areOccurrencesEqual(String s) { + Map map = {}; + for (int i = 0; i < s.length; i++) { + String c = s[i]; + map[c] = (map[c] ?? 0) + 1; + } + return map.values.toSet().length == 1; + } +} diff --git a/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.go b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.go new file mode 100644 index 00000000..41d218d1 --- /dev/null +++ b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.go @@ -0,0 +1,11 @@ +func areOccurrencesEqual(s string) bool { + m := make(map[rune]int) + for _, c := range s { + m[c]++ + } + vals := make(map[int]bool) + for _, v := range m { + vals[v] = true + } + return len(vals) == 1 +} diff --git a/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.java b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.java new file mode 100644 index 00000000..9bafa3b9 --- /dev/null +++ b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.java @@ -0,0 +1,9 @@ +class Solution { + public boolean areOccurrencesEqual(String s) { + Map map = new HashMap<>(); + for (char c : s.toCharArray()) { + map.put(c, map.getOrDefault(c, 0) + 1); + } + return new HashSet<>(map.values()).size() == 1; + } +} diff --git a/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.kt b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.kt new file mode 100644 index 00000000..53edbb27 --- /dev/null +++ b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.kt @@ -0,0 +1,9 @@ +class Solution { + fun areOccurrencesEqual(s: String): Boolean { + val map = mutableMapOf() + for (c in s) { + map[c] = map.getOrDefault(c, 0) + 1 + } + return map.values.toSet().size == 1 + } +} diff --git a/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.py b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.py new file mode 100644 index 00000000..c642a02c --- /dev/null +++ b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.py @@ -0,0 +1,10 @@ +class Solution: + def areOccurrencesEqual(self, s: str) -> bool: + d = {} + for i in s: + if i in d: + d[i] += 1 + else: + d[i] = 1 + all_vals = d.values() + return len(set(all_vals)) == 1 diff --git a/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.py2 b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.py2 new file mode 100644 index 00000000..9574011b --- /dev/null +++ b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.py2 @@ -0,0 +1,10 @@ +class Solution(object): + def areOccurrencesEqual(self, s): + """ + :type s: str + :rtype: bool + """ + d = {} + for c in s: + d[c] = d.get(c, 0) + 1 + return len(set(d.values())) == 1 diff --git a/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.rb b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.rb new file mode 100644 index 00000000..e9ef7c13 --- /dev/null +++ b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.rb @@ -0,0 +1,7 @@ +# @param {String} s +# @return {Boolean} +def are_occurrences_equal(s) + d = Hash.new(0) + s.each_char { |c| d[c] += 1 } + d.values.uniq.length == 1 +end diff --git a/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.rs b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.rs new file mode 100644 index 00000000..5e8e97d3 --- /dev/null +++ b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn are_occurrences_equal(s: String) -> bool { + let mut map = std::collections::HashMap::new(); + for c in s.chars() { + *map.entry(c).or_insert(0) += 1; + } + let mut unique_vals = std::collections::HashSet::new(); + for v in map.values() { + unique_vals.insert(*v); + } + unique_vals.len() == 1 + } +} diff --git a/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.swift b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.swift new file mode 100644 index 00000000..7b755c3f --- /dev/null +++ b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.swift @@ -0,0 +1,9 @@ +class Solution { + func areOccurrencesEqual(_ s: String) -> Bool { + var dict = [Character: Int]() + for c in s { + dict[c, default: 0] += 1 + } + return Set(dict.values).count == 1 + } +} diff --git a/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.ts b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.ts new file mode 100644 index 00000000..9ce10db8 --- /dev/null +++ b/tests/1501-2000/1941. check-if-all-characters-have-equal-number-of-occurrences/sol.ts @@ -0,0 +1,7 @@ +function areOccurrencesEqual(s: string): boolean { + const map = new Map(); + for (const c of s) { + map.set(c, (map.get(c) || 0) + 1); + } + return new Set(map.values()).size === 1; +} diff --git a/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/manifest.yaml b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/manifest.yaml new file mode 100644 index 00000000..8eca6d3e --- /dev/null +++ b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/manifest.yaml @@ -0,0 +1,236 @@ +entry: + id: 1942 + title: the-number-of-the-smallest-unoccupied-chair + params: + times: + type: array + items: + type: array + items: + type: int + targetFriend: + type: int + call: + cpp: "Solution().smallestChair({times}, {targetFriend})" + rust: "Solution::smallest_chair({times}, {targetFriend})" + python3: "Solution().smallestChair({times}, {targetFriend})" + python2: "Solution().smallestChair({times}, {targetFriend})" + ruby: "smallest_chair({times}, {targetFriend})" + java: "new Solution().smallestChair({times}, {targetFriend})" + csharp: "new Solution().SmallestChair({times}, {targetFriend})" + kotlin: "Solution().smallestChair({times}, {targetFriend})" + go: "smallestChair({times}, {targetFriend})" + dart: "Solution().smallestChair({times}, {targetFriend})" + swift: "Solution().smallestChair({times}, {targetFriend})" + typescript: "smallestChair({times}, {targetFriend})" +judge: + type: exact +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().smallestChair(times, targetFriend, {result})" + checker: | + import heapq + + class Checker: + def smallestChair(self, times, targetFriend, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + ordered = sorted((a, b, i) for i, (a, b) in enumerate(times)) + free = [] + busy = [] + next_chair = 0 + answer = None + for arrival, leaving, friend in ordered: + while busy and busy[0][0] <= arrival: + _, chair = heapq.heappop(busy) + heapq.heappush(free, chair) + if free: + chair = heapq.heappop(free) + else: + chair = next_chair + next_chair += 1 + heapq.heappush(busy, (leaving, chair)) + if friend == targetFriend: + answer = chair + break + return result == answer +seed: 1942 +tests: + - name: example-one + in: + times: [[1, 4], [2, 3], [4, 6]] + targetFriend: 1 + out: 1 + - name: example-two + in: + times: [[3, 10], [1, 5], [2, 6]] + targetFriend: 0 + out: 2 + - name: sequential-arrivals + in: + times: [[1, 2], [2, 3], [3, 4]] + targetFriend: 2 + out: 0 + - name: long-first-interval + in: + times: [[1, 100], [2, 3], [4, 5], [6, 7]] + targetFriend: 3 + out: 1 + - name: target-first + in: + times: [[10, 20], [1, 2], [3, 4], [5, 6]] + targetFriend: 0 + out: 0 + - name: nested-intervals + in: + times: [[1, 10], [2, 9], [3, 8], [4, 7], [5, 6]] + targetFriend: 4 + out: 4 + - name: all-disjoint + in: + times: [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] + targetFriend: 4 + out: 0 + - name: reuse-at-same-time + in: + times: [[5, 6], [1, 100], [2, 3], [4, 5]] + targetFriend: 0 + out: 1 + - name: three-overlap + in: + times: [[1, 5], [2, 4], [3, 6], [7, 8]] + targetFriend: 2 + out: 2 + - name: simultaneous-leave-reuse + in: + times: [[2, 5], [1, 10], [3, 4], [4, 6], [7, 9]] + targetFriend: 3 + out: 2 + - name: extreme-times + in: + times: [[1, 100000], [99999, 100000], [50000, 50001]] + targetFriend: 2 + out: 1 + - name: late-target + in: + times: [[100, 200], [1, 101], [2, 3], [4, 5]] + targetFriend: 0 + out: 1 + - name: target-second-overlap + in: + times: [[1, 3], [2, 100], [4, 5], [6, 7], [8, 9]] + targetFriend: 1 + out: 1 + - name: unsorted-friend-indices + in: + times: [[8, 9], [1, 4], [2, 3], [5, 10], [6, 7]] + targetFriend: 3 + out: 0 + - name: nested-with-tail + in: + times: [[1, 6], [2, 5], [3, 4], [7, 8], [9, 10]] + targetFriend: 0 + out: 0 + - name: target-late-after-disjoint + in: + times: [[20, 30], [1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] + targetFriend: 0 + out: 0 + - name: long-chair-held + in: + times: [[1, 100], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]] + targetFriend: 5 + out: 1 + - name: staggered-release + in: + times: [[4, 8], [1, 10], [2, 3], [5, 6], [7, 9]] + targetFriend: 4 + out: 2 + - name: release-before-target + in: + times: [[1, 2], [4, 10], [5, 6], [7, 8], [9, 11]] + targetFriend: 1 + out: 0 + - name: seven-friends + in: + times: [[11, 12], [1, 20], [2, 3], [4, 5], [6, 7], [8, 9], [10, 13]] + targetFriend: 6 + out: 1 + - name: deep-nesting-target + in: + times: [[1, 50], [2, 49], [3, 48], [4, 47], [5, 46], [25, 26]] + targetFriend: 5 + out: 5 + - name: late-disjoint-target + in: + times: [[1, 2], [10, 20], [11, 12], [13, 14], [15, 16]] + targetFriend: 4 + out: 1 + - name: target-at-first-arrival + in: + times: [[6, 7], [1, 9], [2, 3], [4, 5], [8, 10]] + targetFriend: 0 + out: 1 + - name: almost-fully-nested + in: + times: [[1, 8], [2, 7], [3, 6], [4, 5], [9, 10]] + targetFriend: 4 + out: 0 + - name: high-index-target + in: + times: [[100, 101], [1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]] + targetFriend: 6 + out: 0 + - name: target-after-release + in: + times: [[1, 4], [2, 5], [3, 6], [7, 9], [8, 10]] + targetFriend: 3 + out: 0 + - name: overlapping-chain + in: + times: [[1, 100], [2, 99], [3, 98], [4, 97], [50, 51], [52, 53]] + targetFriend: 4 + out: 4 + - name: target-at-release-boundary + in: + times: [[2, 4], [1, 3], [5, 6], [7, 8], [9, 10]] + targetFriend: 2 + out: 0 + - name: mixed-boundary-arrivals + in: + times: [[1, 2], [2, 100], [3, 4], [4, 5]] + targetFriend: 2 + out: 1 + - name: maximum-hold-target + in: + times: [[1, 100000], [2, 99999], [3, 4], [5, 6], [7, 8]] + targetFriend: 1 + out: 1 + - name: near-maximum-arrivals + in: + times: [[99990, 100000], [1, 99991], [2, 3], [4, 5]] + targetFriend: 0 + out: 1 + - name: middle-target + in: + times: [[1, 10], [3, 4], [5, 6], [7, 8], [9, 11]] + targetFriend: 2 + out: 1 + - name: long-second-interval + in: + times: [[2, 100], [1, 3], [4, 5], [6, 7], [8, 9]] + targetFriend: 0 + out: 1 + - name: target-second-friend + in: + times: [[1, 2], [3, 100], [4, 5], [6, 7], [8, 9]] + targetFriend: 1 + out: 0 + - name: seven-with-long-root + in: + times: [[1, 100], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11], [12, 13]] + targetFriend: 6 + out: 1 diff --git a/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.cpp b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.cpp new file mode 100644 index 00000000..99f0854d --- /dev/null +++ b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int smallestChair(vector>& times, int targetFriend) { + vector target_time = times[targetFriend]; + sort(times.begin(), times.end()); + + int n = times.size(); + vector chair_time(n, 0); + + for (auto& time : times) { + for (int i = 0; i < n; i++) { + if (chair_time[i] <= time[0]) { + chair_time[i] = time[1]; + if (time == target_time) { + return i; + } + break; + } + } + } + + return 0; + } +}; diff --git a/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.cs b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.cs new file mode 100644 index 00000000..d922b7e7 --- /dev/null +++ b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.cs @@ -0,0 +1,23 @@ +public class Solution { + public int SmallestChair(int[][] times, int targetFriend) { + int[] target_time = times[targetFriend]; + Array.Sort(times, (a, b) => a[0].CompareTo(b[0])); + + int n = times.Length; + int[] chair_time = new int[n]; + + foreach (int[] time in times) { + for (int i = 0; i < n; i++) { + if (chair_time[i] <= time[0]) { + chair_time[i] = time[1]; + if (time[0] == target_time[0] && time[1] == target_time[1]) { + return i; + } + break; + } + } + } + + return 0; + } +} diff --git a/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.dart b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.dart new file mode 100644 index 00000000..4665cda9 --- /dev/null +++ b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.dart @@ -0,0 +1,23 @@ +class Solution { + int smallestChair(List> times, int targetFriend) { + List target_time = times[targetFriend]; + times.sort((a, b) => a[0].compareTo(b[0])); + + int n = times.length; + List chair_time = List.filled(n, 0); + + for (List time in times) { + for (int i = 0; i < n; i++) { + if (chair_time[i] <= time[0]) { + chair_time[i] = time[1]; + if (time[0] == target_time[0] && time[1] == target_time[1]) { + return i; + } + break; + } + } + } + + return 0; + } +} diff --git a/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.go b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.go new file mode 100644 index 00000000..1d3857cb --- /dev/null +++ b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.go @@ -0,0 +1,23 @@ +func smallestChair(times [][]int, targetFriend int) int { + target_time := times[targetFriend] + sort.Slice(times, func(i, j int) bool { + return times[i][0] < times[j][0] + }) + + n := len(times) + chair_time := make([]int, n) + + for _, time := range times { + for i := 0; i < n; i++ { + if chair_time[i] <= time[0] { + chair_time[i] = time[1] + if time[0] == target_time[0] && time[1] == target_time[1] { + return i + } + break + } + } + } + + return 0 +} diff --git a/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.java b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.java new file mode 100644 index 00000000..1796f994 --- /dev/null +++ b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.java @@ -0,0 +1,23 @@ +class Solution { + public int smallestChair(int[][] times, int targetFriend) { + int[] target_time = times[targetFriend]; + Arrays.sort(times, (a, b) -> Integer.compare(a[0], b[0])); + + int n = times.length; + int[] chair_time = new int[n]; + + for (int[] time : times) { + for (int i = 0; i < n; i++) { + if (chair_time[i] <= time[0]) { + chair_time[i] = time[1]; + if (Arrays.equals(time, target_time)) { + return i; + } + break; + } + } + } + + return 0; + } +} diff --git a/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.kt b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.kt new file mode 100644 index 00000000..ee88edc6 --- /dev/null +++ b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.kt @@ -0,0 +1,23 @@ +class Solution { + fun smallestChair(times: Array, targetFriend: Int): Int { + val target_time = times[targetFriend] + times.sortBy { it[0] } + + val n = times.size + val chair_time = IntArray(n) + + for (time in times) { + for (i in 0 until n) { + if (chair_time[i] <= time[0]) { + chair_time[i] = time[1] + if (time.contentEquals(target_time)) { + return i + } + break + } + } + } + + return 0 + } +} diff --git a/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.py b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.py new file mode 100644 index 00000000..f92b4f6a --- /dev/null +++ b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.py @@ -0,0 +1,17 @@ +class Solution: + def smallestChair(self, times: List[List[int]], targetFriend: int) -> int: + target_time = times[targetFriend] + times.sort() + + n = len(times) + chair_time = [0] * n + + for time in times: + for i in range(n): + if chair_time[i] <= time[0]: + chair_time[i] = time[1] + if time == target_time: + return i + break + + return 0 diff --git a/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.py2 b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.py2 new file mode 100644 index 00000000..c93702d5 --- /dev/null +++ b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def smallestChair(self, times, targetFriend): + """ + :type times: List[List[int]] + :type targetFriend: int + :rtype: int + """ + target_time = times[targetFriend] + times.sort() + + n = len(times) + chair_time = [0] * n + + for time in times: + for i in range(n): + if chair_time[i] <= time[0]: + chair_time[i] = time[1] + if time == target_time: + return i + break + + return 0 diff --git a/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.rb b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.rb new file mode 100644 index 00000000..548fb3ea --- /dev/null +++ b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.rb @@ -0,0 +1,24 @@ +# @param {Integer[][]} times +# @param {Integer} target_friend +# @return {Integer} +def smallest_chair(times, target_friend) + target_time = times[target_friend] + times.sort! + + n = times.length + chair_time = Array.new(n, 0) + + times.each do |time| + (0...n).each do |i| + if chair_time[i] <= time[0] + chair_time[i] = time[1] + if time == target_time + return i + end + break + end + end + end + + 0 +end diff --git a/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.rs b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.rs new file mode 100644 index 00000000..abb5f1a4 --- /dev/null +++ b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn smallest_chair(times: Vec>, target_friend: i32) -> i32 { + let target_time = times[target_friend as usize].clone(); + let mut times = times; + times.sort_by(|a, b| a[0].cmp(&b[0])); + + let n = times.len(); + let mut chair_time = vec![0; n]; + + for time in × { + for i in 0..n { + if chair_time[i] <= time[0] { + chair_time[i] = time[1]; + if *time == target_time { + return i as i32; + } + break; + } + } + } + + 0 + } +} diff --git a/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.swift b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.swift new file mode 100644 index 00000000..b3b9ad7f --- /dev/null +++ b/tests/1501-2000/1942. the-number-of-the-smallest-unoccupied-chair/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func smallestChair(_ times: [[Int]], _ targetFriend: Int) -> Int { + let target_time = times[targetFriend] + let sortedTimes = times.sorted { $0[0] < $1[0] } + + let n = sortedTimes.count + var chair_time = [Int](repeating: 0, count: n) + + for time in sortedTimes { + for i in 0.. a[0] - b[0]); + + const n = times.length; + const chair_time = new Array(n).fill(0); + + for (const time of times) { + for (let i = 0; i < n; i++) { + if (chair_time[i] <= time[0]) { + chair_time[i] = time[1]; + if (time[0] === target_time[0] && time[1] === target_time[1]) { + return i; + } + break; + } + } + } + + return 0; +} diff --git a/tests/1501-2000/1943. describe-the-painting/manifest.yaml b/tests/1501-2000/1943. describe-the-painting/manifest.yaml new file mode 100644 index 00000000..24821340 --- /dev/null +++ b/tests/1501-2000/1943. describe-the-painting/manifest.yaml @@ -0,0 +1,323 @@ +entry: + id: 1943 + title: "describe-the-painting" + params: + segments: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().splitPainting({segments})" + rust: "Solution::split_painting({segments})" + python3: "Solution().splitPainting({segments})" + python2: "Solution().splitPainting({segments})" + ruby: "split_painting({segments})" + java: "new Solution().splitPainting({segments})" + csharp: "new Solution().SplitPainting({segments})" + kotlin: "Solution().splitPainting({segments})" + go: "splitPainting({segments})" + dart: "Solution().splitPainting({segments})" + swift: "Solution().splitPainting({segments})" + typescript: "splitPainting({segments})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().splitPainting(segments, {result})" + checker: | + class Checker: + def splitPainting(self, segments, result): + if not isinstance(result, list): + return False + events = {} + for seg in segments: + if not isinstance(seg, list) or len(seg) != 3: + return False + left, right, color = seg + events[left] = events.get(left, 0) + color + events[right] = events.get(right, 0) - color + points = sorted(events) + expected = [] + total = 0 + for i in range(len(points) - 1): + total += events[points[i]] + if total: + expected.append([points[i], points[i + 1], total]) + def normalize(value): + if not isinstance(value, list): + return None + rows = [] + for row in value: + if not isinstance(row, list) or len(row) != 3: + return None + if not all(isinstance(x, int) and not isinstance(x, bool) for x in row): + return None + if row[0] >= row[1] or row[2] <= 0: + return None + rows.append(list(row)) + rows.sort() + return rows + return normalize(result) == expected + +seed: 1943 + +tests: + - name: "example_one" + in: + segments: + - [1, 4, 5] + - [4, 7, 7] + - [1, 7, 9] + - name: "example_two" + in: + segments: + - [1, 7, 9] + - [6, 8, 15] + - [8, 10, 7] + - name: "example_three" + in: + segments: + - [1, 4, 5] + - [1, 4, 7] + - [4, 7, 1] + - [4, 7, 11] + - name: "single_segment" + in: + segments: + - [1, 2, 1] + - name: "single_long_segment" + in: + segments: + - [1, 100000, 1000000000] + - name: "disjoint_segments" + in: + segments: + - [1, 3, 2] + - [5, 8, 9] + - [10, 11, 20] + - name: "touching_segments" + in: + segments: + - [1, 4, 3] + - [4, 6, 8] + - [6, 9, 13] + - name: "nested_three" + in: + segments: + - [1, 10, 1] + - [3, 8, 10] + - [5, 6, 100] + - name: "same_start" + in: + segments: + - [2, 5, 4] + - [2, 7, 8] + - [2, 9, 16] + - name: "same_end" + in: + segments: + - [1, 9, 4] + - [3, 9, 8] + - [6, 9, 16] + - name: "crossing_pairs" + in: + segments: + - [1, 8, 2] + - [3, 6, 5] + - [5, 10, 11] + - [7, 12, 17] + - name: "all_same_length" + in: + segments: + - [1, 4, 1] + - [3, 6, 2] + - [5, 8, 4] + - [7, 10, 8] + - name: "large_colors" + in: + segments: + - [10, 20, 1000000000] + - [15, 25, 999999999] + - [19, 30, 888888888] + - name: "one_point_gaps" + in: + segments: + - [1, 2, 3] + - [3, 4, 5] + - [5, 6, 7] + - [7, 8, 9] + - name: "alternating_overlap" + in: + segments: + - [1, 5, 2] + - [2, 4, 3] + - [4, 8, 5] + - [6, 9, 7] + - name: "full_chain" + in: + segments: + - [1, 3, 2] + - [2, 5, 3] + - [4, 7, 5] + - [6, 9, 7] + - [8, 11, 11] + - name: "long_and_short" + in: + segments: + - [1, 100, 6] + - [2, 3, 10] + - [50, 51, 20] + - [99, 100, 30] + - name: "duplicate_boundaries" + in: + segments: + - [10, 20, 1] + - [10, 20, 2] + - [20, 30, 4] + - [20, 30, 8] + - name: "negative_free_lower_bound" + in: + segments: + - [1, 1000, 13] + - [250, 750, 17] + - [500, 1000, 19] + - name: "many_short_segments" + in: + segments: + - [1, 2, 1] + - [1, 3, 2] + - [2, 4, 4] + - [3, 5, 8] + - [4, 6, 16] + - [5, 7, 32] + - [6, 8, 64] + - [7, 9, 128] + - name: "boundary_coordinates" + in: + segments: + - [1, 99999, 31] + - [99998, 100000, 37] + - [1, 2, 41] + - name: "four_nested" + in: + segments: + - [1, 100, 1] + - [10, 90, 2] + - [20, 80, 4] + - [30, 70, 8] + - name: "separated_clusters" + in: + segments: + - [1, 10, 3] + - [5, 15, 5] + - [100, 110, 7] + - [105, 120, 11] + - [1000, 1010, 13] + - name: "wide_crossing" + in: + segments: + - [1, 50, 2] + - [10, 40, 3] + - [20, 60, 5] + - [30, 70, 7] + - [45, 80, 11] + - name: "powers_colors" + in: + segments: + - [2, 20, 2] + - [4, 18, 4] + - [6, 16, 8] + - [8, 14, 16] + - name: "odd_boundaries" + in: + segments: + - [1, 7, 12] + - [7, 13, 23] + - [3, 11, 34] + - [5, 9, 45] + - name: "almost_full_range" + in: + segments: + - [1, 99999, 101] + - [2, 99998, 103] + - [3, 99997, 107] + - name: "staggered_five" + in: + segments: + - [1, 12, 6] + - [4, 16, 10] + - [8, 20, 14] + - [12, 24, 18] + - [16, 28, 22] + - name: "nested_with_gaps" + in: + segments: + - [1, 30, 29] + - [2, 5, 31] + - [8, 12, 37] + - [15, 22, 41] + - [25, 29, 43] + - name: "dense_small_domain" + in: + segments: + - [1, 10, 1] + - [1, 9, 2] + - [2, 10, 4] + - [2, 8, 8] + - [3, 7, 16] + - [4, 6, 32] + - name: "ten_overlaps" + in: + segments: + - [1, 21, 101] + - [3, 19, 103] + - [5, 17, 107] + - [7, 15, 109] + - [9, 13, 113] + - [2, 4, 127] + - [6, 8, 131] + - [10, 12, 137] + - name: "large_coordinate_mix" + in: + segments: + - [1, 50000, 100000001] + - [25000, 75000, 100000007] + - [50000, 100000, 100000009] + - [100, 99900, 100000019] + - name: "twenty_event_stress" + in: + segments: + - [1, 100000, 11] + - [1000, 99000, 13] + - [2000, 98000, 17] + - [3000, 97000, 19] + - [4000, 96000, 23] + - [5000, 95000, 29] + - [6000, 94000, 31] + - [7000, 93000, 37] + - [8000, 92000, 41] + - [9000, 91000, 43] + - name: "disjoint_large_stress" + in: + segments: + - [1, 10000, 101] + - [20000, 30000, 103] + - [40000, 50000, 107] + - [60000, 70000, 109] + - [80000, 90000, 113] + - name: "mixed_large_stress" + in: + segments: + - [1, 100000, 1000000000] + - [1, 50000, 999999937] + - [25000, 75000, 999999929] + - [50000, 100000, 999999893] + - [12345, 87654, 999999883] diff --git a/tests/1501-2000/1943. describe-the-painting/sol.cpp b/tests/1501-2000/1943. describe-the-painting/sol.cpp new file mode 100644 index 00000000..007d4406 --- /dev/null +++ b/tests/1501-2000/1943. describe-the-painting/sol.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + vector> splitPainting(vector>& segments) { + vector> events; + for (auto& seg : segments) { + events.push_back({seg[0], seg[2]}); + events.push_back({seg[1], -seg[2]}); + } + sort(events.begin(), events.end()); + + vector> ans; + int prev = -1; + long long mix = 0; + for (auto& e : events) { + if (prev != -1) { + if (e.first != prev && mix != 0) { + ans.push_back({(long long)prev, (long long)e.first, mix}); + } + } + prev = e.first; + mix += e.second; + } + return ans; + } +}; diff --git a/tests/1501-2000/1943. describe-the-painting/sol.cs b/tests/1501-2000/1943. describe-the-painting/sol.cs new file mode 100644 index 00000000..9e917d4b --- /dev/null +++ b/tests/1501-2000/1943. describe-the-painting/sol.cs @@ -0,0 +1,24 @@ +public class Solution { + public IList> SplitPainting(int[][] segments) { + var events = new List<(int pos, int val)>(); + foreach (var seg in segments) { + events.Add((seg[0], seg[2])); + events.Add((seg[1], -seg[2])); + } + events.Sort((a, b) => a.pos.CompareTo(b.pos)); + + var ans = new List>(); + int prev = -1; + long mix = 0; + foreach (var e in events) { + if (prev != -1) { + if (e.pos != prev && mix != 0) { + ans.Add(new List { prev, e.pos, mix }); + } + } + prev = e.pos; + mix += e.val; + } + return ans; + } +} diff --git a/tests/1501-2000/1943. describe-the-painting/sol.dart b/tests/1501-2000/1943. describe-the-painting/sol.dart new file mode 100644 index 00000000..e6a316df --- /dev/null +++ b/tests/1501-2000/1943. describe-the-painting/sol.dart @@ -0,0 +1,24 @@ +class Solution { + List> splitPainting(List> segments) { + List> events = []; + for (var seg in segments) { + events.add([seg[0], seg[2]]); + events.add([seg[1], -seg[2]]); + } + events.sort((a, b) => a[0].compareTo(b[0])); + + List> ans = []; + int prev = -1; + int mix = 0; + for (var e in events) { + if (prev != -1) { + if (e[0] != prev && mix != 0) { + ans.add([prev, e[0], mix]); + } + } + prev = e[0]; + mix += e[1]; + } + return ans; + } +} diff --git a/tests/1501-2000/1943. describe-the-painting/sol.go b/tests/1501-2000/1943. describe-the-painting/sol.go new file mode 100644 index 00000000..edbfa5b4 --- /dev/null +++ b/tests/1501-2000/1943. describe-the-painting/sol.go @@ -0,0 +1,24 @@ +func splitPainting(segments [][]int) [][]int64 { + events := make([][2]int, 0, len(segments)*2) + for _, seg := range segments { + events = append(events, [2]int{seg[0], seg[2]}) + events = append(events, [2]int{seg[1], -seg[2]}) + } + sort.Slice(events, func(i, j int) bool { + return events[i][0] < events[j][0] + }) + + ans := make([][]int64, 0) + prev := -1 + var mix int64 = 0 + for _, e := range events { + if prev != -1 { + if e[0] != prev && mix != 0 { + ans = append(ans, []int64{int64(prev), int64(e[0]), mix}) + } + } + prev = e[0] + mix += int64(e[1]) + } + return ans +} diff --git a/tests/1501-2000/1943. describe-the-painting/sol.java b/tests/1501-2000/1943. describe-the-painting/sol.java new file mode 100644 index 00000000..9abbccc4 --- /dev/null +++ b/tests/1501-2000/1943. describe-the-painting/sol.java @@ -0,0 +1,24 @@ +class Solution { + public List> splitPainting(int[][] segments) { + List events = new ArrayList<>(); + for (int[] seg : segments) { + events.add(new int[]{seg[0], seg[2]}); + events.add(new int[]{seg[1], -seg[2]}); + } + events.sort((a, b) -> a[0] - b[0]); + + List> ans = new ArrayList<>(); + int prev = -1; + long mix = 0; + for (int[] e : events) { + if (prev != -1) { + if (e[0] != prev && mix != 0) { + ans.add(Arrays.asList((long)prev, (long)e[0], mix)); + } + } + prev = e[0]; + mix += e[1]; + } + return ans; + } +} diff --git a/tests/1501-2000/1943. describe-the-painting/sol.kt b/tests/1501-2000/1943. describe-the-painting/sol.kt new file mode 100644 index 00000000..c6975d0a --- /dev/null +++ b/tests/1501-2000/1943. describe-the-painting/sol.kt @@ -0,0 +1,24 @@ +class Solution { + fun splitPainting(segments: Array): List> { + val events = mutableListOf>() + for (seg in segments) { + events.add(Pair(seg[0], seg[2])) + events.add(Pair(seg[1], -seg[2])) + } + events.sortBy { it.first } + + val ans = mutableListOf>() + var prev = -1 + var mix = 0L + for ((pos, amount) in events) { + if (prev != -1) { + if (pos != prev && mix != 0L) { + ans.add(listOf(prev.toLong(), pos.toLong(), mix)) + } + } + prev = pos + mix += amount + } + return ans + } +} diff --git a/tests/1501-2000/1943. describe-the-painting/sol.py b/tests/1501-2000/1943. describe-the-painting/sol.py new file mode 100644 index 00000000..c5a24a99 --- /dev/null +++ b/tests/1501-2000/1943. describe-the-painting/sol.py @@ -0,0 +1,30 @@ +class Solution: + def splitPainting(self, segments: List[List[int]]) -> List[List[int]]: + seg = segments + size: int = len(seg) + + events: list[tuple[int, int]] = [] + + for i in range(0, size): + start: int = seg[i][0] + end: int = seg[i][1] + color: int = seg[i][2] + + events.append((start, color)) + events.append((end, -1 * color)) + + events.sort() + + prev: int = -1 + ans: list[tuple[int, int, int]] = [] + mix_color: int = 0 + + for i in range(0, len(events)): + if prev != -1: + if events[i][0] != prev and mix_color != 0: + ans.append((prev, events[i][0], mix_color)) + + prev = events[i][0] + mix_color += events[i][1] + + return ans diff --git a/tests/1501-2000/1943. describe-the-painting/sol.py2 b/tests/1501-2000/1943. describe-the-painting/sol.py2 new file mode 100644 index 00000000..7c721ef6 --- /dev/null +++ b/tests/1501-2000/1943. describe-the-painting/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def splitPainting(self, segments): + """ + :type segments: List[List[int]] + :rtype: List[List[int]] + """ + events = [] + for start, end, color in segments: + events.append((start, color)) + events.append((end, -color)) + events.sort() + + prev = -1 + ans = [] + mix = 0 + for pos, val in events: + if prev != -1: + if pos != prev and mix != 0: + ans.append([prev, pos, mix]) + prev = pos + mix += val + return ans diff --git a/tests/1501-2000/1943. describe-the-painting/sol.rb b/tests/1501-2000/1943. describe-the-painting/sol.rb new file mode 100644 index 00000000..81fe5ac4 --- /dev/null +++ b/tests/1501-2000/1943. describe-the-painting/sol.rb @@ -0,0 +1,22 @@ +def split_painting(segments) + events = [] + segments.each do |start, ending, color| + events << [start, color] + events << [ending, -color] + end + events.sort! + + prev = -1 + ans = [] + mix = 0 + events.each do |pos, val| + if prev != -1 + if pos != prev && mix != 0 + ans << [prev, pos, mix] + end + end + prev = pos + mix += val + end + ans +end diff --git a/tests/1501-2000/1943. describe-the-painting/sol.rs b/tests/1501-2000/1943. describe-the-painting/sol.rs new file mode 100644 index 00000000..321d9c9a --- /dev/null +++ b/tests/1501-2000/1943. describe-the-painting/sol.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn split_painting(segments: Vec>) -> Vec> { + let mut events: Vec<(i32, i32)> = Vec::new(); + for seg in segments { + events.push((seg[0], seg[2])); + events.push((seg[1], -seg[2])); + } + events.sort(); + + let mut ans: Vec> = Vec::new(); + let mut prev = -1; + let mut mix: i64 = 0; + for (pos, val) in events { + if prev != -1 { + if pos != prev && mix != 0 { + ans.push(vec![prev as i64, pos as i64, mix]); + } + } + prev = pos; + mix += val as i64; + } + ans + } +} diff --git a/tests/1501-2000/1943. describe-the-painting/sol.swift b/tests/1501-2000/1943. describe-the-painting/sol.swift new file mode 100644 index 00000000..6f41f619 --- /dev/null +++ b/tests/1501-2000/1943. describe-the-painting/sol.swift @@ -0,0 +1,24 @@ +class Solution { + func splitPainting(_ segments: [[Int]]) -> [[Int]] { + var events: [(Int, Int)] = [] + for seg in segments { + events.append((seg[0], seg[2])) + events.append((seg[1], -seg[2])) + } + events.sort { $0.0 < $1.0 } + + var ans: [[Int]] = [] + var prev = -1 + var mix = 0 + for (pos, val) in events { + if prev != -1 { + if pos != prev && mix != 0 { + ans.append([prev, pos, mix]) + } + } + prev = pos + mix += val + } + return ans + } +} diff --git a/tests/1501-2000/1943. describe-the-painting/sol.ts b/tests/1501-2000/1943. describe-the-painting/sol.ts new file mode 100644 index 00000000..0be62c2e --- /dev/null +++ b/tests/1501-2000/1943. describe-the-painting/sol.ts @@ -0,0 +1,22 @@ +function splitPainting(segments: number[][]): number[][] { + const events: [number, number][] = []; + for (const seg of segments) { + events.push([seg[0], seg[2]]); + events.push([seg[1], -seg[2]]); + } + events.sort((a, b) => a[0] - b[0]); + + const ans: number[][] = []; + let prev = -1; + let mix = 0; + for (const [pos, val] of events) { + if (prev !== -1) { + if (pos !== prev && mix !== 0) { + ans.push([prev, pos, mix]); + } + } + prev = pos; + mix += val; + } + return ans; +} diff --git a/tests/1501-2000/1944. number-of-visible-people-in-a-queue/manifest.yaml b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/manifest.yaml new file mode 100644 index 00000000..cebe2926 --- /dev/null +++ b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/manifest.yaml @@ -0,0 +1,331 @@ +entry: + id: 1944 + title: number-of-visible-people-in-a-queue + params: + heights: + type: array + items: + type: int + call: + cpp: "Solution().canSeePersonsCount({heights})" + rust: "Solution::can_see_persons_count({heights})" + python3: "Solution().canSeePersonsCount({heights})" + python2: "Solution().canSeePersonsCount({heights})" + ruby: "can_see_persons_count({heights})" + java: "new Solution().canSeePersonsCount({heights})" + csharp: "new Solution().CanSeePersonsCount({heights})" + kotlin: "Solution().canSeePersonsCount({heights})" + go: "canSeePersonsCount({heights})" + dart: "Solution().canSeePersonsCount({heights})" + swift: "Solution().canSeePersonsCount({heights})" + typescript: "canSeePersonsCount({heights})" +judge: + type: exact +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().check(heights, {result})" + checker: | + class Checker: + def check(self, heights, result): + if not isinstance(result, list) or len(result) != len(heights): + return False + expected = [0] * len(heights) + stack = [] + for i in range(len(heights) - 1, -1, -1): + while stack and heights[i] > stack[-1]: + stack.pop() + expected[i] += 1 + if stack: + expected[i] += 1 + stack.append(heights[i]) + return result == expected +seed: 1944 +tests: + - name: static-01 + in: + heights: [1, 2] + out: [1, 0] + judge: + type: exact + - name: static-02 + in: + heights: [2, 1] + out: [1, 0] + judge: + type: exact + - name: static-03 + in: + heights: [10, 6, 8, 5, 11, 9] + out: [3, 1, 2, 1, 1, 0] + judge: + type: exact + - name: static-04 + in: + heights: [5, 1, 2, 3, 10] + out: [4, 1, 1, 1, 0] + judge: + type: exact + - name: static-05 + in: + heights: [1, 2, 3, 4, 5, 6] + out: [1, 1, 1, 1, 1, 0] + judge: + type: exact + - name: static-06 + in: + heights: [6, 5, 4, 3, 2, 1] + out: [1, 1, 1, 1, 1, 0] + judge: + type: exact + - name: static-07 + in: + heights: [3, 1, 2] + out: [2, 1, 0] + judge: + type: exact + - name: static-08 + in: + heights: [2, 1, 3] + out: [2, 1, 0] + judge: + type: exact + - name: static-09 + in: + heights: [4, 1, 3, 2] + out: [2, 1, 1, 0] + judge: + type: exact + - name: static-10 + in: + heights: [2, 4, 1, 3] + out: [1, 2, 1, 0] + judge: + type: exact + - name: static-11 + in: + heights: [5, 3, 1, 2, 4] + out: [2, 3, 1, 1, 0] + judge: + type: exact + - name: static-12 + in: + heights: [4, 2, 5, 1, 3] + out: [2, 1, 2, 1, 0] + judge: + type: exact + - name: static-13 + in: + heights: [1, 5, 2, 4, 3] + out: [1, 2, 1, 1, 0] + judge: + type: exact + - name: static-14 + in: + heights: [7, 2, 6, 1, 5, 3, 4] + out: [2, 1, 2, 1, 2, 1, 0] + judge: + type: exact + - name: static-15 + in: + heights: [4, 1, 2, 3, 5, 6] + out: [4, 1, 1, 1, 1, 0] + judge: + type: exact + - name: static-16 + in: + heights: [6, 1, 2, 3, 4, 5] + out: [5, 1, 1, 1, 1, 0] + judge: + type: exact + - name: static-17 + in: + heights: [8, 3, 7, 2, 6, 1, 5, 4] + out: [2, 1, 2, 1, 2, 1, 1, 0] + judge: + type: exact + - name: static-18 + in: + heights: [4, 7, 1, 6, 2, 5, 3] + out: [1, 2, 1, 2, 1, 1, 0] + judge: + type: exact + - name: static-19 + in: + heights: [9, 1, 8, 2, 7, 3, 6, 4, 5] + out: [2, 1, 2, 1, 2, 1, 2, 1, 0] + judge: + type: exact + - name: static-20 + in: + heights: [5, 9, 1, 8, 2, 7, 3, 6, 4] + out: [1, 2, 1, 2, 1, 2, 1, 1, 0] + judge: + type: exact + - name: static-21 + in: + heights: [10, 2, 9, 1, 8, 3, 7, 4, 6, 5] + out: [2, 1, 2, 1, 2, 1, 2, 1, 1, 0] + judge: + type: exact + - name: static-22 + in: + heights: [3, 8, 2, 7, 1, 6, 4, 5] + out: [1, 2, 1, 2, 1, 2, 1, 0] + judge: + type: exact + - name: static-23 + in: + heights: [11, 4, 10, 2, 9, 1, 8, 3, 7, 5, 6] + out: [2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 0] + judge: + type: exact + - name: static-24 + in: + heights: [6, 10, 2, 9, 1, 8, 3, 7, 4, 5] + out: [1, 2, 1, 2, 1, 2, 1, 2, 1, 0] + judge: + type: exact + - name: static-25 + in: + heights: [1, 4, 2, 8, 3, 7, 5, 6] + out: [1, 2, 1, 2, 1, 2, 1, 0] + judge: + type: exact + - name: static-26 + in: + heights: [12, 1, 11, 2, 10, 3, 9, 4, 8, 5, 7, 6] + out: [2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 0] + judge: + type: exact + - name: static-27 + in: + heights: [7, 1, 6, 2, 5, 3, 4] + out: [2, 1, 2, 1, 2, 1, 0] + judge: + type: exact + - name: static-28 + in: + heights: [2, 7, 3, 6, 1, 5, 4] + out: [1, 2, 1, 2, 1, 1, 0] + judge: + type: exact + - name: static-29 + in: + heights: [9, 4, 8, 1, 7, 2, 6, 3, 5] + out: [2, 1, 2, 1, 2, 1, 2, 1, 0] + judge: + type: exact + - name: static-30 + in: + heights: [5, 2, 9, 1, 8, 3, 7, 4, 6] + out: [2, 1, 2, 1, 2, 1, 2, 1, 0] + judge: + type: exact + - name: static-31 + in: + heights: [13, 6, 12, 1, 11, 2, 10, 3, 9, 4, 8, 5, 7] + out: [2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 0] + judge: + type: exact + - name: static-32 + in: + heights: [8, 1, 7, 2, 6, 3, 5, 4] + out: [2, 1, 2, 1, 2, 1, 1, 0] + judge: + type: exact + - name: static-33 + in: + heights: [14, 3, 13, 2, 12, 1, 11, 4, 10, 5, 9, 6, 8, 7] + out: [2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 0] + judge: + type: exact + - name: static-34 + in: + heights: [4, 10, 1, 9, 2, 8, 3, 7, 5, 6] + out: [1, 2, 1, 2, 1, 2, 1, 2, 1, 0] + judge: + type: exact + - name: static-35 + in: + heights: [15, 1, 14, 2, 13, 3, 12, 4, 11, 5, 10, 6, 9, 7, 8] + out: [2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 0] + judge: + type: exact + - name: generated-01 + in: + heights: + gen: "array" + len: 10 + of: + gen: "int" + min: 1 + max: 100 + distinct: true + sorted: false + elemType: "int" + judge: + type: exact + seed: 194401 + - name: generated-02 + in: + heights: + gen: "array" + len: 50 + of: + gen: "int" + min: 1 + max: 1000 + distinct: true + sorted: false + elemType: "int" + judge: + type: exact + seed: 194402 + - name: generated-03 + in: + heights: + gen: "array" + len: 200 + of: + gen: "int" + min: 1 + max: 100000 + distinct: true + sorted: false + elemType: "int" + judge: + type: exact + seed: 194403 + - name: generated-04 + in: + heights: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: true + sorted: false + elemType: "int" + judge: + type: exact + seed: 194404 + - name: generated-05 + in: + heights: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: true + sorted: false + elemType: "int" + judge: + type: exact + seed: 194405 diff --git a/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.cpp b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.cpp new file mode 100644 index 00000000..5cc3774f --- /dev/null +++ b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector canSeePersonsCount(vector& heights) { + int n = heights.size(); + vector result(n, 0); + vector stack; + + for (int i = n-1; i >= 0; i--) { + int height = heights[i]; + int visibility = 0; + + while (!stack.empty() && height > stack.back()) { + stack.pop_back(); + visibility++; + } + + if (!stack.empty()) { + visibility++; + } + + result[i] = visibility; + stack.push_back(height); + } + + return result; + } +}; diff --git a/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.cs b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.cs new file mode 100644 index 00000000..2696dd97 --- /dev/null +++ b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.cs @@ -0,0 +1,26 @@ +public class Solution { + public int[] CanSeePersonsCount(int[] heights) { + int n = heights.Length; + int[] result = new int[n]; + Stack stack = new Stack(); + + for (int i = n-1; i >= 0; i--) { + int height = heights[i]; + int visibility = 0; + + while (stack.Count > 0 && height > stack.Peek()) { + stack.Pop(); + visibility++; + } + + if (stack.Count > 0) { + visibility++; + } + + result[i] = visibility; + stack.Push(height); + } + + return result; + } +} diff --git a/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.dart b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.dart new file mode 100644 index 00000000..77f9dac4 --- /dev/null +++ b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.dart @@ -0,0 +1,26 @@ +class Solution { + List canSeePersonsCount(List heights) { + int n = heights.length; + List result = List.filled(n, 0); + List stack = []; + + for (int i = n-1; i >= 0; i--) { + int height = heights[i]; + int visibility = 0; + + while (stack.isNotEmpty && height > stack.last) { + stack.removeLast(); + visibility++; + } + + if (stack.isNotEmpty) { + visibility++; + } + + result[i] = visibility; + stack.add(height); + } + + return result; + } +} diff --git a/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.go b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.go new file mode 100644 index 00000000..dc93bcf6 --- /dev/null +++ b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.go @@ -0,0 +1,24 @@ +func canSeePersonsCount(heights []int) []int { + n := len(heights) + result := make([]int, n) + stack := []int{} + + for i := n-1; i >= 0; i-- { + height := heights[i] + visibility := 0 + + for len(stack) > 0 && height > stack[len(stack)-1] { + stack = stack[:len(stack)-1] + visibility++ + } + + if len(stack) > 0 { + visibility++ + } + + result[i] = visibility + stack = append(stack, height) + } + + return result +} diff --git a/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.java b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.java new file mode 100644 index 00000000..1d63e0bf --- /dev/null +++ b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.java @@ -0,0 +1,26 @@ +class Solution { + public int[] canSeePersonsCount(int[] heights) { + int n = heights.length; + int[] result = new int[n]; + Deque stack = new ArrayDeque<>(); + + for (int i = n-1; i >= 0; i--) { + int height = heights[i]; + int visibility = 0; + + while (!stack.isEmpty() && height > stack.peek()) { + stack.pop(); + visibility++; + } + + if (!stack.isEmpty()) { + visibility++; + } + + result[i] = visibility; + stack.push(height); + } + + return result; + } +} diff --git a/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.kt b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.kt new file mode 100644 index 00000000..afbd5e4e --- /dev/null +++ b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.kt @@ -0,0 +1,26 @@ +class Solution { + fun canSeePersonsCount(heights: IntArray): IntArray { + val n = heights.size + val result = IntArray(n) + val stack = mutableListOf() + + for (i in n-1 downTo 0) { + val height = heights[i] + var visibility = 0 + + while (stack.isNotEmpty() && height > stack.last()) { + stack.removeAt(stack.size - 1) + visibility++ + } + + if (stack.isNotEmpty()) { + visibility++ + } + + result[i] = visibility + stack.add(height) + } + + return result + } +} diff --git a/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.py b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.py new file mode 100644 index 00000000..47d69682 --- /dev/null +++ b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.py @@ -0,0 +1,21 @@ +class Solution(object): + def canSeePersonsCount(self, heights): + + n = len(heights) + result = [0] * n + stack = [] + + for i in range(n - 1, -1, -1): + height = heights[i] + visibility = 0 + + while stack and height > stack[-1]: + stack.pop() + visibility += 1 + + if stack: + visibility += 1 + + result[i] = visibility + stack.append(height) + return result diff --git a/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.py2 b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.py2 new file mode 100644 index 00000000..8a5ce171 --- /dev/null +++ b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.py2 @@ -0,0 +1,24 @@ +class Solution(object): + def canSeePersonsCount(self, heights): + """ + :type heights: List[int] + :rtype: List[int] + """ + n = len(heights) + result = [0]*n + stack = [] + + for i in range(n-1,-1,-1): + height = heights[i] + visibility = 0 + + while stack and height > stack[-1]: + stack.pop() + visibility += 1 + + if(stack): + visibility += 1 + + result[i]=visibility + stack.append(height) + return result diff --git a/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.rb b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.rb new file mode 100644 index 00000000..86612c4a --- /dev/null +++ b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.rb @@ -0,0 +1,24 @@ +# @param {Integer[]} heights +# @return {Integer[]} +def can_see_persons_count(heights) + n = heights.length + result = Array.new(n, 0) + stack = [] + + (n-1).downto(0) do |i| + height = heights[i] + visibility = 0 + + while !stack.empty? && height > stack[-1] + stack.pop + visibility += 1 + end + + visibility += 1 unless stack.empty? + + result[i] = visibility + stack << height + end + + result +end diff --git a/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.rs b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.rs new file mode 100644 index 00000000..4a71542e --- /dev/null +++ b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn can_see_persons_count(heights: Vec) -> Vec { + let n = heights.len(); + let mut result = vec![0; n]; + let mut stack: Vec = Vec::new(); + + for i in (0..n).rev() { + let height = heights[i]; + let mut visibility = 0; + + while !stack.is_empty() && height > *stack.last().unwrap() { + stack.pop(); + visibility += 1; + } + + if !stack.is_empty() { + visibility += 1; + } + + result[i] = visibility; + stack.push(height); + } + + result + } +} diff --git a/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.swift b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.swift new file mode 100644 index 00000000..977a4d64 --- /dev/null +++ b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.swift @@ -0,0 +1,26 @@ +class Solution { + func canSeePersonsCount(_ heights: [Int]) -> [Int] { + let n = heights.count + var result = [Int](repeating: 0, count: n) + var stack = [Int]() + + for i in stride(from: n-1, through: 0, by: -1) { + let height = heights[i] + var visibility = 0 + + while !stack.isEmpty && height > stack.last! { + stack.removeLast() + visibility += 1 + } + + if !stack.isEmpty { + visibility += 1 + } + + result[i] = visibility + stack.append(height) + } + + return result + } +} diff --git a/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.ts b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.ts new file mode 100644 index 00000000..2d8daea1 --- /dev/null +++ b/tests/1501-2000/1944. number-of-visible-people-in-a-queue/sol.ts @@ -0,0 +1,24 @@ +function canSeePersonsCount(heights: number[]): number[] { + const n = heights.length; + const result: number[] = new Array(n).fill(0); + const stack: number[] = []; + + for (let i = n - 1; i >= 0; i--) { + const height = heights[i]; + let visibility = 0; + + while (stack.length > 0 && height > stack[stack.length - 1]) { + stack.pop(); + visibility++; + } + + if (stack.length > 0) { + visibility++; + } + + result[i] = visibility; + stack.push(height); + } + + return result; +} diff --git a/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/manifest.yaml b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/manifest.yaml new file mode 100644 index 00000000..1a2b9127 --- /dev/null +++ b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/manifest.yaml @@ -0,0 +1,371 @@ +entry: + id: 1945 + title: "sum-of-digits-of-string-after-convert" + params: + s: + type: string + k: + type: int + call: + cpp: "Solution().getLucky({s}, {k})" + rust: "Solution::get_lucky({s}, {k})" + python3: "Solution().getLucky({s}, {k})" + python2: "Solution().getLucky({s}, {k})" + ruby: "get_lucky({s}, {k})" + java: "new Solution().getLucky({s}, {k})" + csharp: "new Solution().GetLucky({s}, {k})" + kotlin: "Solution().getLucky({s}, {k})" + go: "getLucky({s}, {k})" + dart: "Solution().getLucky({s}, {k})" + swift: "Solution().getLucky({s}, {k})" + typescript: "getLucky({s}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().getLucky(s, k, {result})" + checker: | + class Checker: + def getLucky(self, s, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + value = ''.join(str(ord(ch) - ord('a') + 1) for ch in s) + for _ in range(k): + value = str(sum(ord(ch) - ord('0') for ch in value)) + return result == int(value) + +seed: 1945 + +tests: + - name: example-iiii + in: + s: "iiii" + k: 1 + out: 36 + judge: + type: "exact" + - name: example-leetcode + in: + s: "leetcode" + k: 2 + out: 6 + judge: + type: "exact" + - name: example-zbax + in: + s: "zbax" + k: 2 + out: 8 + judge: + type: "exact" + - name: single-a-k1 + in: + s: "a" + k: 1 + out: 1 + judge: + type: "exact" + - name: single-z-k1 + in: + s: "z" + k: 1 + out: 8 + judge: + type: "exact" + - name: single-z-k10 + in: + s: "z" + k: 10 + out: 8 + judge: + type: "exact" + - name: alphabet-k1 + in: + s: "abcdefghijklmnopqrstuvwxyz" + k: 1 + out: 135 + judge: + type: "exact" + - name: alphabet-k2 + in: + s: "abcdefghijklmnopqrstuvwxyz" + k: 2 + out: 9 + judge: + type: "exact" + - name: alphabet-k10 + in: + s: "abcdefghijklmnopqrstuvwxyz" + k: 10 + out: 9 + judge: + type: "exact" + - name: repeated-a + in: + s: "aaaaaaaaaa" + k: 1 + out: 10 + judge: + type: "exact" + - name: repeated-a-k2 + in: + s: "aaaaaaaaaa" + k: 2 + out: 1 + judge: + type: "exact" + - name: repeated-z + in: + s: "zzzzzzzzzz" + k: 1 + out: 80 + judge: + type: "exact" + - name: repeated-z-k2 + in: + s: "zzzzzzzzzz" + k: 2 + out: 8 + judge: + type: "exact" + - name: alternating-az + in: + s: "azazazazaz" + k: 1 + out: 45 + judge: + type: "exact" + - name: alternating-az-k2 + in: + s: "azazazazaz" + k: 2 + out: 9 + judge: + type: "exact" + - name: tens-k1 + in: + s: "abcdefghij" + k: 1 + out: 46 + judge: + type: "exact" + - name: tens-k2 + in: + s: "abcdefghij" + k: 2 + out: 10 + judge: + type: "exact" + - name: upper-half + in: + s: "nopqrstuvwxyz" + k: 1 + out: 80 + judge: + type: "exact" + - name: upper-half-k3 + in: + s: "nopqrstuvwxyz" + k: 3 + out: 8 + judge: + type: "exact" + - name: two-digit-letters + in: + s: "jklmnopqrstuvwxyz" + k: 1 + out: 90 + judge: + type: "exact" + - name: two-digit-letters-k2 + in: + s: "jklmnopqrstuvwxyz" + k: 2 + out: 9 + judge: + type: "exact" + - name: mixed-short-one + in: + s: "azbycx" + k: 1 + out: 27 + judge: + type: "exact" + - name: mixed-short-two + in: + s: "azbycx" + k: 2 + out: 9 + judge: + type: "exact" + - name: mixed-short-three + in: + s: "azbycx" + k: 3 + out: 9 + judge: + type: "exact" + - name: palindrome + in: + s: "abccba" + k: 1 + out: 12 + judge: + type: "exact" + - name: palindrome-k4 + in: + s: "abccba" + k: 4 + out: 3 + judge: + type: "exact" + - name: high-low-blocks + in: + s: "azzzzaaaaa" + k: 1 + out: 38 + judge: + type: "exact" + - name: high-low-blocks-k2 + in: + s: "azzzzaaaaa" + k: 2 + out: 11 + judge: + type: "exact" + - name: boundary-mnop + in: + s: "mnop" + k: 1 + out: 22 + judge: + type: "exact" + - name: boundary-mnop-k2 + in: + s: "mnop" + k: 2 + out: 4 + judge: + type: "exact" + - name: long-a-100 + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + k: 1 + out: 100 + judge: + type: "exact" + - name: long-a-100-k2 + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + k: 2 + out: 1 + judge: + type: "exact" + - name: long-z-100 + in: + s: "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + k: 1 + out: 800 + judge: + type: "exact" + - name: long-z-100-k2 + in: + s: "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + k: 2 + out: 8 + judge: + type: "exact" + - name: descending-alphabet + in: + s: "zyxwvutsrqponmlkjihgfedcba" + k: 1 + out: 135 + judge: + type: "exact" + - name: descending-alphabet-k5 + in: + s: "zyxwvutsrqponmlkjihgfedcba" + k: 5 + out: 9 + judge: + type: "exact" + - name: digit-heavy-letters + in: + s: "twentyfour" + k: 1 + out: 50 + judge: + type: "exact" + - name: digit-heavy-letters-k2 + in: + s: "twentyfour" + k: 2 + out: 5 + judge: + type: "exact" + - name: gen-short + in: + s: + gen: "str" + len: 1 + alphabet: "abmz" + k: + gen: "int" + min: 1 + max: 10 + judge: + type: "exact" + - name: gen-medium + in: + s: + gen: "str" + len: 17 + alphabet: "aeiouz" + k: + gen: "int" + min: 1 + max: 10 + judge: + type: "exact" + - name: gen-long + in: + s: + gen: "str" + len: 100 + alphabet: "ajkz" + k: + gen: "int" + min: 1 + max: 10 + judge: + type: "exact" + - name: gen-full-alphabet + in: + s: + gen: "str" + len: 100 + alphabet: "abcdefghijklmnopqrstuvwxyz" + k: + gen: "int" + min: 1 + max: 10 + judge: + type: "exact" + - name: gen-max-k + in: + s: + gen: "str" + len: 100 + alphabet: "nopqrstuvwxyz" + k: + gen: "int" + min: 10 + max: 10 + judge: + type: "exact" diff --git a/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.cpp b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.cpp new file mode 100644 index 00000000..cb93ff9f --- /dev/null +++ b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int getLucky(string s, int k) { + string res = ""; + for (char c : s) { + res += to_string(c - 'a' + 1); + } + for (int i = 0; i < k; i++) { + int sum = 0; + for (char c : res) { + sum += c - '0'; + } + res = to_string(sum); + } + return stoi(res); + } +}; diff --git a/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.cs b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.cs new file mode 100644 index 00000000..f23d646b --- /dev/null +++ b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public int GetLucky(string s, int k) { + string res = ""; + foreach (char c in s) { + res += (c - 'a' + 1).ToString(); + } + for (int i = 0; i < k; i++) { + int sum = 0; + foreach (char c in res) { + sum += c - '0'; + } + res = sum.ToString(); + } + return int.Parse(res); + } +} diff --git a/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.dart b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.dart new file mode 100644 index 00000000..f319417c --- /dev/null +++ b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.dart @@ -0,0 +1,16 @@ +class Solution { + int getLucky(String s, int k) { + String res = ''; + for (int i = 0; i < s.length; i++) { + res += (s.codeUnitAt(i) - 'a'.codeUnitAt(0) + 1).toString(); + } + for (int i = 0; i < k; i++) { + int sum = 0; + for (int j = 0; j < res.length; j++) { + sum += int.parse(res[j]); + } + res = sum.toString(); + } + return int.parse(res); + } +} diff --git a/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.go b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.go new file mode 100644 index 00000000..8f77559f --- /dev/null +++ b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.go @@ -0,0 +1,15 @@ +func getLucky(s string, k int) int { + res := "" + for _, c := range s { + res += strconv.Itoa(int(c - 'a' + 1)) + } + for i := 0; i < k; i++ { + sum := 0 + for _, c := range res { + sum += int(c - '0') + } + res = strconv.Itoa(sum) + } + result, _ := strconv.Atoi(res) + return result +} diff --git a/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.java b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.java new file mode 100644 index 00000000..9a7e5f1e --- /dev/null +++ b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.java @@ -0,0 +1,16 @@ +class Solution { + public int getLucky(String s, int k) { + String res = ""; + for (char c : s.toCharArray()) { + res += (c - 'a' + 1); + } + for (int i = 0; i < k; i++) { + int sum = 0; + for (char c : res.toCharArray()) { + sum += c - '0'; + } + res = Integer.toString(sum); + } + return Integer.parseInt(res); + } +} diff --git a/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.kt b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.kt new file mode 100644 index 00000000..e7fc5b72 --- /dev/null +++ b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.kt @@ -0,0 +1,12 @@ +class Solution { + fun getLucky(s: String, k: Int): Int { + var res = "" + for (c in s) { + res += (c - 'a' + 1).toString() + } + repeat(k) { + res = res.map { it - '0' }.sum().toString() + } + return res.toInt() + } +} diff --git a/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.py b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.py new file mode 100644 index 00000000..4771f064 --- /dev/null +++ b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.py @@ -0,0 +1,10 @@ +class Solution: + def getLucky(self, s: str, k: int) -> int: + res = "" + + for c in s: + res += str(ord(c) - ord("a") + 1) + + for i in range(k): + res = str(sum([int(c) for c in res])) + return int(res) diff --git a/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.py2 b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.py2 new file mode 100644 index 00000000..d1e19814 --- /dev/null +++ b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.py2 @@ -0,0 +1,13 @@ +class Solution(object): + def getLucky(self, s, k): + """ + :type s: str + :type k: int + :rtype: int + """ + res = '' + for c in s: + res += str(ord(c) - ord('a') + 1) + for _ in range(k): + res = str(sum(int(x) for x in res)) + return int(res) diff --git a/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.rb b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.rb new file mode 100644 index 00000000..2a69b131 --- /dev/null +++ b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.rb @@ -0,0 +1,10 @@ +def get_lucky(s, k) + res = '' + s.each_char do |c| + res += (c.ord - 'a'.ord + 1).to_s + end + k.times do + res = res.chars.map(&:to_i).sum.to_s + end + res.to_i +end diff --git a/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.rs b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.rs new file mode 100644 index 00000000..ab71307b --- /dev/null +++ b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn get_lucky(s: String, k: i32) -> i32 { + let mut res = String::new(); + for c in s.chars() { + res += &(c as u8 - b'a' + 1).to_string(); + } + for _ in 0..k { + let sum: i32 = res.chars().map(|c| c.to_digit(10).unwrap() as i32).sum(); + res = sum.to_string(); + } + res.parse().unwrap() + } +} diff --git a/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.swift b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.swift new file mode 100644 index 00000000..67379357 --- /dev/null +++ b/tests/1501-2000/1945. sum-of-digits-of-string-after-convert/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func getLucky(_ s: String, _ k: Int) -> Int { + var res = "" + for c in s.unicodeScalars { + res += String(c.value - UnicodeScalar("a").value + 1) + } + for _ in 0.. d: + expected[i] = mapped + active = True + elif change[d] == d or not active: + continue + else: + break + return result == ''.join(expected) + +seed: 1946 + +tests: + - name: "example-1" + in: + num: "132" + change: [9, 8, 5, 0, 3, 6, 4, 2, 6, 8] + - name: "example-2" + in: + num: "021" + change: [9, 4, 3, 5, 7, 2, 1, 9, 0, 6] + - name: "example-3" + in: + num: "5" + change: [1, 4, 7, 5, 3, 2, 5, 6, 9, 4] + - name: "single-increase" + in: + num: "0" + change: [9, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: "single-decrease" + in: + num: "9" + change: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: "all-identity" + in: + num: "0123456789" + change: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + - name: "increase-prefix-stop" + in: + num: "12345" + change: [0, 2, 3, 3, 4, 5, 6, 7, 8, 9] + - name: "increase-middle" + in: + num: "9876543210" + change: [0, 1, 2, 9, 4, 5, 6, 7, 8, 9] + - name: "decrease-before-increase" + in: + num: "53124" + change: [0, 0, 0, 9, 0, 0, 0, 0, 0, 0] + - name: "equal-then-increase" + in: + num: "112233" + change: [0, 1, 2, 9, 4, 5, 6, 7, 8, 9] + - name: "increase-run" + in: + num: "11111" + change: [0, 8, 0, 0, 0, 0, 0, 0, 0, 0] + - name: "stop-after-run" + in: + num: "11211" + change: [0, 8, 0, 0, 0, 0, 0, 0, 0, 0] + - name: "zero-leading" + in: + num: "000123" + change: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: "zero-leading-stop" + in: + num: "00123" + change: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: "only-last" + in: + num: "9998" + change: [0, 0, 0, 0, 0, 0, 0, 0, 0, 9] + - name: "only-first" + in: + num: "8999" + change: [0, 0, 0, 0, 0, 0, 0, 0, 9, 0] + - name: "strictly-decreasing-map" + in: + num: "9876543210" + change: [0, 0, 1, 2, 3, 4, 5, 6, 7, 8] + - name: "strictly-increasing-map" + in: + num: "0123456789" + change: [1, 2, 3, 4, 5, 6, 7, 8, 9, 9] + - name: "mixed-one" + in: + num: "4050607080" + change: [7, 1, 2, 8, 9, 0, 6, 7, 8, 9] + - name: "mixed-two" + in: + num: "2468013579" + change: [0, 9, 8, 7, 6, 5, 4, 3, 2, 1] + - name: "mixed-three" + in: + num: "3141592653589793" + change: [9, 0, 8, 7, 6, 5, 4, 3, 2, 1] + - name: "repeated-boundary" + in: + num: "333444455555" + change: [0, 1, 2, 4, 4, 5, 6, 7, 8, 9] + - name: "map-to-nine" + in: + num: "1234567890" + change: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9] + - name: "map-to-zero" + in: + num: "0123456789" + change: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: "alternating" + in: + num: "0101010101" + change: [2, 3, 0, 1, 4, 5, 6, 7, 8, 9] + - name: "late-start" + in: + num: "999001234" + change: [8, 1, 2, 3, 4, 5, 6, 7, 8, 9] + - name: "late-stop" + in: + num: "123999001" + change: [9, 0, 1, 2, 3, 4, 5, 6, 7, 8] + - name: "length-20" + in: + num: "01234567890123456789" + change: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] + - name: "length-30" + in: + num: "111222333444555666777888999000" + change: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] + - name: "all-nines" + in: + num: "9999999999" + change: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + - name: "all-zeros" + in: + num: "0000000000" + change: [9, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: "one-improving-digit" + in: + num: "5555555555" + change: [0, 1, 2, 3, 4, 9, 6, 7, 8, 9] + - name: "improvement-after-equal" + in: + num: "777888" + change: [0, 1, 2, 3, 4, 5, 6, 7, 9, 9] + - name: "improvement-after-worse" + in: + num: "8172" + change: [0, 1, 2, 3, 4, 5, 6, 9, 8, 9] + - name: "large-static" + in: + num: "99999999999999999999999999999999999999999999999999" + change: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + - name: "large-static-increase" + in: + num: "00000000000000000000000000000000000000000000000000" + change: [9, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: "generated-short" + in: + num: + gen: "str" + len: 128 + alphabet: "0123456789" + change: + gen: "array" + len: 10 + of: + gen: "int" + min: 0 + max: 9 + distinct: false + elemType: "int" + seed: 194601 + - name: "generated-medium" + in: + num: + gen: "str" + len: 1000 + alphabet: "0123456789" + change: + gen: "array" + len: 10 + of: + gen: "int" + min: 0 + max: 9 + distinct: false + elemType: "int" + seed: 194602 + - name: "generated-large" + in: + num: + gen: "str" + len: 100000 + alphabet: "0123456789" + change: + gen: "array" + len: 10 + of: + gen: "int" + min: 0 + max: 9 + distinct: false + elemType: "int" + seed: 194603 + - name: "generated-large-biased" + in: + num: + gen: "str" + len: 100000 + alphabet: "0189" + change: + gen: "array" + len: 10 + of: + gen: "int" + min: 0 + max: 9 + distinct: false + elemType: "int" + seed: 194604 + - name: "generated-long-low-digits" + in: + num: + gen: "str" + len: 50000 + alphabet: "0123" + change: + gen: "array" + len: 10 + of: + gen: "int" + min: 0 + max: 9 + distinct: false + elemType: "int" + seed: 194605 diff --git a/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.cpp b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.cpp new file mode 100644 index 00000000..14efc89e --- /dev/null +++ b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + string maximumNumber(string num, vector& change) { + string a = num; + bool flag = false; + for (int i = 0; i < a.length(); i++) { + int b = a[i] - '0'; + if (b < change[b]) { + a[i] = change[b] + '0'; + flag = true; + } else if (b == change[b] || !flag) { + continue; + } else { + break; + } + } + return a; + } +}; diff --git a/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.cs b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.cs new file mode 100644 index 00000000..efb551e3 --- /dev/null +++ b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public string MaximumNumber(string num, int[] change) { + char[] a = num.ToCharArray(); + bool flag = false; + for (int i = 0; i < a.Length; i++) { + int b = a[i] - '0'; + if (b < change[b]) { + a[i] = (char)(change[b] + '0'); + flag = true; + } else if (b == change[b] || !flag) { + continue; + } else { + break; + } + } + return new string(a); + } +} diff --git a/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.dart b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.dart new file mode 100644 index 00000000..ac4d2387 --- /dev/null +++ b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.dart @@ -0,0 +1,18 @@ +class Solution { + String maximumNumber(String num, List change) { + List a = num.split(''); + bool flag = false; + for (int i = 0; i < a.length; i++) { + int b = int.parse(a[i]); + if (b < change[b]) { + a[i] = change[b].toString(); + flag = true; + } else if (b == change[b] || !flag) { + continue; + } else { + break; + } + } + return a.join(); + } +} diff --git a/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.go b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.go new file mode 100644 index 00000000..37acd967 --- /dev/null +++ b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.go @@ -0,0 +1,16 @@ +func maximumNumber(num string, change []int) string { + a := []byte(num) + flag := false + for i := 0; i < len(a); i++ { + b := int(a[i] - '0') + if b < change[b] { + a[i] = byte(change[b] + '0') + flag = true + } else if b == change[b] || !flag { + continue + } else { + break + } + } + return string(a) +} diff --git a/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.java b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.java new file mode 100644 index 00000000..66d06606 --- /dev/null +++ b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.java @@ -0,0 +1,18 @@ +class Solution { + public String maximumNumber(String num, int[] change) { + char[] a = num.toCharArray(); + boolean flag = false; + for (int i = 0; i < a.length; i++) { + int b = a[i] - '0'; + if (b < change[b]) { + a[i] = (char)(change[b] + '0'); + flag = true; + } else if (b == change[b] || !flag) { + continue; + } else { + break; + } + } + return new String(a); + } +} diff --git a/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.kt b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.kt new file mode 100644 index 00000000..598a75d4 --- /dev/null +++ b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.kt @@ -0,0 +1,18 @@ +class Solution { + fun maximumNumber(num: String, change: IntArray): String { + val a = num.toCharArray() + var flag = false + for (i in a.indices) { + val b = a[i] - '0' + if (b < change[b]) { + a[i] = (change[b] + '0'.toInt()).toChar() + flag = true + } else if (b == change[b] || !flag) { + continue + } else { + break + } + } + return String(a) + } +} diff --git a/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.py b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.py new file mode 100644 index 00000000..3616bf4b --- /dev/null +++ b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.py @@ -0,0 +1,14 @@ +class Solution: + def maximumNumber(self, num: str, change: List[int]) -> str: + a = list(num) + flag = False + for i in range(len(a)): + b = int(a[i]) + if b < change[b]: + a[i] = str(change[b]) + flag = True + elif b == change[b] or not flag: + continue + else: + break + return "".join(a) diff --git a/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.py2 b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.py2 new file mode 100644 index 00000000..9b4ad698 --- /dev/null +++ b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.py2 @@ -0,0 +1,19 @@ +class Solution(object): + def maximumNumber(self, num, change): + """ + :type num: str + :type change: List[int] + :rtype: str + """ + a = list(num) + flag = False + for i in range(len(a)): + b = int(a[i]) + if b < change[b]: + a[i] = str(change[b]) + flag = True + elif b == change[b] or not flag: + continue + else: + break + return "".join(a) diff --git a/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.rb b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.rb new file mode 100644 index 00000000..c23489ef --- /dev/null +++ b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.rb @@ -0,0 +1,19 @@ +# @param {String} num +# @param {Integer[]} change +# @return {String} +def maximum_number(num, change) + a = num.chars + flag = false + a.each_with_index do |ch, i| + b = ch.to_i + if b < change[b] + a[i] = change[b].to_s + flag = true + elsif b == change[b] || !flag + next + else + break + end + end + a.join +end diff --git a/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.rs b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.rs new file mode 100644 index 00000000..17919371 --- /dev/null +++ b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn maximum_number(num: String, change: Vec) -> String { + let mut a: Vec = num.chars().collect(); + let mut flag = false; + for i in 0..a.len() { + let b = a[i].to_digit(10).unwrap() as i32; + if b < change[b as usize] { + a[i] = std::char::from_digit(change[b as usize] as u32, 10).unwrap(); + flag = true; + } else if b == change[b as usize] || !flag { + continue; + } else { + break; + } + } + a.into_iter().collect() + } +} diff --git a/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.swift b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.swift new file mode 100644 index 00000000..35f24799 --- /dev/null +++ b/tests/1501-2000/1946. largest-number-after-mutating-substring/sol.swift @@ -0,0 +1,18 @@ +class Solution { + func maximumNumber(_ num: String, _ change: [Int]) -> String { + var a = Array(num) + var flag = false + for i in 0..>& students, vector>& mentors) { + int m = students.size(); + int maxScore = 0; + vector perm(m); + iota(perm.begin(), perm.end(), 0); + do { + int total = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < students[i].size(); j++) { + if (students[i][j] == mentors[perm[i]][j]) total++; + } + } + maxScore = max(maxScore, total); + } while (next_permutation(perm.begin(), perm.end())); + return maxScore; + } +}; diff --git a/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.cs b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.cs new file mode 100644 index 00000000..927e58d9 --- /dev/null +++ b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.cs @@ -0,0 +1,29 @@ +public class Solution { + public int MaxCompatibilitySum(int[][] students, int[][] mentors) { + int m = students.Length; + int maxScore = 0; + int[] perm = Enumerable.Range(0, m).ToArray(); + do { + int total = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < students[i].Length; j++) { + if (students[i][j] == mentors[perm[i]][j]) total++; + } + } + maxScore = Math.Max(maxScore, total); + } while (NextPermutation(perm)); + return maxScore; + } + + private bool NextPermutation(int[] a) { + int n = a.Length; + int i = n - 2; + while (i >= 0 && a[i] >= a[i+1]) i--; + if (i < 0) return false; + int j = n - 1; + while (a[j] <= a[i]) j--; + int t = a[i]; a[i] = a[j]; a[j] = t; + Array.Reverse(a, i+1, n-i-1); + return true; + } +} diff --git a/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.dart b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.dart new file mode 100644 index 00000000..c9035ab7 --- /dev/null +++ b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.dart @@ -0,0 +1,31 @@ +class Solution { + int maxCompatibilitySum(List> students, List> mentors) { + int m = students.length; + int maxScore = 0; + List perm = List.generate(m, (i) => i); + do { + int total = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < students[i].length; j++) { + if (students[i][j] == mentors[perm[i]][j]) total++; + } + } + if (total > maxScore) maxScore = total; + } while (nextPermutation(perm)); + return maxScore; + } + + bool nextPermutation(List a) { + int n = a.length; + int i = n - 2; + while (i >= 0 && a[i] >= a[i+1]) i--; + if (i < 0) return false; + int j = n - 1; + while (a[j] <= a[i]) j--; + int t = a[i]; a[i] = a[j]; a[j] = t; + for (int l = i+1, r = n-1; l < r; l++, r--) { + t = a[l]; a[l] = a[r]; a[r] = t; + } + return true; + } +} diff --git a/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.go b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.go new file mode 100644 index 00000000..b1870eec --- /dev/null +++ b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.go @@ -0,0 +1,31 @@ +func maxCompatibilitySum(students [][]int, mentors [][]int) int { + m := len(students) + maxScore := 0 + perm := make([]int, m) + for i := 0; i < m; i++ { perm[i] = i } + for { + total := 0 + for i := 0; i < m; i++ { + for j := 0; j < len(students[i]); j++ { + if students[i][j] == mentors[perm[i]][j] { total++ } + } + } + if total > maxScore { maxScore = total } + if !nextPermutation(perm) { break } + } + return maxScore +} + +func nextPermutation(a []int) bool { + n := len(a) + i := n - 2 + for i >= 0 && a[i] >= a[i+1] { i-- } + if i < 0 { return false } + j := n - 1 + for a[j] <= a[i] { j-- } + a[i], a[j] = a[j], a[i] + for l, r := i+1, n-1; l < r; l, r = l+1, r-1 { + a[l], a[r] = a[r], a[l] + } + return true +} diff --git a/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.java b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.java new file mode 100644 index 00000000..5821c5e5 --- /dev/null +++ b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.java @@ -0,0 +1,41 @@ +class Solution { + public int maxCompatibilitySum(int[][] students, int[][] mentors) { + int m = students.length; + int maxScore = 0; + int[] perm = new int[m]; + for (int i = 0; i < m; i++) perm[i] = i; + do { + int total = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < students[i].length; j++) { + if (students[i][j] == mentors[perm[i]][j]) total++; + } + } + maxScore = Math.max(maxScore, total); + } while (nextPermutation(perm)); + return maxScore; + } + + private boolean nextPermutation(int[] a) { + int n = a.length; + int i = n - 2; + while (i >= 0 && a[i] >= a[i+1]) i--; + if (i < 0) return false; + int j = n - 1; + while (a[j] <= a[i]) j--; + swap(a, i, j); + reverse(a, i+1, n-1); + return true; + } + + private void swap(int[] a, int i, int j) { + int t = a[i]; a[i] = a[j]; a[j] = t; + } + + private void reverse(int[] a, int l, int r) { + while (l < r) { + int t = a[l]; a[l] = a[r]; a[r] = t; + l++; r--; + } + } +} diff --git a/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.kt b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.kt new file mode 100644 index 00000000..1a4f135a --- /dev/null +++ b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.kt @@ -0,0 +1,32 @@ +class Solution { + fun maxCompatibilitySum(students: Array, mentors: Array): Int { + val m = students.size + var maxScore = 0 + val perm = IntArray(m) { it } + do { + var total = 0 + for (i in 0 until m) { + for (j in students[i].indices) { + if (students[i][j] == mentors[perm[i]][j]) total++ + } + } + maxScore = maxOf(maxScore, total) + } while (nextPermutation(perm)) + return maxScore + } + + private fun nextPermutation(a: IntArray): Boolean { + var i = a.size - 2 + while (i >= 0 && a[i] >= a[i+1]) i-- + if (i < 0) return false + var j = a.size - 1 + while (a[j] <= a[i]) j-- + var t = a[i]; a[i] = a[j]; a[j] = t + var l = i+1; var r = a.size-1 + while (l < r) { + t = a[l]; a[l] = a[r]; a[r] = t + l++; r-- + } + return true + } +} diff --git a/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.py b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.py new file mode 100644 index 00000000..78b7465b --- /dev/null +++ b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.py @@ -0,0 +1,24 @@ +from itertools import permutations + + +class Solution(object): + def maxCompatibilitySum(self, students, mentors): + """ + :type students: List[List[int]] + :type mentors: List[List[int]] + :rtype: int + """ + + def score(a, b): + return sum(x == y for x, y in zip(a, b)) + + m = len(students) + max_score = 0 + + for perm in permutations(range(m)): + total = 0 + for i in range(m): + total += score(students[i], mentors[perm[i]]) + max_score = max(max_score, total) + + return max_score diff --git a/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.py2 b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.py2 new file mode 100644 index 00000000..d8eed194 --- /dev/null +++ b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def maxCompatibilitySum(self, students, mentors): + """ + :type students: List[List[int]] + :type mentors: List[List[int]] + :rtype: int + """ + import itertools + def score(a, b): + return sum(1 for i in range(len(a)) if a[i] == b[i]) + m = len(students) + max_score = 0 + for perm in itertools.permutations(range(m)): + total = 0 + for i in range(m): + total += score(students[i], mentors[perm[i]]) + max_score = max(max_score, total) + return max_score diff --git a/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.rb b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.rb new file mode 100644 index 00000000..91164ea1 --- /dev/null +++ b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.rb @@ -0,0 +1,15 @@ +# @param {Integer[][]} students +# @param {Integer[][]} mentors +# @return {Integer} +def max_compatibility_sum(students, mentors) + m = students.length + max_score = 0 + (0...m).to_a.permutation.each do |perm| + total = 0 + m.times do |i| + total += (0...students[i].length).count { |j| students[i][j] == mentors[perm[i]][j] } + end + max_score = [max_score, total].max + end + max_score +end diff --git a/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.rs b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.rs new file mode 100644 index 00000000..cc1dcc15 --- /dev/null +++ b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.rs @@ -0,0 +1,35 @@ +impl Solution { + pub fn max_compatibility_sum(students: Vec>, mentors: Vec>) -> i32 { + let m = students.len(); + let mut max_score = 0; + let mut perm: Vec = (0..m).collect(); + loop { + let mut total = 0; + for i in 0..m { + for j in 0..students[i].len() { + if students[i][j] == mentors[perm[i]][j] { total += 1; } + } + } + max_score = max_score.max(total); + if !Self::next_permutation(&mut perm) { break; } + } + max_score + } + + fn next_permutation(a: &mut Vec) -> bool { + let n = a.len(); + let mut i = n as i32 - 2; + while i >= 0 && a[i as usize] >= a[(i+1) as usize] { i -= 1; } + if i < 0 { return false; } + let mut j = n as i32 - 1; + while a[j as usize] <= a[i as usize] { j -= 1; } + a.swap(i as usize, j as usize); + let mut l = (i+1) as usize; + let mut r = n - 1; + while l < r { + a.swap(l, r); + l += 1; r -= 1; + } + true + } +} diff --git a/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.swift b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.swift new file mode 100644 index 00000000..1615a31f --- /dev/null +++ b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.swift @@ -0,0 +1,33 @@ +class Solution { + func maxCompatibilitySum(_ students: [[Int]], _ mentors: [[Int]]) -> Int { + let m = students.count + var maxScore = 0 + var perm = Array(0.. Bool { + let n = a.count + var i = n - 2 + while i >= 0 && a[i] >= a[i+1] { i -= 1 } + if i < 0 { return false } + var j = n - 1 + while a[j] <= a[i] { j -= 1 } + a.swapAt(i, j) + var l = i+1, r = n-1 + while l < r { + a.swapAt(l, r) + l += 1; r -= 1 + } + return true + } +} diff --git a/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.ts b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.ts new file mode 100644 index 00000000..f9baf3c4 --- /dev/null +++ b/tests/1501-2000/1947. maximum-compatibility-score-sum/sol.ts @@ -0,0 +1,36 @@ +function maxCompatibilitySum( + students: number[][], + mentors: number[][], +): number { + const m = students.length; + let maxScore = 0; + const perm: number[] = Array.from({ length: m }, (_, i) => i); + do { + let total = 0; + for (let i = 0; i < m; i++) { + for (let j = 0; j < students[i].length; j++) { + if (students[i][j] === mentors[perm[i]][j]) total++; + } + } + maxScore = Math.max(maxScore, total); + } while (nextPermutation(perm)); + return maxScore; +} + +function nextPermutation(a: number[]): boolean { + const n = a.length; + let i = n - 2; + while (i >= 0 && a[i] >= a[i + 1]) i--; + if (i < 0) return false; + let j = n - 1; + while (a[j] <= a[i]) j--; + [a[i], a[j]] = [a[j], a[i]]; + let l = i + 1, + r = n - 1; + while (l < r) { + [a[l], a[r]] = [a[r], a[l]]; + l++; + r--; + } + return true; +} diff --git a/tests/1501-2000/1948. delete-duplicate-folders-in-system/manifest.yaml b/tests/1501-2000/1948. delete-duplicate-folders-in-system/manifest.yaml new file mode 100644 index 00000000..421f17b8 --- /dev/null +++ b/tests/1501-2000/1948. delete-duplicate-folders-in-system/manifest.yaml @@ -0,0 +1,448 @@ +entry: + id: 1948 + title: "delete-duplicate-folders-in-system" + params: + paths: + type: array + items: + type: array + items: + type: string + call: + cpp: "Solution().deleteDuplicateFolder({paths})" + rust: "Solution::delete_duplicate_folder({paths})" + python3: "Solution().deleteDuplicateFolder({paths})" + python2: "Solution().deleteDuplicateFolder({paths})" + ruby: "delete_duplicate_folder({paths})" + java: "new Solution().deleteDuplicateFolder({paths})" + csharp: "new Solution().DeleteDuplicateFolder({paths})" + kotlin: "Solution().deleteDuplicateFolder({paths})" + go: "deleteDuplicateFolder({paths})" + dart: "Solution().deleteDuplicateFolder({paths})" + swift: "Solution().deleteDuplicateFolder({paths})" + typescript: "deleteDuplicateFolder({paths})" + +judge: + type: "ignore_order" + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().deleteDuplicateFolder(paths, {result})" + checker: | + from collections import Counter + + class Checker: + def deleteDuplicateFolder(self, paths, result): + if not isinstance(result, list): + return False + children = {} + for path in paths: + if not isinstance(path, list) or not path: + return False + node = children + for name in path: + if not isinstance(name, str) or not name: + return False + node = node.setdefault(name, {}) + + counts = Counter() + signatures = {} + + def encode(node): + sig = tuple((name, encode(child)) for name, child in sorted(node.items())) + signatures[id(node)] = sig + if sig: + counts[sig] += 1 + return sig + + encode(children) + expected = [] + + def walk(node, prefix): + for name, child in sorted(node.items()): + sig = signatures[id(child)] + if sig and counts[sig] >= 2: + continue + current = prefix + [name] + expected.append(current) + walk(child, current) + + walk(children, []) + try: + actual = [list(path) for path in result] + except Exception: + return False + if any(not isinstance(path, list) or any(not isinstance(x, str) for x in path) for path in actual): + return False + return sorted(actual) == sorted(expected) + +seed: 1948 + +tests: + - name: "example_one" + in: + paths: + - ["a"] + - ["c"] + - ["d"] + - ["a", "b"] + - ["c", "b"] + - ["d", "a"] + - name: "example_two" + in: + paths: + - ["a"] + - ["c"] + - ["a", "b"] + - ["c", "b"] + - ["a", "b", "x"] + - ["a", "b", "x", "y"] + - ["w"] + - ["w", "y"] + - name: "example_three" + in: + paths: + - ["a", "b"] + - ["c", "d"] + - ["c"] + - ["a"] + - name: "single_root" + in: + paths: + - ["root"] + - name: "two_distinct_roots" + in: + paths: + - ["a"] + - ["b"] + - name: "identical_empty_children" + in: + paths: + - ["a"] + - ["b"] + - ["a", "x"] + - ["b", "x"] + - name: "identical_deep_chain" + in: + paths: + - ["a"] + - ["b"] + - ["a", "x"] + - ["b", "x"] + - ["a", "x", "y"] + - ["b", "x", "y"] + - name: "different_child_names" + in: + paths: + - ["a"] + - ["b"] + - ["a", "x"] + - ["b", "y"] + - name: "same_shape_different_depth" + in: + paths: + - ["a"] + - ["b"] + - ["a", "x"] + - ["b", "y"] + - ["b", "y", "z"] + - name: "nested_duplicate_subfolders" + in: + paths: + - ["a"] + - ["a", "x"] + - ["a", "x", "z"] + - ["b"] + - ["b", "y"] + - ["b", "y", "z"] + - name: "duplicate_subfolders_keep_parents" + in: + paths: + - ["a"] + - ["b"] + - ["a", "x"] + - ["b", "y"] + - ["a", "x", "z"] + - ["b", "y", "z"] + - ["a", "q"] + - name: "three_identical_roots" + in: + paths: + - ["a"] + - ["b"] + - ["c"] + - ["a", "x"] + - ["b", "x"] + - ["c", "x"] + - name: "three_identical_nested" + in: + paths: + - ["a"] + - ["b"] + - ["c"] + - ["a", "x"] + - ["b", "x"] + - ["c", "x"] + - ["a", "x", "y"] + - ["b", "x", "y"] + - ["c", "x", "y"] + - name: "sibling_order_independent" + in: + paths: + - ["r"] + - ["r", "b"] + - ["r", "a"] + - ["r", "a", "z"] + - ["r", "b", "q"] + - name: "duplicate_with_extra_sibling" + in: + paths: + - ["a"] + - ["b"] + - ["a", "x"] + - ["b", "x"] + - ["b", "y"] + - name: "duplicate_non_root" + in: + paths: + - ["r"] + - ["s"] + - ["r", "a"] + - ["s", "b"] + - ["r", "a", "x"] + - ["s", "b", "x"] + - name: "chain_with_unique_leaf" + in: + paths: + - ["a"] + - ["a", "b"] + - ["a", "b", "c"] + - ["a", "b", "c", "d"] + - name: "two_chains_different_lengths" + in: + paths: + - ["a"] + - ["b"] + - ["a", "x"] + - ["b", "y"] + - ["a", "x", "m"] + - name: "wide_unique_tree" + in: + paths: + - ["r"] + - ["r", "a"] + - ["r", "b"] + - ["r", "c"] + - ["r", "d"] + - ["r", "a", "x"] + - ["r", "b", "y"] + - name: "wide_duplicate_trees" + in: + paths: + - ["a"] + - ["b"] + - ["a", "x"] + - ["a", "y"] + - ["b", "x"] + - ["b", "y"] + - name: "duplicate_only_at_leaf_parent" + in: + paths: + - ["a"] + - ["b"] + - ["a", "x"] + - ["b", "y"] + - ["a", "x", "p"] + - ["b", "y", "p"] + - ["a", "x", "q"] + - name: "same_names_different_structure" + in: + paths: + - ["a"] + - ["b"] + - ["a", "x"] + - ["b", "x"] + - ["a", "x", "y"] + - name: "root_and_nested_same_signature" + in: + paths: + - ["a"] + - ["a", "x"] + - ["a", "x", "y"] + - ["b"] + - ["b", "y"] + - name: "many_unique_names" + in: + paths: + - ["a"] + - ["b"] + - ["c"] + - ["d"] + - ["a", "x"] + - ["b", "y"] + - ["c", "z"] + - name: "duplicate_at_two_levels" + in: + paths: + - ["a"] + - ["b"] + - ["a", "x"] + - ["b", "x"] + - ["a", "x", "p"] + - ["b", "x", "p"] + - ["a", "x", "q"] + - ["b", "x", "q"] + - name: "three_level_unique_variants" + in: + paths: + - ["a"] + - ["a", "b"] + - ["a", "b", "c"] + - ["a", "b", "d"] + - ["a", "e"] + - ["f"] + - ["f", "g"] + - name: "duplicate_roots_with_extra_root" + in: + paths: + - ["a"] + - ["b"] + - ["c"] + - ["a", "x"] + - ["b", "x"] + - ["c", "y"] + - name: "nested_same_shape_different_parent" + in: + paths: + - ["r"] + - ["r", "a"] + - ["r", "b"] + - ["r", "a", "x"] + - ["r", "b", "y"] + - ["r", "a", "x", "z"] + - ["r", "b", "y", "z"] + - name: "long_single_chain" + in: + paths: + - ["a"] + - ["a", "b"] + - ["a", "b", "c"] + - ["a", "b", "c", "d"] + - ["a", "b", "c", "d", "e"] + - ["a", "b", "c", "d", "e", "f"] + - name: "two_long_identical_chains" + in: + paths: + - ["a"] + - ["b"] + - ["a", "c"] + - ["b", "d"] + - ["a", "c", "e"] + - ["b", "d", "e"] + - ["a", "c", "e", "f"] + - ["b", "d", "e", "f"] + - name: "large_branching_static" + in: + paths: + - ["r"] + - ["r", "a"] + - ["r", "b"] + - ["r", "c"] + - ["r", "d"] + - ["r", "e"] + - ["r", "a", "x"] + - ["r", "a", "y"] + - ["r", "b", "x"] + - ["r", "b", "y"] + - ["r", "c", "z"] + - ["r", "d", "z"] + - name: "duplicate_names_across_levels" + in: + paths: + - ["a"] + - ["a", "b"] + - ["a", "b", "a"] + - ["c"] + - ["c", "b"] + - ["c", "b", "a"] + - name: "empty_result_after_duplicate_roots" + in: + paths: + - ["a"] + - ["b"] + - ["a", "x"] + - ["b", "x"] + - ["a", "x", "y"] + - ["b", "x", "y"] + - name: "root_unique_nested_duplicates" + in: + paths: + - ["root"] + - ["root", "a"] + - ["root", "b"] + - ["root", "a", "x"] + - ["root", "b", "y"] + - ["root", "a", "x", "z"] + - ["root", "b", "y", "z"] + - name: "mixed_three_components" + in: + paths: + - ["a"] + - ["a", "x"] + - ["b"] + - ["b", "y"] + - ["c"] + - ["c", "z"] + - ["c", "z", "q"] + - name: "large_names" + in: + paths: + - ["abcdefghij"] + - ["klmnopqrst"] + - ["abcdefghij", "uvwxyzabcd"] + - ["klmnopqrst", "zyxwvutsrq"] + - name: "deep_duplicate_subtree" + in: + paths: + - ["a"] + - ["b"] + - ["a", "x"] + - ["b", "y"] + - ["a", "x", "m"] + - ["b", "y", "m"] + - ["a", "x", "m", "n"] + - ["b", "y", "m", "n"] + - name: "four_roots_two_pairs" + in: + paths: + - ["a"] + - ["b"] + - ["c"] + - ["d"] + - ["a", "x"] + - ["b", "x"] + - ["c", "y"] + - ["d", "y"] + - name: "asymmetric_extra_depth" + in: + paths: + - ["a"] + - ["b"] + - ["a", "x"] + - ["b", "y"] + - ["a", "x", "z"] + - ["a", "x", "z", "q"] + - name: "all_unique_nested" + in: + paths: + - ["a"] + - ["a", "b"] + - ["a", "b", "c"] + - ["a", "d"] + - ["e"] + - ["e", "f"] + - ["e", "f", "g"] diff --git a/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.cpp b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.cpp new file mode 100644 index 00000000..86790c91 --- /dev/null +++ b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.cpp @@ -0,0 +1,70 @@ +class Solution { +private: + struct Node { + string name; + map children; + string signature; + + Node(string n) : name(n) {} + }; + + unordered_map signatureCount; + + string dfs(Node* node) { + if (node->children.empty()) { + node->signature = ""; + return ""; + } + + string childSignatures; + for (auto& [name, child] : node->children) { + string childSignature = dfs(child); + childSignatures += name + "(" + childSignature + ")"; + } + + node->signature = childSignatures; + signatureCount[node->signature]++; + return node->signature; + } + + void dfs2(Node* node, vector>& result, vector& currentPath) { + if (!node->children.empty() && signatureCount[node->signature] >= 2) { + return; + } + + currentPath.push_back(node->name); + result.push_back(currentPath); + + for (auto& [name, child] : node->children) { + dfs2(child, result, currentPath); + } + + currentPath.pop_back(); + } + +public: + vector> deleteDuplicateFolder(vector>& paths) { + Node* root = new Node(""); + + for (auto& path : paths) { + Node* node = root; + for (auto& folder : path) { + if (node->children.find(folder) == node->children.end()) { + node->children[folder] = new Node(folder); + } + node = node->children[folder]; + } + } + + dfs(root); + + vector> result; + vector currentPath; + + for (auto& [name, child] : root->children) { + dfs2(child, result, currentPath); + } + + return result; + } +}; diff --git a/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.cs b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.cs new file mode 100644 index 00000000..507b38d0 --- /dev/null +++ b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +public class Solution { + private class Node { + public string Name; + public Dictionary Children = new Dictionary(); + public string Signature = ""; + + public Node(string name) { + Name = name; + } + } + + private Dictionary signatureCount = new Dictionary(); + + public IList> DeleteDuplicateFolder(IList> paths) { + Node root = new Node(""); + + foreach (var path in paths) { + Node node = root; + foreach (var folder in path) { + if (!node.Children.ContainsKey(folder)) { + node.Children[folder] = new Node(folder); + } + node = node.Children[folder]; + } + } + + Dfs(root); + + var result = new List>(); + var currentPath = new List(); + + var sorted = root.Children.Keys.OrderBy(x => x).ToList(); + foreach (var name in sorted) { + Dfs2(root.Children[name], result, currentPath); + } + + return result; + } + + private string Dfs(Node node) { + if (node.Children.Count == 0) { + node.Signature = ""; + return ""; + } + + var childSignatures = new List(); + var sorted = node.Children.Keys.OrderBy(x => x).ToList(); + foreach (var name in sorted) { + var child = node.Children[name]; + var childSignature = Dfs(child); + childSignatures.Add($"{name}({childSignature})"); + } + + node.Signature = string.Join("", childSignatures); + signatureCount[node.Signature] = signatureCount.GetValueOrDefault(node.Signature) + 1; + return node.Signature; + } + + private void Dfs2(Node node, IList> result, List currentPath) { + if (node.Children.Count > 0 && signatureCount.GetValueOrDefault(node.Signature) >= 2) { + return; + } + + currentPath.Add(node.Name); + result.Add(new List(currentPath)); + + var sorted = node.Children.Keys.OrderBy(x => x).ToList(); + foreach (var name in sorted) { + Dfs2(node.Children[name], result, currentPath); + } + + currentPath.RemoveAt(currentPath.Count - 1); + } +} diff --git a/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.dart b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.dart new file mode 100644 index 00000000..030436fc --- /dev/null +++ b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.dart @@ -0,0 +1,69 @@ +class Node1948 { + String name; + Map children = {}; + String signature = ""; + + Node1948(this.name) { + } + } + +class Solution { + + Map signatureCount = {}; + + List> deleteDuplicateFolder(List> paths) { + Node1948 root = Node1948(""); + + for (var path in paths) { + Node1948 node = root; + for (var folder in path) { + if (!node.children.containsKey(folder)) { + node.children[folder] = Node1948(folder); + } + node = node.children[folder]!; + } + } + + dfs(root); + + List> result = []; + List currentPath = []; + + List sorted = root.children.keys.toList()..sort(); + for (var name in sorted) { + dfs2(root.children[name]!, result, currentPath); + } + + return result; + } + + String dfs(Node1948 node) { + if (node.children.isEmpty) { + node.signature = ""; + return ""; + } + List childSignatures = []; + List sorted = node.children.keys.toList()..sort(); + for (var name in sorted) { + Node1948 child = node.children[name]!; + String childSignature = dfs(child); + childSignatures.add("$name($childSignature)"); + } + node.signature = childSignatures.join(); + signatureCount[node.signature] = (signatureCount[node.signature] ?? 0) + 1; + return node.signature; + } + + void dfs2(Node1948 node, List> result, List currentPath) { + if (node.children.isNotEmpty && (signatureCount[node.signature] ?? 0) >= 2) { + return; + } + currentPath.add(node.name); + result.add(List.from(currentPath)); + List sorted = node.children.keys.toList()..sort(); + for (var name in sorted) { + dfs2(node.children[name]!, result, currentPath); + } + currentPath.removeLast(); + } +} diff --git a/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.go b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.go new file mode 100644 index 00000000..c0657ad9 --- /dev/null +++ b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.go @@ -0,0 +1,81 @@ +func deleteDuplicateFolder(paths [][]string) [][]string { + type Node struct { + name string + children map[string]*Node + signature string + } + + root := &Node{name: "", children: make(map[string]*Node)} + + for _, path := range paths { + node := root + for _, folder := range path { + if _, ok := node.children[folder]; !ok { + node.children[folder] = &Node{name: folder, children: make(map[string]*Node)} + } + node = node.children[folder] + } + } + + signatureCount := make(map[string]int) + + var dfs func(node *Node) string + dfs = func(node *Node) string { + if len(node.children) == 0 { + node.signature = "" + return "" + } + childSignatures := make([]string, 0) + sortedKeys := make([]string, 0, len(node.children)) + for name := range node.children { + sortedKeys = append(sortedKeys, name) + } + sort.Strings(sortedKeys) + for _, name := range sortedKeys { + child := node.children[name] + childSignature := dfs(child) + childSignatures = append(childSignatures, name+"("+childSignature+")") + } + node.signature = "" + for _, s := range childSignatures { + node.signature += s + } + signatureCount[node.signature]++ + return node.signature + } + + dfs(root) + + result := make([][]string, 0) + currentPath := make([]string, 0) + + var dfs2 func(node *Node) + dfs2 = func(node *Node) { + if len(node.children) > 0 && signatureCount[node.signature] >= 2 { + return + } + currentPath = append(currentPath, node.name) + result = append(result, append([]string{}, currentPath...)) + + sortedKeys := make([]string, 0, len(node.children)) + for name := range node.children { + sortedKeys = append(sortedKeys, name) + } + sort.Strings(sortedKeys) + for _, name := range sortedKeys { + dfs2(node.children[name]) + } + currentPath = currentPath[:len(currentPath)-1] + } + + sortedKeys := make([]string, 0, len(root.children)) + for name := range root.children { + sortedKeys = append(sortedKeys, name) + } + sort.Strings(sortedKeys) + for _, name := range sortedKeys { + dfs2(root.children[name]) + } + + return result +} diff --git a/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.java b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.java new file mode 100644 index 00000000..f1bc2ea1 --- /dev/null +++ b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.java @@ -0,0 +1,82 @@ +import java.util.*; + +class Solution { + private class Node { + String name; + Map children = new HashMap<>(); + String signature = ""; + + Node(String name) { + this.name = name; + } + } + + private Map signatureCount = new HashMap<>(); + + public List> deleteDuplicateFolder(List> paths) { + String[][] pathArray = new String[paths.size()][]; + for (int i = 0; i < paths.size(); i++) { + pathArray[i] = paths.get(i).toArray(new String[0]); + } + return deleteDuplicateFolder(pathArray); + } + + public List> deleteDuplicateFolder(String[][] paths) { + Node root = new Node(""); + + for (String[] path : paths) { + Node node = root; + for (String folder : path) { + if (!node.children.containsKey(folder)) { + node.children.put(folder, new Node(folder)); + } + node = node.children.get(folder); + } + } + + dfs(root); + + List> result = new ArrayList<>(); + List currentPath = new ArrayList<>(); + + List sorted = new ArrayList<>(root.children.keySet()); + Collections.sort(sorted); + for (String name : sorted) { + dfs2(root.children.get(name), result, currentPath); + } + + return result; + } + + private String dfs(Node node) { + if (node.children.isEmpty()) { + node.signature = ""; + return ""; + } + List childSignatures = new ArrayList<>(); + List sorted = new ArrayList<>(node.children.keySet()); + Collections.sort(sorted); + for (String name : sorted) { + Node child = node.children.get(name); + String childSignature = dfs(child); + childSignatures.add(name + "(" + childSignature + ")"); + } + node.signature = String.join("", childSignatures); + signatureCount.put(node.signature, signatureCount.getOrDefault(node.signature, 0) + 1); + return node.signature; + } + + private void dfs2(Node node, List> result, List currentPath) { + if (!node.children.isEmpty() && signatureCount.get(node.signature) >= 2) { + return; + } + currentPath.add(node.name); + result.add(new ArrayList<>(currentPath)); + List sorted = new ArrayList<>(node.children.keySet()); + Collections.sort(sorted); + for (String name : sorted) { + dfs2(node.children.get(name), result, currentPath); + } + currentPath.remove(currentPath.size() - 1); + } +} diff --git a/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.kt b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.kt new file mode 100644 index 00000000..2f889e00 --- /dev/null +++ b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.kt @@ -0,0 +1,65 @@ +class Solution { + private class Node(val name: String) { + val children = mutableMapOf() + var signature: String = "" + } + + private val signatureCount = mutableMapOf() + + fun deleteDuplicateFolder(paths: List>): List> { + return deleteDuplicateFolder(paths.map { it.toTypedArray() }.toTypedArray()) + } + + fun deleteDuplicateFolder(paths: Array>): List> { + val root = Node("") + + for (path in paths) { + var node = root + for (folder in path) { + if (!node.children.containsKey(folder)) { + node.children[folder] = Node(folder) + } + node = node.children[folder]!! + } + } + + dfs(root) + + val result = mutableListOf>() + val currentPath = mutableListOf() + + root.children.keys.sorted().forEach { name -> + dfs2(root.children[name]!!, result, currentPath) + } + + return result + } + + private fun dfs(node: Node): String { + if (node.children.isEmpty()) { + node.signature = "" + return "" + } + val childSignatures = mutableListOf() + node.children.keys.sorted().forEach { name -> + val child = node.children[name]!! + val childSignature = dfs(child) + childSignatures.add("$name($childSignature)") + } + node.signature = childSignatures.joinToString("") + signatureCount[node.signature] = signatureCount.getOrDefault(node.signature, 0) + 1 + return node.signature + } + + private fun dfs2(node: Node, result: MutableList>, currentPath: MutableList) { + if (node.children.isNotEmpty() && signatureCount[node.signature]!! >= 2) { + return + } + currentPath.add(node.name) + result.add(currentPath.toList()) + node.children.keys.sorted().forEach { name -> + dfs2(node.children[name]!!, result, currentPath) + } + currentPath.removeAt(currentPath.size - 1) + } +} diff --git a/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.py b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.py new file mode 100644 index 00000000..4e31dab8 --- /dev/null +++ b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.py @@ -0,0 +1,52 @@ +from collections import defaultdict + + +class Node: + def __init__(self, name): + self.name = name + self.children = {} + self.signature = "" + + +class Solution: + def deleteDuplicateFolder(self, paths): + root = Node("") + for path in paths: + node = root + for folder in path: + if folder not in node.children: + node.children[folder] = Node(folder) + node = node.children[folder] + + signature_count = defaultdict(int) + + def dfs(node): + if not node.children: + node.signature = "" + return "" + child_signatures = [] + for name, child in sorted(node.children.items()): + child_signature = dfs(child) + child_signatures.append(f"{name}({child_signature})") + node.signature = "".join(child_signatures) + signature_count[node.signature] += 1 + return node.signature + + dfs(root) + + result = [] + current_path = [] + + def dfs2(node): + if node.children and signature_count[node.signature] >= 2: + return + current_path.append(node.name) + result.append(current_path.copy()) + for name, child in sorted(node.children.items()): + dfs2(child) + current_path.pop() + + for name, child in sorted(root.children.items()): + dfs2(child) + + return result diff --git a/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.py2 b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.py2 new file mode 100644 index 00000000..1b3c25cd --- /dev/null +++ b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.py2 @@ -0,0 +1,55 @@ +class Solution(object): + def deleteDuplicateFolder(self, paths): + """ + :type paths: List[List[str]] + :rtype: List[List[str]] + """ + from collections import defaultdict + + class Node: + def __init__(self, name): + self.name = name + self.children = {} + self.signature = "" + + root = Node("") + for path in paths: + node = root + for folder in path: + if folder not in node.children: + node.children[folder] = Node(folder) + node = node.children[folder] + + signature_count = defaultdict(int) + + def dfs(node): + if not node.children: + node.signature = "" + return "" + child_signatures = [] + for name in sorted(node.children.keys()): + child = node.children[name] + child_signature = dfs(child) + child_signatures.append(name + "(" + child_signature + ")") + node.signature = "".join(child_signatures) + signature_count[node.signature] += 1 + return node.signature + + dfs(root) + + result = [] + current_path = [] + + def dfs2(node): + if node.children and signature_count[node.signature] >= 2: + return + current_path.append(node.name) + result.append(current_path[:]) + for name in sorted(node.children.keys()): + dfs2(node.children[name]) + current_path.pop() + + for name in sorted(root.children.keys()): + dfs2(root.children[name]) + + return result diff --git a/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.rb b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.rb new file mode 100644 index 00000000..07787c54 --- /dev/null +++ b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.rb @@ -0,0 +1,57 @@ +# @param {String[][]} paths +# @return {String[][]} +Node1948 = Struct.new(:name, :children, :signature) +def delete_duplicate_folder(paths) + root = Node1948.new("", {}, "") + + paths.each do |path| + node = root + path.each do |folder| + if !node.children.key?(folder) + node.children[folder] = Node1948.new(folder, {}, "") + end + node = node.children[folder] + end + end + + signature_count = Hash.new(0) + + dfs = lambda do |node| + if node.children.empty? + node.signature = "" + return "" + end + child_signatures = [] + node.children.keys.sort.each do |name| + child = node.children[name] + child_signature = dfs.call(child) + child_signatures << "#{name}(#{child_signature})" + end + node.signature = child_signatures.join + signature_count[node.signature] += 1 + node.signature + end + + dfs.call(root) + + result = [] + current_path = [] + + dfs2 = lambda do |node| + if !node.children.empty? && signature_count[node.signature] >= 2 + return + end + current_path << node.name + result << current_path.dup + node.children.keys.sort.each do |name| + dfs2.call(node.children[name]) + end + current_path.pop + end + + root.children.keys.sort.each do |name| + dfs2.call(root.children[name]) + end + + result +end diff --git a/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.rs b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.rs new file mode 100644 index 00000000..917addbe --- /dev/null +++ b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.rs @@ -0,0 +1,83 @@ +use std::collections::HashMap; + +impl Solution { + pub fn delete_duplicate_folder(paths: Vec>) -> Vec> { + struct Node { + name: String, + children: HashMap, + signature: String, + } + + impl Node { + fn new(name: &str) -> Self { + Node { + name: name.to_string(), + children: HashMap::new(), + signature: String::new(), + } + } + } + + let mut root = Node::new(""); + + for path in paths { + let mut node = &mut root; + for folder in path { + if !node.children.contains_key(&folder) { + node.children.insert(folder.clone(), Node::new(&folder)); + } + node = node.children.get_mut(&folder).unwrap(); + } + } + + let mut signature_count: HashMap = HashMap::new(); + + fn dfs(node: &mut Node, signature_count: &mut HashMap) -> String { + if node.children.is_empty() { + node.signature = String::new(); + return String::new(); + } + + let mut child_signatures: Vec = Vec::new(); + let mut sorted: Vec = node.children.keys().cloned().collect(); + sorted.sort(); + for name in sorted { + let child_signature = dfs(node.children.get_mut(&name).unwrap(), signature_count); + child_signatures.push(format!("{}({})", name, child_signature)); + } + + node.signature = child_signatures.join(""); + *signature_count.entry(node.signature.clone()).or_insert(0) += 1; + node.signature.clone() + } + + dfs(&mut root, &mut signature_count); + + let mut result: Vec> = Vec::new(); + let mut current_path: Vec = Vec::new(); + + fn dfs2(node: &Node, signature_count: &HashMap, result: &mut Vec>, current_path: &mut Vec) { + if !node.children.is_empty() && signature_count.get(&node.signature).unwrap_or(&0) >= &2 { + return; + } + + current_path.push(node.name.clone()); + result.push(current_path.clone()); + + let mut sorted: Vec = node.children.keys().cloned().collect(); + sorted.sort(); + for name in sorted { + dfs2(&node.children[&name], signature_count, result, current_path); + } + current_path.pop(); + } + + let mut sorted_root: Vec = root.children.keys().cloned().collect(); + sorted_root.sort(); + for name in sorted_root { + dfs2(&root.children[&name], &signature_count, &mut result, &mut current_path); + } + + result + } +} diff --git a/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.swift b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.swift new file mode 100644 index 00000000..44347dd8 --- /dev/null +++ b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.swift @@ -0,0 +1,73 @@ +class Solution { + class Node { + var name: String + var children: [String: Node] = [:] + var signature: String = "" + + init(_ name: String) { + self.name = name + } + } + + var signatureCount: [String: Int] = [:] + + func deleteDuplicateFolder(_ paths: [[String]]) -> [[String]] { + let root = Node("") + + for path in paths { + var node = root + for folder in path { + if node.children[folder] == nil { + node.children[folder] = Node(folder) + } + node = node.children[folder]! + } + } + + _ = dfs(root) + + var result: [[String]] = [] + var currentPath: [String] = [] + + let sorted = root.children.keys.sorted() + for name in sorted { + dfs2(root.children[name]!, &result, ¤tPath) + } + + return result + } + + func dfs(_ node: Node) -> String { + if node.children.isEmpty { + node.signature = "" + return "" + } + + var childSignatures: [String] = [] + let sorted = node.children.keys.sorted() + for name in sorted { + let child = node.children[name]! + let childSignature = dfs(child) + childSignatures.append("\(name)(\(childSignature))") + } + + node.signature = childSignatures.joined() + signatureCount[node.signature, default: 0] += 1 + return node.signature + } + + func dfs2(_ node: Node, _ result: inout [[String]], _ currentPath: inout [String]) { + if !node.children.isEmpty && (signatureCount[node.signature] ?? 0) >= 2 { + return + } + + currentPath.append(node.name) + result.append(currentPath) + + let sorted = node.children.keys.sorted() + for name in sorted { + dfs2(node.children[name]!, &result, ¤tPath) + } + currentPath.removeLast() + } +} diff --git a/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.ts b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.ts new file mode 100644 index 00000000..c41de818 --- /dev/null +++ b/tests/1501-2000/1948. delete-duplicate-folders-in-system/sol.ts @@ -0,0 +1,79 @@ +function deleteDuplicateFolder(paths: string[][]): string[][] { + class Node { + name: string; + children: Map; + signature: string; + + constructor(name: string) { + this.name = name; + this.children = new Map(); + this.signature = ""; + } + } + + const signatureCount = new Map(); + + const root = new Node(""); + + for (const path of paths) { + let node = root; + for (const folder of path) { + if (!node.children.has(folder)) { + node.children.set(folder, new Node(folder)); + } + node = node.children.get(folder)!; + } + } + + function dfs(node: Node): string { + if (node.children.size === 0) { + node.signature = ""; + return ""; + } + + const childSignatures: string[] = []; + const sorted = [...node.children.keys()].sort(); + for (const name of sorted) { + const child = node.children.get(name)!; + const childSignature = dfs(child); + childSignatures.push(`${name}(${childSignature})`); + } + + node.signature = childSignatures.join(""); + signatureCount.set( + node.signature, + (signatureCount.get(node.signature) || 0) + 1, + ); + return node.signature; + } + + dfs(root); + + const result: string[][] = []; + let currentPath: string[] = []; + + function dfs2(node: Node) { + if ( + node.children.size > 0 && + (signatureCount.get(node.signature) || 0) >= 2 + ) { + return; + } + + currentPath.push(node.name); + result.push([...currentPath]); + + const sorted = [...node.children.keys()].sort(); + for (const name of sorted) { + dfs2(node.children.get(name)!); + } + currentPath.pop(); + } + + const sortedRoot = [...root.children.keys()].sort(); + for (const name of sortedRoot) { + dfs2(root.children.get(name)!); + } + + return result; +} diff --git a/tests/1501-2000/1952. three-divisors/manifest.yaml b/tests/1501-2000/1952. three-divisors/manifest.yaml new file mode 100644 index 00000000..8f7f2761 --- /dev/null +++ b/tests/1501-2000/1952. three-divisors/manifest.yaml @@ -0,0 +1,303 @@ +entry: + id: 1952 + title: "three-divisors" + params: + n: + type: int + call: + cpp: "Solution().isThree({n})" + rust: "Solution::is_three({n})" + python3: "Solution().isThree({n})" + python2: "Solution().isThree({n})" + ruby: "is_three({n})" + java: "new Solution().isThree({n})" + csharp: "new Solution().IsThree({n})" + kotlin: "Solution().isThree({n})" + go: "isThree({n})" + dart: "Solution().isThree({n})" + swift: "Solution().isThree({n})" + typescript: "isThree({n})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().isThree(n, {result})" + checker: | + import math + + class Checker: + def isThree(self, n, result): + if not isinstance(result, bool): + return False + root = math.isqrt(n) + if root * root != n or root < 2: + return result is False + for divisor in range(2, math.isqrt(root) + 1): + if root % divisor == 0: + return result is False + return result is True + +seed: 1952 + +tests: + - name: one + in: + n: 1 + out: false + judge: + type: "exact" + - name: two + in: + n: 2 + out: false + judge: + type: "exact" + - name: three + in: + n: 3 + out: false + judge: + type: "exact" + - name: four + in: + n: 4 + out: true + judge: + type: "exact" + - name: five + in: + n: 5 + out: false + judge: + type: "exact" + - name: six + in: + n: 6 + out: false + judge: + type: "exact" + - name: nine + in: + n: 9 + out: true + judge: + type: "exact" + - name: sixteen + in: + n: 16 + out: false + judge: + type: "exact" + - name: twenty-five + in: + n: 25 + out: true + judge: + type: "exact" + - name: forty-nine + in: + n: 49 + out: true + judge: + type: "exact" + - name: sixty-four + in: + n: 64 + out: false + judge: + type: "exact" + - name: eighty-one + in: + n: 81 + out: false + judge: + type: "exact" + - name: one-hundred + in: + n: 100 + out: false + judge: + type: "exact" + - name: one-hundred-twenty-one + in: + n: 121 + out: true + judge: + type: "exact" + - name: one-hundred-sixty-nine + in: + n: 169 + out: true + judge: + type: "exact" + - name: one-hundred-eighty + in: + n: 180 + out: false + judge: + type: "exact" + - name: two-hundred-eighty-nine + in: + n: 289 + out: true + judge: + type: "exact" + - name: three-hundred-sixty-one + in: + n: 361 + out: true + judge: + type: "exact" + - name: four-hundred + in: + n: 400 + out: false + judge: + type: "exact" + - name: five-hundred-twenty-nine + in: + n: 529 + out: true + judge: + type: "exact" + - name: six-hundred-twenty-five + in: + n: 625 + out: false + judge: + type: "exact" + - name: seven-hundred-twenty-nine + in: + n: 729 + out: false + judge: + type: "exact" + - name: eight-hundred-forty-one + in: + n: 841 + out: true + judge: + type: "exact" + - name: nine-hundred-sixty-one + in: + n: 961 + out: true + judge: + type: "exact" + - name: one-thousand + in: + n: 1000 + out: false + judge: + type: "exact" + - name: one-thousand-two-hundred-twenty-one + in: + n: 1221 + out: false + judge: + type: "exact" + - name: one-thousand-four-hundred-forty-one + in: + n: 1441 + out: false + judge: + type: "exact" + - name: two-thousand-four-hundred-one + in: + n: 2401 + out: false + judge: + type: "exact" + - name: three-thousand-two-hundred-four + in: + n: 3204 + out: false + judge: + type: "exact" + - name: three-thousand-four-hundred-twenty-five + in: + n: 3425 + out: false + judge: + type: "exact" + - name: four-thousand-four-hundred-ninety-six + in: + n: 4496 + out: false + judge: + type: "exact" + - name: five-thousand-two-hundred-ninety-two + in: + n: 5292 + out: false + judge: + type: "exact" + - name: six-thousand-eight-hundred-eighty-nine + in: + n: 6889 + out: true + judge: + type: "exact" + - name: eight-thousand-two-hundred-eighty-one + in: + n: 8281 + out: false + judge: + type: "exact" + - name: ten-thousand + in: + n: 10000 + out: false + judge: + type: "exact" + - name: generated-small + in: + n: + gen: "int" + min: 1 + max: 100 + judge: + type: "exact" + seed: 195201 + - name: generated-medium + in: + n: + gen: "int" + min: 101 + max: 2500 + judge: + type: "exact" + seed: 195202 + - name: generated-upper + in: + n: + gen: "int" + min: 2501 + max: 10000 + judge: + type: "exact" + seed: 195203 + - name: generated-full-range + in: + n: + gen: "int" + min: 1 + max: 10000 + judge: + type: "exact" + seed: 195204 + - name: generated-near-limit + in: + n: + gen: "int" + min: 9900 + max: 10000 + judge: + type: "exact" + seed: 195205 diff --git a/tests/1501-2000/1952. three-divisors/sol.cpp b/tests/1501-2000/1952. three-divisors/sol.cpp new file mode 100644 index 00000000..156b6353 --- /dev/null +++ b/tests/1501-2000/1952. three-divisors/sol.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + bool isThree(int n) { + int count = 0; + for (int i = 1; i <= n; i++) { + if (n % i == 0) { + count++; + } + } + return count == 3; + } +}; diff --git a/tests/1501-2000/1952. three-divisors/sol.cs b/tests/1501-2000/1952. three-divisors/sol.cs new file mode 100644 index 00000000..dec7f723 --- /dev/null +++ b/tests/1501-2000/1952. three-divisors/sol.cs @@ -0,0 +1,11 @@ +public class Solution { + public bool IsThree(int n) { + int count = 0; + for (int i = 1; i <= n; i++) { + if (n % i == 0) { + count++; + } + } + return count == 3; + } +} diff --git a/tests/1501-2000/1952. three-divisors/sol.dart b/tests/1501-2000/1952. three-divisors/sol.dart new file mode 100644 index 00000000..9df40074 --- /dev/null +++ b/tests/1501-2000/1952. three-divisors/sol.dart @@ -0,0 +1,11 @@ +class Solution { + bool isThree(int n) { + var count = 0; + for (var i = 1; i <= n; i++) { + if (n % i == 0) { + count++; + } + } + return count == 3; + } +} diff --git a/tests/1501-2000/1952. three-divisors/sol.go b/tests/1501-2000/1952. three-divisors/sol.go new file mode 100644 index 00000000..305acbdd --- /dev/null +++ b/tests/1501-2000/1952. three-divisors/sol.go @@ -0,0 +1,9 @@ +func isThree(n int) bool { + count := 0 + for i := 1; i <= n; i++ { + if n%i == 0 { + count++ + } + } + return count == 3 +} diff --git a/tests/1501-2000/1952. three-divisors/sol.java b/tests/1501-2000/1952. three-divisors/sol.java new file mode 100644 index 00000000..467f2da2 --- /dev/null +++ b/tests/1501-2000/1952. three-divisors/sol.java @@ -0,0 +1,11 @@ +class Solution { + public boolean isThree(int n) { + int count = 0; + for (int i = 1; i <= n; i++) { + if (n % i == 0) { + count++; + } + } + return count == 3; + } +} diff --git a/tests/1501-2000/1952. three-divisors/sol.kt b/tests/1501-2000/1952. three-divisors/sol.kt new file mode 100644 index 00000000..b35b7be1 --- /dev/null +++ b/tests/1501-2000/1952. three-divisors/sol.kt @@ -0,0 +1,11 @@ +class Solution { + fun isThree(n: Int): Boolean { + var count = 0 + for (i in 1..n) { + if (n % i == 0) { + count++ + } + } + return count == 3 + } +} diff --git a/tests/1501-2000/1952. three-divisors/sol.py b/tests/1501-2000/1952. three-divisors/sol.py new file mode 100644 index 00000000..bcafb119 --- /dev/null +++ b/tests/1501-2000/1952. three-divisors/sol.py @@ -0,0 +1,8 @@ +class Solution: + def isThree(self, n: int) -> bool: + count = 0 + for i in range(1, n + 1): + if n % i == 0: + count += 1 + + return count == 3 diff --git a/tests/1501-2000/1952. three-divisors/sol.py2 b/tests/1501-2000/1952. three-divisors/sol.py2 new file mode 100644 index 00000000..b840709d --- /dev/null +++ b/tests/1501-2000/1952. three-divisors/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def isThree(self, n): + """ + :type n: int + :rtype: bool + """ + count = 0 + for i in range(1, n + 1): + if n % i == 0: + count += 1 + return count == 3 diff --git a/tests/1501-2000/1952. three-divisors/sol.rb b/tests/1501-2000/1952. three-divisors/sol.rb new file mode 100644 index 00000000..dca80184 --- /dev/null +++ b/tests/1501-2000/1952. three-divisors/sol.rb @@ -0,0 +1,9 @@ +# @param {Integer} n +# @return {Boolean} +def is_three(n) + count = 0 + (1..n).each do |i| + count += 1 if n % i == 0 + end + count == 3 +end diff --git a/tests/1501-2000/1952. three-divisors/sol.rs b/tests/1501-2000/1952. three-divisors/sol.rs new file mode 100644 index 00000000..375aa906 --- /dev/null +++ b/tests/1501-2000/1952. three-divisors/sol.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn is_three(n: i32) -> bool { + let mut count = 0; + for i in 1..=n { + if n % i == 0 { + count += 1; + } + } + count == 3 + } +} diff --git a/tests/1501-2000/1952. three-divisors/sol.swift b/tests/1501-2000/1952. three-divisors/sol.swift new file mode 100644 index 00000000..1a80e32f --- /dev/null +++ b/tests/1501-2000/1952. three-divisors/sol.swift @@ -0,0 +1,11 @@ +class Solution { + func isThree(_ n: Int) -> Bool { + var count = 0 + for i in 1...n { + if n % i == 0 { + count += 1 + } + } + return count == 3 + } +} diff --git a/tests/1501-2000/1952. three-divisors/sol.ts b/tests/1501-2000/1952. three-divisors/sol.ts new file mode 100644 index 00000000..8e0ffb25 --- /dev/null +++ b/tests/1501-2000/1952. three-divisors/sol.ts @@ -0,0 +1,9 @@ +function isThree(n: number): boolean { + let count = 0; + for (let i = 1; i <= n; i++) { + if (n % i === 0) { + count++; + } + } + return count === 3; +} diff --git a/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/manifest.yaml b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/manifest.yaml new file mode 100644 index 00000000..87bddbd0 --- /dev/null +++ b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/manifest.yaml @@ -0,0 +1,260 @@ +entry: + id: 1953 + title: "maximum-number-of-weeks-for-which-you-can-work" + params: + milestones: + type: array + items: + type: int + call: + cpp: "Solution().numberOfWeeks({milestones})" + rust: "Solution::number_of_weeks({milestones})" + python3: "Solution().numberOfWeeks({milestones})" + python2: "Solution().numberOfWeeks({milestones})" + ruby: "number_of_weeks({milestones})" + java: "new Solution().numberOfWeeks({milestones})" + csharp: "new Solution().NumberOfWeeks({milestones})" + kotlin: "Solution().numberOfWeeks({milestones})" + go: "numberOfWeeks({milestones})" + dart: "Solution().numberOfWeeks({milestones})" + swift: "Solution().numberOfWeeks({milestones})" + typescript: "numberOfWeeks({milestones})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().numberOfWeeks(milestones, {result})" + checker: | + class Checker: + def numberOfWeeks(self, milestones, result): + if not isinstance(milestones, list) or not milestones: + return False + if any(not isinstance(x, int) or isinstance(x, bool) or x < 1 or x > 1000000000 for x in milestones): + return False + if not isinstance(result, int) or isinstance(result, bool): + return False + total = sum(milestones) + largest = max(milestones) + expected = total if largest <= total - largest else 2 * (total - largest) + 1 + return result == expected + +seed: 1953001 + +tests: + - name: "example_balanced_three" + in: + milestones: [1, 2, 3] + out: 6 + - name: "example_dominant_project" + in: + milestones: [5, 2, 1] + out: 7 + - name: "two_equal_projects" + in: + milestones: [1, 1] + out: 2 + - name: "two_unequal_projects" + in: + milestones: [1, 2] + out: 3 + - name: "single_project_one" + in: + milestones: [1] + out: 1 + - name: "single_project_large" + in: + milestones: [1000000000] + out: 1 + - name: "all_ones" + in: + milestones: [1, 1, 1, 1, 1] + out: 5 + - name: "balanced_four" + in: + milestones: [4, 4, 4, 4] + out: 16 + - name: "largest_exactly_rest" + in: + milestones: [3, 1, 1, 1] + out: 6 + - name: "largest_one_above_rest" + in: + milestones: [4, 1, 1, 1] + out: 7 + - name: "largest_far_above_rest" + in: + milestones: [10, 1, 1] + out: 5 + - name: "two_projects_large_equal" + in: + milestones: [1000000000, 1000000000] + out: 2000000000 + - name: "two_projects_large_dominant" + in: + milestones: [1000000000, 999999999] + out: 1999999999 + - name: "many_small_one_large" + in: + milestones: [20, 1, 1, 1, 1, 1] + out: 11 + - name: "many_small_balances_peak" + in: + milestones: [6, 2, 2, 2] + out: 12 + - name: "zeros_not_allowed_boundary_values" + in: + milestones: [1, 1000000000, 1] + out: 5 + - name: "strictly_increasing" + in: + milestones: [1, 2, 3, 4, 5] + out: 15 + - name: "strictly_decreasing" + in: + milestones: [5, 4, 3, 2, 1] + out: 15 + - name: "duplicate_peaks" + in: + milestones: [7, 7, 1] + out: 15 + - name: "two_maxima_with_tail" + in: + milestones: [9, 9, 2, 2] + out: 22 + - name: "one_peak_just_feasible" + in: + milestones: [8, 3, 3, 2] + out: 16 + - name: "one_peak_just_infeasible" + in: + milestones: [9, 3, 3, 2] + out: 17 + - name: "large_total_small_peak" + in: + milestones: [100, 99, 98, 97] + out: 394 + - name: "power_of_two_values" + in: + milestones: [1, 2, 4, 8, 16] + out: 31 + - name: "prime_values" + in: + milestones: [2, 3, 5, 7, 11] + out: 28 + - name: "one_peak_100_rest_1" + in: + milestones: [100, 1, 1, 1, 1, 1, 1, 1, 1, 1] + out: 19 + - name: "near_maximum_many_projects" + in: + milestones: [1000000000, 999999999, 999999998, 999999997] + out: 3999999994 + - name: "large_dominant_with_three" + in: + milestones: [1000000000, 1, 1, 1] + out: 7 + - name: "large_dominant_with_many" + in: + milestones: [1000000000, 100, 100, 100, 100] + out: 801 + - name: "alternating_sizes" + in: + milestones: [2, 50, 2, 50, 2, 50] + out: 156 + - name: "repeated_moderate" + in: + milestones: [12, 12, 12, 12, 12, 12, 12] + out: 84 + - name: "long_tail" + in: + milestones: [30, 1, 2, 3, 4, 5, 6, 7, 8, 9] + out: 75 + - name: "single_peak_equals_sum_tail" + in: + milestones: [25, 5, 5, 5, 5, 5] + out: 50 + - name: "single_peak_exceeds_sum_tail" + in: + milestones: [26, 5, 5, 5, 5, 5] + out: 51 + - name: "small_mixed" + in: + milestones: [2, 1, 3, 1, 2] + out: 9 + - name: "stress_random_small" + seed: 195301 + in: + milestones: + gen: "array" + len: + gen: "int" + min: 1 + max: 100 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + sorted: false + elemType: "int" + - name: "stress_random_medium" + seed: 195302 + in: + milestones: + gen: "array" + len: + gen: "int" + min: 1000 + max: 5000 + of: + gen: "int" + min: 1 + max: 1000000 + distinct: false + sorted: false + elemType: "int" + - name: "stress_large_uniform" + seed: 195303 + in: + milestones: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" + - name: "stress_large_small_values" + seed: 195304 + in: + milestones: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 3 + distinct: false + sorted: false + elemType: "int" + - name: "stress_large_max_values" + seed: 195305 + in: + milestones: + gen: "array" + len: 100000 + of: + gen: "int" + min: 999999998 + max: 1000000000 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.cpp b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.cpp new file mode 100644 index 00000000..88c236e6 --- /dev/null +++ b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + long long numberOfWeeks(vector& milestones) { + long long total = 0; + long long max_val = 0; + for (int m : milestones) { + total += m; + if (m > max_val) max_val = m; + } + if (max_val <= total - max_val) { + return total; + } else { + return 2 * (total - max_val) + 1; + } + } +}; diff --git a/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.cs b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.cs new file mode 100644 index 00000000..ff317e7a --- /dev/null +++ b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public long NumberOfWeeks(int[] milestones) { + long total = 0; + long maxVal = 0; + foreach (int m in milestones) { + total += m; + if (m > maxVal) maxVal = m; + } + if (maxVal <= total - maxVal) { + return total; + } else { + return 2 * (total - maxVal) + 1; + } + } +} diff --git a/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.dart b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.dart new file mode 100644 index 00000000..33823852 --- /dev/null +++ b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.dart @@ -0,0 +1,15 @@ +class Solution { + int numberOfWeeks(List milestones) { + int total = 0; + int maxVal = 0; + for (int m in milestones) { + total += m; + if (m > maxVal) maxVal = m; + } + if (maxVal <= total - maxVal) { + return total; + } else { + return 2 * (total - maxVal) + 1; + } + } +} diff --git a/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.go b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.go new file mode 100644 index 00000000..14e6fb51 --- /dev/null +++ b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.go @@ -0,0 +1,14 @@ +func numberOfWeeks(milestones []int) int64 { + var total int64 = 0 + var maxVal int64 = 0 + for _, m := range milestones { + total += int64(m) + if int64(m) > maxVal { + maxVal = int64(m) + } + } + if maxVal <= total - maxVal { + return total + } + return 2 * (total - maxVal) + 1 +} diff --git a/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.java b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.java new file mode 100644 index 00000000..faad4c44 --- /dev/null +++ b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.java @@ -0,0 +1,12 @@ +class Solution { + public long numberOfWeeks(int[] milestones) { + long total = 0; + long max_val = 0; + for (int m : milestones) { + total += m; + if (m > max_val) max_val = m; + } + if (max_val <= total - max_val) return total; + else return 2 * (total - max_val) + 1; + } +} diff --git a/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.kt b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.kt new file mode 100644 index 00000000..e3bcbb23 --- /dev/null +++ b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.kt @@ -0,0 +1,11 @@ +class Solution { + fun numberOfWeeks(milestones: IntArray): Long { + var total = 0L + var maxVal = 0L + for (m in milestones) { + total += m + if (m > maxVal) maxVal = m.toLong() + } + return if (maxVal <= total - maxVal) total else 2 * (total - maxVal) + 1 + } +} diff --git a/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.py b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.py new file mode 100644 index 00000000..28838114 --- /dev/null +++ b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.py @@ -0,0 +1,12 @@ +class Solution(object): + def numberOfWeeks(self, milestones): + """ + :type milestones: List[int] + :rtype: int + """ + total = sum(milestones) + max_val = max(milestones) + if max_val <= total - max_val: + return total + else: + return 2 * (total - max_val) + 1 diff --git a/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.py2 b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.py2 new file mode 100644 index 00000000..28838114 --- /dev/null +++ b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def numberOfWeeks(self, milestones): + """ + :type milestones: List[int] + :rtype: int + """ + total = sum(milestones) + max_val = max(milestones) + if max_val <= total - max_val: + return total + else: + return 2 * (total - max_val) + 1 diff --git a/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.rb b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.rb new file mode 100644 index 00000000..c3db257e --- /dev/null +++ b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.rb @@ -0,0 +1,11 @@ +# @param {Integer[]} milestones +# @return {Integer} +def number_of_weeks(milestones) + total = milestones.sum + max_val = milestones.max + if max_val <= total - max_val + total + else + 2 * (total - max_val) + 1 + end +end diff --git a/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.rs b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.rs new file mode 100644 index 00000000..b23c3413 --- /dev/null +++ b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn number_of_weeks(milestones: Vec) -> i64 { + let total: i64 = milestones.iter().map(|&x| x as i64).sum(); + let max_val: i64 = *milestones.iter().max().unwrap_or(&0) as i64; + if max_val <= total - max_val { + total + } else { + 2 * (total - max_val) + 1 + } + } +} diff --git a/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.swift b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.swift new file mode 100644 index 00000000..b3adca6d --- /dev/null +++ b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.swift @@ -0,0 +1,11 @@ +class Solution { + func numberOfWeeks(_ milestones: [Int]) -> Int { + let total = milestones.reduce(0, +) + let maxVal = milestones.max() ?? 0 + if maxVal <= total - maxVal { + return total + } else { + return 2 * (total - maxVal) + 1 + } + } +} diff --git a/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.ts b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.ts new file mode 100644 index 00000000..8984911b --- /dev/null +++ b/tests/1501-2000/1953. maximum-number-of-weeks-for-which-you-can-work/sol.ts @@ -0,0 +1,9 @@ +function numberOfWeeks(milestones: number[]): number { + const total = milestones.reduce((a, b) => a + b, 0); + const maxVal = Math.max(...milestones); + if (maxVal <= total - maxVal) { + return total; + } else { + return 2 * (total - maxVal) + 1; + } +} diff --git a/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/manifest.yaml b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/manifest.yaml new file mode 100644 index 00000000..419eb065 --- /dev/null +++ b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/manifest.yaml @@ -0,0 +1,222 @@ +entry: + id: 1954 + title: "minimum-garden-perimeter-to-collect-enough-apples" + params: + neededApples: + type: long + call: + cpp: "Solution().minimumPerimeter({neededApples})" + rust: "Solution::minimum_perimeter({neededApples})" + python3: "Solution().minimumPerimeter({neededApples})" + python2: "Solution().minimumPerimeter({neededApples})" + ruby: "minimum_perimeter({neededApples})" + java: "new Solution().minimumPerimeter({neededApples})" + csharp: "new Solution().MinimumPerimeter({neededApples})" + kotlin: "Solution().minimumPerimeter({neededApples})" + go: "minimumPerimeter({neededApples})" + dart: "Solution().minimumPerimeter({neededApples})" + swift: "Solution().minimumPerimeter({neededApples})" + typescript: "minimumPerimeter({neededApples})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().minimumPerimeter(neededApples, {result})" + checker: | + class Checker: + def minimumPerimeter(self, neededApples, result): + if not isinstance(neededApples, int) or not isinstance(result, int): + return False + if neededApples < 1 or result < 8 or result % 8 != 0: + return False + k = result // 8 + apples = 2 * k * (k + 1) * (2 * k + 1) + if apples < neededApples: + return False + previous = k - 1 + return previous == 0 or 2 * previous * (previous + 1) * (2 * previous + 1) < neededApples + +seed: 1954 + +tests: + - name: "example_one" + in: + neededApples: 1 + out: 8 + - name: "example_two" + in: + neededApples: 13 + out: 16 + - name: "example_three" + in: + neededApples: 1000000000 + out: 5040 + - name: "zero_to_first_boundary" + in: + neededApples: 12 + out: 8 + - name: "just_over_first_boundary" + in: + neededApples: 13 + out: 16 + - name: "second_boundary" + in: + neededApples: 60 + out: 16 + - name: "just_over_second_boundary" + in: + neededApples: 61 + out: 24 + - name: "third_boundary" + in: + neededApples: 168 + out: 24 + - name: "just_over_third_boundary" + in: + neededApples: 169 + out: 32 + - name: "fourth_boundary" + in: + neededApples: 360 + out: 32 + - name: "just_over_fourth_boundary" + in: + neededApples: 361 + out: 40 + - name: "fifth_boundary" + in: + neededApples: 660 + out: 40 + - name: "just_over_fifth_boundary" + in: + neededApples: 661 + out: 48 + - name: "sixth_boundary" + in: + neededApples: 1092 + out: 48 + - name: "just_over_sixth_boundary" + in: + neededApples: 1093 + out: 56 + - name: "seventh_boundary" + in: + neededApples: 1680 + out: 56 + - name: "just_over_seventh_boundary" + in: + neededApples: 1681 + out: 64 + - name: "eighth_boundary" + in: + neededApples: 2448 + out: 64 + - name: "just_over_eighth_boundary" + in: + neededApples: 2449 + out: 72 + - name: "ninth_boundary" + in: + neededApples: 3420 + out: 72 + - name: "just_over_ninth_boundary" + in: + neededApples: 3421 + out: 80 + - name: "tenth_boundary" + in: + neededApples: 4620 + out: 80 + - name: "just_over_tenth_boundary" + in: + neededApples: 4621 + out: 88 + - name: "eleventh_boundary" + in: + neededApples: 6072 + out: 88 + - name: "just_over_eleventh_boundary" + in: + neededApples: 6073 + out: 96 + - name: "twelfth_boundary" + in: + neededApples: 7800 + out: 96 + - name: "just_over_twelfth_boundary" + in: + neededApples: 7801 + out: 104 + - name: "thirteenth_boundary" + in: + neededApples: 9828 + out: 104 + - name: "just_over_thirteenth_boundary" + in: + neededApples: 9829 + out: 112 + - name: "fourteenth_boundary" + in: + neededApples: 12180 + out: 112 + - name: "just_over_fourteenth_boundary" + in: + neededApples: 12181 + out: 120 + - name: "fifteenth_boundary" + in: + neededApples: 14880 + out: 120 + - name: "just_over_fifteenth_boundary" + in: + neededApples: 14881 + out: 128 + - name: "sixteenth_boundary" + in: + neededApples: 17952 + out: 128 + - name: "near_int_limit" + in: + neededApples: 1000000000000000 + out: 503968 + - name: "generated_small" + seed: 195401 + in: + neededApples: + gen: "int" + min: 1 + max: 1000000 + - name: "generated_medium" + seed: 195402 + in: + neededApples: + gen: "int" + min: 1 + max: 1000000000 + - name: "generated_large" + seed: 195403 + in: + neededApples: + gen: "int" + min: 1000000000000 + max: 100000000000000 + - name: "generated_near_constraint" + seed: 195404 + in: + neededApples: + gen: "int" + min: 900000000000000 + max: 1000000000000000 + - name: "generated_full_range" + seed: 195405 + in: + neededApples: + gen: "int" + min: 1 + max: 1000000000000000 diff --git a/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.cpp b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.cpp new file mode 100644 index 00000000..5e1214a6 --- /dev/null +++ b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + long long minimumPerimeter(long long neededApples) { + long long lo = 0, hi = 100000; + while (lo < hi) { + long long mid = (lo + hi) / 2; + long long apples = 2 * mid * (mid + 1) * (2 * mid + 1); + if (apples >= neededApples) { + hi = mid; + } else { + lo = mid + 1; + } + } + return lo * 8; + } +}; diff --git a/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.cs b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.cs new file mode 100644 index 00000000..732c8a19 --- /dev/null +++ b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public long MinimumPerimeter(long neededApples) { + long lo = 0, hi = 100000; + while (lo < hi) { + long mid = (lo + hi) / 2; + long apples = 2 * mid * (mid + 1) * (2 * mid + 1); + if (apples >= neededApples) { + hi = mid; + } else { + lo = mid + 1; + } + } + return lo * 8; + } +} diff --git a/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.dart b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.dart new file mode 100644 index 00000000..c74d81bc --- /dev/null +++ b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.dart @@ -0,0 +1,15 @@ +class Solution { + int minimumPerimeter(int neededApples) { + var lo = 0, hi = 100000; + while (lo < hi) { + var mid = (lo + hi) ~/ 2; + var apples = 2 * mid * (mid + 1) * (2 * mid + 1); + if (apples >= neededApples) { + hi = mid; + } else { + lo = mid + 1; + } + } + return lo * 8; + } +} diff --git a/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.go b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.go new file mode 100644 index 00000000..f58afb99 --- /dev/null +++ b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.go @@ -0,0 +1,13 @@ +func minimumPerimeter(neededApples int64) int64 { + lo, hi := int64(0), int64(100000) + for lo < hi { + mid := (lo + hi) / 2 + apples := 2 * mid * (mid + 1) * (2*mid + 1) + if apples >= neededApples { + hi = mid + } else { + lo = mid + 1 + } + } + return lo * 8 +} diff --git a/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.java b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.java new file mode 100644 index 00000000..b6f463f2 --- /dev/null +++ b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.java @@ -0,0 +1,15 @@ +class Solution { + public long minimumPerimeter(long neededApples) { + long lo = 0, hi = 100000; + while (lo < hi) { + long mid = (lo + hi) / 2; + long apples = 2 * mid * (mid + 1) * (2 * mid + 1); + if (apples >= neededApples) { + hi = mid; + } else { + lo = mid + 1; + } + } + return lo * 8; + } +} diff --git a/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.kt b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.kt new file mode 100644 index 00000000..af36bf20 --- /dev/null +++ b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun minimumPerimeter(neededApples: Long): Long { + var lo = 0L + var hi = 100000L + while (lo < hi) { + val mid = (lo + hi) / 2 + val apples = 2 * mid * (mid + 1) * (2 * mid + 1) + if (apples >= neededApples) { + hi = mid + } else { + lo = mid + 1 + } + } + return lo * 8 + } +} diff --git a/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.py b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.py new file mode 100644 index 00000000..7498fef9 --- /dev/null +++ b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.py @@ -0,0 +1,11 @@ +class Solution: + def minimumPerimeter(self, neededApples: int) -> int: + lo, hi = 0, 100000 + while lo < hi: + mid = (lo + hi) // 2 + apples = 2 * mid * (mid + 1) * (2 * mid + 1) + if apples >= neededApples: + hi = mid + else: + lo = mid + 1 + return lo * 8 diff --git a/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.py2 b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.py2 new file mode 100644 index 00000000..b20bcc76 --- /dev/null +++ b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def minimumPerimeter(self, neededApples): + """ + :type neededApples: int + :rtype: int + """ + lo, hi = 0, 100000 + while lo < hi: + mid = (lo + hi) // 2 + apples = 2 * mid * (mid + 1) * (2 * mid + 1) + if apples >= neededApples: + hi = mid + else: + lo = mid + 1 + return lo * 8 diff --git a/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.rb b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.rb new file mode 100644 index 00000000..00dedce6 --- /dev/null +++ b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.rb @@ -0,0 +1,15 @@ +# @param {Integer} needed_apples +# @return {Integer} +def minimum_perimeter(needed_apples) + lo, hi = 0, 100000 + while lo < hi + mid = (lo + hi) / 2 + apples = 2 * mid * (mid + 1) * (2 * mid + 1) + if apples >= needed_apples + hi = mid + else + lo = mid + 1 + end + end + lo * 8 +end diff --git a/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.rs b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.rs new file mode 100644 index 00000000..647a2412 --- /dev/null +++ b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn minimum_perimeter(needed_apples: i64) -> i64 { + let mut lo = 0i64; + let mut hi = 100000i64; + while lo < hi { + let mid = (lo + hi) / 2; + let apples = 2 * mid * (mid + 1) * (2 * mid + 1); + if apples >= needed_apples { + hi = mid; + } else { + lo = mid + 1; + } + } + lo * 8 + } +} diff --git a/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.swift b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.swift new file mode 100644 index 00000000..370b6079 --- /dev/null +++ b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func minimumPerimeter(_ neededApples: Int) -> Int { + var lo = 0, hi = 100000 + while lo < hi { + let mid = (lo + hi) / 2 + let apples = 2 * mid * (mid + 1) * (2 * mid + 1) + if apples >= neededApples { + hi = mid + } else { + lo = mid + 1 + } + } + return lo * 8 + } +} diff --git a/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.ts b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.ts new file mode 100644 index 00000000..22b2af2a --- /dev/null +++ b/tests/1501-2000/1954. minimum-garden-perimeter-to-collect-enough-apples/sol.ts @@ -0,0 +1,14 @@ +function minimumPerimeter(neededApples: number): number { + let lo = 0, + hi = 100000; + while (lo < hi) { + const mid = Math.floor((lo + hi) / 2); + const apples = 2 * mid * (mid + 1) * (2 * mid + 1); + if (apples >= neededApples) { + hi = mid; + } else { + lo = mid + 1; + } + } + return lo * 8; +} diff --git a/tests/1501-2000/1955. count-number-of-special-subsequences/manifest.yaml b/tests/1501-2000/1955. count-number-of-special-subsequences/manifest.yaml new file mode 100644 index 00000000..2573a80a --- /dev/null +++ b/tests/1501-2000/1955. count-number-of-special-subsequences/manifest.yaml @@ -0,0 +1,256 @@ +entry: + id: 1955 + title: "count-number-of-special-subsequences" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().countSpecialSubsequences({nums})" + rust: "Solution::count_special_subsequences({nums})" + python3: "Solution().countSpecialSubsequences({nums})" + python2: "Solution().countSpecialSubsequences({nums})" + ruby: "count_special_subsequences({nums})" + java: "new Solution().countSpecialSubsequences({nums})" + csharp: "new Solution().CountSpecialSubsequences({nums})" + kotlin: "Solution().countSpecialSubsequences({nums})" + go: "countSpecialSubsequences({nums})" + dart: "Solution().countSpecialSubsequences({nums})" + swift: "Solution().countSpecialSubsequences({nums})" + typescript: "countSpecialSubsequences({nums})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().countSpecialSubsequences(nums, {result})" + checker: | + class Checker: + def countSpecialSubsequences(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + mod = 1000000007 + dp0 = 0 + dp1 = 0 + dp2 = 0 + for value in nums: + if value == 0: + dp0 = (2 * dp0 + 1) % mod + elif value == 1: + dp1 = (2 * dp1 + dp0) % mod + elif value == 2: + dp2 = (2 * dp2 + dp1) % mod + else: + return False + return result == dp2 + +seed: 1955 + +tests: + - name: "single_zero" + in: + nums: [0] + out: 0 + - name: "single_one" + in: + nums: [1] + out: 0 + - name: "single_two" + in: + nums: [2] + out: 0 + - name: "two_values_zero_one" + in: + nums: [0, 1] + out: 0 + - name: "two_values_zero_two" + in: + nums: [0, 2] + out: 0 + - name: "two_values_one_two" + in: + nums: [1, 2] + out: 0 + - name: "minimum_special" + in: + nums: [0, 1, 2] + out: 1 + - name: "example_one" + in: + nums: [0, 1, 2, 2] + out: 3 + - name: "example_two" + in: + nums: [2, 2, 0, 0] + out: 0 + - name: "example_three" + in: + nums: [0, 1, 2, 0, 1, 2] + out: 7 + - name: "balanced_blocks" + in: + nums: [0, 0, 1, 1, 2, 2] + out: 27 + - name: "zeros_only" + in: + nums: [0, 0, 0, 0, 0] + out: 0 + - name: "ones_only" + in: + nums: [1, 1, 1, 1] + out: 0 + - name: "twos_only" + in: + nums: [2, 2, 2, 2] + out: 0 + - name: "zeros_ones_no_two" + in: + nums: [0, 0, 0, 1, 1] + out: 0 + - name: "ones_twos_no_zero" + in: + nums: [1, 1, 2, 2] + out: 0 + - name: "zero_two_one_two" + in: + nums: [0, 2, 1, 2] + out: 1 + - name: "leading_noise" + in: + nums: [2, 1, 0, 0, 1, 2] + out: 3 + - name: "interleaved_noise" + in: + nums: [0, 2, 0, 1, 2] + out: 3 + - name: "repeated_twos" + in: + nums: [0, 1, 2, 2, 2] + out: 7 + - name: "repeated_ones" + in: + nums: [0, 1, 1, 1, 2, 2, 2] + out: 49 + - name: "repeated_zeros" + in: + nums: [0, 0, 0, 1, 2] + out: 7 + - name: "all_blocks_three" + in: + nums: [0, 0, 0, 1, 1, 2, 2, 2] + out: 147 + - name: "zero_one_zero_one_two" + in: + nums: [0, 1, 0, 1, 2] + out: 5 + - name: "zero_one_two_zero_two" + in: + nums: [0, 1, 2, 0, 2] + out: 3 + - name: "zero_zero_one_zero_one_two" + in: + nums: [0, 0, 1, 0, 1, 2] + out: 13 + - name: "zero_one_two_one_two" + in: + nums: [0, 1, 2, 1, 2] + out: 5 + - name: "zero_one_one_zero_one_two" + in: + nums: [0, 1, 1, 0, 1, 2] + out: 9 + - name: "zero_zero_one_one_zero_one_two" + in: + nums: [0, 0, 1, 1, 0, 1, 2] + out: 25 + - name: "zero_one_two_two_zero_one_two" + in: + nums: [0, 1, 2, 2, 0, 1, 2] + out: 11 + - name: "longer_balanced_blocks" + in: + nums: [0, 0, 0, 1, 1, 1, 2, 2, 2] + out: 343 + - name: "noise_before_and_between" + in: + nums: [2, 0, 1, 2, 1, 0, 1, 2] + out: 11 + - name: "alternating_prefix" + in: + nums: [0, 1, 0, 1, 0, 1, 2, 2] + out: 51 + - name: "generated_small" + seed: 101 + in: + nums: + gen: "array" + len: + gen: "int" + min: 1 + max: 30 + of: + gen: "int" + min: 0 + max: 2 + distinct: false + sorted: false + - name: "generated_medium" + seed: 102 + in: + nums: + gen: "array" + len: + gen: "int" + min: 100 + max: 500 + of: + gen: "int" + min: 0 + max: 2 + distinct: false + sorted: false + - name: "generated_zero_heavy" + seed: 103 + in: + nums: + gen: "array" + len: + gen: "int" + min: 1000 + max: 2000 + of: + gen: "int" + min: 0 + max: 2 + distinct: false + sorted: false + - name: "stress_50000" + seed: 104 + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 0 + max: 2 + distinct: false + sorted: false + - name: "stress_maximum" + seed: 105 + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 0 + max: 2 + distinct: false + sorted: false diff --git a/tests/1501-2000/1955. count-number-of-special-subsequences/sol.cpp b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.cpp new file mode 100644 index 00000000..9cc95046 --- /dev/null +++ b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int countSpecialSubsequences(vector& nums) { + const int MOD = 1'000'000'007; + long long dp0 = 0, dp1 = 0, dp2 = 0; + for (int x : nums) { + if (x == 0) { + dp0 = (2 * dp0 + 1) % MOD; + } else if (x == 1) { + dp1 = (2 * dp1 + dp0) % MOD; + } else { + dp2 = (2 * dp2 + dp1) % MOD; + } + } + return (int)dp2; + } +}; diff --git a/tests/1501-2000/1955. count-number-of-special-subsequences/sol.cs b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.cs new file mode 100644 index 00000000..908cd032 --- /dev/null +++ b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public int CountSpecialSubsequences(int[] nums) { + const int MOD = 1_000_000_007; + long dp0 = 0, dp1 = 0, dp2 = 0; + foreach (int x in nums) { + if (x == 0) { + dp0 = (2 * dp0 + 1) % MOD; + } else if (x == 1) { + dp1 = (2 * dp1 + dp0) % MOD; + } else { + dp2 = (2 * dp2 + dp1) % MOD; + } + } + return (int)dp2; + } +} diff --git a/tests/1501-2000/1955. count-number-of-special-subsequences/sol.dart b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.dart new file mode 100644 index 00000000..d492975a --- /dev/null +++ b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.dart @@ -0,0 +1,16 @@ +class Solution { + int countSpecialSubsequences(List nums) { + const int MOD = 1000000007; + int dp0 = 0, dp1 = 0, dp2 = 0; + for (int x in nums) { + if (x == 0) { + dp0 = (2 * dp0 + 1) % MOD; + } else if (x == 1) { + dp1 = (2 * dp1 + dp0) % MOD; + } else { + dp2 = (2 * dp2 + dp1) % MOD; + } + } + return dp2; + } +} diff --git a/tests/1501-2000/1955. count-number-of-special-subsequences/sol.go b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.go new file mode 100644 index 00000000..ec21db4b --- /dev/null +++ b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.go @@ -0,0 +1,14 @@ +func countSpecialSubsequences(nums []int) int { + const MOD = 1_000_000_007 + dp0, dp1, dp2 := 0, 0, 0 + for _, x := range nums { + if x == 0 { + dp0 = (2*dp0 + 1) % MOD + } else if x == 1 { + dp1 = (2*dp1 + dp0) % MOD + } else { + dp2 = (2*dp2 + dp1) % MOD + } + } + return dp2 +} diff --git a/tests/1501-2000/1955. count-number-of-special-subsequences/sol.java b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.java new file mode 100644 index 00000000..ddcf5ae1 --- /dev/null +++ b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.java @@ -0,0 +1,16 @@ +class Solution { + public int countSpecialSubsequences(int[] nums) { + int MOD = 1_000_000_007; + long dp0 = 0, dp1 = 0, dp2 = 0; + for (int x : nums) { + if (x == 0) { + dp0 = (2 * dp0 + 1) % MOD; + } else if (x == 1) { + dp1 = (2 * dp1 + dp0) % MOD; + } else { + dp2 = (2 * dp2 + dp1) % MOD; + } + } + return (int) dp2; + } +} diff --git a/tests/1501-2000/1955. count-number-of-special-subsequences/sol.kt b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.kt new file mode 100644 index 00000000..a72060d0 --- /dev/null +++ b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun countSpecialSubsequences(nums: IntArray): Int { + val MOD = 1_000_000_007 + var dp0 = 0L + var dp1 = 0L + var dp2 = 0L + for (x in nums) { + when (x) { + 0 -> dp0 = (2 * dp0 + 1) % MOD + 1 -> dp1 = (2 * dp1 + dp0) % MOD + else -> dp2 = (2 * dp2 + dp1) % MOD + } + } + return dp2.toInt() + } +} diff --git a/tests/1501-2000/1955. count-number-of-special-subsequences/sol.py b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.py new file mode 100644 index 00000000..a3994e9c --- /dev/null +++ b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.py @@ -0,0 +1,16 @@ +class Solution: + def countSpecialSubsequences(self, nums: list[int]) -> int: + modulo = 1_000_000_007 + ending_in_zero = 0 + ending_in_one = 0 + ending_in_two = 0 + + for value in nums: + if value == 0: + ending_in_zero = (ending_in_zero * 2 + 1) % modulo + elif value == 1: + ending_in_one = (ending_in_one * 2 + ending_in_zero) % modulo + else: + ending_in_two = (ending_in_two * 2 + ending_in_one) % modulo + + return ending_in_two diff --git a/tests/1501-2000/1955. count-number-of-special-subsequences/sol.py2 b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.py2 new file mode 100644 index 00000000..154cb9a7 --- /dev/null +++ b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def countSpecialSubsequences(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + MOD = 10**9 + 7 + dp0 = dp1 = dp2 = 0 + for x in nums: + if x == 0: + dp0 = (2 * dp0 + 1) % MOD + elif x == 1: + dp1 = (2 * dp1 + dp0) % MOD + else: + dp2 = (2 * dp2 + dp1) % MOD + return dp2 diff --git a/tests/1501-2000/1955. count-number-of-special-subsequences/sol.rb b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.rb new file mode 100644 index 00000000..0af126d8 --- /dev/null +++ b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.rb @@ -0,0 +1,16 @@ +# @param {Integer[]} nums +# @return {Integer} +def count_special_subsequences(nums) + mod = 10**9 + 7 + dp0 = dp1 = dp2 = 0 + nums.each do |x| + if x == 0 + dp0 = (2 * dp0 + 1) % mod + elsif x == 1 + dp1 = (2 * dp1 + dp0) % mod + else + dp2 = (2 * dp2 + dp1) % mod + end + end + dp2 +end diff --git a/tests/1501-2000/1955. count-number-of-special-subsequences/sol.rs b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.rs new file mode 100644 index 00000000..1f680519 --- /dev/null +++ b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn count_special_subsequences(nums: Vec) -> i32 { + const MOD: i64 = 1_000_000_007; + let mut dp0: i64 = 0; + let mut dp1: i64 = 0; + let mut dp2: i64 = 0; + for &x in nums.iter() { + if x == 0 { + dp0 = (2 * dp0 + 1) % MOD; + } else if x == 1 { + dp1 = (2 * dp1 + dp0) % MOD; + } else { + dp2 = (2 * dp2 + dp1) % MOD; + } + } + dp2 as i32 + } +} diff --git a/tests/1501-2000/1955. count-number-of-special-subsequences/sol.swift b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.swift new file mode 100644 index 00000000..d48cbcb9 --- /dev/null +++ b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func countSpecialSubsequences(_ nums: [Int]) -> Int { + let MOD = 1_000_000_007 + var dp0 = 0, dp1 = 0, dp2 = 0 + for x in nums { + if x == 0 { + dp0 = (2 * dp0 + 1) % MOD + } else if x == 1 { + dp1 = (2 * dp1 + dp0) % MOD + } else { + dp2 = (2 * dp2 + dp1) % MOD + } + } + return dp2 + } +} diff --git a/tests/1501-2000/1955. count-number-of-special-subsequences/sol.ts b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.ts new file mode 100644 index 00000000..289885f6 --- /dev/null +++ b/tests/1501-2000/1955. count-number-of-special-subsequences/sol.ts @@ -0,0 +1,16 @@ +function countSpecialSubsequences(nums: number[]): number { + const MOD = 1_000_000_007; + let dp0 = 0, + dp1 = 0, + dp2 = 0; + for (const x of nums) { + if (x === 0) { + dp0 = (2 * dp0 + 1) % MOD; + } else if (x === 1) { + dp1 = (2 * dp1 + dp0) % MOD; + } else { + dp2 = (2 * dp2 + dp1) % MOD; + } + } + return dp2; +} diff --git a/tests/1501-2000/1957. delete-characters-to-make-fancy-string/manifest.yaml b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/manifest.yaml new file mode 100644 index 00000000..c29bea43 --- /dev/null +++ b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/manifest.yaml @@ -0,0 +1,232 @@ +entry: + id: 1957 + title: "delete-characters-to-make-fancy-string" + params: + s: + type: string + call: + cpp: "Solution().makeFancyString({s})" + rust: "Solution::make_fancy_string({s})" + python3: "Solution().makeFancyString({s})" + python2: "Solution().makeFancyString({s})" + ruby: "make_fancy_string({s})" + java: "new Solution().makeFancyString({s})" + csharp: "new Solution().MakeFancyString({s})" + kotlin: "Solution().makeFancyString({s})" + go: "makeFancyString({s})" + dart: "Solution().makeFancyString({s})" + swift: "Solution().makeFancyString({s})" + typescript: "makeFancyString({s})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().makeFancyString(s, {result})" + checker: | + class Checker: + def makeFancyString(self, s, result): + if not isinstance(result, str): + return False + expected = [] + for ch in s: + if len(expected) >= 2 and expected[-1] == ch and expected[-2] == ch: + continue + expected.append(ch) + return result == ''.join(expected) + +seed: 1957 + +tests: + - name: "example_leetcode" + in: + s: "leeetcode" + out: "leetcode" + - name: "example_aabaaaa" + in: + s: "aaabaaaa" + out: "aabaa" + - name: "example_already_fancy" + in: + s: "aab" + out: "aab" + - name: "single_character" + in: + s: "z" + out: "z" + - name: "two_equal" + in: + s: "aa" + out: "aa" + - name: "three_equal" + in: + s: "aaa" + out: "aa" + - name: "four_equal" + in: + s: "aaaa" + out: "aa" + - name: "five_equal" + in: + s: "aaaaa" + out: "aa" + - name: "six_equal" + in: + s: "bbbbbb" + out: "bb" + - name: "alternating" + in: + s: "abababab" + out: "abababab" + - name: "runs_of_two" + in: + s: "aabbccddeeff" + out: "aabbccddeeff" + - name: "many_runs_of_three" + in: + s: "aaabbbcccddd" + out: "aabbccdd" + - name: "mixed_runs" + in: + s: "aabbbcccccddddde" + out: "aabbccdde" + - name: "different_edges" + in: + s: "aaab" + out: "aab" + - name: "same_edges" + in: + s: "baaab" + out: "baab" + - name: "long_middle_run" + in: + s: "abbbbbc" + out: "abbc" + - name: "long_start_run" + in: + s: "ccccccde" + out: "ccde" + - name: "long_end_run" + in: + s: "abcccccc" + out: "abcc" + - name: "all_alphabet_runs" + in: + s: "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrssstttuuuvvvwwwxxxyyyzzz" + out: "aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz" + - name: "lowercase_boundary_a" + in: + s: "aaaaaaaaab" + out: "aab" + - name: "lowercase_boundary_z" + in: + s: "yzzzzzzzzz" + out: "yzz" + - name: "runs_with_singletons" + in: + s: "aaXbbbYccccZdd" + out: "aaXbbYccZdd" + - name: "repeated_pattern" + in: + s: "aaabaaaabaaaa" + out: "aabaabaa" + - name: "only_singletons" + in: + s: "qwertyuiopasdfghjklzxcvbnm" + out: "qwertyuiopasdfghjklzxcvbnm" + - name: "two_char_run_boundaries" + in: + s: "aabccddeeffg" + out: "aabccddeeffg" + - name: "alternating_long_runs" + in: + s: "aaabbaaabbaaabbaaab" + out: "aabbaabbaabbaab" + - name: "nested_run_lengths" + in: + s: "abbbcccccdddddddeeffffffffff" + out: "abbccddeeff" + - name: "all_same_max_small" + in: + s: "mmmmmmmmmmmmmmmmmmmm" + out: "mm" + - name: "one_each_then_run" + in: + s: "abcdefgggggg" + out: "abcdefgg" + - name: "run_then_one_each" + in: + s: "aaaaaabcdefghijkl" + out: "aabcdefghijkl" + - name: "three_runs_with_same_letter_separated" + in: + s: "aaabaaa" + out: "aabaa" + - name: "near_limit_manual" + in: + s: "zzzyyyxxxwwvvvuuutttssrrrqqqpppooonnnmmmllkkkjjjiiihhhgggfff" + out: "zzyyxxwwvvuuttssrrqqppoonnmmllkkjjiihhggff" + - name: "one_long_run_between_changes" + in: + s: "abcdddddddddefgh" + out: "abcddefgh" + - name: "all_two_repetitions" + in: + s: "aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz" + out: "aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz" + - name: "large_static_run" + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: "aa" + - name: "generated_uniform_short" + seed: 195701 + in: + s: + gen: "str" + len: + gen: "int" + min: 1 + max: 200 + alphabet: "abcd" + - name: "generated_uniform_medium" + seed: 195702 + in: + s: + gen: "str" + len: + gen: "int" + min: 1000 + max: 5000 + alphabet: "abcdef" + - name: "generated_binary_long" + seed: 195703 + in: + s: + gen: "str" + len: + gen: "int" + min: 80000 + max: 100000 + alphabet: "ab" + - name: "generated_single_letter_max" + seed: 195704 + in: + s: + gen: "str" + len: 100000 + alphabet: "m" + - name: "generated_low_entropy_long" + seed: 195705 + in: + s: + gen: "str" + len: + gen: "int" + min: 50000 + max: 100000 + alphabet: "abc" diff --git a/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.cpp b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.cpp new file mode 100644 index 00000000..dd05d879 --- /dev/null +++ b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + string makeFancyString(string s) { + if (s.empty()) return ""; + string result = ""; + result += s[0]; + char last = s[0]; + int count = 1; + + for (int i = 1; i < s.size(); i++) { + if (s[i] != last) { + last = s[i]; + count = 0; + } + + count++; + if (count > 2) continue; + + result += s[i]; + } + + return result; + } +}; diff --git a/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.cs b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.cs new file mode 100644 index 00000000..e99f9101 --- /dev/null +++ b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.cs @@ -0,0 +1,23 @@ +public class Solution { + public string MakeFancyString(string s) { + if (string.IsNullOrEmpty(s)) return ""; + var result = new System.Text.StringBuilder(); + result.Append(s[0]); + char last = s[0]; + int count = 1; + + for (int i = 1; i < s.Length; i++) { + if (s[i] != last) { + last = s[i]; + count = 0; + } + + count++; + if (count > 2) continue; + + result.Append(s[i]); + } + + return result.ToString(); + } +} diff --git a/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.dart b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.dart new file mode 100644 index 00000000..25dab02f --- /dev/null +++ b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.dart @@ -0,0 +1,22 @@ +class Solution { + String makeFancyString(String s) { + if (s.isEmpty) return ""; + String result = s[0]; + String last = s[0]; + int count = 1; + + for (int i = 1; i < s.length; i++) { + if (s[i] != last) { + last = s[i]; + count = 0; + } + + count++; + if (count > 2) continue; + + result += s[i]; + } + + return result; + } +} diff --git a/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.go b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.go new file mode 100644 index 00000000..862c2f9c --- /dev/null +++ b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.go @@ -0,0 +1,24 @@ +func makeFancyString(s string) string { + if len(s) == 0 { + return "" + } + result := []byte{s[0]} + last := s[0] + count := 1 + + for i := 1; i < len(s); i++ { + if s[i] != last { + last = s[i] + count = 0 + } + + count++ + if count > 2 { + continue + } + + result = append(result, s[i]) + } + + return string(result) +} diff --git a/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.java b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.java new file mode 100644 index 00000000..1a4fae3f --- /dev/null +++ b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.java @@ -0,0 +1,23 @@ +class Solution { + public String makeFancyString(String s) { + if (s.isEmpty()) return ""; + StringBuilder result = new StringBuilder(); + result.append(s.charAt(0)); + char last = s.charAt(0); + int count = 1; + + for (int i = 1; i < s.length(); i++) { + if (s.charAt(i) != last) { + last = s.charAt(i); + count = 0; + } + + count++; + if (count > 2) continue; + + result.append(s.charAt(i)); + } + + return result.toString(); + } +} diff --git a/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.kt b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.kt new file mode 100644 index 00000000..7947de5d --- /dev/null +++ b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.kt @@ -0,0 +1,23 @@ +class Solution { + fun makeFancyString(s: String): String { + if (s.isEmpty()) return "" + val result = StringBuilder() + result.append(s[0]) + var last = s[0] + var count = 1 + + for (i in 1 until s.length) { + if (s[i] != last) { + last = s[i] + count = 0 + } + + count++ + if (count > 2) continue + + result.append(s[i]) + } + + return result.toString() + } +} diff --git a/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.py b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.py new file mode 100644 index 00000000..42ea2043 --- /dev/null +++ b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.py @@ -0,0 +1,18 @@ +class Solution: + def makeFancyString(self, s: str) -> str: + result = s[0] + last = s[0] + count = 1 + + for i in range(1, len(s)): + if s[i] != last: + last = s[i] + count = 0 + + count += 1 + if count > 2: + continue + + result += s[i] + + return result diff --git a/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.py2 b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.py2 new file mode 100644 index 00000000..7c2b8a5a --- /dev/null +++ b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.py2 @@ -0,0 +1,24 @@ +class Solution(object): + def makeFancyString(self, s): + """ + :type s: str + :rtype: str + """ + if not s: + return "" + result = [s[0]] + last = s[0] + count = 1 + + for i in range(1, len(s)): + if s[i] != last: + last = s[i] + count = 0 + + count += 1 + if count > 2: + continue + + result.append(s[i]) + + return "".join(result) diff --git a/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.rb b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.rb new file mode 100644 index 00000000..39847444 --- /dev/null +++ b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.rb @@ -0,0 +1,22 @@ +# @param {String} s +# @return {String} +def make_fancy_string(s) + return "" if s.empty? + result = s[0] + last = s[0] + count = 1 + + (1...s.length).each do |i| + if s[i] != last + last = s[i] + count = 0 + end + + count += 1 + next if count > 2 + + result += s[i] + end + + result +end diff --git a/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.rs b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.rs new file mode 100644 index 00000000..4c02ce0f --- /dev/null +++ b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn make_fancy_string(s: String) -> String { + if s.is_empty() { + return String::new(); + } + let mut result = String::from(&s[..1]); + let mut last = s.chars().next().unwrap(); + let mut count = 1; + + for ch in s.chars().skip(1) { + if ch != last { + last = ch; + count = 0; + } + + count += 1; + if count > 2 { + continue; + } + + result.push(ch); + } + + result + } +} diff --git a/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.swift b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.swift new file mode 100644 index 00000000..145a04ee --- /dev/null +++ b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.swift @@ -0,0 +1,22 @@ +class Solution { + func makeFancyString(_ s: String) -> String { + if s.isEmpty { return "" } + var result = String(s.first!) + var last = s.first! + var count = 1 + + for ch in s.dropFirst() { + if ch != last { + last = ch + count = 0 + } + + count += 1 + if count > 2 { continue } + + result.append(ch) + } + + return result + } +} diff --git a/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.ts b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.ts new file mode 100644 index 00000000..c9941f55 --- /dev/null +++ b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.ts @@ -0,0 +1,20 @@ +function makeFancyString(s: string): string { + if (s.length === 0) return ""; + let result = s[0]; + let last = s[0]; + let count = 1; + + for (let i = 1; i < s.length; i++) { + if (s[i] !== last) { + last = s[i]; + count = 0; + } + + count++; + if (count > 2) continue; + + result += s[i]; + } + + return result; +} diff --git a/tests/1501-2000/1958. check-if-move-is-legal/manifest.yaml b/tests/1501-2000/1958. check-if-move-is-legal/manifest.yaml new file mode 100644 index 00000000..636916d5 --- /dev/null +++ b/tests/1501-2000/1958. check-if-move-is-legal/manifest.yaml @@ -0,0 +1,590 @@ +entry: + id: 1958 + title: "check-if-move-is-legal" + params: + board: + type: array + items: + type: array + items: + type: char + rMove: + type: int + cMove: + type: int + color: + type: char + call: + cpp: "Solution().checkMove({board}, {rMove}, {cMove}, {color})" + rust: "Solution::check_move({board}, {rMove}, {cMove}, {color})" + python3: "Solution().checkMove({board}, {rMove}, {cMove}, {color})" + python2: "Solution().checkMove({board}, {rMove}, {cMove}, {color})" + ruby: "check_move({board}, {rMove}, {cMove}, {color})" + java: "new Solution().checkMove({board}, {rMove}, {cMove}, {color})" + csharp: "new Solution().CheckMove({board}, {rMove}, {cMove}, {color})" + kotlin: "Solution().checkMove({board}, {rMove}, {cMove}, {color})" + go: "checkMove({board}, {rMove}, {cMove}, {color})" + dart: "Solution().checkMove({board}, {rMove}, {cMove}, {color})" + swift: "Solution().checkMove({board}, {rMove}, {cMove}, {color})" + typescript: "checkMove({board}, {rMove}, {cMove}, {color})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().checkMove(board, rMove, cMove, color, {result})" + checker: | + class Checker: + def checkMove(self, board, rMove, cMove, color, result): + if not isinstance(result, bool): + return False + if board[rMove][cMove] != '.': + return False + other = 'W' if color == 'B' else 'B' + for dr, dc in ((-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)): + r, c = rMove + dr, cMove + dc + count = 0 + while 0 <= r < 8 and 0 <= c < 8 and board[r][c] == other: + count += 1 + r += dr + c += dc + if count and 0 <= r < 8 and 0 <= c < 8 and board[r][c] == color: + expected = True + break + else: + expected = False + return result == expected + +seed: 1958 + +tests: + - name: "example_horizontal" + in: + board: + - [".", ".", ".", "B", ".", ".", ".", "."] + - [".", ".", ".", "W", ".", ".", ".", "."] + - [".", ".", ".", "W", ".", ".", ".", "."] + - [".", ".", ".", "W", ".", ".", ".", "."] + - ["W", "B", "B", ".", "W", "W", "W", "B"] + - [".", ".", ".", "B", ".", ".", ".", "."] + - [".", ".", ".", "B", ".", ".", ".", "."] + - [".", ".", ".", "W", ".", ".", ".", "."] + rMove: 4 + cMove: 3 + color: "B" + out: true + - name: "example_no_endpoint" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", "B", ".", ".", "W", ".", ".", "."] + - [".", ".", "W", ".", ".", ".", ".", "."] + - [".", ".", ".", "W", "B", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", "B", "W", ".", "."] + - [".", ".", ".", ".", ".", ".", "W", "."] + - [".", ".", ".", ".", ".", ".", ".", "B"] + rMove: 4 + cMove: 4 + color: "W" + out: false + - name: "horizontal_one" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", "B", ".", "W", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 3 + cMove: 3 + color: "W" + out: false + - name: "horizontal_two" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - ["B", "W", "W", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 3 + cMove: 3 + color: "B" + out: true + - name: "horizontal_wrong_color" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - ["B", "W", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 3 + cMove: 2 + color: "B" + out: true + - name: "vertical_one" + in: + board: + - [".", ".", ".", "B", ".", ".", ".", "."] + - [".", ".", ".", "W", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 2 + cMove: 3 + color: "B" + out: true + - name: "vertical_two" + in: + board: + - [".", ".", "W", ".", ".", ".", ".", "."] + - [".", ".", "W", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", "B", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 2 + cMove: 2 + color: "B" + out: false + - name: "vertical_blocked" + in: + board: + - [".", ".", "W", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", "B", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 1 + cMove: 2 + color: "B" + out: false + - name: "diagonal_down_right" + in: + board: + - ["B", ".", ".", ".", ".", ".", ".", "."] + - [".", "W", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 2 + cMove: 2 + color: "B" + out: true + - name: "diagonal_down_left" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "B"] + - [".", ".", ".", ".", ".", ".", "W", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 2 + cMove: 5 + color: "B" + out: true + - name: "diagonal_reverse" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", "W", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "B"] + rMove: 6 + cMove: 6 + color: "B" + out: false + - name: "edge_horizontal" + in: + board: + - ["B", "W", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 0 + cMove: 2 + color: "B" + out: true + - name: "edge_vertical" + in: + board: + - ["W", ".", ".", ".", ".", ".", ".", "."] + - ["B", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 2 + cMove: 0 + color: "W" + out: true + - name: "same_color_adjacent" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - ["B", "B", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 3 + cMove: 2 + color: "B" + out: false + - name: "free_gap" + in: + board: + - ["B", ".", ".", ".", ".", ".", ".", "."] + - [".", "W", ".", ".", ".", ".", ".", "."] + - [".", ".", "W", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 3 + cMove: 3 + color: "B" + out: true + - name: "corner_empty" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", "B", ".", ".", ".", ".", ".", "."] + - [".", ".", "W", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 0 + cMove: 0 + color: "B" + out: false + - name: "corner_diagonal" + in: + board: + - [".", "W", ".", ".", ".", ".", ".", "."] + - [".", ".", "W", ".", ".", ".", ".", "."] + - [".", ".", ".", "B", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 0 + cMove: 0 + color: "B" + out: false + - name: "long_horizontal_reverse" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", "W", "W", "W", "B", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 3 + cMove: 2 + color: "B" + out: true + - name: "long_vertical_reverse" + in: + board: + - [".", ".", ".", ".", "B", ".", ".", "."] + - [".", ".", ".", ".", "W", ".", ".", "."] + - [".", ".", ".", ".", "W", ".", ".", "."] + - [".", ".", ".", ".", "W", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 4 + cMove: 4 + color: "B" + out: true + - name: "diagonal_blocked_by_empty" + in: + board: + - ["B", ".", ".", ".", ".", ".", ".", "."] + - [".", "W", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", "W", ".", ".", ".", "."] + - [".", ".", ".", ".", "B", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 2 + cMove: 2 + color: "B" + out: true + - name: "middle_horizontal_white" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - ["W", "B", "B", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 3 + cMove: 3 + color: "W" + out: true + - name: "middle_vertical_white" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", "W", ".", ".", ".", ".", "."] + - [".", ".", "B", ".", ".", ".", ".", "."] + - [".", ".", "B", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 4 + cMove: 2 + color: "W" + out: true + - name: "only_opposite_no_endpoint" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", "W", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 3 + cMove: 3 + color: "B" + out: false + - name: "opposite_chain_reaches_edge" + in: + board: + - ["B", "W", "W", "W", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 0 + cMove: 4 + color: "B" + out: true + - name: "other_direction_legal" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", "B", "W", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 3 + cMove: 5 + color: "B" + out: true + - name: "center_all_empty" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 4 + cMove: 4 + color: "W" + out: false + - name: "anti_diagonal_center" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "B"] + - [".", ".", ".", ".", ".", ".", "W", "."] + - [".", ".", ".", ".", ".", "W", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 3 + cMove: 4 + color: "B" + out: true + - name: "left_edge_no_line" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "."] + - ["W", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - ["B", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 2 + cMove: 0 + color: "B" + out: false + - name: "right_edge_line" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "B"] + - [".", ".", ".", ".", ".", ".", ".", "W"] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 3 + cMove: 7 + color: "B" + out: true + - name: "diagonal_same_color_end" + in: + board: + - ["B", ".", ".", ".", ".", ".", ".", "."] + - [".", "W", ".", ".", ".", ".", ".", "."] + - [".", ".", "W", ".", ".", ".", "."] + - [".", ".", ".", "W", ".", ".", "."] + - [".", ".", ".", ".", "B", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 4 + cMove: 4 + color: "B" + out: true + - name: "diagonal_wrong_color_end" + in: + board: + - ["W", ".", ".", ".", ".", ".", ".", "."] + - [".", "B", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 2 + cMove: 2 + color: "B" + out: false + - name: "two_directions_one_valid" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", "W", ".", ".", ".", "."] + - [".", ".", ".", "W", ".", ".", ".", "."] + - ["B", "W", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 3 + cMove: 2 + color: "B" + out: true + - name: "near_corner_diagonal" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", "B", ".", ".", ".", ".", "."] + - [".", "W", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 3 + cMove: 0 + color: "B" + out: true + - name: "single_opposite_at_border" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", "W", "B", "."] + rMove: 7 + cMove: 4 + color: "B" + out: true + - name: "full_row_alternating" + in: + board: + - [".", ".", ".", ".", ".", ".", ".", "."] + - ["B", "W", "B", "W", ".", "B", "W", "B"] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + - [".", ".", ".", ".", ".", ".", ".", "."] + rMove: 1 + cMove: 4 + color: "W" + out: true diff --git a/tests/1501-2000/1958. check-if-move-is-legal/sol.cpp b/tests/1501-2000/1958. check-if-move-is-legal/sol.cpp new file mode 100644 index 00000000..2058ac42 --- /dev/null +++ b/tests/1501-2000/1958. check-if-move-is-legal/sol.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + bool checkMove(vector>& board, int rMove, int cMove, char color) { + char opposite = (color == 'B') ? 'W' : 'B'; + int dirs[8][2] = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}}; + + for (int i = 0; i < 8; ++i) { + int r = rMove + dirs[i][0]; + int c = cMove + dirs[i][1]; + int cnt = 0; + + while (r >= 0 && r < 8 && c >= 0 && c < 8 && board[r][c] == opposite) { + r += dirs[i][0]; + c += dirs[i][1]; + cnt++; + } + + if (cnt >= 1 && r >= 0 && r < 8 && c >= 0 && c < 8 && board[r][c] == color) { + return true; + } + } + + return false; + } +}; diff --git a/tests/1501-2000/1958. check-if-move-is-legal/sol.cs b/tests/1501-2000/1958. check-if-move-is-legal/sol.cs new file mode 100644 index 00000000..ee549c96 --- /dev/null +++ b/tests/1501-2000/1958. check-if-move-is-legal/sol.cs @@ -0,0 +1,28 @@ +public class Solution { + public bool CheckMove(char[][] board, int rMove, int cMove, char color) { + char opposite = color == 'B' ? 'W' : 'B'; + int[,] dirs = new int[,] { + {-1,-1},{-1,0},{-1,1}, + {0,-1}, {0,1}, + {1,-1},{1,0},{1,1} + }; + + for (int i = 0; i < 8; i++) { + int r = rMove + dirs[i,0]; + int c = cMove + dirs[i,1]; + int cnt = 0; + + while (r >= 0 && r < 8 && c >= 0 && c < 8 && board[r][c] == opposite) { + r += dirs[i,0]; + c += dirs[i,1]; + cnt++; + } + + if (cnt >= 1 && r >= 0 && r < 8 && c >= 0 && c < 8 && board[r][c] == color) { + return true; + } + } + + return false; + } +} diff --git a/tests/1501-2000/1958. check-if-move-is-legal/sol.dart b/tests/1501-2000/1958. check-if-move-is-legal/sol.dart new file mode 100644 index 00000000..75a647e0 --- /dev/null +++ b/tests/1501-2000/1958. check-if-move-is-legal/sol.dart @@ -0,0 +1,28 @@ +class Solution { + bool checkMove(List> board, int rMove, int cMove, String color) { + String opposite = color == 'B' ? 'W' : 'B'; + List> dirs = [ + [-1,-1],[-1,0],[-1,1], + [0,-1], [0,1], + [1,-1],[1,0],[1,1] + ]; + + for (var d in dirs) { + int r = rMove + d[0]; + int c = cMove + d[1]; + int cnt = 0; + + while (r >= 0 && r < 8 && c >= 0 && c < 8 && board[r][c] == opposite) { + r += d[0]; + c += d[1]; + cnt++; + } + + if (cnt >= 1 && r >= 0 && r < 8 && c >= 0 && c < 8 && board[r][c] == color) { + return true; + } + } + + return false; + } +} diff --git a/tests/1501-2000/1958. check-if-move-is-legal/sol.go b/tests/1501-2000/1958. check-if-move-is-legal/sol.go new file mode 100644 index 00000000..98948768 --- /dev/null +++ b/tests/1501-2000/1958. check-if-move-is-legal/sol.go @@ -0,0 +1,25 @@ +func checkMove(board [][]byte, rMove int, cMove int, color byte) bool { + opposite := byte('W') + if color == 'W' { + opposite = 'B' + } + dirs := [][2]int{{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}} + + for _, d := range dirs { + r := rMove + d[0] + c := cMove + d[1] + cnt := 0 + + for r >= 0 && r < 8 && c >= 0 && c < 8 && board[r][c] == opposite { + r += d[0] + c += d[1] + cnt++ + } + + if cnt >= 1 && r >= 0 && r < 8 && c >= 0 && c < 8 && board[r][c] == color { + return true + } + } + + return false +} diff --git a/tests/1501-2000/1958. check-if-move-is-legal/sol.java b/tests/1501-2000/1958. check-if-move-is-legal/sol.java new file mode 100644 index 00000000..64ab74fa --- /dev/null +++ b/tests/1501-2000/1958. check-if-move-is-legal/sol.java @@ -0,0 +1,24 @@ +class Solution { + public boolean checkMove(char[][] board, int rMove, int cMove, char color) { + char opposite = color == 'B' ? 'W' : 'B'; + int[][] dirs = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}}; + + for (int[] d : dirs) { + int r = rMove + d[0]; + int c = cMove + d[1]; + int cnt = 0; + + while (r >= 0 && r < 8 && c >= 0 && c < 8 && board[r][c] == opposite) { + r += d[0]; + c += d[1]; + cnt++; + } + + if (cnt >= 1 && r >= 0 && r < 8 && c >= 0 && c < 8 && board[r][c] == color) { + return true; + } + } + + return false; + } +} diff --git a/tests/1501-2000/1958. check-if-move-is-legal/sol.kt b/tests/1501-2000/1958. check-if-move-is-legal/sol.kt new file mode 100644 index 00000000..4d08e82b --- /dev/null +++ b/tests/1501-2000/1958. check-if-move-is-legal/sol.kt @@ -0,0 +1,28 @@ +class Solution { + fun checkMove(board: Array, rMove: Int, cMove: Int, color: Char): Boolean { + val opposite = if (color == 'B') 'W' else 'B' + val dirs = arrayOf( + intArrayOf(-1,-1), intArrayOf(-1,0), intArrayOf(-1,1), + intArrayOf(0,-1), intArrayOf(0,1), + intArrayOf(1,-1), intArrayOf(1,0), intArrayOf(1,1) + ) + + for (d in dirs) { + var r = rMove + d[0] + var c = cMove + d[1] + var cnt = 0 + + while (r >= 0 && r < 8 && c >= 0 && c < 8 && board[r][c] == opposite) { + r += d[0] + c += d[1] + cnt++ + } + + if (cnt >= 1 && r >= 0 && r < 8 && c >= 0 && c < 8 && board[r][c] == color) { + return true + } + } + + return false + } +} diff --git a/tests/1501-2000/1958. check-if-move-is-legal/sol.py b/tests/1501-2000/1958. check-if-move-is-legal/sol.py new file mode 100644 index 00000000..4bbde342 --- /dev/null +++ b/tests/1501-2000/1958. check-if-move-is-legal/sol.py @@ -0,0 +1,34 @@ +class Solution(object): + def checkMove(self, board, rMove, cMove, color): + """ + :type board: List[List[str]] + :type rMove: int + :type cMove: int + :type color: str + :rtype: bool + """ + opposite = "W" if color == "B" else "B" + directions = [ + (-1, -1), + (-1, 0), + (-1, 1), + (0, -1), + (0, 1), + (1, -1), + (1, 0), + (1, 1), + ] + + for dr, dc in directions: + r, c = rMove + dr, cMove + dc + count = 0 + + while 0 <= r < 8 and 0 <= c < 8 and board[r][c] == opposite: + r += dr + c += dc + count += 1 + + if count >= 1 and 0 <= r < 8 and 0 <= c < 8 and board[r][c] == color: + return True + + return False diff --git a/tests/1501-2000/1958. check-if-move-is-legal/sol.py2 b/tests/1501-2000/1958. check-if-move-is-legal/sol.py2 new file mode 100644 index 00000000..2b116076 --- /dev/null +++ b/tests/1501-2000/1958. check-if-move-is-legal/sol.py2 @@ -0,0 +1,27 @@ +class Solution(object): + def checkMove(self, board, rMove, cMove, color): + """ + :type board: List[List[str]] + :type rMove: int + :type cMove: int + :type color: str + :rtype: bool + """ + opposite = 'W' if color == 'B' else 'B' + directions = [(-1, -1), (-1, 0), (-1, 1), + (0, -1), (0, 1), + (1, -1), (1, 0), (1, 1)] + + for dr, dc in directions: + r, c = rMove + dr, cMove + dc + count = 0 + + while 0 <= r < 8 and 0 <= c < 8 and board[r][c] == opposite: + r += dr + c += dc + count += 1 + + if count >= 1 and 0 <= r < 8 and 0 <= c < 8 and board[r][c] == color: + return True + + return False diff --git a/tests/1501-2000/1958. check-if-move-is-legal/sol.rb b/tests/1501-2000/1958. check-if-move-is-legal/sol.rb new file mode 100644 index 00000000..32bbcc59 --- /dev/null +++ b/tests/1501-2000/1958. check-if-move-is-legal/sol.rb @@ -0,0 +1,29 @@ +# @param {Character[][]} board +# @param {Integer} r_move +# @param {Integer} c_move +# @param {Character} color +# @return {Boolean} +def check_move(board, r_move, c_move, color) + opposite = color == 'B' ? 'W' : 'B' + dirs = [[-1,-1],[-1,0],[-1,1], + [0,-1], [0,1], + [1,-1],[1,0],[1,1]] + + dirs.each do |dr, dc| + r = r_move + dr + c = c_move + dc + cnt = 0 + + while r >= 0 && r < 8 && c >= 0 && c < 8 && board[r][c] == opposite + r += dr + c += dc + cnt += 1 + end + + if cnt >= 1 && r >= 0 && r < 8 && c >= 0 && c < 8 && board[r][c] == color + return true + end + end + + false +end diff --git a/tests/1501-2000/1958. check-if-move-is-legal/sol.rs b/tests/1501-2000/1958. check-if-move-is-legal/sol.rs new file mode 100644 index 00000000..c0bd7fbd --- /dev/null +++ b/tests/1501-2000/1958. check-if-move-is-legal/sol.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn check_move(board: Vec>, r_move: i32, c_move: i32, color: char) -> bool { + let opposite = if color == 'B' { 'W' } else { 'B' }; + let dirs = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]; + + for (dr, dc) in dirs.iter() { + let mut r = r_move + dr; + let mut c = c_move + dc; + let mut cnt = 0; + + while r >= 0 && r < 8 && c >= 0 && c < 8 && board[r as usize][c as usize] == opposite { + r += dr; + c += dc; + cnt += 1; + } + + if cnt >= 1 && r >= 0 && r < 8 && c >= 0 && c < 8 && board[r as usize][c as usize] == color { + return true; + } + } + + false + } +} diff --git a/tests/1501-2000/1958. check-if-move-is-legal/sol.swift b/tests/1501-2000/1958. check-if-move-is-legal/sol.swift new file mode 100644 index 00000000..1d9070c5 --- /dev/null +++ b/tests/1501-2000/1958. check-if-move-is-legal/sol.swift @@ -0,0 +1,24 @@ +class Solution { + func checkMove(_ board: [[Character]], _ rMove: Int, _ cMove: Int, _ color: Character) -> Bool { + let opposite: Character = color == "B" ? "W" : "B" + let dirs = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)] + + for (dr, dc) in dirs { + var r = rMove + dr + var c = cMove + dc + var cnt = 0 + + while r >= 0 && r < 8 && c >= 0 && c < 8 && board[r][c] == opposite { + r += dr + c += dc + cnt += 1 + } + + if cnt >= 1 && r >= 0 && r < 8 && c >= 0 && c < 8 && board[r][c] == color { + return true + } + } + + return false + } +} diff --git a/tests/1501-2000/1958. check-if-move-is-legal/sol.ts b/tests/1501-2000/1958. check-if-move-is-legal/sol.ts new file mode 100644 index 00000000..94711269 --- /dev/null +++ b/tests/1501-2000/1958. check-if-move-is-legal/sol.ts @@ -0,0 +1,43 @@ +function checkMove( + board: string[][], + rMove: number, + cMove: number, + color: string, +): boolean { + const opposite = color === "B" ? "W" : "B"; + const dirs = [ + [-1, -1], + [-1, 0], + [-1, 1], + [0, -1], + [0, 1], + [1, -1], + [1, 0], + [1, 1], + ]; + + for (const [dr, dc] of dirs) { + let r = rMove + dr; + let c = cMove + dc; + let cnt = 0; + + while (r >= 0 && r < 8 && c >= 0 && c < 8 && board[r][c] === opposite) { + r += dr; + c += dc; + cnt++; + } + + if ( + cnt >= 1 && + r >= 0 && + r < 8 && + c >= 0 && + c < 8 && + board[r][c] === color + ) { + return true; + } + } + + return false; +} diff --git a/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/manifest.yaml b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/manifest.yaml new file mode 100644 index 00000000..d6e75bdf --- /dev/null +++ b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/manifest.yaml @@ -0,0 +1,961 @@ +entry: + id: 1959 + title: "minimum-total-space-wasted-with-k-resizing-operations" + params: + nums: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().minSpaceWastedKResizing({nums}, {k})" + rust: "Solution::min_space_wasted_k_resizing({nums}, {k})" + python3: "Solution().minSpaceWastedKResizing({nums}, {k})" + python2: "Solution().minSpaceWastedKResizing({nums}, {k})" + ruby: "min_space_wasted_k_resizing({nums}, {k})" + java: "new Solution().minSpaceWastedKResizing({nums}, {k})" + csharp: "new Solution().MinSpaceWastedKResizing({nums}, {k})" + kotlin: "Solution().minSpaceWastedKResizing({nums}, {k})" + go: "minSpaceWastedKResizing({nums}, {k})" + dart: "Solution().minSpaceWastedKResizing({nums}, {k})" + swift: "Solution().minSpaceWastedKResizing({nums}, {k})" + typescript: "minSpaceWastedKResizing({nums}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().minSpaceWastedKResizing(nums, k, {result})" + checker: | + class Checker: + def minSpaceWastedKResizing(self, nums, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + n = len(nums) + if n < 1 or not (0 <= k < n): + return False + prefix = [0] + for value in nums: + prefix.append(prefix[-1] + value) + inf = 10 ** 30 + dp = [inf] * (n + 1) + current_max = 0 + for i in range(1, n + 1): + current_max = max(current_max, nums[i - 1]) + dp[i] = current_max * i - prefix[i] + for _ in range(k): + nxt = [inf] * (n + 1) + for end in range(1, n + 1): + segment_max = 0 + for start in range(end - 1, -1, -1): + segment_max = max(segment_max, nums[start]) + cost = segment_max * (end - start) - (prefix[end] - prefix[start]) + nxt[end] = min(nxt[end], dp[start] + cost) + dp = nxt + return result == dp[n] + +seed: 1959 + +tests: + - name: "ex1" + in: + nums: [10, 20] + k: 0 + out: 10 + - name: "ex2" + in: + nums: [10, 20, 30] + k: 1 + out: 10 + - name: "ex3" + in: + nums: [10, 20, 15, 30, 20] + k: 2 + out: 15 + - name: "single_element" + in: + nums: [7] + k: 0 + out: 0 + - name: "equal_values" + in: + nums: [5, 5, 5, 5] + k: 0 + out: 0 + - name: "increasing_no_resize" + in: + nums: [1, 2, 3, 4, 5] + k: 0 + out: 10 + - name: "increasing_max_resizes" + in: + nums: [1, 2, 3, 4, 5] + k: 4 + out: 0 + - name: "decreasing_no_resize" + in: + nums: [5, 4, 3, 2, 1] + k: 0 + out: 10 + - name: "decreasing_two_resizes" + in: + nums: [10, 9, 8, 7, 6, 5] + k: 2 + out: 3 + - name: "alternating_extremes" + in: + nums: [1, 100, 1, 100, 1, 100] + k: 2 + out: 198 + - name: "repeated_spikes" + in: + nums: [1, 100, 2, 100, 3, 100] + k: 1 + out: 195 + - name: "mixed_k_zero" + in: + nums: [3, 1, 4, 1, 5, 9] + k: 0 + out: 31 + - name: "mixed_k_one" + in: + nums: [3, 1, 4, 1, 5, 9] + k: 1 + out: 11 + - name: "mixed_max_resizes" + in: + nums: [3, 1, 4, 1, 5, 9] + k: 5 + out: 0 + - name: "duplicate_peaks" + in: + nums: [2, 8, 2, 8, 2, 8, 2] + k: 2 + out: 12 + - name: "large_values" + in: + nums: [1000000, 1, 1000000] + k: 1 + out: 999999 + - name: "valley_one_resize" + in: + nums: [9, 1, 1, 1, 9] + k: 1 + out: 24 + - name: "two_constant_blocks" + in: + nums: [2, 2, 50, 50, 3, 3] + k: 2 + out: 0 + - name: "plateaus" + in: + nums: [1, 1, 3, 3, 2, 2, 4, 4] + k: 3 + out: 0 + - name: "short_two_no_resize" + in: + nums: [1, 1000000] + k: 0 + out: 999999 + - name: "short_two_resize" + in: + nums: [1, 1000000] + k: 1 + out: 0 + - name: "short_three_no_resize" + in: + nums: [1000000, 1, 1000000] + k: 0 + out: 999999 + - name: "short_three_one_resize" + in: + nums: [1000000, 1, 1000000] + k: 1 + out: 999999 + - name: "short_three_max_resize" + in: + nums: [1000000, 1, 1000000] + k: 2 + out: 0 + - name: "mixed_small" + in: + nums: [8, 3, 7, 2, 6, 1, 5, 4] + k: 2 + out: 14 + - name: "mixed_many_resizes" + in: + nums: [8, 3, 7, 2, 6, 1, 5, 4] + k: 5 + out: 5 + - name: "sawtooth" + in: + nums: [1, 3, 2, 4, 3, 5, 4, 6, 5, 7] + k: 3 + out: 8 + - name: "ten_alternating" + in: + nums: [10, 1, 9, 2, 8, 3, 7, 4, 6, 5] + k: 4 + out: 14 + - name: "ten_max_resizes" + in: + nums: [10, 1, 9, 2, 8, 3, 7, 4, 6, 5] + k: 9 + out: 0 + - name: "twenty_zigzag" + in: + nums: + [1, 20, 2, 19, 3, 18, 4, 17, 5, 16, 6, 15, 7, 14, 8, 13, 9, 12, 10, 11] + k: 5 + out: 82 + - name: "twenty_increasing_no_resize" + in: + nums: + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] + k: 0 + out: 190 + - name: "twenty_increasing_max_resize" + in: + nums: + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] + k: 19 + out: 0 + - name: "repeated_peaks" + in: + nums: [1, 10, 2, 10, 3, 10, 4, 10, 5, 10] + k: 4 + out: 18 + - name: "randomish" + in: + nums: [17, 4, 23, 9, 1, 14, 8, 30, 6, 12, 19, 2] + k: 4 + out: 69 + - name: "fifty_modulated" + in: + nums: + [ + 1, + 38, + 75, + 11, + 48, + 85, + 21, + 58, + 95, + 31, + 68, + 4, + 41, + 78, + 14, + 51, + 88, + 24, + 61, + 98, + 34, + 71, + 7, + 44, + 81, + 17, + 54, + 91, + 27, + 64, + 101, + 37, + 74, + 10, + 47, + 84, + 20, + 57, + 94, + 30, + 67, + 3, + 40, + 77, + 13, + 50, + 87, + 23, + 60, + 97, + ] + k: 7 + out: 1834 + - name: "fifty_reverse" + in: + nums: + [ + 50, + 49, + 48, + 47, + 46, + 45, + 44, + 43, + 42, + 41, + 40, + 39, + 38, + 37, + 36, + 35, + 34, + 33, + 32, + 31, + 30, + 29, + 28, + 27, + 26, + 25, + 24, + 23, + 22, + 21, + 20, + 19, + 18, + 17, + 16, + 15, + 14, + 13, + 12, + 11, + 10, + 9, + 8, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + ] + k: 12 + out: 72 + - name: "hundred_modulated" + in: + nums: + [ + 1, + 7920, + 15839, + 23758, + 31677, + 39596, + 47515, + 55434, + 63353, + 71272, + 79191, + 87110, + 95029, + 102948, + 110867, + 118786, + 126705, + 134624, + 142543, + 150462, + 158381, + 166300, + 174219, + 182138, + 190057, + 197976, + 205895, + 213814, + 221733, + 229652, + 237571, + 245490, + 253409, + 261328, + 269247, + 277166, + 285085, + 293004, + 300923, + 308842, + 316761, + 324680, + 332599, + 340518, + 348437, + 356356, + 364275, + 372194, + 380113, + 388032, + 395951, + 403870, + 411789, + 419708, + 427627, + 435546, + 443465, + 451384, + 459303, + 467222, + 475141, + 483060, + 490979, + 498898, + 506817, + 514736, + 522655, + 530574, + 538493, + 546412, + 554331, + 562250, + 570169, + 578088, + 586007, + 593926, + 601845, + 609764, + 617683, + 625602, + 633521, + 641440, + 649359, + 657278, + 665197, + 673116, + 681035, + 688954, + 696873, + 704792, + 712711, + 720630, + 728549, + 736468, + 744387, + 752306, + 760225, + 768144, + 776063, + 783982, + ] + k: 25 + out: 1140336 + - name: "hundred_reverse" + in: + nums: + [ + 100, + 99, + 98, + 97, + 96, + 95, + 94, + 93, + 92, + 91, + 90, + 89, + 88, + 87, + 86, + 85, + 84, + 83, + 82, + 81, + 80, + 79, + 78, + 77, + 76, + 75, + 74, + 73, + 72, + 71, + 70, + 69, + 68, + 67, + 66, + 65, + 64, + 63, + 62, + 61, + 60, + 59, + 58, + 57, + 56, + 55, + 54, + 53, + 52, + 51, + 50, + 49, + 48, + 47, + 46, + 45, + 44, + 43, + 42, + 41, + 40, + 39, + 38, + 37, + 36, + 35, + 34, + 33, + 32, + 31, + 30, + 29, + 28, + 27, + 26, + 25, + 24, + 23, + 22, + 21, + 20, + 19, + 18, + 17, + 16, + 15, + 14, + 13, + 12, + 11, + 10, + 9, + 8, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + ] + k: 40 + out: 77 + - name: "two_hundred_modulated" + in: + nums: + [ + 1, + 123458, + 246915, + 370372, + 493829, + 617286, + 740743, + 864200, + 987657, + 111114, + 234571, + 358028, + 481485, + 604942, + 728399, + 851856, + 975313, + 98770, + 222227, + 345684, + 469141, + 592598, + 716055, + 839512, + 962969, + 86426, + 209883, + 333340, + 456797, + 580254, + 703711, + 827168, + 950625, + 73182, + 196639, + 320096, + 443553, + 567010, + 690467, + 813924, + 937381, + 60138, + 183595, + 307052, + 430509, + 553966, + 677423, + 800880, + 924337, + 47094, + 170551, + 294008, + 417465, + 540922, + 664379, + 787836, + 911293, + 34050, + 157507, + 280964, + 404421, + 527878, + 651335, + 774792, + 898249, + 21006, + 144463, + 267920, + 391377, + 514834, + 638291, + 761748, + 885205, + 7962, + 130419, + 253876, + 377333, + 500790, + 624247, + 747704, + 871161, + 3918, + 127375, + 250832, + 374289, + 497746, + 621203, + 744660, + 868117, + 874, + 124331, + 247788, + 371245, + 494702, + 618159, + 741616, + 865073, + 121287, + 244744, + 368201, + 491658, + 615115, + 738572, + 862029, + 985486, + 109943, + 233400, + 356857, + 480314, + 603771, + 727228, + 850685, + 974142, + 97599, + 221056, + 344513, + 467970, + 591427, + 714884, + 838341, + 961798, + 85255, + 208712, + 332169, + 455626, + 579083, + 702540, + 825997, + 949454, + 72011, + 195468, + 318925, + 442382, + 565839, + 689296, + 812753, + 936210, + 58967, + 182424, + 305881, + 429338, + 552795, + 676252, + 799709, + 923166, + 45923, + 169380, + 292837, + 416294, + 539751, + 663208, + 786665, + 910122, + 32879, + 156336, + 279793, + 403250, + 526707, + 650164, + 773621, + 897078, + 2035, + 125492, + 248949, + 372406, + 495863, + 619320, + 742777, + 866234, + 989691, + 112148, + 235605, + 359062, + 482519, + 605976, + 729433, + 852890, + 976347, + 99804, + 223261, + 346718, + ] + k: 60 + out: 23579287 + - name: "two_hundred_reverse" + in: + nums: + [ + 200, + 199, + 198, + 197, + 196, + 195, + 194, + 193, + 192, + 191, + 190, + 189, + 188, + 187, + 186, + 185, + 184, + 183, + 182, + 181, + 180, + 179, + 178, + 177, + 176, + 175, + 174, + 173, + 172, + 171, + 170, + 169, + 168, + 167, + 166, + 165, + 164, + 163, + 162, + 161, + 160, + 159, + 158, + 157, + 156, + 155, + 154, + 153, + 152, + 151, + 150, + 149, + 148, + 147, + 146, + 145, + 144, + 143, + 142, + 141, + 140, + 139, + 138, + 137, + 136, + 135, + 134, + 133, + 132, + 131, + 130, + 129, + 128, + 127, + 126, + 125, + 124, + 123, + 122, + 121, + 120, + 119, + 118, + 117, + 116, + 115, + 114, + 113, + 112, + 111, + 110, + 109, + 108, + 107, + 106, + 105, + 104, + 103, + 102, + 101, + 100, + 99, + 98, + 97, + 96, + 95, + 94, + 93, + 92, + 91, + 90, + 89, + 88, + 87, + 86, + 85, + 84, + 83, + 82, + 81, + 80, + 79, + 78, + 77, + 76, + 75, + 74, + 73, + 72, + 71, + 70, + 69, + 68, + 67, + 66, + 65, + 64, + 63, + 62, + 61, + 60, + 59, + 58, + 57, + 56, + 55, + 54, + 53, + 52, + 51, + 50, + 49, + 48, + 47, + 46, + 45, + 44, + 43, + 42, + 41, + 40, + 39, + 38, + 37, + 36, + 35, + 34, + 33, + 32, + 31, + 30, + 29, + 28, + 27, + 26, + 25, + 24, + 23, + 22, + 21, + 20, + 19, + 18, + 17, + 16, + 15, + 14, + 13, + 12, + 11, + 10, + 9, + 8, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + ] + k: 99 + out: 100 diff --git a/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.cpp b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.cpp new file mode 100644 index 00000000..89fc3682 --- /dev/null +++ b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int minSpaceWastedKResizing(vector& nums, int k) { + int n = nums.size(); + vector P(n + 1, 0); + for (int i = 0; i < n; i++) { + P[i+1] = P[i] + nums[i]; + } + const int INF = 1000000000; + vector dp(n + 1, INF); + int max_v = 0; + for (int i = 1; i <= n; i++) { + max_v = max(max_v, nums[i-1]); + dp[i] = max_v * i - P[i]; + } + for (int t = 0; t < k; t++) { + vector new_dp(n + 1, INF); + new_dp[0] = 0; + for (int i = 1; i <= n; i++) { + int cur_max = 0; + for (int j = i - 1; j >= 0; j--) { + cur_max = max(cur_max, nums[j]); + int waste = cur_max * (i - j) - (P[i] - P[j]); + if (dp[j] != INF) new_dp[i] = min(new_dp[i], dp[j] + waste); + } + } + dp = new_dp; + } + return dp[n]; + } +}; diff --git a/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.cs b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.cs new file mode 100644 index 00000000..066bf8d8 --- /dev/null +++ b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.cs @@ -0,0 +1,30 @@ +public class Solution { + public int MinSpaceWastedKResizing(int[] nums, int k) { + int n = nums.Length; + int[] P = new int[n + 1]; + for (int i = 0; i < n; i++) { + P[i+1] = P[i] + nums[i]; + } + int inf = 1000000000; + int[] dp = Enumerable.Repeat(inf, n + 1).ToArray(); + int max_v = 0; + for (int i = 1; i <= n; i++) { + max_v = Math.Max(max_v, nums[i-1]); + dp[i] = max_v * i - P[i]; + } + for (int t = 0; t < k; t++) { + int[] new_dp = Enumerable.Repeat(inf, n + 1).ToArray(); + new_dp[0] = 0; + for (int i = 1; i <= n; i++) { + int cur_max = 0; + for (int j = i - 1; j >= 0; j--) { + cur_max = Math.Max(cur_max, nums[j]); + int waste = cur_max * (i - j) - (P[i] - P[j]); + if (dp[j] != inf) new_dp[i] = Math.Min(new_dp[i], dp[j] + waste); + } + } + dp = new_dp; + } + return dp[n]; + } +} diff --git a/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.dart b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.dart new file mode 100644 index 00000000..cb82cccf --- /dev/null +++ b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.dart @@ -0,0 +1,31 @@ +class Solution { + int minSpaceWastedKResizing(List nums, int k) { + int n = nums.length; + List P = List.filled(n + 1, 0); + for (int i = 0; i < n; i++) { + P[i+1] = P[i] + nums[i]; + } + List dp = List.filled(n + 1, 1 << 60); + int maxV = 0; + for (int i = 1; i <= n; i++) { + maxV = maxV > nums[i-1] ? maxV : nums[i-1]; + dp[i] = maxV * i - P[i]; + } + for (int t = 0; t < k; t++) { + List newDp = List.filled(n + 1, 1 << 60); + newDp[0] = 0; + for (int i = 1; i <= n; i++) { + int curMax = 0; + for (int j = i - 1; j >= 0; j--) { + curMax = curMax > nums[j] ? curMax : nums[j]; + int waste = curMax * (i - j) - (P[i] - P[j]); + if (dp[j] + waste < newDp[i]) { + newDp[i] = dp[j] + waste; + } + } + } + dp = newDp; + } + return dp[n]; + } +} diff --git a/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.go b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.go new file mode 100644 index 00000000..37de6ab9 --- /dev/null +++ b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.go @@ -0,0 +1,36 @@ +func minSpaceWastedKResizing(nums []int, k int) int { + n := len(nums) + P := make([]int, n+1) + for i := 0; i < n; i++ { + P[i+1] = P[i] + nums[i] + } + dp := make([]int, n+1) + const inf = int(^uint(0) >> 1) + for i := range dp { dp[i] = inf } + maxV := 0 + for i := 1; i <= n; i++ { + if nums[i-1] > maxV { + maxV = nums[i-1] + } + dp[i] = maxV*i - P[i] + } + for t := 0; t < k; t++ { + newDp := make([]int, n+1) + for i := range newDp { newDp[i] = inf } + newDp[0] = 0 + for i := 1; i <= n; i++ { + curMax := 0 + for j := i - 1; j >= 0; j-- { + if nums[j] > curMax { + curMax = nums[j] + } + waste := curMax*(i-j) - (P[i] - P[j]) + if dp[j] != inf && dp[j]+waste < newDp[i] { + newDp[i] = dp[j] + waste + } + } + } + dp = newDp + } + return dp[n] +} diff --git a/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.java b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.java new file mode 100644 index 00000000..0654c9b1 --- /dev/null +++ b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.java @@ -0,0 +1,32 @@ +class Solution { + public int minSpaceWastedKResizing(int[] nums, int k) { + int n = nums.length; + int[] P = new int[n + 1]; + for (int i = 0; i < n; i++) { + P[i+1] = P[i] + nums[i]; + } + int inf = 1000000000; + int[] dp = new int[n + 1]; + Arrays.fill(dp, inf); + int max_v = 0; + for (int i = 1; i <= n; i++) { + max_v = Math.max(max_v, nums[i-1]); + dp[i] = max_v * i - P[i]; + } + for (int t = 0; t < k; t++) { + int[] new_dp = new int[n + 1]; + Arrays.fill(new_dp, inf); + new_dp[0] = 0; + for (int i = 1; i <= n; i++) { + int cur_max = 0; + for (int j = i - 1; j >= 0; j--) { + cur_max = Math.max(cur_max, nums[j]); + int waste = cur_max * (i - j) - (P[i] - P[j]); + if (dp[j] != inf) new_dp[i] = Math.min(new_dp[i], dp[j] + waste); + } + } + dp = new_dp; + } + return dp[n]; + } +} diff --git a/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.kt b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.kt new file mode 100644 index 00000000..d7b3cc43 --- /dev/null +++ b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.kt @@ -0,0 +1,30 @@ +class Solution { + fun minSpaceWastedKResizing(nums: IntArray, k: Int): Int { + val n = nums.size + val P = IntArray(n + 1) + for (i in 0 until n) { + P[i+1] = P[i] + nums[i] + } + val inf = 1_000_000_000 + var dp = IntArray(n + 1) { inf } + var max_v = 0 + for (i in 1..n) { + max_v = maxOf(max_v, nums[i-1]) + dp[i] = max_v * i - P[i] + } + repeat(k) { + val new_dp = IntArray(n + 1) { inf } + new_dp[0] = 0 + for (i in 1..n) { + var cur_max = 0 + for (j in i-1 downTo 0) { + cur_max = maxOf(cur_max, nums[j]) + val waste = cur_max * (i - j) - (P[i] - P[j]) + if (dp[j] != inf) new_dp[i] = minOf(new_dp[i], dp[j] + waste) + } + } + dp = new_dp + } + return dp[n] + } +} diff --git a/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.py b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.py new file mode 100644 index 00000000..aec74587 --- /dev/null +++ b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.py @@ -0,0 +1,30 @@ +class Solution: + def minSpaceWastedKResizing(self, nums: List[int], k: int) -> int: + n = len(nums) + # 1. Prefix Sums for O(1) Integral calculation + P = [0] * (n + 1) + for i in range(n): + P[i + 1] = P[i] + nums[i] + + # 2. Memory-Efficient DP: Only store the previous k-state + # Base Case: k=0 (No resizes, one constant size for the whole array) + dp = [float("inf")] * (n + 1) + max_v = 0 + for i in range(1, n + 1): + max_v = max(max_v, nums[i - 1]) + dp[i] = max_v * i - P[i] + + # 3. Successive Approximation for k = 1 to k + for _ in range(k): + new_dp = [float("inf")] * (n + 1) + new_dp[0] = 0 + for i in range(1, n + 1): + cur_max = 0 + # Searching for the optimal 'Heaviside Jump' point + for j in range(i - 1, -1, -1): + cur_max = max(cur_max, nums[j]) + waste = cur_max * (i - j) - (P[i] - P[j]) + new_dp[i] = min(new_dp[i], dp[j] + waste) + dp = new_dp + + return dp[n] diff --git a/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.py2 b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.py2 new file mode 100644 index 00000000..0d1014bf --- /dev/null +++ b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.py2 @@ -0,0 +1,27 @@ +class Solution(object): + def minSpaceWastedKResizing(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + n = len(nums) + P = [0] * (n + 1) + for i in range(n): + P[i+1] = P[i] + nums[i] + dp = [float('inf')] * (n + 1) + max_v = 0 + for i in range(1, n + 1): + max_v = max(max_v, nums[i-1]) + dp[i] = max_v * i - P[i] + for _ in range(k): + new_dp = [float('inf')] * (n + 1) + new_dp[0] = 0 + for i in range(1, n + 1): + cur_max = 0 + for j in range(i - 1, -1, -1): + cur_max = max(cur_max, nums[j]) + waste = cur_max * (i - j) - (P[i] - P[j]) + new_dp[i] = min(new_dp[i], dp[j] + waste) + dp = new_dp + return dp[n] diff --git a/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.rb b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.rb new file mode 100644 index 00000000..987aa09f --- /dev/null +++ b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.rb @@ -0,0 +1,30 @@ +# @param {Integer[]} nums +# @param {Integer} k +# @return {Integer} +def min_space_wasted_k_resizing(nums, k) + n = nums.length + p = [0] * (n + 1) + (0...n).each do |i| + p[i+1] = p[i] + nums[i] + end + dp = Array.new(n + 1, Float::INFINITY) + max_v = 0 + (1..n).each do |i| + max_v = [max_v, nums[i-1]].max + dp[i] = max_v * i - p[i] + end + k.times do + new_dp = Array.new(n + 1, Float::INFINITY) + new_dp[0] = 0 + (1..n).each do |i| + cur_max = 0 + (i-1).downto(0) do |j| + cur_max = [cur_max, nums[j]].max + waste = cur_max * (i - j) - (p[i] - p[j]) + new_dp[i] = [new_dp[i], dp[j] + waste].min + end + end + dp = new_dp + end + dp[n] +end diff --git a/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.rs b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.rs new file mode 100644 index 00000000..c4585734 --- /dev/null +++ b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.rs @@ -0,0 +1,33 @@ +impl Solution { + pub fn min_space_wasted_k_resizing(nums: Vec, k: i32) -> i32 { + let n = nums.len(); + let mut p = vec![0; n + 1]; + for i in 0..n { + p[i+1] = p[i] + nums[i]; + } + let inf = 1_000_000_000i32; + let mut dp = vec![inf; n + 1]; + dp[0] = 0; + let mut max_v = 0; + for i in 1..=n { + max_v = max_v.max(nums[i-1]); + dp[i] = max_v * i as i32 - p[i]; + } + for _ in 0..k { + let mut new_dp = vec![inf; n + 1]; + new_dp[0] = 0; + for i in 1..=n { + let mut cur_max = 0; + for j in (0..i).rev() { + cur_max = cur_max.max(nums[j]); + let waste = cur_max * (i as i32 - j as i32) - (p[i] - p[j]); + if dp[j] != i32::MAX { + if dp[j] != inf { new_dp[i] = new_dp[i].min(dp[j] + waste); } + } + } + } + dp = new_dp; + } + dp[n] + } +} diff --git a/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.swift b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.swift new file mode 100644 index 00000000..61081bab --- /dev/null +++ b/tests/1501-2000/1959. minimum-total-space-wasted-with-k-resizing-operations/sol.swift @@ -0,0 +1,30 @@ +class Solution { + func minSpaceWastedKResizing(_ nums: [Int], _ k: Int) -> Int { + let n = nums.count + var P = [Int](repeating: 0, count: n + 1) + for i in 0..= 0; j--) { + curMax = Math.max(curMax, nums[j]); + const waste = curMax * (i - j) - (P[i] - P[j]); + newDp[i] = Math.min(newDp[i], dp[j] + waste); + } + } + dp = newDp; + } + return dp[n]; +} diff --git a/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/manifest.yaml b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/manifest.yaml new file mode 100644 index 00000000..6449a3d6 --- /dev/null +++ b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/manifest.yaml @@ -0,0 +1,227 @@ +entry: + id: 1960 + title: "maximum-product-of-the-length-of-two-palindromic-substrings" + params: + s: + type: string + call: + cpp: "Solution().maxProduct({s})" + rust: "Solution::max_product({s})" + python3: "Solution().maxProduct({s})" + python2: "Solution().maxProduct({s})" + ruby: "max_product({s})" + java: "new Solution().maxProduct({s})" + csharp: "new Solution().MaxProduct({s})" + kotlin: "Solution().maxProduct({s})" + go: "maxProduct({s})" + dart: "Solution().maxProduct({s})" + swift: "Solution().maxProduct({s})" + typescript: "maxProduct({s})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().maxProduct(s, {result})" + checker: | + class Checker: + def maxProduct(self, s, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + n = len(s) + if n < 2 or n > 100000 or any(c < 'a' or c > 'z' for c in s): + return False + d = [0] * n + left_center = 0 + right_center = -1 + for i in range(n): + radius = 1 if i > right_center else min(d[left_center + right_center - i], right_center - i + 1) + while i - radius >= 0 and i + radius < n and s[i - radius] == s[i + radius]: + radius += 1 + d[i] = radius + if i + radius - 1 > right_center: + left_center = i - radius + 1 + right_center = i + radius - 1 + ending = [0] * n + starting = [0] * n + for i, radius in enumerate(d): + length = 2 * radius - 1 + ending[i + radius - 1] = max(ending[i + radius - 1], length) + starting[i - radius + 1] = max(starting[i - radius + 1], length) + for i in range(n - 2, -1, -1): + ending[i] = max(ending[i], ending[i + 1] - 2) + for i in range(1, n): + ending[i] = max(ending[i], ending[i - 1]) + starting[i] = max(starting[i], starting[i - 1] - 2) + for i in range(n - 2, -1, -1): + starting[i] = max(starting[i], starting[i + 1]) + expected = max(ending[i] * starting[i + 1] for i in range(n - 1)) + return result == expected + +seed: 19601960 + +tests: + - name: "two_different" + in: + s: "ab" + out: 1 + - name: "two_equal" + in: + s: "aa" + out: 1 + - name: "single_center" + in: + s: "aba" + out: 1 + - name: "short_run" + in: + s: "aaa" + out: 1 + - name: "example_one" + in: + s: "ababbb" + out: 9 + - name: "example_two" + in: + s: "zaaaxbbby" + out: 9 + - name: "no_long_palindromes" + in: + s: "abcde" + out: 1 + - name: "two_pairs" + in: + s: "aabb" + out: 1 + - name: "even_palindrome_only" + in: + s: "abba" + out: 1 + - name: "classic_long" + in: + s: "racecar" + out: 5 + - name: "even_run" + in: + s: "aaaaaa" + out: 9 + - name: "odd_run" + in: + s: "aaaaaaa" + out: 9 + - name: "overlapping_candidates" + in: + s: "abababa" + out: 9 + - name: "two_long_palindromes" + in: + s: "abcbaabcba" + out: 25 + - name: "alternating_long" + in: + s: "abababababababababab" + out: 99 + - name: "large_uniform" + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: 625 + - name: "large_alternating" + in: + s: "ababababababababababababababababababababababababab" + out: 625 + - name: "mixed_center" + in: + s: "abacaba" + out: 9 + - name: "two_five_palindromes" + in: + s: "xyzyxabcba" + out: 25 + - name: "nested_palindrome" + in: + s: "aabaa" + out: 3 + - name: "nested_separated" + in: + s: "aaabaaa" + out: 9 + - name: "even_block_boundary" + in: + s: "abcddcbaefg" + out: 1 + - name: "uniform_blocks" + in: + s: "aaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbb" + out: 441 + - name: "all_distinct" + in: + s: "abcdefghijklmnopqrstuvwxyz" + out: 1 + - name: "one_long_palindrome" + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: 2499 + - name: "repeated_triplet" + in: + s: "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc" + out: 1 + - name: "edge_letter_left" + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" + out: 2401 + - name: "edge_letter_right" + in: + s: "xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: 2401 + - name: "two_even_blocks" + in: + s: "abccbaabccba" + out: 1 + - name: "word_palindromes" + in: + s: "civiclevel" + out: 25 + - name: "two_odd_words" + in: + s: "noonmadam" + out: 5 + - name: "generated_uniform" + in: + s: + gen: "str" + len: 100000 + alphabet: "a" + seed: 19601 + - name: "generated_binary" + in: + s: + gen: "str" + len: 100000 + alphabet: "ab" + seed: 19602 + - name: "generated_small_alphabet" + in: + s: + gen: "str" + len: 99999 + alphabet: "abc" + seed: 19603 + - name: "generated_full_alphabet" + in: + s: + gen: "str" + len: 100000 + alphabet: "abcdefghijklmnopqrstuvwxyz" + seed: 19604 + - name: "generated_repeated_pattern" + in: + s: + gen: "str" + len: 50000 + alphabet: "abcd" + seed: 19605 diff --git a/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.cpp b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.cpp new file mode 100644 index 00000000..b0133f6a --- /dev/null +++ b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.cpp @@ -0,0 +1,81 @@ +class Solution { +public: + long long maxProduct(string s) { + int n = s.length(); + + // Manacher (odd length only) + vector d(n); + int l = 0; + int r = -1; + + for (int i = 0; i < n; i++) { + int k; + if (i > r) { + k = 1; + } else { + k = min(d[l + r - i], r - i + 1); + } + + while (i - k >= 0 && i + k < n && s[i - k] == s[i + k]) { + k++; + } + + d[i] = k; + + if (i + k - 1 > r) { + l = i - k + 1; + r = i + k - 1; + } + } + + // left[i] = max palindrome ending at i + vector left(n, 0); + + for (int i = 0; i < n; i++) { + int radius = d[i]; + int length = 2 * radius - 1; + int end = i + radius - 1; + left[end] = max(left[end], length); + } + + // propagate backwards (reduce by 2) + for (int i = n - 2; i >= 0; i--) { + left[i] = max(left[i], left[i + 1] - 2); + } + + // prefix max + for (int i = 1; i < n; i++) { + left[i] = max(left[i], left[i - 1]); + } + + + // right[i] = max palindrome starting at i + vector right(n, 0); + + for (int i = 0; i < n; i++) { + int radius = d[i]; + int length = 2 * radius - 1; + int start = i - radius + 1; + right[start] = max(right[start], length); + } + + // propagate forward (reduce by 2) + for (int i = 1; i < n; i++) { + right[i] = max(right[i], right[i - 1] - 2); + } + + // suffix max + for (int i = n - 2; i >= 0; i--) { + right[i] = max(right[i], right[i + 1]); + } + + + // try all splits + long long ans = 0; + for (int i = 0; i < n - 1; i++) { + ans = max(ans, (long long)left[i] * right[i + 1]); + } + + return ans; + } +}; diff --git a/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.cs b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.cs new file mode 100644 index 00000000..ad2ba3c0 --- /dev/null +++ b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.cs @@ -0,0 +1,80 @@ +public class Solution { + public long MaxProduct(string s) { + int n = s.Length; + + // Manacher (odd length only) + int[] d = new int[n]; + int l = 0; + int r = -1; + + for (int i = 0; i < n; i++) { + int k; + if (i > r) { + k = 1; + } else { + k = Math.Min(d[l + r - i], r - i + 1); + } + + while (i - k >= 0 && i + k < n && s[i - k] == s[i + k]) { + k++; + } + + d[i] = k; + + if (i + k - 1 > r) { + l = i - k + 1; + r = i + k - 1; + } + } + + // left[i] = max palindrome ending at i + int[] left = new int[n]; + + for (int i = 0; i < n; i++) { + int radius = d[i]; + int length = 2 * radius - 1; + int end = i + radius - 1; + left[end] = Math.Max(left[end], length); + } + + // propagate backwards (reduce by 2) + for (int i = n - 2; i >= 0; i--) { + left[i] = Math.Max(left[i], left[i + 1] - 2); + } + + // prefix max + for (int i = 1; i < n; i++) { + left[i] = Math.Max(left[i], left[i - 1]); + } + + + // right[i] = max palindrome starting at i + int[] right = new int[n]; + + for (int i = 0; i < n; i++) { + int radius = d[i]; + int length = 2 * radius - 1; + int start = i - radius + 1; + right[start] = Math.Max(right[start], length); + } + + // propagate forward (reduce by 2) + for (int i = 1; i < n; i++) { + right[i] = Math.Max(right[i], right[i - 1] - 2); + } + + // suffix max + for (int i = n - 2; i >= 0; i--) { + right[i] = Math.Max(right[i], right[i + 1]); + } + + + // try all splits + long ans = 0; + for (int i = 0; i < n - 1; i++) { + ans = Math.Max(ans, (long)left[i] * right[i + 1]); + } + + return ans; + } +} diff --git a/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.dart b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.dart new file mode 100644 index 00000000..fba8ef3e --- /dev/null +++ b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.dart @@ -0,0 +1,83 @@ +class Solution { + int maxProduct(String s) { + int n = s.length; + + // Manacher (odd length only) + List d = List.filled(n, 0); + int l = 0; + int r = -1; + + for (int i = 0; i < n; i++) { + int k; + if (i > r) { + k = 1; + } else { + k = d[l + r - i] < r - i + 1 ? d[l + r - i] : r - i + 1; + } + + while (i - k >= 0 && i + k < n && s[i - k] == s[i + k]) { + k++; + } + + d[i] = k; + + if (i + k - 1 > r) { + l = i - k + 1; + r = i + k - 1; + } + } + + // left[i] = max palindrome ending at i + List left = List.filled(n, 0); + + for (int i = 0; i < n; i++) { + int radius = d[i]; + int length = 2 * radius - 1; + int end = i + radius - 1; + left[end] = left[end] > length ? left[end] : length; + } + + // propagate backwards (reduce by 2) + for (int i = n - 2; i >= 0; i--) { + int val = left[i + 1] - 2; + left[i] = left[i] > val ? left[i] : val; + } + + // prefix max + for (int i = 1; i < n; i++) { + left[i] = left[i] > left[i - 1] ? left[i] : left[i - 1]; + } + + + // right[i] = max palindrome starting at i + List right = List.filled(n, 0); + + for (int i = 0; i < n; i++) { + int radius = d[i]; + int length = 2 * radius - 1; + int start = i - radius + 1; + right[start] = right[start] > length ? right[start] : length; + } + + // propagate forward (reduce by 2) + for (int i = 1; i < n; i++) { + int val = right[i - 1] - 2; + right[i] = right[i] > val ? right[i] : val; + } + + // suffix max + for (int i = n - 2; i >= 0; i--) { + right[i] = right[i] > right[i + 1] ? right[i] : right[i + 1]; + } + + + // try all splits + int ans = 0; + for (int i = 0; i < n - 1; i++) { + int prod = left[i] * right[i + 1]; + ans = ans > prod ? ans : prod; + } + + return ans; + } +} diff --git a/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.go b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.go new file mode 100644 index 00000000..152244c7 --- /dev/null +++ b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.go @@ -0,0 +1,97 @@ +func maxProduct(s string) int64 { + n := len(s) + + // Manacher (odd length only) + d := make([]int, n) + l := 0 + r := -1 + + for i := 0; i < n; i++ { + k := 1 + if i <= r { + mirror := l + r - i + k = d[mirror] + if r-i+1 < k { + k = r - i + 1 + } + } + + for i-k >= 0 && i+k < n && s[i-k] == s[i+k] { + k++ + } + + d[i] = k + + if i+k-1 > r { + l = i - k + 1 + r = i + k - 1 + } + } + + // left[i] = max palindrome ending at i + left := make([]int, n) + + for i := 0; i < n; i++ { + radius := d[i] + length := 2*radius - 1 + end := i + radius - 1 + if left[end] < length { + left[end] = length + } + } + + // propagate backwards (reduce by 2) + for i := n - 2; i >= 0; i-- { + val := left[i+1] - 2 + if left[i] < val { + left[i] = val + } + } + + // prefix max + for i := 1; i < n; i++ { + if left[i] < left[i-1] { + left[i] = left[i-1] + } + } + + + // right[i] = max palindrome starting at i + right := make([]int, n) + + for i := 0; i < n; i++ { + radius := d[i] + length := 2*radius - 1 + start := i - radius + 1 + if right[start] < length { + right[start] = length + } + } + + // propagate forward (reduce by 2) + for i := 1; i < n; i++ { + val := right[i-1] - 2 + if right[i] < val { + right[i] = val + } + } + + // suffix max + for i := n - 2; i >= 0; i-- { + if right[i] < right[i+1] { + right[i] = right[i+1] + } + } + + + // try all splits + var ans int64 = 0 + for i := 0; i < n-1; i++ { + prod := int64(left[i]) * int64(right[i+1]) + if ans < prod { + ans = prod + } + } + + return ans +} diff --git a/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.java b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.java new file mode 100644 index 00000000..96c2ba55 --- /dev/null +++ b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.java @@ -0,0 +1,80 @@ +class Solution { + public long maxProduct(String s) { + int n = s.length(); + + // Manacher (odd length only) + int[] d = new int[n]; + int l = 0; + int r = -1; + + for (int i = 0; i < n; i++) { + int k; + if (i > r) { + k = 1; + } else { + k = Math.min(d[l + r - i], r - i + 1); + } + + while (i - k >= 0 && i + k < n && s.charAt(i - k) == s.charAt(i + k)) { + k++; + } + + d[i] = k; + + if (i + k - 1 > r) { + l = i - k + 1; + r = i + k - 1; + } + } + + // left[i] = max palindrome ending at i + int[] left = new int[n]; + + for (int i = 0; i < n; i++) { + int radius = d[i]; + int length = 2 * radius - 1; + int end = i + radius - 1; + left[end] = Math.max(left[end], length); + } + + // propagate backwards (reduce by 2) + for (int i = n - 2; i >= 0; i--) { + left[i] = Math.max(left[i], left[i + 1] - 2); + } + + // prefix max + for (int i = 1; i < n; i++) { + left[i] = Math.max(left[i], left[i - 1]); + } + + + // right[i] = max palindrome starting at i + int[] right = new int[n]; + + for (int i = 0; i < n; i++) { + int radius = d[i]; + int length = 2 * radius - 1; + int start = i - radius + 1; + right[start] = Math.max(right[start], length); + } + + // propagate forward (reduce by 2) + for (int i = 1; i < n; i++) { + right[i] = Math.max(right[i], right[i - 1] - 2); + } + + // suffix max + for (int i = n - 2; i >= 0; i--) { + right[i] = Math.max(right[i], right[i + 1]); + } + + + // try all splits + long ans = 0; + for (int i = 0; i < n - 1; i++) { + ans = Math.max(ans, (long) left[i] * right[i + 1]); + } + + return ans; + } +} diff --git a/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.kt b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.kt new file mode 100644 index 00000000..f4e9ac1d --- /dev/null +++ b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.kt @@ -0,0 +1,80 @@ +class Solution { + fun maxProduct(s: String): Long { + val n = s.length + + // Manacher (odd length only) + val d = IntArray(n) + var l = 0 + var r = -1 + + for (i in 0 until n) { + var k: Int + if (i > r) { + k = 1 + } else { + k = minOf(d[l + r - i], r - i + 1) + } + + while (i - k >= 0 && i + k < n && s[i - k] == s[i + k]) { + k++ + } + + d[i] = k + + if (i + k - 1 > r) { + l = i - k + 1 + r = i + k - 1 + } + } + + // left[i] = max palindrome ending at i + val left = IntArray(n) + + for (i in 0 until n) { + val radius = d[i] + val length = 2 * radius - 1 + val end = i + radius - 1 + left[end] = maxOf(left[end], length) + } + + // propagate backwards (reduce by 2) + for (i in n - 2 downTo 0) { + left[i] = maxOf(left[i], left[i + 1] - 2) + } + + // prefix max + for (i in 1 until n) { + left[i] = maxOf(left[i], left[i - 1]) + } + + + // right[i] = max palindrome starting at i + val right = IntArray(n) + + for (i in 0 until n) { + val radius = d[i] + val length = 2 * radius - 1 + val start = i - radius + 1 + right[start] = maxOf(right[start], length) + } + + // propagate forward (reduce by 2) + for (i in 1 until n) { + right[i] = maxOf(right[i], right[i - 1] - 2) + } + + // suffix max + for (i in n - 2 downTo 0) { + right[i] = maxOf(right[i], right[i + 1]) + } + + + // try all splits + var ans = 0L + for (i in 0 until n - 1) { + ans = maxOf(ans, left[i].toLong() * right[i + 1].toLong()) + } + + return ans + } +} diff --git a/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.py b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.py new file mode 100644 index 00000000..34b2b22a --- /dev/null +++ b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.py @@ -0,0 +1,64 @@ +class Solution: + def maxProduct(self, s): + n = len(s) + + # Manacher (odd length only) + d = [0] * n + l = 0 + r = -1 + + for i in range(n): + if i > r: + k = 1 + else: + k = min(d[l + r - i], r - i + 1) + + while i - k >= 0 and i + k < n and s[i - k] == s[i + k]: + k += 1 + + d[i] = k + + if i + k - 1 > r: + l = i - k + 1 + r = i + k - 1 + + # left[i] = max palindrome ending at i + left = [0] * n + + for i in range(n): + radius = d[i] + length = 2 * radius - 1 + end = i + radius - 1 + left[end] = max(left[end], length) + + # propagate backwards (reduce by 2) + for i in range(n - 2, -1, -1): + left[i] = max(left[i], left[i + 1] - 2) + + # prefix max + for i in range(1, n): + left[i] = max(left[i], left[i - 1]) + + # right[i] = max palindrome starting at i + right = [0] * n + + for i in range(n): + radius = d[i] + length = 2 * radius - 1 + start = i - radius + 1 + right[start] = max(right[start], length) + + # propagate forward (reduce by 2) + for i in range(1, n): + right[i] = max(right[i], right[i - 1] - 2) + + # suffix max + for i in range(n - 2, -1, -1): + right[i] = max(right[i], right[i + 1]) + + # try all splits + ans = 0 + for i in range(n - 1): + ans = max(ans, left[i] * right[i + 1]) + + return ans diff --git a/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.py2 b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.py2 new file mode 100644 index 00000000..19446fe3 --- /dev/null +++ b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.py2 @@ -0,0 +1,70 @@ +class Solution(object): + def maxProduct(self, s): + """ + :type s: str + :rtype: int + """ + n = len(s) + + # Manacher (odd length only) + d = [0] * n + l = 0 + r = -1 + + for i in range(n): + if i > r: + k = 1 + else: + k = min(d[l + r - i], r - i + 1) + + while i - k >= 0 and i + k < n and s[i - k] == s[i + k]: + k += 1 + + d[i] = k + + if i + k - 1 > r: + l = i - k + 1 + r = i + k - 1 + + # left[i] = max palindrome ending at i + left = [0] * n + + for i in range(n): + radius = d[i] + length = 2 * radius - 1 + end = i + radius - 1 + left[end] = max(left[end], length) + + # propagate backwards (reduce by 2) + for i in range(n - 2, -1, -1): + left[i] = max(left[i], left[i + 1] - 2) + + # prefix max + for i in range(1, n): + left[i] = max(left[i], left[i - 1]) + + + # right[i] = max palindrome starting at i + right = [0] * n + + for i in range(n): + radius = d[i] + length = 2 * radius - 1 + start = i - radius + 1 + right[start] = max(right[start], length) + + # propagate forward (reduce by 2) + for i in range(1, n): + right[i] = max(right[i], right[i - 1] - 2) + + # suffix max + for i in range(n - 2, -1, -1): + right[i] = max(right[i], right[i + 1]) + + + # try all splits + ans = 0 + for i in range(n - 1): + ans = max(ans, left[i] * right[i + 1]) + + return ans diff --git a/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.rb b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.rb new file mode 100644 index 00000000..44c07636 --- /dev/null +++ b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.rb @@ -0,0 +1,79 @@ +# @param {String} s +# @return {Integer} +def max_product(s) + n = s.length + + # Manacher (odd length only) + d = Array.new(n, 0) + l = 0 + r = -1 + + for i in 0...n + if i > r + k = 1 + else + k = [d[l + r - i], r - i + 1].min + end + + while i - k >= 0 && i + k < n && s[i - k] == s[i + k] + k += 1 + end + + d[i] = k + + if i + k - 1 > r + l = i - k + 1 + r = i + k - 1 + end + end + + # left[i] = max palindrome ending at i + left = Array.new(n, 0) + + for i in 0...n + radius = d[i] + length = 2 * radius - 1 + end_idx = i + radius - 1 + left[end_idx] = [left[end_idx], length].max + end + + # propagate backwards (reduce by 2) + (n - 2).downto(0) do |i| + left[i] = [left[i], left[i + 1] - 2].max + end + + # prefix max + for i in 1...n + left[i] = [left[i], left[i - 1]].max + end + + + # right[i] = max palindrome starting at i + right = Array.new(n, 0) + + for i in 0...n + radius = d[i] + length = 2 * radius - 1 + start_idx = i - radius + 1 + right[start_idx] = [right[start_idx], length].max + end + + # propagate forward (reduce by 2) + for i in 1...n + right[i] = [right[i], right[i - 1] - 2].max + end + + # suffix max + (n - 2).downto(0) do |i| + right[i] = [right[i], right[i + 1]].max + end + + + # try all splits + ans = 0 + for i in 0...(n - 1) + ans = [ans, left[i] * right[i + 1]].max + end + + return ans +end diff --git a/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.rs b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.rs new file mode 100644 index 00000000..6ae3baa2 --- /dev/null +++ b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.rs @@ -0,0 +1,83 @@ +impl Solution { + pub fn max_product(s: String) -> i64 { + let n = s.len(); + let s = s.as_bytes(); + + // Manacher (odd length only) + let mut d = vec![0; n]; + let mut l: usize = 0; + let mut r: i32 = -1; + + for i in 0..n { + let mut k: usize; + if i as i32 > r { + k = 1; + } else { + let mirror = (l as i32 + r - i as i32) as usize; + k = (d[mirror]).min((r - i as i32 + 1) as usize); + } + + while i >= k && i + k < n && s[i - k] == s[i + k] { + k += 1; + } + + d[i] = k; + + if (i + k - 1) as i32 > r { + l = i - k + 1; + r = (i + k - 1) as i32; + } + } + + // left[i] = max palindrome ending at i + let mut left = vec![0; n]; + + for i in 0..n { + let radius = d[i]; + let length = 2 * radius - 1; + let end = i + radius - 1; + left[end] = left[end].max(length); + } + + // propagate backwards (reduce by 2) + for i in (0..(n - 1)).rev() { + left[i] = left[i].max(left[i + 1].saturating_sub(2)); + } + + // prefix max + for i in 1..n { + left[i] = left[i].max(left[i - 1]); + } + + + // right[i] = max palindrome starting at i + let mut right = vec![0; n]; + + for i in 0..n { + let radius = d[i]; + let length = 2 * radius - 1; + let start = i - radius + 1; + right[start] = right[start].max(length); + } + + // propagate forward (reduce by 2) + for i in 1..n { + right[i] = right[i].max(right[i - 1].saturating_sub(2)); + } + + // suffix max + for i in (0..(n - 1)).rev() { + right[i] = right[i].max(right[i + 1]); + } + + + // try all splits + let mut ans: i64 = 0; + for i in 0..(n - 1) { + let prod = (left[i] as i64) * (right[i + 1] as i64); + ans = ans.max(prod); + } + + ans + } +} diff --git a/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.swift b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.swift new file mode 100644 index 00000000..acaac29f --- /dev/null +++ b/tests/1501-2000/1960. maximum-product-of-the-length-of-two-palindromic-substrings/sol.swift @@ -0,0 +1,81 @@ +class Solution { + func maxProduct(_ s: String) -> Int { + let chars = Array(s) + let n = chars.count + + // Manacher (odd length only) + var d = [Int](repeating: 0, count: n) + var l = 0 + var r = -1 + + for i in 0.. r { + k = 1 + } else { + k = min(d[l + r - i], r - i + 1) + } + + while i - k >= 0 && i + k < n && chars[i - k] == chars[i + k] { + k += 1 + } + + d[i] = k + + if i + k - 1 > r { + l = i - k + 1 + r = i + k - 1 + } + } + + // left[i] = max palindrome ending at i + var left = [Int](repeating: 0, count: n) + + for i in 0.. r) { + k = 1; + } else { + k = Math.min(d[l + r - i], r - i + 1); + } + + while (i - k >= 0 && i + k < n && s[i - k] === s[i + k]) { + k++; + } + + d[i] = k; + + if (i + k - 1 > r) { + l = i - k + 1; + r = i + k - 1; + } + } + + // left[i] = max palindrome ending at i + const left: number[] = new Array(n).fill(0); + + for (let i = 0; i < n; i++) { + const radius = d[i]; + const length = 2 * radius - 1; + const end = i + radius - 1; + left[end] = Math.max(left[end], length); + } + + // propagate backwards (reduce by 2) + for (let i = n - 2; i >= 0; i--) { + left[i] = Math.max(left[i], left[i + 1] - 2); + } + + // prefix max + for (let i = 1; i < n; i++) { + left[i] = Math.max(left[i], left[i - 1]); + } + + // right[i] = max palindrome starting at i + const right: number[] = new Array(n).fill(0); + + for (let i = 0; i < n; i++) { + const radius = d[i]; + const length = 2 * radius - 1; + const start = i - radius + 1; + right[start] = Math.max(right[start], length); + } + + // propagate forward (reduce by 2) + for (let i = 1; i < n; i++) { + right[i] = Math.max(right[i], right[i - 1] - 2); + } + + // suffix max + for (let i = n - 2; i >= 0; i--) { + right[i] = Math.max(right[i], right[i + 1]); + } + + // try all splits + let ans = 0; + for (let i = 0; i < n - 1; i++) { + ans = Math.max(ans, left[i] * right[i + 1]); + } + + return ans; +} diff --git a/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/manifest.yaml b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/manifest.yaml new file mode 100644 index 00000000..8876a78c --- /dev/null +++ b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/manifest.yaml @@ -0,0 +1,324 @@ +entry: + id: 1961 + title: "check-if-string-is-a-prefix-of-array" + params: + s: + type: string + words: + type: array + items: + type: string + call: + cpp: "Solution().isPrefixString({s}, {words})" + rust: "Solution::is_prefix_string({s}, {words})" + python3: "Solution().isPrefixString({s}, {words})" + python2: "Solution().isPrefixString({s}, {words})" + ruby: "is_prefix_string({s}, {words})" + java: "new Solution().isPrefixString({s}, {words})" + csharp: "new Solution().IsPrefixString({s}, {words})" + kotlin: "Solution().isPrefixString({s}, {words})" + go: "isPrefixString({s}, {words})" + dart: "Solution().isPrefixString({s}, {words})" + swift: "Solution().isPrefixString({s}, {words})" + typescript: "isPrefixString({s}, {words})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().isPrefixString(s, words, {result})" + checker: | + class Checker: + def isPrefixString(self, s, words, result): + if not isinstance(result, bool): + return False + built = "" + expected = False + for word in words: + built += word + if built == s: + expected = True + break + if len(built) >= len(s): + break + return result == expected + +seed: 1961 + +tests: + - name: "example_full_prefix" + in: + s: "iloveleetcode" + words: ["i", "love", "leetcode", "apples"] + out: true + - name: "example_wrong_order" + in: + s: "iloveleetcode" + words: ["apples", "i", "love", "leetcode"] + out: false + - name: "single_word_equal" + in: + s: "abc" + words: ["abc"] + out: true + - name: "single_word_short" + in: + s: "abcd" + words: ["abc"] + out: false + - name: "single_word_long" + in: + s: "abc" + words: ["abcd"] + out: false + - name: "one_word_prefix_but_not_complete" + in: + s: "ab" + words: ["a", "b"] + out: true + - name: "prefix_requires_all_words" + in: + s: "abcdef" + words: ["ab", "cd", "ef"] + out: true + - name: "prefix_stops_before_extra_word" + in: + s: "abcd" + words: ["ab", "cd", "ef"] + out: true + - name: "extra_word_changes_result" + in: + s: "abcdefg" + words: ["ab", "cd", "ef"] + out: false + - name: "first_word_mismatch" + in: + s: "xbc" + words: ["abc", "bc"] + out: false + - name: "middle_word_mismatch" + in: + s: "abXdef" + words: ["ab", "c", "def"] + out: false + - name: "mismatch_after_complete_word" + in: + s: "abcdx" + words: ["ab", "cd", "x"] + out: true + - name: "repeated_single_letters" + in: + s: "aaaa" + words: ["a", "a", "a", "a", "a"] + out: true + - name: "repeated_letters_too_long" + in: + s: "aaaaaa" + words: ["a", "a", "a", "a", "a"] + out: false + - name: "repeated_letters_short" + in: + s: "aaa" + words: ["a", "a", "a", "a"] + out: true + - name: "one_character_word_exact" + in: + s: "z" + words: ["z", "a"] + out: true + - name: "one_character_word_mismatch" + in: + s: "y" + words: ["z"] + out: false + - name: "case_is_not_ignored" + in: + s: "abc" + words: ["a", "B", "c"] + out: false + - name: "similar_suffix_is_not_prefix" + in: + s: "abcdef" + words: ["ab", "ce", "f"] + out: false + - name: "word_boundary_exact" + in: + s: "hello" + words: ["he", "llo", "world"] + out: true + - name: "word_boundary_mismatch" + in: + s: "hellp" + words: ["he", "llo", "world"] + out: false + - name: "large_word_count_exact" + in: + s: "abcdefghijklmnopqrstuvwxyz" + words: + [ + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + ] + out: true + - name: "large_word_count_missing_last" + in: + s: "abcdefghijklmnopqrstuvwxyz!" + words: + [ + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + ] + out: false + - name: "twenty_character_word" + in: + s: "abcdefghijklmnopqrst" + words: ["abcdefghijklmnopqrst"] + out: true + - name: "twenty_character_word_mismatch" + in: + s: "abcdefghijklmnopqrsu" + words: ["abcdefghijklmnopqrst"] + out: false + - name: "many_twenty_character_words" + in: + s: "abcdefghijklmnopqrstabcdefghijklmnopqrst" + words: ["abcdefghijklmnopqrst", "abcdefghijklmnopqrst", "z"] + out: true + - name: "empty_not_allowed_but_value_case" + in: + s: "a" + words: ["a", "b", "c", "d"] + out: true + - name: "concatenation_overshoots" + in: + s: "abcde" + words: ["ab", "c", "def"] + out: false + - name: "concatenation_overshoots_by_one" + in: + s: "abcd" + words: ["ab", "cdx"] + out: false + - name: "prefix_with_long_tail" + in: + s: "prefix" + words: ["pre", "fix", "tail", "tail", "tail"] + out: true + - name: "prefix_not_allowed_from_later_words" + in: + s: "prefix" + words: ["x", "pre", "fix"] + out: false + - name: "numeric_looking_letters" + in: + s: "abcabc" + words: ["abc", "abc"] + out: true + - name: "alternating_words" + in: + s: "abababa" + words: ["ab", "ab", "ab", "a", "b"] + out: true + - name: "alternating_wrong_final" + in: + s: "abababb" + words: ["ab", "ab", "ab", "a", "b"] + out: false + - name: "all_same_long_string" + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + words: + [ + "aaaa", + "aaaa", + "aaaa", + "aaaa", + "aaaa", + "aaaa", + "aaaa", + "aaaa", + "aaaa", + "aaaa", + "b", + ] + out: true + - name: "all_same_long_string_missing" + in: + s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + words: + [ + "aaaa", + "aaaa", + "aaaa", + "aaaa", + "aaaa", + "aaaa", + "aaaa", + "aaaa", + "aaaa", + "aaaa", + ] + out: false + - name: "prefix_ends_at_word_limit" + in: + s: "onetwothree" + words: ["one", "two", "three"] + out: true + - name: "prefix_needs_unavailable_word" + in: + s: "onetwothreefour" + words: ["one", "two", "three"] + out: false diff --git a/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.cpp b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.cpp new file mode 100644 index 00000000..9d83559c --- /dev/null +++ b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + bool isPrefixString(string s, vector& words) { + string res = ""; + int i = 0; + while (res.length() < s.length()) { + if (i >= words.size()) return false; + res += words[i]; + i++; + } + return res == s; + } +}; diff --git a/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.cs b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.cs new file mode 100644 index 00000000..079d3d69 --- /dev/null +++ b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.cs @@ -0,0 +1,12 @@ +public class Solution { + public bool IsPrefixString(string s, string[] words) { + string res = ""; + int i = 0; + while (res.Length < s.Length) { + if (i >= words.Length) return false; + res += words[i]; + i++; + } + return res == s; + } +} diff --git a/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.dart b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.dart new file mode 100644 index 00000000..e848f858 --- /dev/null +++ b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.dart @@ -0,0 +1,12 @@ +class Solution { + bool isPrefixString(String s, List words) { + String res = ''; + int i = 0; + while (res.length < s.length) { + if (i >= words.length) return false; + res += words[i]; + i++; + } + return res == s; + } +} diff --git a/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.go b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.go new file mode 100644 index 00000000..e1951421 --- /dev/null +++ b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.go @@ -0,0 +1,12 @@ +func isPrefixString(s string, words []string) bool { + res := "" + i := 0 + for len(res) < len(s) { + if i >= len(words) { + return false + } + res += words[i] + i++ + } + return res == s +} diff --git a/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.java b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.java new file mode 100644 index 00000000..10022614 --- /dev/null +++ b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.java @@ -0,0 +1,12 @@ +class Solution { + public boolean isPrefixString(String s, String[] words) { + StringBuilder res = new StringBuilder(); + int i = 0; + while (res.length() < s.length()) { + if (i >= words.length) return false; + res.append(words[i]); + i++; + } + return res.toString().equals(s); + } +} diff --git a/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.kt b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.kt new file mode 100644 index 00000000..e7e006f4 --- /dev/null +++ b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.kt @@ -0,0 +1,12 @@ +class Solution { + fun isPrefixString(s: String, words: Array): Boolean { + var res = StringBuilder() + var i = 0 + while (res.length < s.length) { + if (i >= words.size) return false + res.append(words[i]) + i++ + } + return res.toString() == s + } +} diff --git a/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.py b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.py new file mode 100644 index 00000000..14ea1397 --- /dev/null +++ b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.py @@ -0,0 +1,10 @@ +class Solution: + def isPrefixString(self, s: str, words: List[str]) -> bool: + res = "" + i = 0 + while len(res) < len(s): + if i >= len(words): + return False + res += words[i] + i += 1 + return res == s diff --git a/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.py2 b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.py2 new file mode 100644 index 00000000..bf4ac213 --- /dev/null +++ b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def isPrefixString(self, s, words): + """ + :type s: str + :type words: List[str] + :rtype: bool + """ + res = '' + i = 0 + while len(res) < len(s): + if i >= len(words): + return False + res += words[i] + i += 1 + return res == s diff --git a/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.rb b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.rb new file mode 100644 index 00000000..721eccb8 --- /dev/null +++ b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.rb @@ -0,0 +1,13 @@ +# @param {String} s +# @param {String[]} words +# @return {Boolean} +def is_prefix_string(s, words) + res = '' + i = 0 + while res.length < s.length + return false if i >= words.length + res += words[i] + i += 1 + end + res == s +end diff --git a/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.rs b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.rs new file mode 100644 index 00000000..88ecc858 --- /dev/null +++ b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.rs @@ -0,0 +1,14 @@ +impl Solution { + pub fn is_prefix_string(s: String, words: Vec) -> bool { + let mut res = String::new(); + let mut i = 0; + while res.len() < s.len() { + if i >= words.len() { + return false; + } + res.push_str(&words[i]); + i += 1; + } + res == s + } +} diff --git a/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.swift b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.swift new file mode 100644 index 00000000..20ad1f8f --- /dev/null +++ b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.swift @@ -0,0 +1,12 @@ +class Solution { + func isPrefixString(_ s: String, _ words: [String]) -> Bool { + var res = "" + var i = 0 + while res.count < s.count { + if i >= words.count { return false } + res += words[i] + i += 1 + } + return res == s + } +} diff --git a/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.ts b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.ts new file mode 100644 index 00000000..7b3ed7c2 --- /dev/null +++ b/tests/1501-2000/1961. check-if-string-is-a-prefix-of-array/sol.ts @@ -0,0 +1,10 @@ +function isPrefixString(s: string, words: string[]): boolean { + let res = ""; + let i = 0; + while (res.length < s.length) { + if (i >= words.length) return false; + res += words[i]; + i++; + } + return res === s; +} diff --git a/tests/1501-2000/1962. remove-stones-to-minimize-the-total/manifest.yaml b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/manifest.yaml new file mode 100644 index 00000000..4848b2a0 --- /dev/null +++ b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/manifest.yaml @@ -0,0 +1,320 @@ +entry: + id: 1962 + title: "remove-stones-to-minimize-the-total" + params: + piles: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().minStoneSum({piles}, {k})" + rust: "Solution::min_stone_sum({piles}, {k})" + python3: "Solution().minStoneSum({piles}, {k})" + python2: "Solution().minStoneSum({piles}, {k})" + ruby: "min_stone_sum({piles}, {k})" + java: "new Solution().minStoneSum({piles}, {k})" + csharp: "new Solution().MinStoneSum({piles}, {k})" + kotlin: "Solution().minStoneSum({piles}, {k})" + go: "minStoneSum({piles}, {k})" + dart: "Solution().minStoneSum({piles}, {k})" + swift: "Solution().minStoneSum({piles}, {k})" + typescript: "minStoneSum({piles}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().minStoneSum(piles, k, {result})" + checker: | + import heapq + + class Checker: + def minStoneSum(self, piles, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + heap = [-int(x) for x in piles] + heapq.heapify(heap) + for _ in range(k): + x = -heapq.heappop(heap) + heapq.heappush(heap, -(x - x // 2)) + return result == -sum(heap) + +seed: 1962 + +tests: + - name: "example_one" + in: + piles: [5, 4, 9] + k: 2 + out: 12 + - name: "example_two" + in: + piles: [4, 3, 6, 7] + k: 3 + out: 12 + - name: "single_even_once" + in: + piles: [10] + k: 1 + out: 5 + - name: "single_odd_once" + in: + piles: [9] + k: 1 + out: 5 + - name: "single_repeated" + in: + piles: [100] + k: 10 + out: 1 + - name: "single_until_one" + in: + piles: [1] + k: 100000 + out: 1 + - name: "all_ones" + in: + piles: [1, 1, 1, 1, 1] + k: 100 + out: 5 + - name: "two_equal" + in: + piles: [8, 8] + k: 1 + out: 12 + - name: "two_equal_many" + in: + piles: [8, 8] + k: 5 + out: 3 + - name: "odd_values" + in: + piles: [3, 5, 7, 9, 11] + k: 4 + out: 20 + - name: "large_gap" + in: + piles: [1, 1, 1, 10000] + k: 3 + out: 1253 + - name: "large_gap_many" + in: + piles: [1, 1, 10000] + k: 20 + out: 3 + - name: "zero_not_allowed_boundary" + in: + piles: [2, 2, 2] + k: 1 + out: 5 + - name: "powers_of_two" + in: + piles: [2, 4, 8, 16, 32] + k: 5 + out: 22 + - name: "mixed_small" + in: + piles: [2, 3, 4, 5, 6] + k: 6 + out: 10 + - name: "many_piles_one_round" + in: + piles: [2, 4, 6, 8, 10, 12, 14, 16] + k: 1 + out: 64 + - name: "many_piles_full_round" + in: + piles: [2, 4, 6, 8, 10, 12, 14, 16] + k: 8 + out: 32 + - name: "all_maximum" + in: + piles: [10000, 10000, 10000, 10000] + k: 1 + out: 35000 + - name: "all_maximum_many" + in: + piles: [10000, 10000, 10000, 10000] + k: 100000 + out: 4 + - name: "alternating" + in: + piles: [1, 100, 2, 99, 3, 98] + k: 7 + out: 69 + - name: "duplicates_and_small" + in: + piles: [7, 7, 7, 1, 1] + k: 3 + out: 14 + - name: "k_one_maximum" + in: + piles: [1, 2, 3, 9999] + k: 1 + out: 5006 + - name: "k_equals_length" + in: + piles: [9, 8, 7, 6] + k: 4 + out: 16 + - name: "deep_reduction_odd" + in: + piles: [9999] + k: 13 + out: 2 + - name: "deep_reduction_even" + in: + piles: [8192] + k: 13 + out: 1 + - name: "balanced_medium" + in: + piles: [101, 203, 405, 809] + k: 9 + out: 254 + - name: "ten_varied" + in: + piles: [13, 26, 39, 52, 65, 78, 91, 104, 117, 130] + k: 17 + out: 190 + - name: "near_max_varied" + in: + piles: [9991, 9993, 9995, 9997, 9999] + k: 7 + out: 19991 + - name: "many_ones_and_big" + in: + piles: [1, 1, 1, 1, 1, 5000, 6000] + k: 9 + out: 506 + - name: "long_small_cycle" + in: + piles: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] + k: 25 + out: 24 + - name: "large_static_array" + in: + piles: + [ + 10000, + 9999, + 9998, + 9997, + 9996, + 9995, + 9994, + 9993, + 9992, + 9991, + 9990, + 9989, + 9988, + 9987, + 9986, + 9985, + 9984, + 9983, + 9982, + 9981, + ] + k: 100 + out: 6256 + - name: "generated_small" + seed: 196201 + in: + piles: + gen: "array" + len: + gen: "int" + min: 1 + max: 30 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + k: + gen: "int" + min: 1 + max: 100 + - name: "generated_medium" + seed: 196202 + in: + piles: + gen: "array" + len: + gen: "int" + min: 50 + max: 300 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + k: + gen: "int" + min: 1 + max: 1000 + - name: "generated_large" + seed: 196203 + in: + piles: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + k: + gen: "int" + min: 1 + max: 100000 + - name: "generated_large_low_k" + seed: 196204 + in: + piles: + gen: "array" + len: + gen: "int" + min: 50000 + max: 100000 + of: + gen: "int" + min: 5000 + max: 10000 + distinct: false + sorted: false + k: + gen: "int" + min: 1 + max: 100 + - name: "generated_large_high_k" + seed: 196205 + in: + piles: + gen: "array" + len: + gen: "int" + min: 1000 + max: 5000 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + k: + gen: "int" + min: 50000 + max: 100000 diff --git a/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.cpp b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.cpp new file mode 100644 index 00000000..6d240bfe --- /dev/null +++ b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int minStoneSum(vector& piles, int k) { + priority_queue maxHeap(piles.begin(), piles.end()); + for (int i = 0; i < k; i++) { + int x = maxHeap.top(); maxHeap.pop(); + int reduced = (x + 1) / 2; + maxHeap.push(reduced); + } + int sum = 0; + while (!maxHeap.empty()) { + sum += maxHeap.top(); + maxHeap.pop(); + } + return sum; + } +}; diff --git a/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.cs b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.cs new file mode 100644 index 00000000..5cf2db48 --- /dev/null +++ b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +public class Solution { + public int MinStoneSum(int[] piles, int k) { + var maxHeap = new List(piles); + for (int i = maxHeap.Count / 2 - 1; i >= 0; i--) SiftDown(maxHeap, i); + for (int i = 0; i < k; i++) { + int x = maxHeap[0]; + int reduced = (x + 1) / 2; + maxHeap[0] = reduced; + SiftDown(maxHeap, 0); + } + int sum = 0; + foreach (int x in maxHeap) sum += x; + return sum; + } + + private static void SiftDown(List heap, int i) { + while (true) { + int left = i * 2 + 1; + if (left >= heap.Count) return; + int right = left + 1; + int child = right < heap.Count && heap[right] > heap[left] ? right : left; + if (heap[i] >= heap[child]) return; + int t = heap[i]; heap[i] = heap[child]; heap[child] = t; + i = child; + } + } +} diff --git a/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.dart b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.dart new file mode 100644 index 00000000..990cffed --- /dev/null +++ b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.dart @@ -0,0 +1,24 @@ +class Solution { + int minStoneSum(List piles, int k) { + var heap = List.from(piles); + heap.sort((a, b) => b.compareTo(a)); + for (int i = 0; i < k; i++) { + int x = heap[0]; + int reduced = (x + 1) ~/ 2; + heap[0] = reduced; + int j = 0; + while (true) { + int left = j * 2 + 1; + if (left >= heap.length) break; + int right = left + 1; + int child = right < heap.length && heap[right] > heap[left] ? right : left; + if (heap[j] >= heap[child]) break; + int tmp = heap[j]; heap[j] = heap[child]; heap[child] = tmp; + j = child; + } + } + int sum = 0; + for (int p in heap) sum += p; + return sum; + } +} diff --git a/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.go b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.go new file mode 100644 index 00000000..118ce826 --- /dev/null +++ b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.go @@ -0,0 +1,27 @@ +func minStoneSum(piles []int, k int) int { + h := append([]int(nil), piles...) + for i := len(h)/2 - 1; i >= 0; i-- { siftDown(h, i) } + for i := 0; i < k; i++ { + x := h[0] + reduced := (x + 1) / 2 + h[0] = reduced + siftDown(h, 0) + } + sum := 0 + for _, p := range h { + sum += p + } + return sum +} + +func siftDown(h []int, i int) { + for { + left := i*2 + 1 + if left >= len(h) { return } + child := left + if right := left + 1; right < len(h) && h[right] > h[left] { child = right } + if h[i] >= h[child] { return } + h[i], h[child] = h[child], h[i] + i = child + } +} diff --git a/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.java b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.java new file mode 100644 index 00000000..bff3a281 --- /dev/null +++ b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.java @@ -0,0 +1,16 @@ +import java.util.*; + +class Solution { + public int minStoneSum(int[] piles, int k) { + PriorityQueue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + for (int p : piles) maxHeap.offer(p); + for (int i = 0; i < k; i++) { + int x = maxHeap.poll(); + int reduced = (x + 1) / 2; + maxHeap.offer(reduced); + } + int sum = 0; + for (int p : maxHeap) sum += p; + return sum; + } +} diff --git a/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.kt b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.kt new file mode 100644 index 00000000..cca2dee5 --- /dev/null +++ b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.kt @@ -0,0 +1,14 @@ +import java.util.PriorityQueue + +class Solution { + fun minStoneSum(piles: IntArray, k: Int): Int { + val maxHeap = PriorityQueue(compareByDescending { it }) + for (p in piles) maxHeap.add(p) + repeat(k) { + val x = maxHeap.poll() + val reduced = (x + 1) / 2 + maxHeap.add(reduced) + } + return maxHeap.sum() + } +} diff --git a/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.py b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.py new file mode 100644 index 00000000..be49ec66 --- /dev/null +++ b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.py @@ -0,0 +1,17 @@ +from math import ceil +import heapq +from typing import List + + +class Solution: + def minStoneSum(self, piles: List[int], k: int) -> int: + + piles = [-p for p in piles] + heapq.heapify(piles) + + for _ in range(k): + x = -heapq.heappop(piles) + reduced = ceil(x / 2) + heapq.heappush(piles, -reduced) + + return -sum(piles) diff --git a/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.py2 b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.py2 new file mode 100644 index 00000000..91fc72e2 --- /dev/null +++ b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def minStoneSum(self, piles, k): + """ + :type piles: List[int] + :type k: int + :rtype: int + """ + import heapq + piles = [-p for p in piles] + heapq.heapify(piles) + for _ in range(k): + x = -heapq.heappop(piles) + reduced = (x + 1) // 2 + heapq.heappush(piles, -reduced) + return -sum(piles) diff --git a/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.rb b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.rb new file mode 100644 index 00000000..cca3be8e --- /dev/null +++ b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.rb @@ -0,0 +1,20 @@ +# @param {Integer[]} piles +# @param {Integer} k +# @return {Integer} +def min_stone_sum(piles, k) + heap = piles.map { |p| -p } + heap.sort! + k.times do + x = -heap[0] + reduced = (x + 1) / 2 + heap[0] = -reduced + i = 0 + while (child = i * 2 + 1) < heap.length + child += 1 if child + 1 < heap.length && heap[child + 1] < heap[child] + break if heap[i] <= heap[child] + heap[i], heap[child] = heap[child], heap[i] + i = child + end + end + -heap.sum +end diff --git a/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.rs b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.rs new file mode 100644 index 00000000..bdf97f02 --- /dev/null +++ b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.rs @@ -0,0 +1,16 @@ +use std::collections::BinaryHeap; + +impl Solution { + pub fn min_stone_sum(piles: Vec, k: i32) -> i32 { + let mut heap = BinaryHeap::new(); + for p in piles { + heap.push(p); + } + for _ in 0..k { + let x = heap.pop().unwrap(); + let reduced = (x + 1) / 2; + heap.push(reduced); + } + heap.iter().sum() + } +} diff --git a/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.swift b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.swift new file mode 100644 index 00000000..2ff0551d --- /dev/null +++ b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.swift @@ -0,0 +1,21 @@ +class Solution { + func minStoneSum(_ piles: [Int], _ k: Int) -> Int { + var heap = piles.sorted(by: >) + for _ in 0..= heap.count { break } + let right = left + 1 + let child = right < heap.count && heap[right] > heap[left] ? right : left + if heap[i] >= heap[child] { break } + heap.swapAt(i, child) + i = child + } + } + return heap.reduce(0, +) + } +} diff --git a/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.ts b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.ts new file mode 100644 index 00000000..4c20bdce --- /dev/null +++ b/tests/1501-2000/1962. remove-stones-to-minimize-the-total/sol.ts @@ -0,0 +1,24 @@ +function minStoneSum(piles: number[], k: number): number { + const maxHeap: number[] = []; + for (const p of piles) { + maxHeap.push(p); + } + maxHeap.sort((a, b) => b - a); + for (let i = 0; i < k; i++) { + const x = maxHeap[0]; + const reduced = Math.ceil(x / 2); + maxHeap[0] = reduced; + let idx = 0; + while (true) { + const left = idx * 2 + 1; + if (left >= maxHeap.length) break; + const right = left + 1; + const child = + right < maxHeap.length && maxHeap[right] > maxHeap[left] ? right : left; + if (maxHeap[idx] >= maxHeap[child]) break; + [maxHeap[idx], maxHeap[child]] = [maxHeap[child], maxHeap[idx]]; + idx = child; + } + } + return maxHeap.reduce((a, b) => a + b, 0); +} diff --git a/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/manifest.yaml b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/manifest.yaml new file mode 100644 index 00000000..0a2b6ced --- /dev/null +++ b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/manifest.yaml @@ -0,0 +1,194 @@ +entry: + id: 1963 + title: "minimum-number-of-swaps-to-make-the-string-balanced" + params: + s: + type: string + call: + cpp: "Solution().minSwaps({s})" + rust: "Solution::min_swaps({s})" + python3: "Solution().minSwaps({s})" + python2: "Solution().minSwaps({s})" + ruby: "min_swaps({s})" + java: "new Solution().minSwaps({s})" + csharp: "new Solution().MinSwaps({s})" + kotlin: "Solution().minSwaps({s})" + go: "minSwaps({s})" + dart: "Solution().minSwaps({s})" + swift: "Solution().minSwaps({s})" + typescript: "minSwaps({s})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().minSwaps(s, {result})" + checker: | + class Checker: + def minSwaps(self, s, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + balance = 0 + for ch in s: + if ch == '[': + balance += 1 + else: + balance = max(0, balance - 1) + return result == (balance + 1) // 2 + +seed: 1963 + +tests: + - name: example-one + in: + s: "][][" + out: 1 + - name: example-two + in: + s: "]]][[[" + out: 2 + - name: example-three + in: + s: "[]" + out: 0 + - name: reversed-two + in: + s: "][" + out: 1 + - name: nested-three + in: + s: "[[[]]]" + out: 0 + - name: alternating-four + in: + s: "[][]" + out: 0 + - name: alternating-eight + in: + s: "[][][][]" + out: 0 + - name: reversed-four + in: + s: "]]][[[" + out: 2 + - name: reversed-eight + in: + s: "]]]]]]]][[[[[[[[" + out: 4 + - name: reversed-twelve + in: + s: "]]]]]]]]]]]][[[[[[[[[[[[" + out: 6 + - name: reversed-sixteen + in: + s: "]]]]]]]]]]]]]]]][[[[[[[[[[[[[[[[" + out: 8 + - name: nested-five + in: + s: "[[[[[]]]]]" + out: 0 + - name: nested-eight + in: + s: "[[[[[[[[]]]]]]]]" + out: 0 + - name: prefix-deficit-one + in: + s: "][[]" + out: 1 + - name: prefix-deficit-two + in: + s: "]][][][[" + out: 1 + - name: prefix-deficit-three + in: + s: "]]][[][][[" + out: 2 + - name: delayed-deficit + in: + s: "[][][][]" + out: 0 + - name: close-run-middle + in: + s: "[[]]][][[]" + out: 1 + - name: two-close-runs + in: + s: "]][][][[]][[" + out: 1 + - name: three-close-runs + in: + s: "][][" + out: 1 + - name: four-close-runs + in: + s: "]]][[[" + out: 2 + out: 2 + - name: shifted-pairs + in: + s: "][[]][[]][][" + out: 1 + - name: shifted-pairs-long + in: + s: "][][" + out: 1 + - name: balanced-components + in: + s: "[][[]][][[]]" + out: 0 + - name: balanced-deep-components + in: + s: "[[[]]][[]][]" + out: 0 + - name: late-leading-close + in: + s: "[][][][]" + out: 0 + - name: one-swap-late + in: + s: "][][" + out: 1 + out: 1 + - name: two-swaps-late + in: + s: "]]]][[[[" + out: 2 + - name: repeated-small + in: + s: "[][][][]" + out: 0 + out: 0 + - name: repeated-medium + in: + s: "[][][][][][]" + out: 0 + out: 0 + - name: all-close-six + in: + s: "]]][[[" + out: 2 + - name: all-close-ten + in: + s: "]]]][[[[" + out: 2 + - name: balanced-wide + in: + s: "[][][[]][][[[]]][]" + out: 0 + - name: unbalanced-wide + in: + s: "][][" + out: 1 + - name: maximal-small + in: + s: "]]]]]]]]]][[[[[[[[[[" + out: 5 + - name: maximal-twenty + in: + s: "]]]]]]]]]]]]]]]]]]]][[[[[[[[[[[[[[[[[[[[" + out: 10 diff --git a/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.cpp b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.cpp new file mode 100644 index 00000000..79b15533 --- /dev/null +++ b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int minSwaps(string s) { + int swap = 0; + for (char c : s) { + if (c == '[') { + swap++; + } else { + if (swap > 0) { + swap--; + } + } + } + return (swap + 1) / 2; + } +}; diff --git a/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.cs b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.cs new file mode 100644 index 00000000..bf03ccd6 --- /dev/null +++ b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int MinSwaps(string s) { + int swap = 0; + foreach (char c in s) { + if (c == '[') { + swap++; + } else { + if (swap > 0) { + swap--; + } + } + } + return (swap + 1) / 2; + } +} diff --git a/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.dart b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.dart new file mode 100644 index 00000000..fb585fc6 --- /dev/null +++ b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.dart @@ -0,0 +1,15 @@ +class Solution { + int minSwaps(String s) { + int swap = 0; + for (int i = 0; i < s.length; i++) { + if (s[i] == '[') { + swap++; + } else { + if (swap > 0) { + swap--; + } + } + } + return (swap + 1) ~/ 2; + } +} diff --git a/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.go b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.go new file mode 100644 index 00000000..4b109303 --- /dev/null +++ b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.go @@ -0,0 +1,13 @@ +func minSwaps(s string) int { + swap := 0 + for _, c := range s { + if c == '[' { + swap++ + } else { + if swap > 0 { + swap-- + } + } + } + return (swap + 1) / 2 +} diff --git a/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.java b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.java new file mode 100644 index 00000000..a7e903ec --- /dev/null +++ b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.java @@ -0,0 +1,15 @@ +class Solution { + public int minSwaps(String s) { + int swap = 0; + for (char c : s.toCharArray()) { + if (c == '[') { + swap++; + } else { + if (swap > 0) { + swap--; + } + } + } + return (swap + 1) / 2; + } +} diff --git a/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.kt b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.kt new file mode 100644 index 00000000..ea89f5dd --- /dev/null +++ b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun minSwaps(s: String): Int { + var swap = 0 + for (c in s) { + if (c == '[') { + swap++ + } else { + if (swap > 0) { + swap-- + } + } + } + return (swap + 1) / 2 + } +} diff --git a/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.py b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.py new file mode 100644 index 00000000..b878ab38 --- /dev/null +++ b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.py @@ -0,0 +1,10 @@ +class Solution: + def minSwaps(self, s: str) -> int: + swap = 0 + for char in s: + if char == "[": + swap += 1 + else: + if swap > 0: + swap -= 1 + return (swap + 1) // 2 diff --git a/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.py2 b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.py2 new file mode 100644 index 00000000..64b1e869 --- /dev/null +++ b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def minSwaps(self, s): + """ + :type s: str + :rtype: int + """ + swap = 0 + for char in s: + if char == "[": + swap += 1 + else: + if swap > 0: + swap -= 1 + return (swap + 1) // 2 diff --git a/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.rb b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.rb new file mode 100644 index 00000000..77a7d0da --- /dev/null +++ b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.rb @@ -0,0 +1,15 @@ +# @param {String} s +# @return {Integer} +def min_swaps(s) + swap = 0 + s.each_char do |char| + if char == "[" + swap += 1 + else + if swap > 0 + swap -= 1 + end + end + end + (swap + 1) / 2 +end diff --git a/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.rs b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.rs new file mode 100644 index 00000000..6bc6802a --- /dev/null +++ b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn min_swaps(s: String) -> i32 { + let mut swap = 0; + for c in s.chars() { + if c == '[' { + swap += 1; + } else { + if swap > 0 { + swap -= 1; + } + } + } + (swap + 1) / 2 + } +} diff --git a/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.swift b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.swift new file mode 100644 index 00000000..514b1e64 --- /dev/null +++ b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func minSwaps(_ s: String) -> Int { + var swap = 0 + for char in s { + if char == "[" { + swap += 1 + } else { + if swap > 0 { + swap -= 1 + } + } + } + return (swap + 1) / 2 + } +} diff --git a/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.ts b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.ts new file mode 100644 index 00000000..e6bbc9a3 --- /dev/null +++ b/tests/1501-2000/1963. minimum-number-of-swaps-to-make-the-string-balanced/sol.ts @@ -0,0 +1,13 @@ +function minSwaps(s: string): number { + let swap = 0; + for (const char of s) { + if (char === "[") { + swap++; + } else { + if (swap > 0) { + swap--; + } + } + } + return Math.floor((swap + 1) / 2); +} diff --git a/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/manifest.yaml b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/manifest.yaml new file mode 100644 index 00000000..3c8c69e8 --- /dev/null +++ b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/manifest.yaml @@ -0,0 +1,232 @@ +entry: + id: 1964 + title: "find-the-longest-valid-obstacle-course-at-each-position" + params: + obstacles: + type: array + items: + type: int + call: + cpp: "Solution().longestObstacleCourseAtEachPosition({obstacles})" + rust: "Solution::longest_obstacle_course_at_each_position({obstacles})" + python3: "Solution().longestObstacleCourseAtEachPosition({obstacles})" + python2: "Solution().longestObstacleCourseAtEachPosition({obstacles})" + ruby: "longest_obstacle_course_at_each_position({obstacles})" + java: "new Solution().longestObstacleCourseAtEachPosition({obstacles})" + csharp: "new Solution().LongestObstacleCourseAtEachPosition({obstacles})" + kotlin: "Solution().longestObstacleCourseAtEachPosition({obstacles})" + go: "longestObstacleCourseAtEachPosition({obstacles})" + dart: "Solution().longestObstacleCourseAtEachPosition({obstacles})" + swift: "Solution().longestObstacleCourseAtEachPosition({obstacles})" + typescript: "longestObstacleCourseAtEachPosition({obstacles})" + +judge: + type: "exact" + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(obstacles, {result})" + checker: | + from bisect import bisect_right + class Checker: + def check(self, obstacles, result): + if not isinstance(result, list) or len(result) != len(obstacles): + return False + tails = [] + expected = [] + for value in obstacles: + pos = bisect_right(tails, value) + if pos == len(tails): + tails.append(value) + else: + tails[pos] = value + expected.append(pos + 1) + return result == expected + +seed: 1964 + +tests: + - name: example-1 + in: + obstacles: [1, 2, 3, 2] + out: [1, 2, 3, 3] + - name: example-2 + in: + obstacles: [2, 2, 1] + out: [1, 2, 1] + - name: example-3 + in: + obstacles: [3, 1, 5, 6, 4, 2] + out: [1, 1, 2, 3, 2, 2] + - name: two-increasing + in: + obstacles: [1, 2] + out: [1, 2] + - name: two-decreasing + in: + obstacles: [2, 1] + out: [1, 1] + - name: all-equal + in: + obstacles: [7, 7, 7, 7, 7] + out: [1, 2, 3, 4, 5] + - name: strictly-increasing + in: + obstacles: [1, 2, 3, 4, 5, 6] + out: [1, 2, 3, 4, 5, 6] + - name: strictly-decreasing + in: + obstacles: [6, 5, 4, 3, 2, 1] + out: [1, 1, 1, 1, 1, 1] + - name: alternating + in: + obstacles: [1, 3, 2, 4, 3, 5, 4] + out: [1, 2, 2, 3, 3, 4, 4] + - name: repeated-blocks + in: + obstacles: [2, 1, 2, 1, 2, 1, 2] + out: [1, 1, 2, 2, 3, 3, 4] + - name: plateaus + in: + obstacles: [1, 1, 2, 2, 1, 2] + out: [1, 2, 3, 4, 3, 5] + - name: high-low-high + in: + obstacles: [10000000, 1, 10000000] + out: [1, 1, 2] + - name: minimum-values + in: + obstacles: [1, 1, 1] + out: [1, 2, 3] + - name: maximum-values + in: + obstacles: [10000000, 10000000, 9999999] + out: [1, 2, 1] + - name: valleys + in: + obstacles: [5, 1, 4, 2, 3, 1, 6] + out: [1, 1, 2, 2, 3, 2, 4] + - name: duplicate-interleaving + in: + obstacles: [3, 3, 2, 3, 2, 4] + out: [1, 2, 1, 3, 2, 4] + - name: powers + in: + obstacles: [1, 2, 4, 2, 8, 4, 16] + out: [1, 2, 3, 3, 4, 4, 5] + - name: sawtooth + in: + obstacles: [2, 5, 1, 4, 3, 6, 2, 7] + out: [1, 2, 1, 2, 2, 3, 2, 4] + - name: many-equal-with-drops + in: + obstacles: [4, 4, 4, 3, 4, 4, 2, 4] + out: [1, 2, 3, 1, 4, 5, 1, 6] + - name: staircase-with-duplicates + in: + obstacles: [1, 2, 2, 3, 1, 3, 4, 4] + out: [1, 2, 3, 4, 2, 5, 6, 7] + - name: single-min + in: + obstacles: [1] + out: [1] + - name: single-max + in: + obstacles: [10000000] + out: [1] + - name: mixed-small + in: + obstacles: [4, 2, 2, 3, 1, 5, 3] + out: [1, 1, 2, 3, 1, 4, 4] + - name: long-flat + in: + obstacles: [9, 9, 9, 9, 9, 9, 9, 9] + out: [1, 2, 3, 4, 5, 6, 7, 8] + - name: nested + in: + obstacles: [1, 5, 2, 2, 3, 1, 4, 4, 6] + out: [1, 2, 2, 3, 4, 2, 5, 6, 7] + - name: near-limit-values + in: + obstacles: [9999998, 9999999, 10000000, 9999999, 10000000] + out: [1, 2, 3, 3, 4] + - name: descending-then-flat + in: + obstacles: [5, 4, 3, 3, 3, 4, 4] + out: [1, 1, 1, 2, 3, 4, 5] + - name: flat-then-ascending + in: + obstacles: [2, 2, 2, 3, 1, 4] + out: [1, 2, 3, 4, 1, 5] + - name: two-runs + in: + obstacles: [1, 3, 5, 2, 4, 6] + out: [1, 2, 3, 2, 3, 4] + - name: repeated-rise + in: + obstacles: [2, 1, 2, 3, 2, 3, 3] + out: [1, 1, 2, 3, 3, 4, 5] + - name: generator-short + in: + obstacles: + gen: "array" + len: 25 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + - name: generator-medium + in: + obstacles: + gen: "array" + len: 250 + of: + gen: "int" + min: 1 + max: 10000 + distinct: false + sorted: false + elemType: "int" + - name: generator-duplicates + in: + obstacles: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 8 + distinct: false + sorted: false + elemType: "int" + - name: generator-large + in: + obstacles: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 10000000 + distinct: false + sorted: false + elemType: "int" + - name: generator-near-maximum + in: + obstacles: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 10000000 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.cpp b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.cpp new file mode 100644 index 00000000..8dedc081 --- /dev/null +++ b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + vector longestObstacleCourseAtEachPosition(vector& obstacles) { + vector tails; + vector res; + res.reserve(obstacles.size()); + for (int x : obstacles) { + int idx = upper_bound(tails.begin(), tails.end(), x) - tails.begin(); + res.push_back(idx + 1); + if (idx == tails.size()) { + tails.push_back(x); + } else { + tails[idx] = x; + } + } + return res; + } +}; diff --git a/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.cs b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.cs new file mode 100644 index 00000000..20fbd7f7 --- /dev/null +++ b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.cs @@ -0,0 +1,30 @@ +public class Solution { + public int[] LongestObstacleCourseAtEachPosition(int[] obstacles) { + List tails = new List(); + int[] res = new int[obstacles.Length]; + for (int i = 0; i < obstacles.Length; i++) { + int x = obstacles[i]; + int idx = UpperBound(tails, x); + res[i] = idx + 1; + if (idx == tails.Count) { + tails.Add(x); + } else { + tails[idx] = x; + } + } + return res; + } + + private int UpperBound(List list, int target) { + int lo = 0, hi = list.Count; + while (lo < hi) { + int mid = lo + (hi - lo) / 2; + if (list[mid] <= target) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; + } +} diff --git a/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.dart b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.dart new file mode 100644 index 00000000..dddfb6ae --- /dev/null +++ b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.dart @@ -0,0 +1,30 @@ +class Solution { + List longestObstacleCourseAtEachPosition(List obstacles) { + final tails = []; + final res = List.filled(obstacles.length, 0); + for (int i = 0; i < obstacles.length; i++) { + final x = obstacles[i]; + final idx = upperBound(tails, x); + res[i] = idx + 1; + if (idx == tails.length) { + tails.add(x); + } else { + tails[idx] = x; + } + } + return res; + } + + int upperBound(List list, int target) { + int lo = 0, hi = list.length; + while (lo < hi) { + final mid = lo + ((hi - lo) >> 1); + if (list[mid] <= target) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; + } +} diff --git a/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.go b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.go new file mode 100644 index 00000000..ba8155c9 --- /dev/null +++ b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.go @@ -0,0 +1,27 @@ +func longestObstacleCourseAtEachPosition(obstacles []int) []int { + tails := make([]int, 0, len(obstacles)) + res := make([]int, len(obstacles)) + for i, x := range obstacles { + idx := upperBound(tails, x) + res[i] = idx + 1 + if idx == len(tails) { + tails = append(tails, x) + } else { + tails[idx] = x + } + } + return res +} + +func upperBound(arr []int, target int) int { + lo, hi := 0, len(arr) + for lo < hi { + mid := lo + (hi-lo)/2 + if arr[mid] <= target { + lo = mid + 1 + } else { + hi = mid + } + } + return lo +} diff --git a/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.java b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.java new file mode 100644 index 00000000..a0ddb745 --- /dev/null +++ b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.java @@ -0,0 +1,32 @@ +class Solution { + public int[] longestObstacleCourseAtEachPosition(int[] obstacles) { + int n = obstacles.length; + int[] tails = new int[n]; + int len = 0; + int[] res = new int[n]; + for (int i = 0; i < n; i++) { + int x = obstacles[i]; + int idx = upperBound(tails, len, x); + res[i] = idx + 1; + if (idx == len) { + tails[len++] = x; + } else { + tails[idx] = x; + } + } + return res; + } + + private int upperBound(int[] arr, int len, int target) { + int lo = 0, hi = len; + while (lo < hi) { + int mid = lo + (hi - lo) / 2; + if (arr[mid] <= target) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; + } +} diff --git a/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.kt b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.kt new file mode 100644 index 00000000..d3ce2c69 --- /dev/null +++ b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.kt @@ -0,0 +1,31 @@ +class Solution { + fun longestObstacleCourseAtEachPosition(obstacles: IntArray): IntArray { + val tails = mutableListOf() + val res = IntArray(obstacles.size) + for (i in obstacles.indices) { + val x = obstacles[i] + val idx = upperBound(tails, x) + res[i] = idx + 1 + if (idx == tails.size) { + tails.add(x) + } else { + tails[idx] = x + } + } + return res + } + + private fun upperBound(list: List, target: Int): Int { + var lo = 0 + var hi = list.size + while (lo < hi) { + val mid = lo + (hi - lo) / 2 + if (list[mid] <= target) { + lo = mid + 1 + } else { + hi = mid + } + } + return lo + } +} diff --git a/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.py b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.py new file mode 100644 index 00000000..c2cb73e7 --- /dev/null +++ b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.py @@ -0,0 +1,14 @@ +class Solution: + def longestObstacleCourseAtEachPosition(self, obstacles: list[int]) -> list[int]: + from bisect import bisect_right + + tails = [] + answer = [] + for height in obstacles: + index = bisect_right(tails, height) + if index == len(tails): + tails.append(height) + else: + tails[index] = height + answer.append(index + 1) + return answer diff --git a/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.py2 b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.py2 new file mode 100644 index 00000000..5529124e --- /dev/null +++ b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.py2 @@ -0,0 +1,18 @@ +import bisect + +class Solution(object): + def longestObstacleCourseAtEachPosition(self, obstacles): + """ + :type obstacles: List[int] + :rtype: List[int] + """ + tails = [] + res = [] + for x in obstacles: + idx = bisect.bisect_right(tails, x) + if idx == len(tails): + tails.append(x) + else: + tails[idx] = x + res.append(idx + 1) + return res diff --git a/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.rb b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.rb new file mode 100644 index 00000000..3519a119 --- /dev/null +++ b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.rb @@ -0,0 +1,16 @@ +# @param {Integer[]} obstacles +# @return {Integer[]} +def longest_obstacle_course_at_each_position(obstacles) + tails = [] + res = [] + obstacles.each do |x| + idx = tails.bsearch_index { |t| t > x } || tails.length + if idx == tails.length + tails << x + else + tails[idx] = x + end + res << idx + 1 + end + res +end diff --git a/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.rs b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.rs new file mode 100644 index 00000000..0bc21129 --- /dev/null +++ b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.rs @@ -0,0 +1,30 @@ +impl Solution { + pub fn longest_obstacle_course_at_each_position(obstacles: Vec) -> Vec { + let mut tails: Vec = Vec::new(); + let mut res = Vec::with_capacity(obstacles.len()); + for &x in &obstacles { + let idx = upper_bound(&tails, x); + res.push((idx + 1) as i32); + if idx == tails.len() { + tails.push(x); + } else { + tails[idx] = x; + } + } + res + } +} + +fn upper_bound(arr: &Vec, target: i32) -> usize { + let mut lo = 0; + let mut hi = arr.len(); + while lo < hi { + let mid = lo + (hi - lo) / 2; + if arr[mid] <= target { + lo = mid + 1; + } else { + hi = mid; + } + } + lo +} diff --git a/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.swift b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.swift new file mode 100644 index 00000000..5ba71b69 --- /dev/null +++ b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.swift @@ -0,0 +1,29 @@ +class Solution { + func longestObstacleCourseAtEachPosition(_ obstacles: [Int]) -> [Int] { + var tails: [Int] = [] + var res: [Int] = [] + for x in obstacles { + let idx = upperBound(tails, x) + res.append(idx + 1) + if idx == tails.count { + tails.append(x) + } else { + tails[idx] = x + } + } + return res + } + + private func upperBound(_ arr: [Int], _ target: Int) -> Int { + var lo = 0, hi = arr.count + while lo < hi { + let mid = lo + (hi - lo) / 2 + if arr[mid] <= target { + lo = mid + 1 + } else { + hi = mid + } + } + return lo + } +} diff --git a/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.ts b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.ts new file mode 100644 index 00000000..ffc81f93 --- /dev/null +++ b/tests/1501-2000/1964. find-the-longest-valid-obstacle-course-at-each-position/sol.ts @@ -0,0 +1,28 @@ +function longestObstacleCourseAtEachPosition(obstacles: number[]): number[] { + const tails: number[] = []; + const res: number[] = []; + for (const x of obstacles) { + const idx = upperBound(tails, x); + res.push(idx + 1); + if (idx === tails.length) { + tails.push(x); + } else { + tails[idx] = x; + } + } + return res; +} + +function upperBound(arr: number[], target: number): number { + let lo = 0, + hi = arr.length; + while (lo < hi) { + const mid = lo + ((hi - lo) >> 1); + if (arr[mid] <= target) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; +} diff --git a/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/manifest.yaml b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/manifest.yaml new file mode 100644 index 00000000..f5168323 --- /dev/null +++ b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/manifest.yaml @@ -0,0 +1,326 @@ +entry: + id: 1967 + title: "number-of-strings-that-appear-as-substrings-in-word" + params: + patterns: + type: array + items: + type: string + word: + type: string + call: + cpp: "Solution().numOfStrings({patterns}, {word})" + rust: "Solution::num_of_strings({patterns}, {word})" + python3: "Solution().numOfStrings({patterns}, {word})" + python2: "Solution().numOfStrings({patterns}, {word})" + ruby: "num_of_strings({patterns}, {word})" + java: "new Solution().numOfStrings({patterns}, {word})" + csharp: "new Solution().NumOfStrings({patterns}, {word})" + kotlin: "Solution().numOfStrings({patterns}, {word})" + go: "numOfStrings({patterns}, {word})" + dart: "Solution().numOfStrings({patterns}, {word})" + swift: "Solution().numOfStrings({patterns}, {word})" + typescript: "numOfStrings({patterns}, {word})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().numOfStrings(patterns, word, {result})" + checker: | + class Checker: + def numOfStrings(self, patterns, word, result): + if isinstance(result, bool) or not isinstance(result, int): + return False + return result == sum(1 for pattern in patterns if pattern in word) + +seed: 1967 + +tests: + - name: "example_basic" + in: + patterns: ["a", "abc", "bc", "d"] + word: "abc" + out: 3 + - name: "example_runs" + in: + patterns: ["a", "b", "c"] + word: "aaaaabbbbb" + out: 2 + - name: "example_duplicates" + in: + patterns: ["a", "a", "a"] + word: "ab" + out: 3 + - name: "single_match" + in: + patterns: ["z"] + word: "z" + out: 1 + - name: "single_miss" + in: + patterns: ["z"] + word: "a" + out: 0 + - name: "whole_word" + in: + patterns: ["abc", "ab", "bc", "abcd"] + word: "abc" + out: 3 + - name: "repeated_pattern" + in: + patterns: ["aa", "aa", "aaa", "b"] + word: "aaaa" + out: 3 + - name: "overlapping_matches" + in: + patterns: ["aba", "bab", "ab", "ba", "ac"] + word: "ababa" + out: 4 + - name: "all_misses" + in: + patterns: ["x", "y", "z", "xy", "yz"] + word: "aaaa" + out: 0 + - name: "one_letter_word" + in: + patterns: ["a", "aa", "b", "ab"] + word: "a" + out: 1 + - name: "alternating" + in: + patterns: ["a", "b", "ab", "ba", "aba", "bab"] + word: "ababab" + out: 6 + - name: "prefixes" + in: + patterns: ["a", "ab", "abc", "abcd", "abcde"] + word: "abcd" + out: 4 + - name: "suffixes" + in: + patterns: ["d", "cd", "bcd", "abcd", "abcde"] + word: "abcd" + out: 4 + - name: "interior" + in: + patterns: ["b", "bc", "c", "abc", "bcd"] + word: "abcd" + out: 5 + - name: "case_lowercase_only" + in: + patterns: ["q", "qq", "w", "qw"] + word: "qqq" + out: 2 + - name: "long_pattern_miss" + in: + patterns: ["aaaaaaaaab", "aaaaaaaaa", "baaaaaaaaa"] + word: "aaaaaaaaaa" + out: 1 + - name: "many_duplicates" + in: + patterns: ["cat", "cat", "cat", "dog", "cat", "bird"] + word: "catdog" + out: 5 + - name: "single_char_repetition" + in: + patterns: ["a", "aa", "aaa", "aaaa", "aaaaa", "b"] + word: "aaaa" + out: 4 + - name: "middle_only" + in: + patterns: ["bc", "cd", "bcd", "abc", "abcd"] + word: "abcd" + out: 5 + - name: "disjoint_alphabet" + in: + patterns: ["a", "ab", "ba", "aba"] + word: "bbbb" + out: 0 + - name: "all_same" + in: + patterns: ["m", "m", "m", "m"] + word: "m" + out: 4 + - name: "length_four" + in: + patterns: ["abcd", "bcde", "cdef", "defg"] + word: "abcdefg" + out: 4 + - name: "length_limit_pattern" + in: + patterns: + [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "b", + ] + word: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: 1 + - name: "length_limit_word" + in: + patterns: + ["a", "aa", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "b"] + word: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: 3 + - name: "near_limit_mismatch" + in: + patterns: + [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + ] + word: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: 1 + - name: "mixed_words" + in: + patterns: ["hello", "ell", "llo", "world", "low", "o"] + word: "helloworld" + out: 6 + - name: "no_empty_patterns" + in: + patterns: ["x", "xx", "xxx"] + word: "xxxx" + out: 3 + - name: "alternating_long" + in: + patterns: ["abab", "baba", "ababa", "babab", "aab"] + word: "abababa" + out: 4 + - name: "rare_letters" + in: + patterns: ["z", "yz", "xyz", "wxyz", "x"] + word: "wxyz" + out: 5 + - name: "pattern_order_irrelevant" + in: + patterns: ["no", "yes", "maybe", "on", "es"] + word: "yesorno" + out: 3 + - name: "overlap_single_letter" + in: + patterns: ["a", "b", "c", "d", "e", "f", "g", "h"] + word: "abcdefgh" + out: 8 + - name: "long_repeated_blocks" + in: + patterns: ["abcabc", "bcab", "cabc", "abc", "bca", "cab", "ac"] + word: "abcabcabc" + out: 6 + - name: "punctuation_not_allowed" + in: + patterns: ["aa", "bb", "cc", "dd"] + word: "aabbcc" + out: 3 + - name: "all_word_substrings" + in: + patterns: ["a", "b", "c", "ab", "bc", "abc", "ac"] + word: "abc" + out: 6 + - name: "generated_small" + seed: 196701 + in: + patterns: + gen: "array" + len: + gen: "int" + min: 1 + max: 20 + of: + gen: "str" + len: + gen: "int" + min: 1 + max: 10 + alphabet: "abc" + word: + gen: "str" + len: + gen: "int" + min: 1 + max: 30 + alphabet: "abc" + - name: "generated_medium" + seed: 196702 + in: + patterns: + gen: "array" + len: + gen: "int" + min: 30 + max: 60 + of: + gen: "str" + len: + gen: "int" + min: 1 + max: 50 + alphabet: "abcd" + word: + gen: "str" + len: + gen: "int" + min: 50 + max: 80 + alphabet: "abcd" + - name: "generated_max_patterns" + seed: 196703 + in: + patterns: + gen: "array" + len: 100 + of: + gen: "str" + len: + gen: "int" + min: 1 + max: 100 + alphabet: "abcde" + word: + gen: "str" + len: 100 + alphabet: "abcde" + - name: "generated_max_repetitive" + seed: 196704 + in: + patterns: + gen: "array" + len: 100 + of: + gen: "str" + len: + gen: "int" + min: 1 + max: 100 + alphabet: "ab" + word: + gen: "str" + len: 100 + alphabet: "ab" + - name: "generated_max_alphabet" + seed: 196705 + in: + patterns: + gen: "array" + len: + gen: "int" + min: 80 + max: 100 + of: + gen: "str" + len: + gen: "int" + min: 80 + max: 100 + alphabet: "abcdefghijklmnopqrstuvwxyz" + word: + gen: "str" + len: + gen: "int" + min: 80 + max: 100 + alphabet: "abcdefghijklmnopqrstuvwxyz" diff --git a/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.cpp b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.cpp new file mode 100644 index 00000000..c3e67e08 --- /dev/null +++ b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int numOfStrings(vector& patterns, string word) { + int count = 0; + for (string& s : patterns) { + if (word.find(s) != string::npos) { + count++; + } + } + return count; + } +}; diff --git a/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.cs b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.cs new file mode 100644 index 00000000..3ab9f23b --- /dev/null +++ b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.cs @@ -0,0 +1,11 @@ +public class Solution { + public int NumOfStrings(string[] patterns, string word) { + int count = 0; + foreach (string s in patterns) { + if (word.Contains(s)) { + count++; + } + } + return count; + } +} diff --git a/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.dart b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.dart new file mode 100644 index 00000000..8b325dfd --- /dev/null +++ b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.dart @@ -0,0 +1,11 @@ +class Solution { + int numOfStrings(List patterns, String word) { + int count = 0; + for (String s in patterns) { + if (word.contains(s)) { + count++; + } + } + return count; + } +} diff --git a/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.go b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.go new file mode 100644 index 00000000..1d1e0d3c --- /dev/null +++ b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.go @@ -0,0 +1,9 @@ +func numOfStrings(patterns []string, word string) int { + count := 0 + for _, s := range patterns { + if strings.Contains(word, s) { + count++ + } + } + return count +} diff --git a/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.java b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.java new file mode 100644 index 00000000..e18d71f7 --- /dev/null +++ b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.java @@ -0,0 +1,11 @@ +class Solution { + public int numOfStrings(String[] patterns, String word) { + int count = 0; + for (String s : patterns) { + if (word.contains(s)) { + count++; + } + } + return count; + } +} diff --git a/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.kt b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.kt new file mode 100644 index 00000000..39276ce6 --- /dev/null +++ b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.kt @@ -0,0 +1,11 @@ +class Solution { + fun numOfStrings(patterns: Array, word: String): Int { + var count = 0 + for (s in patterns) { + if (word.contains(s)) { + count++ + } + } + return count + } +} diff --git a/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.py b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.py new file mode 100644 index 00000000..e1cee2a8 --- /dev/null +++ b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.py @@ -0,0 +1,7 @@ +class Solution: + def numOfStrings(self, patterns: list[str], word: str) -> int: + count = 0 + for s in patterns: + if s in word: + count += 1 + return count diff --git a/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.py2 b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.py2 new file mode 100644 index 00000000..f0d5d1f4 --- /dev/null +++ b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def numOfStrings(self, patterns, word): + """ + :type patterns: List[str] + :type word: str + :rtype: int + """ + count = 0 + for s in patterns: + if s in word: + count += 1 + return count diff --git a/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.rb b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.rb new file mode 100644 index 00000000..08f2c4ae --- /dev/null +++ b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.rb @@ -0,0 +1,12 @@ +# @param {String[]} patterns +# @param {String} word +# @return {Integer} +def num_of_strings(patterns, word) + count = 0 + patterns.each do |s| + if word.include?(s) + count += 1 + end + end + count +end diff --git a/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.rs b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.rs new file mode 100644 index 00000000..d037e351 --- /dev/null +++ b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.rs @@ -0,0 +1,11 @@ +impl Solution { + pub fn num_of_strings(patterns: Vec, word: String) -> i32 { + let mut count = 0; + for s in patterns { + if word.contains(&s) { + count += 1; + } + } + count + } +} diff --git a/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.swift b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.swift new file mode 100644 index 00000000..13ff9158 --- /dev/null +++ b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.swift @@ -0,0 +1,11 @@ +class Solution { + func numOfStrings(_ patterns: [String], _ word: String) -> Int { + var count = 0 + for s in patterns { + if word.contains(s) { + count += 1 + } + } + return count + } +} diff --git a/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.ts b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.ts new file mode 100644 index 00000000..4e434644 --- /dev/null +++ b/tests/1501-2000/1967. number-of-strings-that-appear-as-substrings-in-word/sol.ts @@ -0,0 +1,9 @@ +function numOfStrings(patterns: string[], word: string): number { + let count = 0; + for (const s of patterns) { + if (word.includes(s)) { + count++; + } + } + return count; +} diff --git a/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/manifest.yaml b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/manifest.yaml new file mode 100644 index 00000000..a0493d95 --- /dev/null +++ b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/manifest.yaml @@ -0,0 +1,357 @@ +entry: + id: 1968 + title: "array-with-elements-not-equal-to-average-of-neighbors" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().rearrangeArray({nums})" + rust: "Solution::rearrange_array({nums})" + python3: "Solution().rearrangeArray({nums})" + python2: "Solution().rearrangeArray({nums})" + ruby: "rearrange_array({nums})" + java: "new Solution().rearrangeArray({nums})" + csharp: "new Solution().RearrangeArray({nums})" + kotlin: "Solution().rearrangeArray({nums})" + go: "rearrangeArray({nums})" + dart: "Solution().rearrangeArray({nums})" + swift: "Solution().rearrangeArray({nums})" + typescript: "rearrangeArray({nums})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().rearrangeArray(nums, {result})" + checker: | + class Checker: + def rearrangeArray(self, nums, result): + if not isinstance(result, list) or len(result) != len(nums): + return False + if len(set(nums)) != len(nums): + return False + if sorted(result) != sorted(nums): + return False + for i in range(1, len(result) - 1): + if 2 * result[i] == result[i - 1] + result[i + 1]: + return False + return True + +seed: 1968 + +tests: + - name: "example_one" + in: + nums: [1, 2, 3, 4, 5] + - name: "example_two" + in: + nums: [6, 2, 0, 9, 7] + - name: "minimum_three_consecutive" + in: + nums: [0, 1, 2] + - name: "three_reversed" + in: + nums: [10, 4, 7] + - name: "three_negative_like_range" + in: + nums: [100, 0, 50] + - name: "four_consecutive" + in: + nums: [1, 2, 3, 4] + - name: "four_reverse" + in: + nums: [9, 7, 5, 3] + - name: "duplicates_are_not_allowed_but_values_are_close" + in: + nums: [2, 4, 5, 7, 9, 10] + - name: "sparse_values" + in: + nums: [0, 100, 1000, 10000, 100000] + - name: "powers_of_two" + in: + nums: [1, 2, 4, 8, 16, 32, 64] + - name: "alternating_input" + in: + nums: [0, 100, 1, 99, 2, 98, 3] + - name: "already_wiggle_like" + in: + nums: [1, 8, 3, 10, 5, 12, 7, 14] + - name: "centered_values" + in: + nums: [10, 20, 30, 40, 50, 60, 70, 80, 90] + - name: "small_random_a" + in: + nums: [13, 2, 29, 7, 19, 41, 5, 23, 11] + - name: "small_random_b" + in: + nums: [99, 1, 55, 34, 21, 8, 76, 3, 42, 67] + - name: "eleven_values" + in: + nums: [0, 3, 8, 14, 21, 31, 44, 58, 73, 89, 100] + - name: "dense_zero_prefix" + in: + nums: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + - name: "dense_high_values" + in: + nums: [99989, 99990, 99991, 99992, 99993, 99994, 99995, 99996] + - name: "mixed_gaps" + in: + nums: [4, 400, 40, 4000, 40000, 400000, 4000000] + - name: "prime_values" + in: + nums: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + - name: "even_values" + in: + nums: [2, 4, 6, 8, 10, 12, 14, 16, 18] + - name: "odd_values" + in: + nums: [1, 3, 5, 7, 9, 11, 13, 15, 17] + - name: "permuted_range_15" + in: + nums: [8, 1, 14, 3, 10, 6, 12, 0, 5, 13, 2, 9, 4, 11, 7] + - name: "large_gaps_15" + in: + nums: + [ + 0, + 1000, + 2000, + 3001, + 5000, + 8000, + 13000, + 21000, + 34000, + 55000, + 89000, + 100000, + 999, + 7777, + 44444, + ] + - name: "twenty_consecutive" + in: + nums: + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] + - name: "twenty_reverse" + in: + nums: + [19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] + - name: "twenty_spread" + in: + nums: + [ + 0, + 7, + 21, + 42, + 70, + 105, + 147, + 196, + 252, + 315, + 385, + 462, + 546, + 637, + 735, + 840, + 952, + 1071, + 1197, + 1330, + ] + - name: "thirty_mixed" + in: + nums: + [ + 17, + 2, + 88, + 31, + 5, + 144, + 63, + 9, + 101, + 27, + 12, + 76, + 49, + 3, + 120, + 66, + 18, + 95, + 40, + 7, + 133, + 54, + 22, + 109, + 35, + 1, + 82, + 14, + 127, + 58, + ] + - name: "thirty_one_range" + in: + nums: + [ + 30, + 0, + 29, + 1, + 28, + 2, + 27, + 3, + 26, + 4, + 25, + 5, + 24, + 6, + 23, + 7, + 22, + 8, + 21, + 9, + 20, + 10, + 19, + 11, + 18, + 12, + 17, + 13, + 16, + 14, + 15, + ] + - name: "forty_values" + in: + nums: + [ + 3, + 17, + 29, + 41, + 58, + 64, + 79, + 86, + 101, + 117, + 132, + 149, + 163, + 178, + 194, + 207, + 223, + 241, + 256, + 271, + 289, + 302, + 318, + 337, + 351, + 369, + 384, + 401, + 417, + 433, + 449, + 466, + 482, + 501, + 517, + 533, + 551, + 568, + 584, + 600, + ] + - name: "large_static_100" + in: + nums: + gen: "array" + len: 100 + distinct: true + sorted: false + elemType: "int" + of: + gen: "int" + min: 0 + max: 100000 + - name: "generated_small_distinct" + seed: 196801 + in: + nums: + gen: "array" + len: + gen: "int" + min: 3 + max: 30 + distinct: true + sorted: false + elemType: "int" + of: + gen: "int" + min: 0 + max: 100000 + - name: "generated_medium_distinct" + seed: 196802 + in: + nums: + gen: "array" + len: + gen: "int" + min: 500 + max: 1000 + distinct: true + sorted: false + elemType: "int" + of: + gen: "int" + min: 0 + max: 100000 + - name: "generated_large_distinct_a" + seed: 196803 + in: + nums: + gen: "array" + len: 50000 + distinct: true + sorted: false + elemType: "int" + of: + gen: "int" + min: 0 + max: 100000 + - name: "generated_large_distinct_b" + seed: 196804 + in: + nums: + gen: "array" + len: 100000 + distinct: true + sorted: false + elemType: "int" + of: + gen: "int" + min: 0 + max: 100000 diff --git a/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.cpp b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.cpp new file mode 100644 index 00000000..0c4f0ded --- /dev/null +++ b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector rearrangeArray(vector& nums) { + sort(nums.begin(), nums.end()); + vector res(nums.size()); + int mid = (nums.size() + 1) / 2; + int j = 0; + for (int i = 0; i < nums.size(); i += 2) { + res[i] = nums[j++]; + } + j = mid; + for (int i = 1; i < nums.size(); i += 2) { + res[i] = nums[j++]; + } + return res; + } +}; diff --git a/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.cs b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.cs new file mode 100644 index 00000000..1ef0ba2d --- /dev/null +++ b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public int[] RearrangeArray(int[] nums) { + Array.Sort(nums); + int[] res = new int[nums.Length]; + int mid = (nums.Length + 1) / 2; + int j = 0; + for (int i = 0; i < nums.Length; i += 2) { + res[i] = nums[j++]; + } + j = mid; + for (int i = 1; i < nums.Length; i += 2) { + res[i] = nums[j++]; + } + return res; + } +} diff --git a/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.dart b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.dart new file mode 100644 index 00000000..ec52ab50 --- /dev/null +++ b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.dart @@ -0,0 +1,16 @@ +class Solution { + List rearrangeArray(List nums) { + nums.sort(); + List res = List.filled(nums.length, 0); + int mid = (nums.length + 1) ~/ 2; + int j = 0; + for (int i = 0; i < nums.length; i += 2) { + res[i] = nums[j++]; + } + j = mid; + for (int i = 1; i < nums.length; i += 2) { + res[i] = nums[j++]; + } + return res; + } +} diff --git a/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.go b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.go new file mode 100644 index 00000000..899154b3 --- /dev/null +++ b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.go @@ -0,0 +1,16 @@ +func rearrangeArray(nums []int) []int { + sort.Ints(nums) + res := make([]int, len(nums)) + mid := (len(nums) + 1) / 2 + j := 0 + for i := 0; i < len(nums); i += 2 { + res[i] = nums[j] + j++ + } + j = mid + for i := 1; i < len(nums); i += 2 { + res[i] = nums[j] + j++ + } + return res +} diff --git a/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.java b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.java new file mode 100644 index 00000000..45dda149 --- /dev/null +++ b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.java @@ -0,0 +1,14 @@ +class Solution { + public int[] rearrangeArray(int[] nums) { + Arrays.sort(nums); + int[] res = new int[nums.length]; + int mid = (nums.length + 1) / 2; + for (int i = 0, j = 0; i < nums.length; i += 2, j++) { + res[i] = nums[j]; + } + for (int i = 1, j = mid; i < nums.length; i += 2, j++) { + res[i] = nums[j]; + } + return res; + } +} diff --git a/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.kt b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.kt new file mode 100644 index 00000000..c7173cd0 --- /dev/null +++ b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun rearrangeArray(nums: IntArray): IntArray { + nums.sort() + val res = IntArray(nums.size) + val mid = (nums.size + 1) / 2 + var j = 0 + for (i in nums.indices step 2) { + res[i] = nums[j++] + } + j = mid + for (i in 1 until nums.size step 2) { + res[i] = nums[j++] + } + return res + } +} diff --git a/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.py b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.py new file mode 100644 index 00000000..a9762ed2 --- /dev/null +++ b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.py @@ -0,0 +1,12 @@ +class Solution(object): + def rearrangeArray(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + nums.sort() + res = [0] * len(nums) + mid = (len(nums) + 1) // 2 + res[::2] = nums[:mid] + res[1::2] = nums[mid:] + return res diff --git a/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.py2 b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.py2 new file mode 100644 index 00000000..a9762ed2 --- /dev/null +++ b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def rearrangeArray(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + nums.sort() + res = [0] * len(nums) + mid = (len(nums) + 1) // 2 + res[::2] = nums[:mid] + res[1::2] = nums[mid:] + return res diff --git a/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.rb b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.rb new file mode 100644 index 00000000..f5ac017a --- /dev/null +++ b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.rb @@ -0,0 +1,15 @@ +# @param {Integer[]} nums +# @return {Integer[]} +def rearrange_array(nums) + nums.sort! + res = Array.new(nums.length, 0) + mid = (nums.length + 1) / 2 + res.each_index do |i| + if i.even? + res[i] = nums[i/2] + else + res[i] = nums[mid + (i-1)/2] + end + end + res +end diff --git a/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.rs b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.rs new file mode 100644 index 00000000..e66d84a8 --- /dev/null +++ b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn rearrange_array(nums: Vec) -> Vec { + let mut nums = nums; + nums.sort(); + let mut res = vec![0; nums.len()]; + let mid = (nums.len() + 1) / 2; + let mut j = 0; + for i in (0..nums.len()).step_by(2) { + res[i] = nums[j]; + j += 1; + } + j = mid; + for i in (1..nums.len()).step_by(2) { + res[i] = nums[j]; + j += 1; + } + res + } +} diff --git a/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.swift b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.swift new file mode 100644 index 00000000..ca76dbab --- /dev/null +++ b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.swift @@ -0,0 +1,22 @@ +class Solution { + func rearrangeArray(_ nums: [Int]) -> [Int] { + var nums = nums.sorted() + var res = Array(repeating: 0, count: nums.count) + let mid = (nums.count + 1) / 2 + var j = 0 + var i = 0 + while i < nums.count { + res[i] = nums[j] + j += 1 + i += 2 + } + j = mid + i = 1 + while i < nums.count { + res[i] = nums[j] + j += 1 + i += 2 + } + return res + } +} diff --git a/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.ts b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.ts new file mode 100644 index 00000000..a87a87ca --- /dev/null +++ b/tests/1501-2000/1968. array-with-elements-not-equal-to-average-of-neighbors/sol.ts @@ -0,0 +1,14 @@ +function rearrangeArray(nums: number[]): number[] { + nums.sort((a, b) => a - b); + const res: number[] = new Array(nums.length).fill(0); + const mid = Math.floor((nums.length + 1) / 2); + let j = 0; + for (let i = 0; i < nums.length; i += 2) { + res[i] = nums[j++]; + } + j = mid; + for (let i = 1; i < nums.length; i += 2) { + res[i] = nums[j++]; + } + return res; +} diff --git a/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/manifest.yaml b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/manifest.yaml new file mode 100644 index 00000000..51fe3eaa --- /dev/null +++ b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/manifest.yaml @@ -0,0 +1,221 @@ +entry: + id: 1969 + title: "minimum-non-zero-product-of-the-array-elements" + params: + p: + type: int + call: + cpp: "Solution().minNonZeroProduct({p})" + rust: "Solution::min_non_zero_product({p})" + python3: "Solution().minNonZeroProduct({p})" + python2: "Solution().minNonZeroProduct({p})" + ruby: "min_non_zero_product({p})" + java: "new Solution().minNonZeroProduct({p})" + csharp: "new Solution().MinNonZeroProduct({p})" + kotlin: "Solution().minNonZeroProduct({p})" + go: "minNonZeroProduct({p})" + dart: "Solution().minNonZeroProduct({p})" + swift: "Solution().minNonZeroProduct({p})" + typescript: "minNonZeroProduct({p})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().minNonZeroProduct(p, {result})" + checker: | + class Checker: + def minNonZeroProduct(self, p, result): + if not isinstance(p, int) or not (1 <= p <= 60): + return False + if not isinstance(result, int): + return False + mod = 1000000007 + maximum = (1 << p) - 1 + exponent = (1 << (p - 1)) - 1 + expected = pow(maximum - 1, exponent, mod) * maximum % mod + return result == expected + +seed: 1969 + +tests: + - name: "p_1" + in: + p: 1 + out: 1 + - name: "p_2" + in: + p: 2 + out: 6 + - name: "p_3" + in: + p: 3 + out: 1512 + - name: "p_4" + in: + p: 4 + out: 581202553 + - name: "p_5" + in: + p: 5 + out: 202795991 + - name: "p_6" + in: + p: 6 + out: 57405498 + - name: "p_7" + in: + p: 7 + out: 316555604 + - name: "p_8" + in: + p: 8 + out: 9253531 + - name: "p_9" + in: + p: 9 + out: 857438053 + - name: "p_10" + in: + p: 10 + out: 586669277 + - name: "p_11" + in: + p: 11 + out: 647824153 + - name: "p_12" + in: + p: 12 + out: 93512543 + - name: "p_13" + in: + p: 13 + out: 391630296 + - name: "p_14" + in: + p: 14 + out: 187678728 + - name: "p_15" + in: + p: 15 + out: 431467833 + - name: "p_16" + in: + p: 16 + out: 539112180 + - name: "p_17" + in: + p: 17 + out: 368376380 + - name: "p_18" + in: + p: 18 + out: 150112795 + - name: "p_19" + in: + p: 19 + out: 484576688 + - name: "p_20" + in: + p: 20 + out: 212293935 + - name: "p_21" + in: + p: 21 + out: 828477683 + - name: "p_22" + in: + p: 22 + out: 106294648 + - name: "p_23" + in: + p: 23 + out: 618323081 + - name: "p_24" + in: + p: 24 + out: 186692306 + - name: "p_25" + in: + p: 25 + out: 513022074 + - name: "p_26" + in: + p: 26 + out: 109245444 + - name: "p_27" + in: + p: 27 + out: 821184946 + - name: "p_28" + in: + p: 28 + out: 2043018 + - name: "p_29" + in: + p: 29 + out: 26450314 + - name: "p_30" + in: + p: 30 + out: 945196305 + - name: "p_31" + in: + p: 31 + out: 138191773 + - name: "p_32" + in: + p: 32 + out: 505517599 + - name: "p_33" + in: + p: 33 + out: 861896614 + - name: "p_40" + in: + p: 40 + out: 554966674 + - name: "p_60" + in: + p: 60 + out: 813987236 + - name: "generated_small_to_medium" + seed: 101 + in: + p: + gen: "int" + min: 1 + max: 20 + - name: "generated_mid" + seed: 202 + in: + p: + gen: "int" + min: 21 + max: 40 + - name: "generated_large" + seed: 303 + in: + p: + gen: "int" + min: 41 + max: 60 + - name: "generated_full_range_a" + seed: 404 + in: + p: + gen: "int" + min: 1 + max: 60 + - name: "generated_full_range_b" + seed: 505 + in: + p: + gen: "int" + min: 1 + max: 60 diff --git a/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.cpp b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.cpp new file mode 100644 index 00000000..e36c64f2 --- /dev/null +++ b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int minNonZeroProduct(int p) { + const long long MOD = 1e9 + 7; + long long maxNum = (1LL << p) - 1; + long long count = (1LL << (p - 1)) - 1; + + auto powMod = [&](long long x, long long n) { + x %= MOD; + long long result = 1; + while (n) { + if (n & 1) { + result = (result * x) % MOD; + } + x = (x * x) % MOD; + n >>= 1; + } + return result; + }; + + long long ans = powMod(maxNum - 1, count) * (maxNum % MOD) % MOD; + return (int)ans; + } +}; diff --git a/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.cs b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.cs new file mode 100644 index 00000000..b082919a --- /dev/null +++ b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.cs @@ -0,0 +1,23 @@ +public class Solution { + public int MinNonZeroProduct(int p) { + const long MOD = 1_000_000_007; + long maxNum = (1L << p) - 1; + long count = (1L << (p - 1)) - 1; + + long PowMod(long x, long n) { + x %= MOD; + long result = 1; + while (n > 0) { + if ((n & 1) == 1) { + result = (result * x) % MOD; + } + x = (x * x) % MOD; + n >>= 1; + } + return result; + } + + long pow = PowMod(maxNum - 1, count); + return (int)((pow * (maxNum % MOD)) % MOD); + } +} diff --git a/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.dart b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.dart new file mode 100644 index 00000000..e2d495bd --- /dev/null +++ b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.dart @@ -0,0 +1,22 @@ +class Solution { + int minNonZeroProduct(int p) { + const int mod = 1000000007; + int maxNum = (1 << p) - 1; + int count = (1 << (p - 1)) - 1; + + int powMod(int x, int n) { + x %= mod; + int result = 1; + while (n > 0) { + if (n & 1 == 1) { + result = (result * x) % mod; + } + x = (x * x) % mod; + n >>= 1; + } + return result; + } + + return (powMod(maxNum - 1, count) * (maxNum % mod)) % mod; + } +} diff --git a/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.go b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.go new file mode 100644 index 00000000..a002f211 --- /dev/null +++ b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.go @@ -0,0 +1,21 @@ +func minNonZeroProduct(p int) int { + const mod = 1000000007 + maxNum := (int64(1) << p) - 1 + count := (int64(1) << (p - 1)) - 1 + + powMod := func(x, n int64) int64 { + x %= mod + result := int64(1) + for n > 0 { + if n&1 == 1 { + result = (result * x) % mod + } + x = (x * x) % mod + n >>= 1 + } + return result + } + + ans := powMod(maxNum-1, count) * (maxNum % mod) % mod + return int(ans) +} diff --git a/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.java b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.java new file mode 100644 index 00000000..081b4046 --- /dev/null +++ b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.java @@ -0,0 +1,23 @@ +class Solution { + public int minNonZeroProduct(int p) { + long mod = 1_000_000_007L; + long maxNum = (1L << p) - 1; + long count = (1L << (p - 1)) - 1; + + long powMod = powMod(maxNum - 1, count, mod); + return (int)((powMod * (maxNum % mod)) % mod); + } + + private long powMod(long x, long n, long mod) { + long result = 1; + x %= mod; + while (n > 0) { + if ((n & 1) == 1) { + result = (result * x) % mod; + } + x = (x * x) % mod; + n >>= 1; + } + return result; + } +} diff --git a/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.kt b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.kt new file mode 100644 index 00000000..4fe95f33 --- /dev/null +++ b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.kt @@ -0,0 +1,24 @@ +class Solution { + fun minNonZeroProduct(p: Int): Int { + val mod = 1_000_000_007L + val maxNum = (1L shl p) - 1 + val count = (1L shl (p - 1)) - 1 + + fun powMod(x: Long, n: Long): Long { + var base = x % mod + var exp = n + var res = 1L + while (exp > 0) { + if ((exp and 1L) == 1L) { + res = (res * base) % mod + } + base = (base * base) % mod + exp = exp shr 1 + } + return res + } + + val pow = powMod(maxNum - 1, count) + return ((pow * (maxNum % mod)) % mod).toInt() + } +} diff --git a/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.py b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.py new file mode 100644 index 00000000..787ebb8d --- /dev/null +++ b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.py @@ -0,0 +1,21 @@ +class Solution(object): + def minNonZeroProduct(self, p): + """ + :type p: int + :rtype: int + """ + MOD = 10**9 + 7 + max_num = (1 << p) - 1 + count = (1 << (p - 1)) - 1 + + def mod_pow(x, n): + result = 1 + x = x % MOD + while n: + if n % 2: + result = result * x % MOD + x = x * x % MOD + n //= 2 + return result + + return (mod_pow(max_num - 1, count) * max_num) % MOD diff --git a/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.py2 b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.py2 new file mode 100644 index 00000000..ca051c28 --- /dev/null +++ b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.py2 @@ -0,0 +1,21 @@ +class Solution(object): + def minNonZeroProduct(self, p): + """ + :type p: int + :rtype: int + """ + MOD = 10**9 + 7 + max_num = (1 << p) - 1 + count = (1 << (p - 1)) - 1 + + def mod_pow(x, n): + result = 1 + x = x % MOD + while n: + if n % 2: + result = result * x % MOD + x = x * x % MOD + n //= 2 + return result + + return int((mod_pow(max_num - 1, count) * max_num) % MOD) diff --git a/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.rb b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.rb new file mode 100644 index 00000000..0e6110ef --- /dev/null +++ b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.rb @@ -0,0 +1,20 @@ +# @param {Integer} p +# @return {Integer} +def min_non_zero_product(p) + mod = 10**9 + 7 + max_num = (1 << p) - 1 + count = (1 << (p - 1)) - 1 + + pow_mod = ->(x, n) { + result = 1 + x %= mod + while n > 0 + result = (result * x) % mod if n & 1 == 1 + x = (x * x) % mod + n >>= 1 + end + result + } + + (pow_mod.call(max_num - 1, count) * max_num) % mod +end diff --git a/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.rs b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.rs new file mode 100644 index 00000000..97b03fb4 --- /dev/null +++ b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.rs @@ -0,0 +1,23 @@ +impl Solution { + pub fn min_non_zero_product(p: i32) -> i32 { + const MOD: i64 = 1_000_000_007; + let max_num = (1i64 << p) - 1; + let count = (1i64 << (p - 1)) - 1; + + fn pow_mod(mut x: i64, mut n: i64, mod_val: i64) -> i64 { + x %= mod_val; + let mut result = 1; + while n > 0 { + if n & 1 == 1 { + result = (result * x) % mod_val; + } + x = (x * x) % mod_val; + n >>= 1; + } + result + } + + let pow = pow_mod(max_num - 1, count, MOD); + ((pow * (max_num % MOD)) % MOD) as i32 + } +} diff --git a/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.swift b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.swift new file mode 100644 index 00000000..8db67ff4 --- /dev/null +++ b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func minNonZeroProduct(_ p: Int) -> Int { + let mod = 1_000_000_007 + let maxNum = (1 << p) - 1 + let count = (1 << (p - 1)) - 1 + + func powMod(_ x: Int, _ n: Int) -> Int { + var base = x % mod + var exp = n + var result = 1 + while exp > 0 { + if exp & 1 == 1 { + result = (result * base) % mod + } + base = (base * base) % mod + exp >>= 1 + } + return result + } + + return (powMod(maxNum - 1, count) * (maxNum % mod)) % mod + } +} diff --git a/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.ts b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.ts new file mode 100644 index 00000000..3f7ffa82 --- /dev/null +++ b/tests/1501-2000/1969. minimum-non-zero-product-of-the-array-elements/sol.ts @@ -0,0 +1,21 @@ +function minNonZeroProduct(p: number): number { + const MOD = 1000000007n; + const maxNum = (1n << BigInt(p)) - 1n; + const count = (1n << BigInt(p - 1)) - 1n; + + const powMod = (x: bigint, n: bigint): bigint => { + let base = x % MOD; + let exp = n; + let result = 1n; + while (exp > 0) { + if (exp & 1n) { + result = (result * base) % BigInt(MOD); + } + base = (base * base) % MOD; + exp >>= 1n; + } + return result; + }; + + return Number((powMod(maxNum - 1n, count) * (maxNum % MOD)) % MOD); +} diff --git a/tests/1501-2000/1970. last-day-where-you-can-still-cross/manifest.yaml b/tests/1501-2000/1970. last-day-where-you-can-still-cross/manifest.yaml new file mode 100644 index 00000000..769ffdb8 --- /dev/null +++ b/tests/1501-2000/1970. last-day-where-you-can-still-cross/manifest.yaml @@ -0,0 +1,675 @@ +entry: + id: 1970 + title: "last-day-where-you-can-still-cross" + params: + row: + type: int + col: + type: int + cells: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().latestDayToCross({row}, {col}, {cells})" + rust: "Solution::latest_day_to_cross({row}, {col}, {cells})" + python3: "Solution().latestDayToCross({row}, {col}, {cells})" + python2: "Solution().latestDayToCross({row}, {col}, {cells})" + ruby: "latest_day_to_cross({row}, {col}, {cells})" + java: "new Solution().latestDayToCross({row}, {col}, {cells})" + csharp: "new Solution().LatestDayToCross({row}, {col}, {cells})" + kotlin: "Solution().latestDayToCross({row}, {col}, {cells})" + go: "latestDayToCross({row}, {col}, {cells})" + dart: "Solution().latestDayToCross({row}, {col}, {cells})" + swift: "Solution().latestDayToCross({row}, {col}, {cells})" + typescript: "latestDayToCross({row}, {col}, {cells})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().latestDayToCross(row, col, cells, {result})" + checker: | + from collections import deque + + class Checker: + def latestDayToCross(self, row, col, cells, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if len(cells) != row * col: + return False + + def can(day): + blocked = [[False] * col for _ in range(row)] + for r, c in cells[:day]: + blocked[r - 1][c - 1] = True + q = deque() + seen = [[False] * col for _ in range(row)] + for c in range(col): + if not blocked[0][c]: + q.append((0, c)) + seen[0][c] = True + while q: + r, c = q.popleft() + if r == row - 1: + return True + for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): + nr, nc = r + dr, c + dc + if 0 <= nr < row and 0 <= nc < col and not seen[nr][nc] and not blocked[nr][nc]: + seen[nr][nc] = True + q.append((nr, nc)) + return False + + expected = 0 + for day in range(1, len(cells) + 1): + if can(day): + expected = day + else: + break + return result == expected + +seed: 1970 + +tests: + - name: "example_1" + in: + row: 2 + col: 2 + cells: + - [1, 1] + - [2, 1] + - [1, 2] + - [2, 2] + out: 2 + - name: "example_2" + in: + row: 2 + col: 2 + cells: + - [1, 1] + - [1, 2] + - [2, 1] + - [2, 2] + out: 1 + - name: "example_3" + in: + row: 3 + col: 3 + cells: + - [1, 2] + - [2, 1] + - [3, 3] + - [2, 2] + - [1, 1] + - [1, 3] + - [2, 3] + - [3, 2] + - [3, 1] + out: 3 + - name: "two_by_two_column_first" + in: + row: 2 + col: 2 + cells: + - [1, 1] + - [2, 1] + - [2, 2] + - [1, 2] + out: 2 + - name: "two_by_two_other" + in: + row: 2 + col: 2 + cells: + - [2, 2] + - [1, 2] + - [2, 1] + - [1, 1] + out: 2 + - name: "two_by_three_row_major" + in: + row: 2 + col: 3 + cells: + - [1, 1] + - [1, 2] + - [1, 3] + - [2, 1] + - [2, 2] + - [2, 3] + out: 2 + - name: "two_by_three_bottom_first" + in: + row: 2 + col: 3 + cells: + - [2, 1] + - [2, 2] + - [2, 3] + - [1, 1] + - [1, 2] + - [1, 3] + out: 2 + - name: "two_by_three_middle_cut" + in: + row: 2 + col: 3 + cells: + - [1, 2] + - [2, 2] + - [1, 1] + - [2, 1] + - [1, 3] + - [2, 3] + out: 4 + - name: "two_by_three_edges" + in: + row: 2 + col: 3 + cells: + - [1, 1] + - [2, 3] + - [1, 3] + - [2, 1] + - [1, 2] + - [2, 2] + out: 4 + - name: "three_by_two_row_major" + in: + row: 3 + col: 2 + cells: + - [1, 1] + - [1, 2] + - [2, 1] + - [2, 2] + - [3, 1] + - [3, 2] + out: 1 + - name: "three_by_two_bottom_first" + in: + row: 3 + col: 2 + cells: + - [3, 1] + - [3, 2] + - [1, 1] + - [2, 1] + - [1, 2] + - [2, 2] + out: 1 + - name: "three_by_two_zigzag" + in: + row: 3 + col: 2 + cells: + - [1, 1] + - [2, 2] + - [3, 1] + - [1, 2] + - [2, 1] + - [3, 2] + out: 1 + - name: "three_by_three_diagonal" + in: + row: 3 + col: 3 + cells: + - [1, 1] + - [2, 2] + - [3, 3] + - [1, 2] + - [2, 1] + - [3, 2] + - [1, 3] + - [2, 3] + - [3, 1] + out: 2 + - name: "three_by_three_border" + in: + row: 3 + col: 3 + cells: + - [1, 1] + - [1, 3] + - [3, 1] + - [3, 3] + - [1, 2] + - [2, 1] + - [2, 3] + - [3, 2] + - [2, 2] + out: 4 + - name: "three_by_three_center_last" + in: + row: 3 + col: 3 + cells: + - [2, 2] + - [1, 2] + - [3, 2] + - [2, 1] + - [2, 3] + - [1, 1] + - [1, 3] + - [3, 1] + - [3, 3] + out: 4 + - name: "three_by_three_snake" + in: + row: 3 + col: 3 + cells: + - [1, 1] + - [1, 2] + - [1, 3] + - [2, 3] + - [2, 2] + - [2, 1] + - [3, 1] + - [3, 2] + - [3, 3] + out: 2 + - name: "three_by_three_reverse_snake" + in: + row: 3 + col: 3 + cells: + - [3, 3] + - [3, 2] + - [3, 1] + - [2, 1] + - [2, 2] + - [2, 3] + - [1, 3] + - [1, 2] + - [1, 1] + out: 2 + - name: "three_by_four_row_major" + in: + row: 3 + col: 4 + cells: + - [1, 1] + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 1] + - [2, 2] + - [2, 3] + - [2, 4] + - [3, 1] + - [3, 2] + - [3, 3] + - [3, 4] + out: 3 + - name: "three_by_four_columns" + in: + row: 3 + col: 4 + cells: + - [1, 1] + - [2, 1] + - [3, 1] + - [1, 2] + - [2, 2] + - [3, 2] + - [1, 3] + - [2, 3] + - [3, 3] + - [1, 4] + - [2, 4] + - [3, 4] + out: 9 + - name: "three_by_four_alternating" + in: + row: 3 + col: 4 + cells: + - [1, 2] + - [2, 3] + - [3, 4] + - [1, 4] + - [2, 1] + - [3, 2] + - [1, 3] + - [2, 4] + - [3, 1] + - [1, 1] + - [2, 2] + - [3, 3] + out: 4 + - name: "four_by_two_column_stripe" + in: + row: 4 + col: 2 + cells: + - [1, 1] + - [2, 1] + - [3, 1] + - [4, 1] + - [1, 2] + - [2, 2] + - [3, 2] + - [4, 2] + out: 4 + - name: "four_by_two_alternating" + in: + row: 4 + col: 2 + cells: + - [1, 1] + - [2, 2] + - [3, 1] + - [4, 2] + - [1, 2] + - [2, 1] + - [3, 2] + - [4, 1] + out: 1 + - name: "four_by_three_row_major" + in: + row: 4 + col: 3 + cells: + - [1, 1] + - [1, 2] + - [1, 3] + - [2, 1] + - [2, 2] + - [2, 3] + - [3, 1] + - [3, 2] + - [3, 3] + - [4, 1] + - [4, 2] + - [4, 3] + out: 2 + - name: "four_by_three_reverse_rows" + in: + row: 4 + col: 3 + cells: + - [4, 3] + - [4, 2] + - [4, 1] + - [3, 3] + - [3, 2] + - [3, 1] + - [2, 3] + - [2, 2] + - [2, 1] + - [1, 3] + - [1, 2] + - [1, 1] + out: 2 + - name: "four_by_four_row_major" + in: + row: 4 + col: 4 + cells: + - [1, 1] + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 1] + - [2, 2] + - [2, 3] + - [2, 4] + - [3, 1] + - [3, 2] + - [3, 3] + - [3, 4] + - [4, 1] + - [4, 2] + - [4, 3] + - [4, 4] + out: 3 + - name: "four_by_four_column_major" + in: + row: 4 + col: 4 + cells: + - [1, 1] + - [2, 1] + - [3, 1] + - [4, 1] + - [1, 2] + - [2, 2] + - [3, 2] + - [4, 2] + - [1, 3] + - [2, 3] + - [3, 3] + - [4, 3] + - [1, 4] + - [2, 4] + - [3, 4] + - [4, 4] + out: 12 + - name: "four_by_four_center_first" + in: + row: 4 + col: 4 + cells: + - [2, 2] + - [2, 3] + - [3, 2] + - [3, 3] + - [1, 2] + - [1, 3] + - [4, 2] + - [4, 3] + - [2, 1] + - [3, 1] + - [2, 4] + - [3, 4] + - [1, 1] + - [1, 4] + - [4, 1] + - [4, 4] + out: 10 + - name: "four_by_four_diagonal" + in: + row: 4 + col: 4 + cells: + - [1, 1] + - [2, 2] + - [3, 3] + - [4, 4] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 1] + - [1, 3] + - [2, 4] + - [3, 1] + - [4, 2] + - [1, 4] + - [2, 1] + - [3, 2] + - [4, 3] + out: 3 + - name: "four_by_four_snake" + in: + row: 4 + col: 4 + cells: + - [1, 1] + - [1, 2] + - [1, 3] + - [1, 4] + - [2, 4] + - [2, 3] + - [2, 2] + - [2, 1] + - [3, 1] + - [3, 2] + - [3, 3] + - [3, 4] + - [4, 4] + - [4, 3] + - [4, 2] + - [4, 1] + out: 3 + - name: "five_by_two_row_major" + in: + row: 5 + col: 2 + cells: + - [1, 1] + - [1, 2] + - [2, 1] + - [2, 2] + - [3, 1] + - [3, 2] + - [4, 1] + - [4, 2] + - [5, 1] + - [5, 2] + out: 1 + - name: "five_by_two_bottom_up" + in: + row: 5 + col: 2 + cells: + - [5, 1] + - [5, 2] + - [4, 1] + - [4, 2] + - [3, 1] + - [3, 2] + - [2, 1] + - [2, 2] + - [1, 1] + - [1, 2] + out: 1 + - name: "six_by_two_checker" + in: + row: 6 + col: 2 + cells: + - [1, 1] + - [2, 2] + - [3, 1] + - [4, 2] + - [5, 1] + - [6, 2] + - [1, 2] + - [2, 1] + - [3, 2] + - [4, 1] + - [5, 2] + - [6, 1] + out: 1 + - name: "two_by_six_middle_first" + in: + row: 2 + col: 6 + cells: + - [1, 3] + - [2, 3] + - [1, 4] + - [2, 4] + - [1, 1] + - [2, 1] + - [1, 2] + - [2, 2] + - [1, 5] + - [2, 5] + - [1, 6] + - [2, 6] + out: 10 + - name: "two_by_six_alternating" + in: + row: 2 + col: 6 + cells: + - [1, 1] + - [2, 2] + - [1, 3] + - [2, 4] + - [1, 5] + - [2, 6] + - [1, 2] + - [2, 1] + - [1, 4] + - [2, 3] + - [1, 6] + - [2, 5] + out: 5 + - name: "seven_by_two_rows" + in: + row: 7 + col: 2 + cells: + - [1, 1] + - [1, 2] + - [2, 1] + - [2, 2] + - [3, 1] + - [3, 2] + - [4, 1] + - [4, 2] + - [5, 1] + - [5, 2] + - [6, 1] + - [6, 2] + - [7, 1] + - [7, 2] + out: 1 + - name: "three_by_five_center_columns" + in: + row: 3 + col: 5 + cells: + - [1, 3] + - [2, 3] + - [3, 3] + - [1, 2] + - [2, 2] + - [3, 2] + - [1, 4] + - [2, 4] + - [3, 4] + - [1, 1] + - [2, 1] + - [3, 1] + - [1, 5] + - [2, 5] + - [3, 5] + out: 12 + - name: "four_by_five_cross_first" + in: + row: 4 + col: 5 + cells: + - [1, 3] + - [2, 3] + - [3, 3] + - [4, 3] + - [2, 2] + - [2, 4] + - [3, 2] + - [3, 4] + - [1, 2] + - [1, 4] + - [4, 2] + - [4, 4] + - [1, 1] + - [1, 5] + - [4, 1] + - [4, 5] + - [2, 1] + - [2, 5] + - [3, 1] + - [3, 5] + out: 13 diff --git a/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.cpp b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.cpp new file mode 100644 index 00000000..55f6cd08 --- /dev/null +++ b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.cpp @@ -0,0 +1,57 @@ +class Solution { +public: + int latestDayToCross(int row, int col, vector>& cells) { + int left = 1, right = cells.size(), answer = 0; + while (left <= right) { + int mid = (left + right) / 2; + if (canCross(mid, row, col, cells)) { + answer = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + return answer; + } + +private: + bool canCross(int day, int row, int col, vector>& cells) { + vector> grid(row, vector(col, 0)); + for (int i = 0; i < day; i++) { + int r = cells[i][0] - 1; + int c = cells[i][1] - 1; + grid[r][c] = 1; + } + + vector queueR, queueC; + vector> visited(row, vector(col, false)); + + for (int c = 0; c < col; c++) { + if (grid[0][c] == 0) { + queueR.push_back(0); + queueC.push_back(c); + visited[0][c] = true; + } + } + + int dr[4] = {1, -1, 0, 0}; + int dc[4] = {0, 0, 1, -1}; + int head = 0; + while (head < queueR.size()) { + int r = queueR[head]; + int c = queueC[head]; + head++; + if (r == row - 1) return true; + for (int k = 0; k < 4; k++) { + int nr = r + dr[k]; + int nc = c + dc[k]; + if (nr >= 0 && nr < row && nc >= 0 && nc < col && !visited[nr][nc] && grid[nr][nc] == 0) { + visited[nr][nc] = true; + queueR.push_back(nr); + queueC.push_back(nc); + } + } + } + return false; + } +}; diff --git a/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.cs b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.cs new file mode 100644 index 00000000..c079a0ce --- /dev/null +++ b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.cs @@ -0,0 +1,56 @@ +public class Solution { + public int LatestDayToCross(int row, int col, int[][] cells) { + int left = 1, right = cells.Length, answer = 0; + while (left <= right) { + int mid = (left + right) / 2; + if (CanCross(mid, row, col, cells)) { + answer = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + return answer; + } + + private bool CanCross(int day, int row, int col, int[][] cells) { + int[,] grid = new int[row, col]; + for (int i = 0; i < day; i++) { + int r = cells[i][0] - 1; + int c = cells[i][1] - 1; + grid[r, c] = 1; + } + + List queueR = new List(); + List queueC = new List(); + bool[,] visited = new bool[row, col]; + + for (int c = 0; c < col; c++) { + if (grid[0, c] == 0) { + queueR.Add(0); + queueC.Add(c); + visited[0, c] = true; + } + } + + int[] dr = {1, -1, 0, 0}; + int[] dc = {0, 0, 1, -1}; + int head = 0; + while (head < queueR.Count) { + int r = queueR[head]; + int c = queueC[head]; + head++; + if (r == row - 1) return true; + for (int k = 0; k < 4; k++) { + int nr = r + dr[k]; + int nc = c + dc[k]; + if (nr >= 0 && nr < row && nc >= 0 && nc < col && !visited[nr, nc] && grid[nr, nc] == 0) { + visited[nr, nc] = true; + queueR.Add(nr); + queueC.Add(nc); + } + } + } + return false; + } +} diff --git a/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.dart b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.dart new file mode 100644 index 00000000..1600d4f4 --- /dev/null +++ b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.dart @@ -0,0 +1,56 @@ +class Solution { + int latestDayToCross(int row, int col, List> cells) { + int left = 1, right = cells.length, answer = 0; + while (left <= right) { + int mid = (left + right) ~/ 2; + if (canCross(mid, row, col, cells)) { + answer = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + return answer; + } + + bool canCross(int day, int row, int col, List> cells) { + List> grid = List.generate(row, (_) => List.filled(col, 0)); + for (int i = 0; i < day; i++) { + int r = cells[i][0] - 1; + int c = cells[i][1] - 1; + grid[r][c] = 1; + } + + List queueR = []; + List queueC = []; + List> visited = List.generate(row, (_) => List.filled(col, false)); + + for (int c = 0; c < col; c++) { + if (grid[0][c] == 0) { + queueR.add(0); + queueC.add(c); + visited[0][c] = true; + } + } + + List dr = [1, -1, 0, 0]; + List dc = [0, 0, 1, -1]; + int head = 0; + while (head < queueR.length) { + int r = queueR[head]; + int c = queueC[head]; + head++; + if (r == row - 1) return true; + for (int k = 0; k < 4; k++) { + int nr = r + dr[k]; + int nc = c + dc[k]; + if (nr >= 0 && nr < row && nc >= 0 && nc < col && !visited[nr][nc] && grid[nr][nc] == 0) { + visited[nr][nc] = true; + queueR.add(nr); + queueC.add(nc); + } + } + } + return false; + } +} diff --git a/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.go b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.go new file mode 100644 index 00000000..ac0c20e3 --- /dev/null +++ b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.go @@ -0,0 +1,63 @@ +func latestDayToCross(row int, col int, cells [][]int) int { + left, right := 1, len(cells) + answer := 0 + for left <= right { + mid := (left + right) / 2 + if canCross(mid, row, col, cells) { + answer = mid + left = mid + 1 + } else { + right = mid - 1 + } + } + return answer +} + +func canCross(day int, row int, col int, cells [][]int) bool { + grid := make([][]int, row) + for i := range grid { + grid[i] = make([]int, col) + } + for i := 0; i < day; i++ { + r := cells[i][0] - 1 + c := cells[i][1] - 1 + grid[r][c] = 1 + } + + queueR := make([]int, 0, row*col) + queueC := make([]int, 0, row*col) + visited := make([][]bool, row) + for i := range visited { + visited[i] = make([]bool, col) + } + + for c := 0; c < col; c++ { + if grid[0][c] == 0 { + queueR = append(queueR, 0) + queueC = append(queueC, c) + visited[0][c] = true + } + } + + dr := []int{1, -1, 0, 0} + dc := []int{0, 0, 1, -1} + head := 0 + for head < len(queueR) { + r := queueR[head] + c := queueC[head] + head++ + if r == row-1 { + return true + } + for k := 0; k < 4; k++ { + nr := r + dr[k] + nc := c + dc[k] + if nr >= 0 && nr < row && nc >= 0 && nc < col && !visited[nr][nc] && grid[nr][nc] == 0 { + visited[nr][nc] = true + queueR = append(queueR, nr) + queueC = append(queueC, nc) + } + } + } + return false +} diff --git a/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.java b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.java new file mode 100644 index 00000000..c43f918b --- /dev/null +++ b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.java @@ -0,0 +1,59 @@ +class Solution { + public int latestDayToCross(int row, int col, int[][] cells) { + int left = 1, right = cells.length, answer = 0; + while (left <= right) { + int mid = (left + right) / 2; + if (canCross(mid, row, col, cells)) { + answer = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + return answer; + } + + private boolean canCross(int day, int row, int col, int[][] cells) { + int[][] grid = new int[row][col]; + for (int i = 0; i < day; i++) { + int r = cells[i][0] - 1; + int c = cells[i][1] - 1; + grid[r][c] = 1; + } + + int[] queueR = new int[row * col]; + int[] queueC = new int[row * col]; + int head = 0, tail = 0; + boolean[][] visited = new boolean[row][col]; + + for (int c = 0; c < col; c++) { + if (grid[0][c] == 0) { + queueR[tail] = 0; + queueC[tail] = c; + tail++; + visited[0][c] = true; + } + } + + int[] dr = {1, -1, 0, 0}; + int[] dc = {0, 0, 1, -1}; + + while (head < tail) { + int r = queueR[head]; + int c = queueC[head]; + head++; + if (r == row - 1) return true; + for (int k = 0; k < 4; k++) { + int nr = r + dr[k]; + int nc = c + dc[k]; + if (nr >= 0 && nr < row && nc >= 0 && nc < col && !visited[nr][nc] && grid[nr][nc] == 0) { + visited[nr][nc] = true; + queueR[tail] = nr; + queueC[tail] = nc; + tail++; + } + } + } + return false; + } +} diff --git a/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.kt b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.kt new file mode 100644 index 00000000..5c59f595 --- /dev/null +++ b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.kt @@ -0,0 +1,62 @@ +class Solution { + fun latestDayToCross(row: Int, col: Int, cells: Array): Int { + var left = 1 + var right = cells.size + var answer = 0 + while (left <= right) { + val mid = (left + right) / 2 + if (canCross(mid, row, col, cells)) { + answer = mid + left = mid + 1 + } else { + right = mid - 1 + } + } + return answer + } + + private fun canCross(day: Int, row: Int, col: Int, cells: Array): Boolean { + val grid = Array(row) { IntArray(col) } + for (i in 0 until day) { + val r = cells[i][0] - 1 + val c = cells[i][1] - 1 + grid[r][c] = 1 + } + + val queueR = IntArray(row * col) + val queueC = IntArray(row * col) + var head = 0 + var tail = 0 + val visited = Array(row) { BooleanArray(col) } + + for (c in 0 until col) { + if (grid[0][c] == 0) { + queueR[tail] = 0 + queueC[tail] = c + tail++ + visited[0][c] = true + } + } + + val dr = intArrayOf(1, -1, 0, 0) + val dc = intArrayOf(0, 0, 1, -1) + + while (head < tail) { + val r = queueR[head] + val c = queueC[head] + head++ + if (r == row - 1) return true + for (k in 0 until 4) { + val nr = r + dr[k] + val nc = c + dc[k] + if (nr >= 0 && nr < row && nc >= 0 && nc < col && !visited[nr][nc] && grid[nr][nc] == 0) { + visited[nr][nc] = true + queueR[tail] = nr + queueC[tail] = nc + tail++ + } + } + } + return false + } +} diff --git a/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.py b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.py new file mode 100644 index 00000000..9d8865e7 --- /dev/null +++ b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.py @@ -0,0 +1,52 @@ +class Solution: + def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int: + def canCross(day): + grid = [[0] * col for _ in range(row)] + + for i in range(day): + r, c = cells[i][0] - 1, cells[i][1] - 1 + grid[r][c] = 1 + + queue = deque() + visited = [[False] * col for _ in range(row)] + + for c in range(col): + if grid[0][c] == 0: + queue.append((0, c)) + visited[0][c] = True + + directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] + + while queue: + r, c = queue.popleft() + + if r == row - 1: + return True + + for dr, dc in directions: + nr, nc = r + dr, c + dc + + if ( + 0 <= nr < row + and 0 <= nc < col + and not visited[nr][nc] + and grid[nr][nc] == 0 + ): + visited[nr][nc] = True + queue.append((nr, nc)) + + return False + + left, right = 1, len(cells) + answer = 0 + + while left <= right: + mid = (left + right) // 2 + + if canCross(mid): + answer = mid + left = mid + 1 + else: + right = mid - 1 + + return answer diff --git a/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.py2 b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.py2 new file mode 100644 index 00000000..97d247ad --- /dev/null +++ b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.py2 @@ -0,0 +1,47 @@ +class Solution(object): + def latestDayToCross(self, row, col, cells): + """ + :type row: int + :type col: int + :type cells: List[List[int]] + :rtype: int + """ + def canCross(day): + grid = [[0] * col for _ in range(row)] + for i in range(day): + r, c = cells[i][0] - 1, cells[i][1] - 1 + grid[r][c] = 1 + + queue = [] + visited = [[False] * col for _ in range(row)] + head = 0 + + for c in range(col): + if grid[0][c] == 0: + queue.append((0, c)) + visited[0][c] = True + + directions = [(1,0), (-1,0), (0,1), (0,-1)] + + while head < len(queue): + r, c = queue[head] + head += 1 + if r == row - 1: + return True + for dr, dc in directions: + nr, nc = r + dr, c + dc + if 0 <= nr < row and 0 <= nc < col and not visited[nr][nc] and grid[nr][nc] == 0: + visited[nr][nc] = True + queue.append((nr, nc)) + return False + + left, right = 1, len(cells) + answer = 0 + while left <= right: + mid = (left + right) // 2 + if canCross(mid): + answer = mid + left = mid + 1 + else: + right = mid - 1 + return answer diff --git a/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.rb b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.rb new file mode 100644 index 00000000..2cddd9f8 --- /dev/null +++ b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.rb @@ -0,0 +1,54 @@ +# @param {Integer} row +# @param {Integer} col +# @param {Integer[][]} cells +# @return {Integer} +def latest_day_to_cross(row, col, cells) + can_cross = ->(day) { + grid = Array.new(row) { Array.new(col, 0) } + (0...day).each do |i| + r = cells[i][0] - 1 + c = cells[i][1] - 1 + grid[r][c] = 1 + end + + queue = [] + visited = Array.new(row) { Array.new(col, false) } + head = 0 + + (0...col).each do |c| + if grid[0][c] == 0 + queue << [0, c] + visited[0][c] = true + end + end + + directions = [[1,0], [-1,0], [0,1], [0,-1]] + + while head < queue.length + r, c = queue[head] + head += 1 + return true if r == row - 1 + directions.each do |dr, dc| + nr, nc = r + dr, c + dc + if nr >= 0 && nr < row && nc >= 0 && nc < col && !visited[nr][nc] && grid[nr][nc] == 0 + visited[nr][nc] = true + queue << [nr, nc] + end + end + end + false + } + + left, right = 1, cells.length + answer = 0 + while left <= right + mid = (left + right) / 2 + if can_cross.call(mid) + answer = mid + left = mid + 1 + else + right = mid - 1 + end + end + answer +end diff --git a/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.rs b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.rs new file mode 100644 index 00000000..0fa6aac0 --- /dev/null +++ b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.rs @@ -0,0 +1,64 @@ +impl Solution { + pub fn latest_day_to_cross(row: i32, col: i32, cells: Vec>) -> i32 { + let row = row as usize; + let col = col as usize; + let mut left = 1; + let mut right = cells.len() as i32; + let mut answer = 0; + while left <= right { + let mid = (left + right) / 2; + if Self::can_cross(mid as usize, row, col, &cells) { + answer = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + answer + } + + fn can_cross(day: usize, row: usize, col: usize, cells: &Vec>) -> bool { + let mut grid = vec![vec![0; col]; row]; + for i in 0..day { + let r = (cells[i][0] - 1) as usize; + let c = (cells[i][1] - 1) as usize; + grid[r][c] = 1; + } + + let mut queue_r = vec![0usize; row * col]; + let mut queue_c = vec![0usize; row * col]; + let mut visited = vec![vec![false; col]; row]; + let mut head = 0; + let mut tail = 0; + + for c in 0..col { + if grid[0][c] == 0 { + queue_r[tail] = 0; + queue_c[tail] = c; + tail += 1; + visited[0][c] = true; + } + } + + let dr = [1, -1, 0, 0]; + let dc = [0, 0, 1, -1]; + + while head < tail { + let r = queue_r[head]; + let c = queue_c[head]; + head += 1; + if r == row - 1 { return true; } + for k in 0..4 { + let nr = r as i32 + dr[k]; + let nc = c as i32 + dc[k]; + if nr >= 0 && nr < row as i32 && nc >= 0 && nc < col as i32 && !visited[nr as usize][nc as usize] && grid[nr as usize][nc as usize] == 0 { + visited[nr as usize][nc as usize] = true; + queue_r[tail] = nr as usize; + queue_c[tail] = nc as usize; + tail += 1; + } + } + } + false + } +} diff --git a/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.swift b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.swift new file mode 100644 index 00000000..03799892 --- /dev/null +++ b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.swift @@ -0,0 +1,56 @@ +class Solution { + func latestDayToCross(_ row: Int, _ col: Int, _ cells: [[Int]]) -> Int { + var left = 1, right = cells.count, answer = 0 + while left <= right { + let mid = (left + right) / 2 + if canCross(mid, row, col, cells) { + answer = mid + left = mid + 1 + } else { + right = mid - 1 + } + } + return answer + } + + func canCross(_ day: Int, _ row: Int, _ col: Int, _ cells: [[Int]]) -> Bool { + var grid = [[Int]](repeating: [Int](repeating: 0, count: col), count: row) + for i in 0..= 0 && nr < row && nc >= 0 && nc < col && !visited[nr][nc] && grid[nr][nc] == 0 { + visited[nr][nc] = true + queueR.append(nr) + queueC.append(nc) + } + } + } + return false + } +} diff --git a/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.ts b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.ts new file mode 100644 index 00000000..cbb1fb21 --- /dev/null +++ b/tests/1501-2000/1970. last-day-where-you-can-still-cross/sol.ts @@ -0,0 +1,72 @@ +function latestDayToCross(row: number, col: number, cells: number[][]): number { + let left = 1, + right = cells.length, + answer = 0; + while (left <= right) { + const mid = Math.floor((left + right) / 2); + if (canCross(mid, row, col, cells)) { + answer = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + return answer; +} + +function canCross( + day: number, + row: number, + col: number, + cells: number[][], +): boolean { + const grid: number[][] = Array.from({ length: row }, () => + Array(col).fill(0), + ); + for (let i = 0; i < day; i++) { + const r = cells[i][0] - 1; + const c = cells[i][1] - 1; + grid[r][c] = 1; + } + + const queueR: number[] = []; + const queueC: number[] = []; + const visited: boolean[][] = Array.from({ length: row }, () => + Array(col).fill(false), + ); + + for (let c = 0; c < col; c++) { + if (grid[0][c] === 0) { + queueR.push(0); + queueC.push(c); + visited[0][c] = true; + } + } + + const dr = [1, -1, 0, 0]; + const dc = [0, 0, 1, -1]; + let head = 0; + while (head < queueR.length) { + const r = queueR[head]; + const c = queueC[head]; + head++; + if (r === row - 1) return true; + for (let k = 0; k < 4; k++) { + const nr = r + dr[k]; + const nc = c + dc[k]; + if ( + nr >= 0 && + nr < row && + nc >= 0 && + nc < col && + !visited[nr][nc] && + grid[nr][nc] === 0 + ) { + visited[nr][nc] = true; + queueR.push(nr); + queueC.push(nc); + } + } + } + return false; +} diff --git a/tests/1501-2000/1971. find-if-path-exists-in-graph/manifest.yaml b/tests/1501-2000/1971. find-if-path-exists-in-graph/manifest.yaml new file mode 100644 index 00000000..e7f73943 --- /dev/null +++ b/tests/1501-2000/1971. find-if-path-exists-in-graph/manifest.yaml @@ -0,0 +1,613 @@ +entry: + id: 1971 + title: find-if-path-exists-in-graph + params: + n: + type: int + edges: + type: array + items: + type: array + items: + type: int + source: + type: int + destination: + type: int + call: + cpp: "Solution().validPath({n}, {edges}, {source}, {destination})" + rust: "Solution::valid_path({n}, {edges}, {source}, {destination})" + python3: "Solution().validPath({n}, {edges}, {source}, {destination})" + python2: "Solution().validPath({n}, {edges}, {source}, {destination})" + ruby: "valid_path({n}, {edges}, {source}, {destination})" + java: "new Solution().validPath({n}, {edges}, {source}, {destination})" + csharp: "new Solution().ValidPath({n}, {edges}, {source}, {destination})" + kotlin: "Solution().validPath({n}, {edges}, {source}, {destination})" + go: "validPath({n}, {edges}, {source}, {destination})" + dart: "Solution().validPath({n}, {edges}, {source}, {destination})" + swift: "Solution().validPath({n}, {edges}, {source}, {destination})" + typescript: "validPath({n}, {edges}, {source}, {destination})" + +judge: + type: exact + +limits: + time_ms: 2000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().validPath(n, edges, source, destination, {result})" + checker: | + from collections import deque + + class Checker: + def validPath(self, n, edges, source, destination, result): + if not isinstance(result, bool): + return False + graph = [[] for _ in range(n)] + for edge in edges: + if not isinstance(edge, list) or len(edge) != 2: + return False + u, v = edge + if not (0 <= u < n and 0 <= v < n and u != v): + return False + graph[u].append(v) + graph[v].append(u) + seen = {source} + queue = deque([source]) + while queue: + node = queue.popleft() + if node == destination: + return result is True + for neighbor in graph[node]: + if neighbor not in seen: + seen.add(neighbor) + queue.append(neighbor) + return result is False + +seed: 1971 + +tests: + - name: triangle-connected + in: + n: 3 + edges: + - [0, 1] + - [1, 2] + - [2, 0] + source: 0 + destination: 2 + out: true + - name: disconnected-components + in: + n: 6 + edges: + - [0, 1] + - [0, 2] + - [3, 5] + - [5, 4] + - [4, 3] + source: 0 + destination: 5 + out: false + - name: single-vertex-self-query + in: + n: 1 + edges: [] + source: 0 + destination: 0 + out: true + - name: isolated-different-vertices + in: + n: 2 + edges: [] + source: 0 + destination: 1 + out: false + - name: direct-edge + in: + n: 4 + edges: + - [1, 3] + source: 3 + destination: 1 + out: true + - name: reversed-multi-hop + in: + n: 5 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + source: 3 + destination: 0 + out: true + - name: long-chain + in: + n: 10 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + source: 0 + destination: 9 + out: true + - name: chain-separated + in: + n: 10 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [4, 5] + - [5, 6] + - [6, 7] + source: 0 + destination: 7 + out: false + - name: cycle-with-tail + in: + n: 8 + edges: + - [0, 1] + - [1, 2] + - [2, 0] + - [2, 3] + - [3, 4] + - [4, 5] + source: 5 + destination: 1 + out: true + - name: cycle-isolated + in: + n: 8 + edges: + - [0, 1] + - [1, 2] + - [2, 0] + - [4, 5] + - [5, 6] + - [6, 4] + source: 0 + destination: 7 + out: false + - name: hub-connected + in: + n: 7 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + - [0, 5] + source: 4 + destination: 5 + out: true + - name: hub-missing-target + in: + n: 7 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [0, 4] + source: 4 + destination: 6 + out: false + - name: multiple-components-middle + in: + n: 9 + edges: + - [0, 1] + - [1, 2] + - [3, 4] + - [4, 5] + - [6, 7] + source: 3 + destination: 5 + out: true + - name: multiple-components-cross-query + in: + n: 9 + edges: + - [0, 1] + - [1, 2] + - [3, 4] + - [4, 5] + - [6, 7] + source: 2 + destination: 7 + out: false + - name: dense-six + in: + n: 6 + edges: + - [0, 1] + - [0, 2] + - [0, 3] + - [1, 2] + - [1, 4] + - [2, 3] + - [2, 5] + - [3, 4] + - [4, 5] + source: 5 + destination: 0 + out: true + - name: sparse-late-connection + in: + n: 12 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [7, 8] + - [8, 9] + - [3, 7] + source: 0 + destination: 9 + out: true + - name: sparse-no-connection + in: + n: 12 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [7, 8] + - [8, 9] + source: 0 + destination: 9 + out: false + - name: source-in-large-component + in: + n: 15 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [10, 11] + - [11, 12] + source: 9 + destination: 12 + out: false + - name: endpoint-in-large-component + in: + n: 15 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [10, 11] + - [11, 12] + source: 0 + destination: 9 + out: true + - name: two-vertex-cycle-not-allowed + in: + n: 3 + edges: + - [0, 1] + source: 0 + destination: 1 + out: true + - name: isolated-source + in: + n: 8 + edges: + - [1, 2] + - [2, 3] + - [4, 5] + - [5, 6] + source: 0 + destination: 6 + out: false + - name: isolated-destination + in: + n: 8 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [4, 5] + source: 0 + destination: 7 + out: false + - name: query-same-in-cycle + in: + n: 5 + edges: + - [0, 1] + - [1, 2] + - [2, 0] + source: 2 + destination: 2 + out: true + - name: query-same-isolated + in: + n: 5 + edges: + - [0, 1] + source: 4 + destination: 4 + out: true + - name: alternating-components + in: + n: 14 + edges: + - [0, 2] + - [2, 4] + - [4, 6] + - [1, 3] + - [3, 5] + - [5, 7] + - [8, 10] + - [10, 12] + - [9, 11] + source: 0 + destination: 6 + out: true + - name: alternating-components-disconnected + in: + n: 14 + edges: + - [0, 2] + - [2, 4] + - [4, 6] + - [1, 3] + - [3, 5] + - [5, 7] + - [8, 10] + - [10, 12] + - [9, 11] + source: 0 + destination: 7 + out: false + - name: bridge-between-cycles + in: + n: 10 + edges: + - [0, 1] + - [1, 2] + - [2, 0] + - [3, 4] + - [4, 5] + - [5, 3] + - [2, 3] + source: 1 + destination: 5 + out: true + - name: bridge-absent-between-cycles + in: + n: 10 + edges: + - [0, 1] + - [1, 2] + - [2, 0] + - [3, 4] + - [4, 5] + - [5, 3] + source: 1 + destination: 5 + out: false + - name: tree-branch + in: + n: 11 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [5, 7] + - [5, 8] + - [6, 9] + - [6, 10] + source: 3 + destination: 10 + out: true + - name: tree-branch-missing + in: + n: 11 + edges: + - [0, 1] + - [0, 2] + - [1, 3] + - [1, 4] + - [2, 5] + - [2, 6] + - [5, 7] + - [5, 8] + source: 3 + destination: 10 + out: false + - name: high-label-edge + in: + n: 100 + edges: + - [98, 99] + - [50, 98] + source: 50 + destination: 99 + out: true + - name: high-label-isolated + in: + n: 100 + edges: + - [0, 1] + - [1, 2] + - [98, 99] + source: 0 + destination: 99 + out: false + - name: large-chain-endpoints + in: + n: 50 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + - [11, 12] + - [12, 13] + - [13, 14] + - [14, 15] + - [15, 16] + - [16, 17] + - [17, 18] + - [18, 19] + - [19, 20] + - [20, 21] + - [21, 22] + - [22, 23] + - [23, 24] + - [24, 25] + - [25, 26] + - [26, 27] + - [27, 28] + - [28, 29] + - [29, 30] + - [30, 31] + - [31, 32] + - [32, 33] + - [33, 34] + - [34, 35] + - [35, 36] + - [36, 37] + - [37, 38] + - [38, 39] + - [39, 40] + - [40, 41] + - [41, 42] + - [42, 43] + - [43, 44] + - [44, 45] + - [45, 46] + - [46, 47] + - [47, 48] + - [48, 49] + source: 0 + destination: 49 + out: true + - name: large-chain-off-component + in: + n: 50 + edges: + - [0, 1] + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + - [8, 9] + - [10, 11] + - [11, 12] + - [12, 13] + - [13, 14] + - [14, 15] + - [15, 16] + - [16, 17] + - [17, 18] + - [18, 19] + - [19, 20] + - [20, 21] + - [21, 22] + - [22, 23] + - [23, 24] + - [24, 25] + - [25, 26] + - [26, 27] + - [27, 28] + - [28, 29] + - [29, 30] + - [30, 31] + - [31, 32] + - [32, 33] + - [33, 34] + - [34, 35] + - [35, 36] + - [36, 37] + - [37, 38] + - [38, 39] + - [39, 40] + - [40, 41] + - [41, 42] + - [42, 43] + - [43, 44] + - [44, 45] + - [45, 46] + - [46, 47] + - [47, 48] + - [48, 49] + source: 0 + destination: 49 + out: false + - name: dense-two-components + in: + n: 12 + edges: + - [0, 1] + - [0, 2] + - [1, 2] + - [1, 3] + - [2, 3] + - [3, 4] + - [4, 5] + - [6, 7] + - [6, 8] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + source: 0 + destination: 11 + out: false + - name: dense-two-components-connected-query + in: + n: 12 + edges: + - [0, 1] + - [0, 2] + - [1, 2] + - [1, 3] + - [2, 3] + - [3, 4] + - [4, 5] + - [6, 7] + - [6, 8] + - [7, 8] + - [8, 9] + - [9, 10] + - [10, 11] + source: 0 + destination: 5 + out: true diff --git a/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.cpp b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.cpp new file mode 100644 index 00000000..ae549e01 --- /dev/null +++ b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + bool validPath(int n, vector>& edges, int source, int destination) { + if (source == destination) return true; + unordered_map> graph; + for (auto& edge : edges) { + graph[edge[0]].push_back(edge[1]); + graph[edge[1]].push_back(edge[0]); + } + queue q; + unordered_set visited; + q.push(source); + visited.insert(source); + while (!q.empty()) { + int node = q.front(); + q.pop(); + if (node == destination) return true; + for (int neighbor : graph[node]) { + if (visited.find(neighbor) == visited.end()) { + visited.insert(neighbor); + q.push(neighbor); + } + } + } + return false; + } +}; diff --git a/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.cs b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.cs new file mode 100644 index 00000000..b611c8d9 --- /dev/null +++ b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.cs @@ -0,0 +1,28 @@ +public class Solution { + public bool ValidPath(int n, int[][] edges, int source, int destination) { + if (source == destination) return true; + var graph = new Dictionary>(); + foreach (var edge in edges) { + if (!graph.ContainsKey(edge[0])) graph[edge[0]] = new List(); + if (!graph.ContainsKey(edge[1])) graph[edge[1]] = new List(); + graph[edge[0]].Add(edge[1]); + graph[edge[1]].Add(edge[0]); + } + var queue = new Queue(); + var visited = new HashSet(); + queue.Enqueue(source); + visited.Add(source); + while (queue.Count > 0) { + int node = queue.Dequeue(); + if (node == destination) return true; + if (graph.ContainsKey(node)) { + foreach (int neighbor in graph[node]) { + if (visited.Add(neighbor)) { + queue.Enqueue(neighbor); + } + } + } + } + return false; + } +} diff --git a/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.dart b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.dart new file mode 100644 index 00000000..88def72f --- /dev/null +++ b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.dart @@ -0,0 +1,25 @@ +class Solution { + bool validPath(int n, List> edges, int source, int destination) { + if (source == destination) return true; + Map> graph = {}; + for (var edge in edges) { + graph.putIfAbsent(edge[0], () => []).add(edge[1]); + graph.putIfAbsent(edge[1], () => []).add(edge[0]); + } + Queue queue = Queue(); + Set visited = {}; + queue.add(source); + visited.add(source); + while (queue.isNotEmpty) { + int node = queue.removeFirst(); + if (node == destination) return true; + for (int neighbor in graph[node] ?? []) { + if (!visited.contains(neighbor)) { + visited.add(neighbor); + queue.add(neighbor); + } + } + } + return false; + } +} diff --git a/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.go b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.go new file mode 100644 index 00000000..490cfe59 --- /dev/null +++ b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.go @@ -0,0 +1,27 @@ +func validPath(n int, edges [][]int, source int, destination int) bool { + if source == destination { + return true + } + graph := make(map[int][]int) + for _, edge := range edges { + graph[edge[0]] = append(graph[edge[0]], edge[1]) + graph[edge[1]] = append(graph[edge[1]], edge[0]) + } + queue := []int{source} + visited := make(map[int]bool) + visited[source] = true + for len(queue) > 0 { + node := queue[0] + queue = queue[1:] + if node == destination { + return true + } + for _, neighbor := range graph[node] { + if !visited[neighbor] { + visited[neighbor] = true + queue = append(queue, neighbor) + } + } + } + return false +} diff --git a/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.java b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.java new file mode 100644 index 00000000..b45d4b45 --- /dev/null +++ b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.java @@ -0,0 +1,25 @@ +class Solution { + public boolean validPath(int n, int[][] edges, int source, int destination) { + if (source == destination) return true; + Map> graph = new HashMap<>(); + for (int[] edge : edges) { + graph.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(edge[1]); + graph.computeIfAbsent(edge[1], k -> new ArrayList<>()).add(edge[0]); + } + Queue queue = new LinkedList<>(); + Set visited = new HashSet<>(); + queue.offer(source); + visited.add(source); + while (!queue.isEmpty()) { + int node = queue.poll(); + if (node == destination) return true; + for (int neighbor : graph.getOrDefault(node, Collections.emptyList())) { + if (!visited.contains(neighbor)) { + visited.add(neighbor); + queue.offer(neighbor); + } + } + } + return false; + } +} diff --git a/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.kt b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.kt new file mode 100644 index 00000000..b3f9d884 --- /dev/null +++ b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.kt @@ -0,0 +1,24 @@ +class Solution { + fun validPath(n: Int, edges: Array, source: Int, destination: Int): Boolean { + if (source == destination) return true + val graph = HashMap>() + for (edge in edges) { + graph.getOrPut(edge[0]) { mutableListOf() }.add(edge[1]) + graph.getOrPut(edge[1]) { mutableListOf() }.add(edge[0]) + } + val queue = ArrayDeque() + val visited = HashSet() + queue.add(source) + visited.add(source) + while (queue.isNotEmpty()) { + val node = queue.removeFirst() + if (node == destination) return true + for (neighbor in graph[node] ?: emptyList()) { + if (visited.add(neighbor)) { + queue.add(neighbor) + } + } + } + return false + } +} diff --git a/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.py b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.py new file mode 100644 index 00000000..a7a1b0e0 --- /dev/null +++ b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.py @@ -0,0 +1,59 @@ +from collections import deque +from typing import List + + +class Graph: + def __init__(self, directed=False): + self.adj_list = {} + self.directed = directed + + def add_node(self, node): + if node not in self.adj_list: + self.adj_list[node] = set() + + def add_edge(self, node1, node2): + self.add_node(node1) + self.add_node(node2) + self.adj_list[node1].add(node2) + if not self.directed: + self.adj_list[node2].add(node1) + + def DFS(self, current_node, target_node, visited=None) -> bool: + if visited is None: + visited = set() + if current_node == target_node: + return True + if current_node in visited: + return False + visited.add(current_node) + for neighbor in self.adj_list.get(current_node, []): + if self.DFS(neighbor, target_node, visited): + return True + return False + + def BFS(self, current_node, target_node): + if current_node == target_node: + return True + queue = deque([current_node]) + visited = {current_node} + while queue: + current = queue.popleft() + for neighbor in self.adj_list.get(current, []): + if neighbor == target_node: + return True + if neighbor not in visited: + visited.add(neighbor) + queue.append(neighbor) + return False + + +class Solution: + def validPath( + self, n: int, edges: List[List[int]], source: int, destination: int + ) -> bool: + if source == destination: + return True + graph1 = Graph() + for i in edges: + graph1.add_edge(i[0], i[1]) + return graph1.BFS(current_node=source, target_node=destination) diff --git a/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.py2 b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.py2 new file mode 100644 index 00000000..323f0872 --- /dev/null +++ b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.py2 @@ -0,0 +1,31 @@ +class Solution(object): + def validPath(self, n, edges, source, destination): + """ + :type n: int + :type edges: List[List[int]] + :type source: int + :type destination: int + :rtype: bool + """ + if source == destination: + return True + graph = {} + for u, v in edges: + if u not in graph: + graph[u] = [] + if v not in graph: + graph[v] = [] + graph[u].append(v) + graph[v].append(u) + from collections import deque + queue = deque([source]) + visited = {source} + while queue: + node = queue.popleft() + if node == destination: + return True + for neighbor in graph.get(node, []): + if neighbor not in visited: + visited.add(neighbor) + queue.append(neighbor) + return False diff --git a/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.rb b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.rb new file mode 100644 index 00000000..7b1f3182 --- /dev/null +++ b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.rb @@ -0,0 +1,26 @@ +# @param {Integer} n +# @param {Integer[][]} edges +# @param {Integer} source +# @param {Integer} destination +# @return {Boolean} +def valid_path(n, edges, source, destination) + return true if source == destination + graph = Hash.new { |h, k| h[k] = [] } + edges.each do |u, v| + graph[u] << v + graph[v] << u + end + queue = [source] + visited = {source => true} + until queue.empty? + node = queue.shift + return true if node == destination + graph[node].each do |neighbor| + unless visited[neighbor] + visited[neighbor] = true + queue << neighbor + end + end + end + false +end diff --git a/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.rs b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.rs new file mode 100644 index 00000000..e26d50e2 --- /dev/null +++ b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.rs @@ -0,0 +1,25 @@ +impl Solution { + pub fn valid_path(n: i32, edges: Vec>, source: i32, destination: i32) -> bool { + if source == destination { return true; } + let mut graph: std::collections::HashMap> = std::collections::HashMap::new(); + for edge in edges { + graph.entry(edge[0]).or_insert(vec![]).push(edge[1]); + graph.entry(edge[1]).or_insert(vec![]).push(edge[0]); + } + let mut queue = std::collections::VecDeque::new(); + let mut visited = std::collections::HashSet::new(); + queue.push_back(source); + visited.insert(source); + while let Some(node) = queue.pop_front() { + if node == destination { return true; } + if let Some(neighbors) = graph.get(&node) { + for &neighbor in neighbors { + if visited.insert(neighbor) { + queue.push_back(neighbor); + } + } + } + } + false + } +} diff --git a/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.swift b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.swift new file mode 100644 index 00000000..a887ee50 --- /dev/null +++ b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.swift @@ -0,0 +1,23 @@ +class Solution { + func validPath(_ n: Int, _ edges: [[Int]], _ source: Int, _ destination: Int) -> Bool { + if source == destination { return true } + var graph = [Int: [Int]]() + for edge in edges { + graph[edge[0], default: []].append(edge[1]) + graph[edge[1], default: []].append(edge[0]) + } + var queue = [source] + var visited = Set([source]) + while !queue.isEmpty { + let node = queue.removeFirst() + if node == destination { return true } + for neighbor in graph[node] ?? [] { + if !visited.contains(neighbor) { + visited.insert(neighbor) + queue.append(neighbor) + } + } + } + return false + } +} diff --git a/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.ts b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.ts new file mode 100644 index 00000000..729b33fd --- /dev/null +++ b/tests/1501-2000/1971. find-if-path-exists-in-graph/sol.ts @@ -0,0 +1,28 @@ +function validPath( + n: number, + edges: number[][], + source: number, + destination: number, +): boolean { + if (source === destination) return true; + const graph: Map = new Map(); + for (const [u, v] of edges) { + if (!graph.has(u)) graph.set(u, []); + if (!graph.has(v)) graph.set(v, []); + graph.get(u)!.push(v); + graph.get(v)!.push(u); + } + const queue: number[] = [source]; + const visited = new Set([source]); + while (queue.length > 0) { + const node = queue.shift()!; + if (node === destination) return true; + for (const neighbor of graph.get(node) || []) { + if (!visited.has(neighbor)) { + visited.add(neighbor); + queue.push(neighbor); + } + } + } + return false; +} diff --git a/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/manifest.yaml b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/manifest.yaml new file mode 100644 index 00000000..8c5d3c07 --- /dev/null +++ b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/manifest.yaml @@ -0,0 +1,226 @@ +entry: + id: 1974 + title: "minimum-time-to-type-word-using-special-typewriter" + params: + word: + type: string + call: + cpp: "Solution().minTimeToType({word})" + rust: "Solution::min_time_to_type({word})" + python3: "Solution().minTimeToType({word})" + python2: "Solution().minTimeToType({word})" + ruby: "min_time_to_type({word})" + java: "new Solution().minTimeToType({word})" + csharp: "new Solution().MinTimeToType({word})" + kotlin: "Solution().minTimeToType({word})" + go: "minTimeToType({word})" + dart: "Solution().minTimeToType({word})" + swift: "Solution().minTimeToType({word})" + typescript: "minTimeToType({word})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().minTimeToType(word, {result})" + checker: | + class Checker: + def minTimeToType(self, word, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not isinstance(word, str) or not (1 <= len(word) <= 100): + return False + if any(ch < 'a' or ch > 'z' for ch in word): + return False + total = 0 + current = 0 + for ch in word: + target = ord(ch) - ord('a') + distance = abs(target - current) + total += min(distance, 26 - distance) + 1 + current = target + return result == total + +seed: 1974 + +tests: + - name: "example_abc" + in: + word: "abc" + out: 5 + - name: "example_bza" + in: + word: "bza" + out: 7 + - name: "example_zjpc" + in: + word: "zjpc" + out: 34 + - name: "single_a" + in: + word: "a" + out: 1 + - name: "single_z" + in: + word: "z" + out: 2 + - name: "single_m" + in: + word: "m" + out: 13 + - name: "same_letter" + in: + word: "aaaaaa" + out: 6 + - name: "repeated_z" + in: + word: "zzzzz" + out: 6 + - name: "forward_alphabet" + in: + word: "abcdefghijklmnopqrstuvwxyz" + out: 51 + - name: "reverse_alphabet" + in: + word: "zyxwvutsrqponmlkjihgfedcba" + out: 52 + - name: "all_wraps" + in: + word: "azazazaz" + out: 15 + - name: "alternating_edges" + in: + word: "azbzcydxewfv" + out: 69 + - name: "half_circle" + in: + word: "anananan" + out: 99 + - name: "opposite_jumps" + in: + word: "ananan" + out: 71 + - name: "nearby_backtrack" + in: + word: "abcdefedcba" + out: 21 + - name: "large_forward_20" + in: + word: "abcdefghijklmnopqrst" + out: 39 + - name: "large_backward_20" + in: + word: "tsrqponmlkjihgfedcba" + out: 46 + - name: "wrap_to_a" + in: + word: "yzabc" + out: 11 + - name: "wrap_from_a" + in: + word: "azbycxdwev" + out: 55 + - name: "alternating_far" + in: + word: "amzamzamz" + out: 86 + - name: "central_letters" + in: + word: "mnlk" + out: 20 + - name: "all_vowels" + in: + word: "aeiou" + out: 25 + - name: "mixed_short" + in: + word: "leetcode" + out: 70 + - name: "mixed_long" + in: + word: "typewriter" + out: 99 + - name: "palindrome" + in: + word: "abccba" + out: 10 + - name: "zigzag" + in: + word: "azbycxdwev" + out: 55 + - name: "two_cycles" + in: + word: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" + out: 103 + - name: "max_length_same" + in: + word: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + out: 100 + - name: "max_length_wrap" + in: + word: "azazazazazazazazazazazazazazazazazazazazazazazazazazazazazazazazazazazazazazazazazazazazazazazazazaz" + out: 199 + - name: "repeated_pattern" + in: + word: "qwertyqwerty" + out: 98 + - name: "boundary_pair" + in: + word: "mz" + out: 27 + - name: "boundary_pair_reverse" + in: + word: "zm" + out: 16 + - name: "generated_short" + seed: 197401 + in: + word: + gen: "str" + len: + gen: "int" + min: 1 + max: 10 + alphabet: "abmnz" + - name: "generated_medium" + seed: 197402 + in: + word: + gen: "str" + len: + gen: "int" + min: 20 + max: 40 + alphabet: "acfjnrvz" + - name: "generated_full_alphabet" + seed: 197403 + in: + word: + gen: "str" + len: + gen: "int" + min: 80 + max: 100 + alphabet: "abcdefghijklmnopqrstuvwxyz" + - name: "generated_edge_letters" + seed: 197404 + in: + word: + gen: "str" + len: + gen: "int" + min: 50 + max: 100 + alphabet: "az" + - name: "generated_stress" + seed: 197405 + in: + word: + gen: "str" + len: 100 + alphabet: "abdgkoswz" diff --git a/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.cpp b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.cpp new file mode 100644 index 00000000..2140b44f --- /dev/null +++ b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int minTimeToType(string word) { + int answer = 0; + char pointer = 'a'; + + for (char c : word) { + int clockwise = abs(c - pointer); + int counterclockwise = 26 - clockwise; + answer += min(clockwise, counterclockwise) + 1; + pointer = c; + } + + return answer; + } +}; diff --git a/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.cs b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.cs new file mode 100644 index 00000000..957e9464 --- /dev/null +++ b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int MinTimeToType(string word) { + int answer = 0; + char pointer = 'a'; + + foreach (char c in word) { + int clockwise = Math.Abs(c - pointer); + int counterclockwise = 26 - clockwise; + answer += Math.Min(clockwise, counterclockwise) + 1; + pointer = c; + } + + return answer; + } +} diff --git a/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.dart b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.dart new file mode 100644 index 00000000..1045da2f --- /dev/null +++ b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.dart @@ -0,0 +1,16 @@ +class Solution { + int minTimeToType(String word) { + int answer = 0; + int pointer = 'a'.codeUnitAt(0); + + for (int i = 0; i < word.length; i++) { + int current = word.codeUnitAt(i); + int clockwise = (current - pointer).abs(); + int counterclockwise = 26 - clockwise; + answer += (clockwise < counterclockwise ? clockwise : counterclockwise) + 1; + pointer = current; + } + + return answer; + } +} diff --git a/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.go b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.go new file mode 100644 index 00000000..2d472d61 --- /dev/null +++ b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.go @@ -0,0 +1,20 @@ +func minTimeToType(word string) int { + answer := 0 + pointer := byte('a') + + for i := 0; i < len(word); i++ { + clockwise := int(word[i]) - int(pointer) + if clockwise < 0 { + clockwise = -clockwise + } + counterclockwise := 26 - clockwise + if clockwise < counterclockwise { + answer += clockwise + 1 + } else { + answer += counterclockwise + 1 + } + pointer = word[i] + } + + return answer +} diff --git a/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.java b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.java new file mode 100644 index 00000000..348b5f12 --- /dev/null +++ b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.java @@ -0,0 +1,15 @@ +class Solution { + public int minTimeToType(String word) { + int answer = 0; + char pointer = 'a'; + + for (char c : word.toCharArray()) { + int clockwise = Math.abs(c - pointer); + int counterclockwise = 26 - clockwise; + answer += Math.min(clockwise, counterclockwise) + 1; + pointer = c; + } + + return answer; + } +} diff --git a/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.kt b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.kt new file mode 100644 index 00000000..298922f7 --- /dev/null +++ b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun minTimeToType(word: String): Int { + var answer = 0 + var pointer = 'a' + + for (char in word) { + val clockwise = Math.abs(char - pointer) + val counterclockwise = 26 - clockwise + answer += minOf(clockwise, counterclockwise) + 1 + pointer = char + } + + return answer + } +} diff --git a/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.py b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.py new file mode 100644 index 00000000..5228b7c8 --- /dev/null +++ b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.py @@ -0,0 +1,12 @@ +class Solution: + def minTimeToType(self, word: str) -> int: + answer = 0 + pointer = "a" + + for char in word: + clockwise = abs(ord(char) - ord(pointer)) + counterclockwise = 26 - clockwise + answer += min(clockwise, counterclockwise) + 1 + pointer = char + + return answer diff --git a/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.py2 b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.py2 new file mode 100644 index 00000000..6abb8d92 --- /dev/null +++ b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def minTimeToType(self, word): + """ + :type word: str + :rtype: int + """ + answer = 0 + pointer = 'a' + + for char in word: + clockwise = abs(ord(char) - ord(pointer)) + counterclockwise = 26 - clockwise + answer += min(clockwise, counterclockwise) + 1 + pointer = char + + return answer diff --git a/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.rb b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.rb new file mode 100644 index 00000000..979fdbb8 --- /dev/null +++ b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.rb @@ -0,0 +1,15 @@ +# @param {String} word +# @return {Integer} +def min_time_to_type(word) + answer = 0 + pointer = 'a' + + word.each_char do |char| + clockwise = (char.ord - pointer.ord).abs + counterclockwise = 26 - clockwise + answer += [clockwise, counterclockwise].min + 1 + pointer = char + end + + answer +end diff --git a/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.rs b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.rs new file mode 100644 index 00000000..bc243e0d --- /dev/null +++ b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn min_time_to_type(word: String) -> i32 { + let mut answer = 0; + let mut pointer = 'a' as u8; + + for c in word.bytes() { + let clockwise = (c as i32 - pointer as i32).abs(); + let counterclockwise = 26 - clockwise; + answer += clockwise.min(counterclockwise) + 1; + pointer = c; + } + + answer + } +} diff --git a/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.swift b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.swift new file mode 100644 index 00000000..d3a1ffc2 --- /dev/null +++ b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func minTimeToType(_ word: String) -> Int { + var answer = 0 + var pointer = Character("a") + + for char in word { + let clockwise = abs(Int(char.asciiValue!) - Int(pointer.asciiValue!)) + let counterclockwise = 26 - clockwise + answer += min(clockwise, counterclockwise) + 1 + pointer = char + } + + return answer + } +} diff --git a/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.ts b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.ts new file mode 100644 index 00000000..5835b615 --- /dev/null +++ b/tests/1501-2000/1974. minimum-time-to-type-word-using-special-typewriter/sol.ts @@ -0,0 +1,14 @@ +function minTimeToType(word: string): number { + let answer = 0; + let pointer = "a".charCodeAt(0); + + for (let i = 0; i < word.length; i++) { + let current = word.charCodeAt(i); + let clockwise = Math.abs(current - pointer); + let counterclockwise = 26 - clockwise; + answer += Math.min(clockwise, counterclockwise) + 1; + pointer = current; + } + + return answer; +} diff --git a/tests/1501-2000/1975. maximum-matrix-sum/manifest.yaml b/tests/1501-2000/1975. maximum-matrix-sum/manifest.yaml new file mode 100644 index 00000000..5d18d5fe --- /dev/null +++ b/tests/1501-2000/1975. maximum-matrix-sum/manifest.yaml @@ -0,0 +1,397 @@ +entry: + id: 1975 + title: "maximum-matrix-sum" + params: + matrix: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().maxMatrixSum({matrix})" + rust: "Solution::max_matrix_sum({matrix})" + python3: "Solution().maxMatrixSum({matrix})" + python2: "Solution().maxMatrixSum({matrix})" + ruby: "max_matrix_sum({matrix})" + java: "new Solution().maxMatrixSum({matrix})" + csharp: "new Solution().MaxMatrixSum({matrix})" + kotlin: "Solution().maxMatrixSum({matrix})" + go: "maxMatrixSum({matrix})" + dart: "Solution().maxMatrixSum({matrix})" + swift: "Solution().maxMatrixSum({matrix})" + typescript: "maxMatrixSum({matrix})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().maxMatrixSum(matrix, {result})" + checker: | + class Checker: + def maxMatrixSum(self, matrix, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not isinstance(matrix, list) or not matrix: + return False + n = len(matrix) + if any(not isinstance(row, list) or len(row) != n for row in matrix): + return False + values = [v for row in matrix for v in row] + if any(not isinstance(v, int) or isinstance(v, bool) for v in values): + return False + expected = sum(abs(v) for v in values) + if sum(v < 0 for v in values) % 2: + expected -= 2 * min(abs(v) for v in values) + return result == expected + +seed: 1975 + +tests: + - name: "example_one" + in: + matrix: + elemType: "int" + value: + - [1, -1] + - [-1, 1] + out: 4 + - name: "example_two" + in: + matrix: + elemType: "int" + value: + - [1, 2, 3] + - [-1, -2, -3] + - [1, 2, 3] + out: 16 + - name: "all_positive_two" + in: + matrix: + elemType: "int" + value: + - [1, 2] + - [3, 4] + out: 10 + - name: "one_negative_even_cells" + in: + matrix: + elemType: "int" + value: + - [-1, 2] + - [3, 4] + out: 8 + - name: "one_negative_odd_cells" + in: + matrix: + elemType: "int" + value: + - [-9, 2] + - [3, 4] + out: 14 + - name: "all_negative_four" + in: + matrix: + elemType: "int" + value: + - [-1, -2] + - [-3, -4] + out: 10 + - name: "all_negative_nine" + in: + matrix: + elemType: "int" + value: + - [-1, -2, -3] + - [-4, -5, -6] + - [-7, -8, -9] + out: 43 + - name: "zeros_only" + in: + matrix: + elemType: "int" + value: + - [0, 0] + - [0, 0] + out: 0 + - name: "mixed_zero_odd_negative" + in: + matrix: + elemType: "int" + value: + - [-5, 0] + - [0, 0] + out: 5 + - name: "mixed_zero_even_negative" + in: + matrix: + elemType: "int" + value: + - [-5, 0] + - [-7, 0] + out: 12 + - name: "minimum_abs_is_zero" + in: + matrix: + elemType: "int" + value: + - [-8, -3] + - [-2, 0] + out: 13 + - name: "duplicate_magnitudes" + in: + matrix: + elemType: "int" + value: + - [-6, 6] + - [-6, 6] + out: 24 + - name: "negative_minimum_not_first" + in: + matrix: + elemType: "int" + value: + - [8, -1, -7] + - [2, -9, 3] + - [4, 5, -6] + out: 45 + - name: "checkerboard_signs" + in: + matrix: + elemType: "int" + value: + - [1, -2, 3] + - [-4, 5, -6] + - [7, -8, 9] + out: 45 + - name: "three_by_three_one_negative" + in: + matrix: + elemType: "int" + value: + - [10, 20, 30] + - [40, -50, 60] + - [70, 80, 90] + out: 430 + - name: "three_by_three_two_negatives" + in: + matrix: + elemType: "int" + value: + - [-10, 20, 30] + - [40, -50, 60] + - [70, 80, 90] + out: 450 + - name: "four_by_four_balanced" + in: + matrix: + elemType: "int" + value: + - [1, -2, 3, -4] + - [-5, 6, -7, 8] + - [9, -10, 11, -12] + - [-13, 14, -15, 16] + out: 136 + - name: "four_by_four_all_negative" + in: + matrix: + elemType: "int" + value: + - [-1, -2, -3, -4] + - [-5, -6, -7, -8] + - [-9, -10, -11, -12] + - [-13, -14, -15, -16] + out: 136 + - name: "large_values_even_negative" + in: + matrix: + elemType: "int" + value: + - [100000, -100000] + - [-99999, 99998] + out: 399997 + - name: "large_values_odd_negative_zero" + in: + matrix: + elemType: "int" + value: + - [-100000, 99999, 0] + - [99998, 99997, 99996] + - [99995, 99994, 99993] + out: 799972 + - name: "negative_one_is_minimum" + in: + matrix: + elemType: "int" + value: + - [-100, -50] + - [-25, 1] + out: 174 + - name: "positive_one_is_minimum" + in: + matrix: + elemType: "int" + value: + - [-100, -50] + - [-25, 1] + out: 174 + - name: "repeated_rows" + in: + matrix: + elemType: "int" + value: + - [3, -3, 3] + - [3, -3, 3] + - [3, -3, 3] + out: 21 + - name: "single_magnitude_negative" + in: + matrix: + elemType: "int" + value: + - [-42, 7] + - [8, 9] + out: 52 + - name: "odd_negative_without_zero" + in: + matrix: + elemType: "int" + value: + - [-4, 5, 6] + - [7, 8, 9] + - [10, 11, 12] + out: 64 + - name: "five_by_five_positive" + in: + matrix: + elemType: "int" + value: + - [1, 2, 3, 4, 5] + - [6, 7, 8, 9, 10] + - [11, 12, 13, 14, 15] + - [16, 17, 18, 19, 20] + - [21, 22, 23, 24, 25] + out: 325 + - name: "five_by_five_odd_negatives" + in: + matrix: + elemType: "int" + value: + - [-1, 2, 3, 4, 5] + - [6, -7, 8, 9, 10] + - [11, 12, -13, 14, 15] + - [16, 17, 18, 19, 20] + - [21, 22, 23, 24, 25] + out: 323 + - name: "five_by_five_even_negatives" + in: + matrix: + elemType: "int" + value: + - [-1, 2, 3, 4, 5] + - [6, -7, 8, 9, 10] + - [11, 12, 13, 14, 15] + - [16, 17, 18, 19, 20] + - [21, 22, 23, 24, 25] + out: 325 + - name: "alternating_large_four" + in: + matrix: + elemType: "int" + value: + - [100000, -100000, 100000, -100000] + - [-100000, 100000, -100000, 100000] + - [100000, -100000, 100000, -100000] + - [-100000, 100000, -100000, 100000] + out: 1600000 + - name: "all_min_value_three" + in: + matrix: + elemType: "int" + value: + - [-100000, -100000, -100000] + - [-100000, -100000, -100000] + - [-100000, -100000, -100000] + out: 700000 + - name: "near_zero_values" + in: + matrix: + elemType: "int" + value: + - [-1, 1, -1] + - [1, -1, 1] + - [-1, 1, -1] + out: 7 + - name: "six_by_six_mixed" + in: + matrix: + elemType: "int" + value: + - [-1, 2, -3, 4, -5, 6] + - [7, -8, 9, -10, 11, -12] + - [13, 14, -15, 16, 17, 18] + - [-19, 20, 21, -22, 23, 24] + - [25, -26, 27, 28, -29, 30] + - [31, 32, -33, 34, 35, -36] + out: 664 + - name: "seven_by_seven_zero_border" + in: + matrix: + elemType: "int" + value: + - [0, 0, 0, 0, 0, 0, 0] + - [0, -2, 3, -4, 5, -6, 0] + - [0, 7, -8, 9, -10, 11, 0] + - [0, -12, 13, -14, 15, -16, 0] + - [0, 17, -18, 19, -20, 21, 0] + - [0, -22, 23, -24, 25, -26, 0] + - [0, 0, 0, 0, 0, 0, 0] + out: 350 + - name: "eight_by_eight_constant" + in: + matrix: + elemType: "int" + value: + - [17, 17, 17, 17, 17, 17, 17, 17] + - [17, 17, 17, 17, 17, 17, 17, 17] + - [17, 17, 17, 17, 17, 17, 17, 17] + - [17, 17, 17, 17, 17, 17, 17, 17] + - [17, 17, 17, 17, 17, 17, 17, 17] + - [17, 17, 17, 17, 17, 17, 17, 17] + - [17, 17, 17, 17, 17, 17, 17, 17] + - [17, 17, 17, 17, 17, 17, 17, 17] + out: 1088 + - name: "eight_by_eight_one_negative" + in: + matrix: + elemType: "int" + value: + - [-17, 17, 17, 17, 17, 17, 17, 17] + - [17, 17, 17, 17, 17, 17, 17, 17] + - [17, 17, 17, 17, 17, 17, 17, 17] + - [17, 17, 17, 17, 17, 17, 17, 17] + - [17, 17, 17, 17, 17, 17, 17, 17] + - [17, 17, 17, 17, 17, 17, 17, 17] + - [17, 17, 17, 17, 17, 17, 17, 17] + - [17, 17, 17, 17, 17, 17, 17, 17] + out: 1054 + - name: "nine_by_nine_sparse_negatives" + in: + matrix: + elemType: "int" + value: + - [-9, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 8, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, -7, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 6, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, -5, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 4, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, -3, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 2, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, -1] + out: 45 diff --git a/tests/1501-2000/1975. maximum-matrix-sum/sol.cpp b/tests/1501-2000/1975. maximum-matrix-sum/sol.cpp new file mode 100644 index 00000000..3ea4d185 --- /dev/null +++ b/tests/1501-2000/1975. maximum-matrix-sum/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + long long maxMatrixSum(vector>& matrix) { + long long totalSum = 0; + int neg = 0; + int minAbs = INT_MAX; + for (auto& row : matrix) { + for (int v : row) { + if (v < 0) neg++; + int av = abs(v); + totalSum += av; + minAbs = min(minAbs, av); + } + } + return neg % 2 == 0 ? totalSum : totalSum - 2LL * minAbs; + } +}; diff --git a/tests/1501-2000/1975. maximum-matrix-sum/sol.cs b/tests/1501-2000/1975. maximum-matrix-sum/sol.cs new file mode 100644 index 00000000..7d711e30 --- /dev/null +++ b/tests/1501-2000/1975. maximum-matrix-sum/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public long MaxMatrixSum(int[][] matrix) { + long totalSum = 0; + int neg = 0; + int minAbs = int.MaxValue; + foreach (var row in matrix) { + foreach (int v in row) { + if (v < 0) neg++; + int av = Math.Abs(v); + totalSum += av; + minAbs = Math.Min(minAbs, av); + } + } + return neg % 2 == 0 ? totalSum : totalSum - 2L * minAbs; + } +} diff --git a/tests/1501-2000/1975. maximum-matrix-sum/sol.dart b/tests/1501-2000/1975. maximum-matrix-sum/sol.dart new file mode 100644 index 00000000..ce66978c --- /dev/null +++ b/tests/1501-2000/1975. maximum-matrix-sum/sol.dart @@ -0,0 +1,16 @@ +class Solution { + int maxMatrixSum(List> matrix) { + int totalSum = 0; + int neg = 0; + int minAbs = 1 << 31; // large + for (var row in matrix) { + for (var v in row) { + if (v < 0) neg++; + int av = v.abs(); + totalSum += av; + if (av < minAbs) minAbs = av; + } + } + return neg % 2 == 0 ? totalSum : totalSum - 2 * minAbs; + } +} diff --git a/tests/1501-2000/1975. maximum-matrix-sum/sol.go b/tests/1501-2000/1975. maximum-matrix-sum/sol.go new file mode 100644 index 00000000..e3920244 --- /dev/null +++ b/tests/1501-2000/1975. maximum-matrix-sum/sol.go @@ -0,0 +1,24 @@ +func maxMatrixSum(matrix [][]int) int64 { + totalSum := int64(0) + neg := 0 + minAbs := int(^uint(0) >> 1) // max int + for _, row := range matrix { + for _, v := range row { + if v < 0 { + neg++ + } + av := v + if av < 0 { + av = -av + } + totalSum += int64(av) + if av < minAbs { + minAbs = av + } + } + } + if neg%2 == 0 { + return totalSum + } + return totalSum - 2*int64(minAbs) +} diff --git a/tests/1501-2000/1975. maximum-matrix-sum/sol.java b/tests/1501-2000/1975. maximum-matrix-sum/sol.java new file mode 100644 index 00000000..8328ea52 --- /dev/null +++ b/tests/1501-2000/1975. maximum-matrix-sum/sol.java @@ -0,0 +1,16 @@ +class Solution { + public long maxMatrixSum(int[][] matrix) { + long totalSum = 0; + int neg = 0; + int minAbs = Integer.MAX_VALUE; + for (int[] row : matrix) { + for (int v : row) { + if (v < 0) neg++; + int av = Math.abs(v); + totalSum += av; + minAbs = Math.min(minAbs, av); + } + } + return neg % 2 == 0 ? totalSum : totalSum - 2L * minAbs; + } +} diff --git a/tests/1501-2000/1975. maximum-matrix-sum/sol.kt b/tests/1501-2000/1975. maximum-matrix-sum/sol.kt new file mode 100644 index 00000000..4b1fd350 --- /dev/null +++ b/tests/1501-2000/1975. maximum-matrix-sum/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun maxMatrixSum(matrix: Array): Long { + var totalSum = 0L + var neg = 0 + var minAbs = Int.MAX_VALUE + for (row in matrix) { + for (v in row) { + if (v < 0) neg++ + val av = Math.abs(v) + totalSum += av + minAbs = Math.min(minAbs, av) + } + } + return if (neg % 2 == 0) totalSum else totalSum - 2L * minAbs + } +} diff --git a/tests/1501-2000/1975. maximum-matrix-sum/sol.py b/tests/1501-2000/1975. maximum-matrix-sum/sol.py new file mode 100644 index 00000000..09cc8aa9 --- /dev/null +++ b/tests/1501-2000/1975. maximum-matrix-sum/sol.py @@ -0,0 +1,15 @@ +class Solution: + def maxMatrixSum(self, matrix: list[list[int]]) -> int: + totalSum = 0 + neg = 0 + minAbs = float("inf") + + for row in matrix: + for v in row: + if v < 0: + neg += 1 + av = abs(v) + totalSum += av + minAbs = min(minAbs, av) + + return totalSum if neg % 2 == 0 else totalSum - 2 * minAbs diff --git a/tests/1501-2000/1975. maximum-matrix-sum/sol.py2 b/tests/1501-2000/1975. maximum-matrix-sum/sol.py2 new file mode 100644 index 00000000..b3d84739 --- /dev/null +++ b/tests/1501-2000/1975. maximum-matrix-sum/sol.py2 @@ -0,0 +1,17 @@ +class Solution(object): + def maxMatrixSum(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: int + """ + total_sum = 0 + neg = 0 + min_abs = float('inf') + for row in matrix: + for v in row: + if v < 0: + neg += 1 + av = abs(v) + total_sum += av + min_abs = min(min_abs, av) + return total_sum if neg % 2 == 0 else total_sum - 2 * min_abs diff --git a/tests/1501-2000/1975. maximum-matrix-sum/sol.rb b/tests/1501-2000/1975. maximum-matrix-sum/sol.rb new file mode 100644 index 00000000..e0995f06 --- /dev/null +++ b/tests/1501-2000/1975. maximum-matrix-sum/sol.rb @@ -0,0 +1,18 @@ +# @param {Integer[][]} matrix +# @return {Integer} +def max_matrix_sum(matrix) + total_sum = 0 + neg = 0 + min_abs = Float::INFINITY + matrix.each do |row| + row.each do |v| + if v < 0 + neg += 1 + end + av = v.abs + total_sum += av + min_abs = [min_abs, av].min + end + end + neg.even? ? total_sum : total_sum - 2 * min_abs +end diff --git a/tests/1501-2000/1975. maximum-matrix-sum/sol.rs b/tests/1501-2000/1975. maximum-matrix-sum/sol.rs new file mode 100644 index 00000000..b70c5fe7 --- /dev/null +++ b/tests/1501-2000/1975. maximum-matrix-sum/sol.rs @@ -0,0 +1,22 @@ +impl Solution { + pub fn max_matrix_sum(matrix: Vec>) -> i64 { + let mut total_sum: i64 = 0; + let mut neg = 0; + let mut min_abs = i32::MAX; + for row in &matrix { + for &v in row { + if v < 0 { + neg += 1; + } + let av = v.abs(); + total_sum += av as i64; + min_abs = min_abs.min(av); + } + } + if neg % 2 == 0 { + total_sum + } else { + total_sum - 2 * min_abs as i64 + } + } +} diff --git a/tests/1501-2000/1975. maximum-matrix-sum/sol.swift b/tests/1501-2000/1975. maximum-matrix-sum/sol.swift new file mode 100644 index 00000000..d678a8be --- /dev/null +++ b/tests/1501-2000/1975. maximum-matrix-sum/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func maxMatrixSum(_ matrix: [[Int]]) -> Int { + var totalSum = 0 + var neg = 0 + var minAbs = Int.max + for row in matrix { + for v in row { + if v < 0 { neg += 1 } + let av = abs(v) + totalSum += av + minAbs = min(minAbs, av) + } + } + return neg % 2 == 0 ? totalSum : totalSum - 2 * minAbs + } +} diff --git a/tests/1501-2000/1975. maximum-matrix-sum/sol.ts b/tests/1501-2000/1975. maximum-matrix-sum/sol.ts new file mode 100644 index 00000000..bc47192b --- /dev/null +++ b/tests/1501-2000/1975. maximum-matrix-sum/sol.ts @@ -0,0 +1,14 @@ +function maxMatrixSum(matrix: number[][]): number { + let totalSum = 0; + let neg = 0; + let minAbs = Number.MAX_SAFE_INTEGER; + for (const row of matrix) { + for (const v of row) { + if (v < 0) neg++; + const av = Math.abs(v); + totalSum += av; + minAbs = Math.min(minAbs, av); + } + } + return neg % 2 === 0 ? totalSum : totalSum - 2 * minAbs; +} diff --git a/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/manifest.yaml b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/manifest.yaml new file mode 100644 index 00000000..73db1030 --- /dev/null +++ b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/manifest.yaml @@ -0,0 +1,780 @@ +entry: + id: 1976 + title: "number-of-ways-to-arrive-at-destination" + params: + n: + type: int + roads: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().countPaths({n}, {roads})" + rust: "Solution::count_paths({n}, {roads})" + python3: "Solution().countPaths({n}, {roads})" + python2: "Solution().countPaths({n}, {roads})" + ruby: "count_paths({n}, {roads})" + java: "new Solution().countPaths({n}, {roads})" + csharp: "new Solution().CountPaths({n}, {roads})" + kotlin: "Solution().countPaths({n}, {roads})" + go: "countPaths({n}, {roads})" + dart: "Solution().countPaths({n}, {roads})" + swift: "Solution().countPaths({n}, {roads})" + typescript: "countPaths({n}, {roads})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().countPaths(n, roads, {result})" + checker: | + import heapq + + class Checker: + def countPaths(self, n, roads, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + graph = [[] for _ in range(n)] + for edge in roads: + if not isinstance(edge, list) or len(edge) != 3: + return False + u, v, w = edge + graph[u].append((v, w)) + graph[v].append((u, w)) + mod = 1000000007 + inf = 10**30 + dist = [inf] * n + ways = [0] * n + dist[0] = 0 + ways[0] = 1 + heap = [(0, 0)] + while heap: + d, u = heapq.heappop(heap) + if d != dist[u]: + continue + for v, w in graph[u]: + nd = d + w + if nd < dist[v]: + dist[v] = nd + ways[v] = ways[u] + heapq.heappush(heap, (nd, v)) + elif nd == dist[v]: + ways[v] = (ways[v] + ways[u]) % mod + return result == ways[n - 1] + +seed: 1976001 + +tests: + - name: "example_one" + in: + n: 7 + roads: + - [0, 6, 7] + - [0, 1, 2] + - [1, 2, 3] + - [1, 3, 3] + - [6, 3, 3] + - [3, 5, 1] + - [6, 5, 1] + - [2, 5, 1] + - [0, 4, 5] + - [4, 6, 2] + out: 4 + - name: "two_nodes" + in: + n: 2 + roads: + - [1, 0, 10] + out: 1 + - name: "three_line" + in: + n: 3 + roads: + - [0, 1, 2] + - [1, 2, 3] + out: 1 + - name: "three_direct_shorter" + in: + n: 3 + roads: + - [0, 1, 10] + - [1, 2, 10] + - [0, 2, 5] + out: 1 + - name: "three_equal_routes" + in: + n: 3 + roads: + - [0, 1, 4] + - [1, 2, 4] + - [0, 2, 8] + out: 2 + - name: "diamond" + in: + n: 4 + roads: + - [0, 1, 1] + - [0, 2, 1] + - [1, 3, 1] + - [2, 3, 1] + - [1, 2, 5] + out: 2 + - name: "diamond_with_long_edges" + in: + n: 4 + roads: + - [0, 1, 7] + - [0, 2, 7] + - [1, 3, 9] + - [2, 3, 9] + - [0, 3, 100] + out: 2 + - name: "three_layer_four_paths" + in: + n: 6 + roads: + - [0, 1, 1] + - [0, 2, 1] + - [1, 3, 1] + - [1, 4, 1] + - [2, 3, 1] + - [2, 4, 1] + - [3, 5, 1] + - [4, 5, 1] + out: 4 + - name: "zero_choice_long_detour" + in: + n: 5 + roads: + - [0, 1, 3] + - [1, 4, 3] + - [0, 2, 1] + - [2, 3, 20] + - [3, 4, 20] + - [0, 4, 20] + out: 1 + - name: "equal_direct_and_two_hop" + in: + n: 4 + roads: + - [0, 3, 6] + - [0, 1, 2] + - [1, 3, 4] + - [0, 2, 3] + - [2, 3, 3] + - [1, 2, 100] + out: 3 + - name: "large_weights" + in: + n: 4 + roads: + - [0, 1, 1000000000] + - [1, 3, 1000000000] + - [0, 2, 1000000000] + - [2, 3, 1000000000] + - [0, 3, 2000000001] + out: 2 + - name: "dense_four" + in: + n: 4 + roads: + - [0, 1, 1] + - [0, 2, 1] + - [0, 3, 2] + - [1, 2, 9] + - [1, 3, 1] + - [2, 3, 1] + out: 3 + - name: "dense_five_unique" + in: + n: 5 + roads: + - [0, 1, 2] + - [0, 2, 9] + - [0, 3, 20] + - [0, 4, 50] + - [1, 2, 2] + - [1, 3, 10] + - [1, 4, 30] + - [2, 3, 2] + - [2, 4, 20] + - [3, 4, 2] + out: 1 + - name: "dense_five_many" + in: + n: 5 + roads: + - [0, 1, 1] + - [0, 2, 1] + - [0, 3, 1] + - [0, 4, 3] + - [1, 2, 8] + - [1, 3, 8] + - [1, 4, 2] + - [2, 3, 8] + - [2, 4, 2] + - [3, 4, 2] + out: 4 + - name: "six_layer_three" + in: + n: 6 + roads: + - [0, 1, 2] + - [0, 2, 2] + - [1, 3, 2] + - [2, 4, 2] + - [3, 5, 2] + - [4, 5, 2] + - [1, 4, 20] + - [2, 3, 20] + out: 2 + - name: "seven_chain" + in: + n: 7 + roads: + - [0, 1, 1] + - [1, 2, 1] + - [2, 3, 1] + - [3, 4, 1] + - [4, 5, 1] + - [5, 6, 1] + - [0, 6, 20] + out: 1 + - name: "seven_layer_paths" + in: + n: 7 + roads: + - [0, 1, 1] + - [0, 2, 1] + - [1, 3, 1] + - [2, 3, 1] + - [1, 4, 1] + - [2, 5, 1] + - [3, 6, 1] + - [4, 6, 1] + - [5, 6, 1] + out: 4 + - name: "eight_chain_with_shortcut" + in: + n: 8 + roads: + - [0, 1, 2] + - [1, 2, 2] + - [2, 3, 2] + - [3, 4, 2] + - [4, 5, 2] + - [5, 6, 2] + - [6, 7, 2] + - [0, 3, 5] + - [3, 7, 7] + - [0, 7, 30] + out: 1 + - name: "eight_two_routes" + in: + n: 8 + roads: + - [0, 1, 1] + - [0, 2, 1] + - [1, 3, 1] + - [2, 4, 1] + - [3, 5, 1] + - [4, 6, 1] + - [5, 7, 1] + - [6, 7, 1] + - [1, 2, 9] + - [3, 4, 9] + out: 2 + - name: "nine_dense_shortest" + in: + n: 9 + roads: + - [0, 1, 1] + - [0, 2, 1] + - [0, 3, 1] + - [1, 4, 1] + - [2, 5, 1] + - [3, 6, 1] + - [4, 7, 1] + - [5, 7, 1] + - [6, 8, 1] + - [7, 8, 1] + - [0, 8, 20] + out: 1 + - name: "ten_single_shortest" + in: + n: 10 + roads: + - [0, 1, 1] + - [1, 2, 1] + - [2, 3, 1] + - [3, 4, 1] + - [4, 5, 1] + - [5, 6, 1] + - [6, 7, 1] + - [7, 8, 1] + - [8, 9, 1] + - [0, 9, 50] + - [0, 5, 20] + out: 1 + - name: "ten_equal_branches" + in: + n: 10 + roads: + - [0, 1, 1] + - [0, 2, 1] + - [0, 3, 1] + - [1, 4, 1] + - [2, 5, 1] + - [3, 6, 1] + - [4, 7, 1] + - [5, 8, 1] + - [6, 8, 1] + - [7, 9, 1] + - [8, 9, 1] + out: 3 + - name: "eleven_modest" + in: + n: 11 + roads: + - [0, 1, 2] + - [0, 2, 2] + - [1, 3, 2] + - [2, 4, 2] + - [3, 5, 2] + - [4, 6, 2] + - [5, 7, 2] + - [6, 8, 2] + - [7, 9, 2] + - [8, 10, 2] + - [0, 10, 100] + - [3, 4, 10] + - [5, 6, 10] + out: 1 + - name: "twelve_parallel_layers" + in: + n: 12 + roads: + - [0, 1, 1] + - [0, 2, 1] + - [1, 3, 1] + - [1, 4, 1] + - [2, 5, 1] + - [2, 6, 1] + - [3, 7, 1] + - [4, 8, 1] + - [5, 9, 1] + - [6, 10, 1] + - [7, 11, 1] + - [8, 11, 1] + - [9, 11, 1] + - [10, 11, 1] + out: 4 + - name: "twelve_weight_ties" + in: + n: 12 + roads: + - [0, 1, 5] + - [0, 2, 5] + - [1, 3, 5] + - [2, 4, 5] + - [3, 5, 5] + - [4, 6, 5] + - [5, 7, 5] + - [6, 8, 5] + - [7, 9, 5] + - [8, 10, 5] + - [9, 11, 5] + - [10, 11, 5] + - [0, 11, 1000] + out: 2 + - name: "fifteen_chain" + in: + n: 15 + roads: + - [0, 1, 3] + - [1, 2, 3] + - [2, 3, 3] + - [3, 4, 3] + - [4, 5, 3] + - [5, 6, 3] + - [6, 7, 3] + - [7, 8, 3] + - [8, 9, 3] + - [9, 10, 3] + - [10, 11, 3] + - [11, 12, 3] + - [12, 13, 3] + - [13, 14, 3] + - [0, 14, 1000] + out: 1 + - name: "fifteen_four_routes" + in: + n: 15 + roads: + - [0, 1, 1] + - [0, 2, 1] + - [1, 3, 1] + - [2, 4, 1] + - [3, 5, 1] + - [4, 6, 1] + - [5, 7, 1] + - [6, 8, 1] + - [7, 9, 1] + - [8, 10, 1] + - [9, 11, 1] + - [10, 12, 1] + - [11, 13, 1] + - [12, 13, 1] + - [13, 14, 1] + out: 2 + - name: "twenty_chain" + in: + n: 20 + roads: + - [0, 1, 1] + - [1, 2, 1] + - [2, 3, 1] + - [3, 4, 1] + - [4, 5, 1] + - [5, 6, 1] + - [6, 7, 1] + - [7, 8, 1] + - [8, 9, 1] + - [9, 10, 1] + - [10, 11, 1] + - [11, 12, 1] + - [12, 13, 1] + - [13, 14, 1] + - [14, 15, 1] + - [15, 16, 1] + - [16, 17, 1] + - [17, 18, 1] + - [18, 19, 1] + - [0, 19, 1000000000] + out: 1 + - name: "twenty_four_dense" + in: + n: 24 + roads: + - [0, 1, 2] + - [0, 2, 2] + - [1, 3, 2] + - [2, 4, 2] + - [3, 5, 2] + - [4, 6, 2] + - [5, 7, 2] + - [6, 8, 2] + - [7, 9, 2] + - [8, 10, 2] + - [9, 11, 2] + - [10, 12, 2] + - [11, 13, 2] + - [12, 14, 2] + - [13, 15, 2] + - [14, 16, 2] + - [15, 17, 2] + - [16, 18, 2] + - [17, 19, 2] + - [18, 20, 2] + - [19, 21, 2] + - [20, 22, 2] + - [21, 23, 2] + - [0, 23, 1000] + out: 1 + - name: "thirty_single_path" + in: + n: 30 + roads: + - [0, 1, 4] + - [1, 2, 4] + - [2, 3, 4] + - [3, 4, 4] + - [4, 5, 4] + - [5, 6, 4] + - [6, 7, 4] + - [7, 8, 4] + - [8, 9, 4] + - [9, 10, 4] + - [10, 11, 4] + - [11, 12, 4] + - [12, 13, 4] + - [13, 14, 4] + - [14, 15, 4] + - [15, 16, 4] + - [16, 17, 4] + - [17, 18, 4] + - [18, 19, 4] + - [19, 20, 4] + - [20, 21, 4] + - [21, 22, 4] + - [22, 23, 4] + - [23, 24, 4] + - [24, 25, 4] + - [25, 26, 4] + - [26, 27, 4] + - [27, 28, 4] + - [28, 29, 4] + - [0, 29, 1000000000] + out: 1 + - name: "forty_two_two_routes" + in: + n: 42 + roads: + - [0, 1, 1] + - [0, 2, 1] + - [1, 3, 1] + - [2, 4, 1] + - [3, 5, 1] + - [4, 6, 1] + - [5, 7, 1] + - [6, 8, 1] + - [7, 9, 1] + - [8, 10, 1] + - [9, 11, 1] + - [10, 12, 1] + - [11, 13, 1] + - [12, 14, 1] + - [13, 15, 1] + - [14, 16, 1] + - [15, 17, 1] + - [16, 18, 1] + - [17, 19, 1] + - [18, 20, 1] + - [19, 21, 1] + - [20, 22, 1] + - [21, 23, 1] + - [22, 24, 1] + - [23, 25, 1] + - [24, 26, 1] + - [25, 27, 1] + - [26, 28, 1] + - [27, 29, 1] + - [28, 30, 1] + - [29, 31, 1] + - [30, 32, 1] + - [31, 33, 1] + - [32, 34, 1] + - [33, 35, 1] + - [34, 36, 1] + - [35, 37, 1] + - [36, 38, 1] + - [37, 39, 1] + - [38, 40, 1] + - [39, 41, 1] + out: 1 + - name: "fifty_mixed" + in: + n: 50 + roads: + - [0, 1, 3] + - [0, 2, 3] + - [1, 3, 3] + - [2, 4, 3] + - [3, 5, 3] + - [4, 6, 3] + - [5, 7, 3] + - [6, 8, 3] + - [7, 9, 3] + - [8, 10, 3] + - [9, 11, 3] + - [10, 12, 3] + - [11, 13, 3] + - [12, 14, 3] + - [13, 15, 3] + - [14, 16, 3] + - [15, 17, 3] + - [16, 18, 3] + - [17, 19, 3] + - [18, 20, 3] + - [19, 21, 3] + - [20, 22, 3] + - [21, 23, 3] + - [22, 24, 3] + - [23, 25, 3] + - [24, 26, 3] + - [25, 27, 3] + - [26, 28, 3] + - [27, 29, 3] + - [28, 30, 3] + - [29, 31, 3] + - [30, 32, 3] + - [31, 33, 3] + - [32, 34, 3] + - [33, 35, 3] + - [34, 36, 3] + - [35, 37, 3] + - [36, 38, 3] + - [37, 39, 3] + - [38, 40, 3] + - [39, 41, 3] + - [40, 42, 3] + - [41, 43, 3] + - [42, 44, 3] + - [43, 45, 3] + - [44, 46, 3] + - [45, 47, 3] + - [46, 48, 3] + - [47, 49, 3] + - [0, 49, 1000000000] + out: 1 + - name: "large_sparse" + in: + n: 100 + roads: + - [0, 1, 10] + - [1, 2, 10] + - [2, 3, 10] + - [3, 4, 10] + - [4, 5, 10] + - [5, 6, 10] + - [6, 7, 10] + - [7, 8, 10] + - [8, 9, 10] + - [9, 10, 10] + - [10, 11, 10] + - [11, 12, 10] + - [12, 13, 10] + - [13, 14, 10] + - [14, 15, 10] + - [15, 16, 10] + - [16, 17, 10] + - [17, 18, 10] + - [18, 19, 10] + - [19, 20, 10] + - [20, 21, 10] + - [21, 22, 10] + - [22, 23, 10] + - [23, 24, 10] + - [24, 25, 10] + - [25, 26, 10] + - [26, 27, 10] + - [27, 28, 10] + - [28, 29, 10] + - [29, 30, 10] + - [30, 31, 10] + - [31, 32, 10] + - [32, 33, 10] + - [33, 34, 10] + - [34, 35, 10] + - [35, 36, 10] + - [36, 37, 10] + - [37, 38, 10] + - [38, 39, 10] + - [39, 40, 10] + - [40, 41, 10] + - [41, 42, 10] + - [42, 43, 10] + - [43, 44, 10] + - [44, 45, 10] + - [45, 46, 10] + - [46, 47, 10] + - [47, 48, 10] + - [48, 49, 10] + - [49, 50, 10] + - [50, 51, 10] + - [51, 52, 10] + - [52, 53, 10] + - [53, 54, 10] + - [54, 55, 10] + - [55, 56, 10] + - [56, 57, 10] + - [57, 58, 10] + - [58, 59, 10] + - [59, 60, 10] + - [60, 61, 10] + - [61, 62, 10] + - [62, 63, 10] + - [63, 64, 10] + - [64, 65, 10] + - [65, 66, 10] + - [66, 67, 10] + - [67, 68, 10] + - [68, 69, 10] + - [69, 70, 10] + - [70, 71, 10] + - [71, 72, 10] + - [72, 73, 10] + - [73, 74, 10] + - [74, 75, 10] + - [75, 76, 10] + - [76, 77, 10] + - [77, 78, 10] + - [78, 79, 10] + - [79, 80, 10] + - [80, 81, 10] + - [81, 82, 10] + - [82, 83, 10] + - [83, 84, 10] + - [84, 85, 10] + - [85, 86, 10] + - [86, 87, 10] + - [87, 88, 10] + - [88, 89, 10] + - [89, 90, 10] + - [90, 91, 10] + - [91, 92, 10] + - [92, 93, 10] + - [93, 94, 10] + - [94, 95, 10] + - [95, 96, 10] + - [96, 97, 10] + - [97, 98, 10] + - [98, 99, 10] + - [0, 99, 1000000000] + out: 1 + - name: "fourteen_two_equal" + in: + n: 14 + roads: + - [0, 1, 4] + - [0, 2, 4] + - [1, 3, 4] + - [2, 4, 4] + - [3, 5, 4] + - [4, 6, 4] + - [5, 7, 4] + - [6, 8, 4] + - [7, 9, 4] + - [8, 10, 4] + - [9, 11, 4] + - [10, 12, 4] + - [11, 13, 4] + - [12, 13, 4] + out: 2 + - name: "twenty_five_direct_dominated" + in: + n: 25 + roads: + - [0, 1, 2] + - [1, 2, 2] + - [2, 3, 2] + - [3, 4, 2] + - [4, 5, 2] + - [5, 6, 2] + - [6, 7, 2] + - [7, 8, 2] + - [8, 9, 2] + - [9, 10, 2] + - [10, 11, 2] + - [11, 12, 2] + - [12, 13, 2] + - [13, 14, 2] + - [14, 15, 2] + - [15, 16, 2] + - [16, 17, 2] + - [17, 18, 2] + - [18, 19, 2] + - [19, 20, 2] + - [20, 21, 2] + - [21, 22, 2] + - [22, 23, 2] + - [23, 24, 2] + - [0, 24, 1000] + out: 1 diff --git a/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.cpp b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.cpp new file mode 100644 index 00000000..ac1983bf --- /dev/null +++ b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + int countPaths(int n, vector>& roads) { + vector>> graph(n); + for (auto& road : roads) { + int u = road[0], v = road[1], time = road[2]; + graph[u].push_back({v, time}); + graph[v].push_back({u, time}); + } + + vector dist(n, LLONG_MAX); + vector ways(n, 0); + dist[0] = 0; + ways[0] = 1; + + priority_queue, vector>, greater>> pq; + pq.push({0, 0}); + + const int MOD = 1'000'000'007; + + while (!pq.empty()) { + auto [d, node] = pq.top(); + pq.pop(); + + if (d > dist[node]) continue; + + for (auto& [neighbor, time] : graph[node]) { + if (dist[node] + time < dist[neighbor]) { + dist[neighbor] = dist[node] + time; + ways[neighbor] = ways[node]; + pq.push({dist[neighbor], neighbor}); + } else if (dist[node] + time == dist[neighbor]) { + ways[neighbor] = (ways[neighbor] + ways[node]) % MOD; + } + } + } + + return ways[n - 1]; + } +}; diff --git a/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.cs b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.cs new file mode 100644 index 00000000..aa85bc86 --- /dev/null +++ b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; + +public class Solution { + public int CountPaths(int n, int[][] roads) { + var graph = new List>(); + for (int i = 0; i < n; i++) { + graph.Add(new List<(int, int)>()); + } + foreach (var road in roads) { + int u = road[0], v = road[1], time = road[2]; + graph[u].Add((v, time)); + graph[v].Add((u, time)); + } + + var dist = new long[n]; + var ways = new int[n]; + for (int i = 0; i < n; i++) dist[i] = long.MaxValue; + dist[0] = 0; + ways[0] = 1; + + var pq = new SortedSet<(long, int)>(); + pq.Add((0, 0)); + + const int MOD = 1_000_000_007; + + while (pq.Count > 0) { + var (d, node) = pq.Min; + pq.Remove(pq.Min); + + if (d > dist[node]) continue; + + foreach (var (neighbor, time) in graph[node]) { + if (dist[node] + time < dist[neighbor]) { + dist[neighbor] = dist[node] + time; + ways[neighbor] = ways[node]; + pq.Add((dist[neighbor], neighbor)); + } else if (dist[node] + time == dist[neighbor]) { + ways[neighbor] = (ways[neighbor] + ways[node]) % MOD; + } + } + } + + return ways[n - 1]; + } +} diff --git a/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.dart b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.dart new file mode 100644 index 00000000..62bf4239 --- /dev/null +++ b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.dart @@ -0,0 +1,43 @@ +import 'dart:collection'; + +class Solution { + int countPaths(int n, List> roads) { + List>> graph = List.generate(n, (_) => []); + for (var road in roads) { + int u = road[0], v = road[1], time = road[2]; + graph[u].add([v, time]); + graph[v].add([u, time]); + } + + List dist = List.filled(n, 1 << 60); + List ways = List.filled(n, 0); + dist[0] = 0; + ways[0] = 1; + + var pq = PriorityQueue>((a, b) => a[0].compareTo(b[0])); + pq.add([0, 0]); + + int MOD = 1000000007; + + while (pq.isNotEmpty) { + var curr = pq.removeFirst(); + int d = curr[0], node = curr[1]; + + if (d > dist[node]) continue; + + for (var edge in graph[node]) { + int neighbor = edge[0], time = edge[1]; + + if (dist[node] + time < dist[neighbor]) { + dist[neighbor] = dist[node] + time; + ways[neighbor] = ways[node]; + pq.add([dist[neighbor], neighbor]); + } else if (dist[node] + time == dist[neighbor]) { + ways[neighbor] = (ways[neighbor] + ways[node]) % MOD; + } + } + } + + return ways[n-1]; + } +} diff --git a/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.go b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.go new file mode 100644 index 00000000..6355cf5a --- /dev/null +++ b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.go @@ -0,0 +1,66 @@ +type Item struct { + dist int64 + node int +} + +type PriorityQueue []Item + +func (pq PriorityQueue) Len() int { return len(pq) } +func (pq PriorityQueue) Less(i, j int) bool { return pq[i].dist < pq[j].dist } +func (pq PriorityQueue) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] } +func (pq *PriorityQueue) Push(x interface{}) { *pq = append(*pq, x.(Item)) } +func (pq *PriorityQueue) Pop() interface{} { + old := *pq + n := len(old) + item := old[n-1] + *pq = old[:n-1] + return item +} + +func countPaths(n int, roads [][]int) int { + graph := make([][][2]int, n) + for _, road := range roads { + u, v, time := road[0], road[1], road[2] + graph[u] = append(graph[u], [2]int{v, time}) + graph[v] = append(graph[v], [2]int{u, time}) + } + + dist := make([]int64, n) + for i := range dist { + dist[i] = int64(1<<62) + } + ways := make([]int, n) + dist[0] = 0 + ways[0] = 1 + + pq := &PriorityQueue{} + heap.Init(pq) + heap.Push(pq, Item{0, 0}) + + MOD := int64(1_000_000_007) + + for pq.Len() > 0 { + item := heap.Pop(pq).(Item) + d := item.dist + node := item.node + + if d > dist[node] { + continue + } + + for _, edge := range graph[node] { + neighbor := edge[0] + time := int64(edge[1]) + + if dist[node] + time < dist[neighbor] { + dist[neighbor] = dist[node] + time + ways[neighbor] = ways[node] + heap.Push(pq, Item{dist[neighbor], neighbor}) + } else if dist[node] + time == dist[neighbor] { + ways[neighbor] = (ways[neighbor] + ways[node]) % int(MOD) + } + } + } + + return ways[n-1] +} diff --git a/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.java b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.java new file mode 100644 index 00000000..3260a0e9 --- /dev/null +++ b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.java @@ -0,0 +1,48 @@ +import java.util.*; + +class Solution { + public int countPaths(int n, int[][] roads) { + List> graph = new ArrayList<>(); + for (int i = 0; i < n; i++) { + graph.add(new ArrayList<>()); + } + for (int[] road : roads) { + graph.get(road[0]).add(new int[]{road[1], road[2]}); + graph.get(road[1]).add(new int[]{road[0], road[2]}); + } + + long[] dist = new long[n]; + int[] ways = new int[n]; + Arrays.fill(dist, Long.MAX_VALUE); + dist[0] = 0; + ways[0] = 1; + + PriorityQueue pq = new PriorityQueue<>((a, b) -> Long.compare(a[0], b[0])); + pq.offer(new long[]{0, 0}); + + int MOD = 1_000_000_007; + + while (!pq.isEmpty()) { + long[] curr = pq.poll(); + long d = curr[0]; + int node = (int) curr[1]; + + if (d > dist[node]) continue; + + for (int[] edge : graph.get(node)) { + int neighbor = edge[0]; + int time = edge[1]; + + if (dist[node] + time < dist[neighbor]) { + dist[neighbor] = dist[node] + time; + ways[neighbor] = ways[node]; + pq.offer(new long[]{dist[neighbor], neighbor}); + } else if (dist[node] + time == dist[neighbor]) { + ways[neighbor] = (ways[neighbor] + ways[node]) % MOD; + } + } + } + + return ways[n-1]; + } +} diff --git a/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.kt b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.kt new file mode 100644 index 00000000..20213581 --- /dev/null +++ b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.kt @@ -0,0 +1,39 @@ +import java.util.* + +class Solution { + fun countPaths(n: Int, roads: Array): Int { + val graph = Array(n) { mutableListOf>() } + for (road in roads) { + graph[road[0]].add(Pair(road[1], road[2])) + graph[road[1]].add(Pair(road[0], road[2])) + } + + val dist = LongArray(n) { Long.MAX_VALUE } + val ways = IntArray(n) + dist[0] = 0 + ways[0] = 1 + + val pq = PriorityQueue>(compareBy { it.first }) + pq.add(Pair(0L, 0)) + + val MOD = 1_000_000_007 + + while (pq.isNotEmpty()) { + val (d, node) = pq.poll() + + if (d > dist[node]) continue + + for ((neighbor, time) in graph[node]) { + if (dist[node] + time < dist[neighbor]) { + dist[neighbor] = dist[node] + time + ways[neighbor] = ways[node] + pq.add(Pair(dist[neighbor], neighbor)) + } else if (dist[node] + time == dist[neighbor]) { + ways[neighbor] = (ways[neighbor] + ways[node]) % MOD + } + } + } + + return ways[n-1] + } +} diff --git a/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.py b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.py new file mode 100644 index 00000000..49fda8e5 --- /dev/null +++ b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.py @@ -0,0 +1,36 @@ +import heapq + + +class Solution: + def countPaths(self, n: int, roads: List[List[int]]) -> int: + graph = [[] for _ in range(n)] + for u, v, time in roads: + graph[u].append((v, time)) + graph[v].append((u, time)) + + dist = [float("inf")] * n + ways = [0] * n + + dist[0] = 0 + ways[0] = 1 + + pq = [(0, 0)] + + MOD = 10**9 + 7 + + # Dijkstra's algorithm + while pq: + d, node = heapq.heappop(pq) + + if d > dist[node]: + continue + + for neighbor, time in graph[node]: + if dist[node] + time < dist[neighbor]: + dist[neighbor] = dist[node] + time + ways[neighbor] = ways[node] + heapq.heappush(pq, (dist[neighbor], neighbor)) + elif dist[node] + time == dist[neighbor]: + ways[neighbor] = (ways[neighbor] + ways[node]) % MOD + + return ways[n - 1] diff --git a/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.py2 b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.py2 new file mode 100644 index 00000000..0a3551db --- /dev/null +++ b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.py2 @@ -0,0 +1,30 @@ + +import heapq + + +class Solution(object): + def countPaths(self, n, roads): + graph = [[] for _ in xrange(n)] + for left, right, time in roads: + graph[left].append((right, time)) + graph[right].append((left, time)) + + modulo = 1000000007 + distance = [float('inf')] * n + ways = [0] * n + distance[0] = 0 + ways[0] = 1 + heap = [(0, 0)] + while heap: + current_distance, node = heapq.heappop(heap) + if current_distance != distance[node]: + continue + for neighbor, weight in graph[node]: + candidate = current_distance + weight + if candidate < distance[neighbor]: + distance[neighbor] = candidate + ways[neighbor] = ways[node] + heapq.heappush(heap, (candidate, neighbor)) + elif candidate == distance[neighbor]: + ways[neighbor] = (ways[neighbor] + ways[node]) % modulo + return ways[-1] diff --git a/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.rb b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.rb new file mode 100644 index 00000000..5782e9cb --- /dev/null +++ b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.rb @@ -0,0 +1,41 @@ +# @param {Integer} n +# @param {Integer[][]} roads +# @return {Integer} +def count_paths(n, roads) + graph = Array.new(n) { [] } + roads.each do |u, v, time| + graph[u] << [v, time] + graph[v] << [u, time] + end + + dist = Array.new(n, Float::INFINITY) + ways = Array.new(n, 0) + + dist[0] = 0 + ways[0] = 1 + + pq = [[0, 0]] + + mod = 10**9 + 7 + + until pq.empty? + d, node = pq.shift + + if d > dist[node] + next + end + + graph[node].each do |neighbor, time| + if dist[node] + time < dist[neighbor] + dist[neighbor] = dist[node] + time + ways[neighbor] = ways[node] + pq << [dist[neighbor], neighbor] + pq.sort_by! { |a| a[0] } + elsif dist[node] + time == dist[neighbor] + ways[neighbor] = (ways[neighbor] + ways[node]) % mod + end + end + end + + ways[n-1] +end diff --git a/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.rs b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.rs new file mode 100644 index 00000000..74985643 --- /dev/null +++ b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.rs @@ -0,0 +1,60 @@ +use std::collections::BinaryHeap; +use std::cmp::Ordering; + +#[derive(Eq, PartialEq)] +struct Item { + dist: i64, + node: usize, +} + +impl Ord for Item { + fn cmp(&self, other: &Self) -> Ordering { + other.dist.cmp(&self.dist) + } +} + +impl PartialOrd for Item { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Solution { + pub fn count_paths(n: i32, roads: Vec>) -> i32 { + let n = n as usize; + let mut graph = vec![vec![]; n]; + for road in &roads { + let u = road[0] as usize; + let v = road[1] as usize; + let time = road[2] as i64; + graph[u].push((v, time)); + graph[v].push((u, time)); + } + + let mut dist = vec![i64::MAX; n]; + let mut ways = vec![0i64; n]; + dist[0] = 0; + ways[0] = 1; + + let mut pq = BinaryHeap::new(); + pq.push(Item { dist: 0, node: 0 }); + + let MOD = 1_000_000_007i64; + + while let Some(Item { dist: d, node }) = pq.pop() { + if d > dist[node] { continue; } + + for &(neighbor, time) in &graph[node] { + if dist[node] + time < dist[neighbor] { + dist[neighbor] = dist[node] + time; + ways[neighbor] = ways[node]; + pq.push(Item { dist: dist[neighbor], node: neighbor }); + } else if dist[node] + time == dist[neighbor] { + ways[neighbor] = (ways[neighbor] + ways[node]) % MOD; + } + } + } + + ways[n - 1] as i32 + } +} diff --git a/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.swift b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.swift new file mode 100644 index 00000000..17d97391 --- /dev/null +++ b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.swift @@ -0,0 +1,41 @@ +class Solution { + func countPaths(_ n: Int, _ roads: [[Int]]) -> Int { + var graph = [[(neighbor: Int, time: Int)]](repeating: [], count: n) + for road in roads { + let u = road[0], v = road[1], time = road[2] + graph[u].append((neighbor: v, time: time)) + graph[v].append((neighbor: u, time: time)) + } + + var dist = [Int](repeating: Int.max, count: n) + var ways = [Int](repeating: 0, count: n) + dist[0] = 0 + ways[0] = 1 + + var pq = [(0, 0)] + + let MOD = 1_000_000_007 + + while !pq.isEmpty { + pq.sort { $0.0 < $1.0 } + let (d, node) = pq.removeFirst() + + if d > dist[node] { continue } + + for edge in graph[node] { + let neighbor = edge.neighbor + let time = edge.time + + if dist[node] + time < dist[neighbor] { + dist[neighbor] = dist[node] + time + ways[neighbor] = ways[node] + pq.append((dist[neighbor], neighbor)) + } else if dist[node] + time == dist[neighbor] { + ways[neighbor] = (ways[neighbor] + ways[node]) % MOD + } + } + } + + return ways[n-1] + } +} diff --git a/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.ts b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.ts new file mode 100644 index 00000000..83c1c921 --- /dev/null +++ b/tests/1501-2000/1976. number-of-ways-to-arrive-at-destination/sol.ts @@ -0,0 +1,35 @@ +function countPaths(n: number, roads: number[][]): number { + const graph: [number, number][][] = Array.from({ length: n }, () => []); + for (const [u, v, time] of roads) { + graph[u].push([v, time]); + graph[v].push([u, time]); + } + + const dist: number[] = new Array(n).fill(Number.MAX_SAFE_INTEGER); + const ways: number[] = new Array(n).fill(0); + dist[0] = 0; + ways[0] = 1; + + const pq: [number, number][] = [[0, 0]]; + + const MOD = 1_000_000_007; + + while (pq.length > 0) { + pq.sort((a, b) => a[0] - b[0]); + const [d, node] = pq.shift()!; + + if (d > dist[node]) continue; + + for (const [neighbor, time] of graph[node]) { + if (dist[node] + time < dist[neighbor]) { + dist[neighbor] = dist[node] + time; + ways[neighbor] = ways[node]; + pq.push([dist[neighbor], neighbor]); + } else if (dist[node] + time === dist[neighbor]) { + ways[neighbor] = (ways[neighbor] + ways[node]) % MOD; + } + } + } + + return ways[n - 1]; +} diff --git a/tests/1501-2000/1977. number-of-ways-to-separate-numbers/manifest.yaml b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/manifest.yaml new file mode 100644 index 00000000..4083cc63 --- /dev/null +++ b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/manifest.yaml @@ -0,0 +1,306 @@ +entry: + id: 1977 + title: "number-of-ways-to-separate-numbers" + params: + num: + type: string + call: + cpp: "Solution().numberOfCombinations({num})" + rust: "Solution::number_of_combinations({num})" + python3: "Solution().numberOfCombinations({num})" + python2: "Solution().numberOfCombinations({num})" + ruby: "number_of_combinations({num})" + java: "new Solution().numberOfCombinations({num})" + csharp: "new Solution().NumberOfCombinations({num})" + kotlin: "Solution().numberOfCombinations({num})" + go: "numberOfCombinations({num})" + dart: "Solution().numberOfCombinations({num})" + swift: "Solution().numberOfCombinations({num})" + typescript: "numberOfCombinations({num})" + +judge: + type: "exact" + +limits: + time_ms: 10000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().check(num, {result})" + checker: | + class Checker: + def check(self, num, result): + mod = 1000000007 + n = len(num) + dp = [[0] * (n + 1) for _ in range(n)] + for i in range(n): + if num[i] == "0": + continue + for j in range(i + 1, n + 1): + if i == 0: + dp[i][j] = 1 + continue + length = j - i + value = dp[i][j - 1] + if i - length >= 0 and num[i - length:i] <= num[i:j]: + value += dp[i - length][i] + if i - length + 1 >= 0 and num[i - length + 1:i] > num[i:j - 1]: + value += dp[i - length + 1][i] + dp[i][j] = value % mod + expected = sum(dp[i][n] for i in range(n)) % mod + return result == expected + +seed: 1977 + +tests: + - name: zero + in: + num: "0" + out: 0 + judge: + type: "exact" + - name: one + in: + num: "1" + out: 1 + judge: + type: "exact" + - name: nine + in: + num: "9" + out: 1 + judge: + type: "exact" + - name: leading-zero-example + in: + num: "094" + out: 0 + judge: + type: "exact" + - name: ten + in: + num: "10" + out: 1 + judge: + type: "exact" + - name: equal-two-digits + in: + num: "11" + out: 2 + judge: + type: "exact" + - name: increasing-two-digits + in: + num: "12" + out: 2 + judge: + type: "exact" + - name: decreasing-two-digits + in: + num: "21" + out: 1 + judge: + type: "exact" + - name: repeated-nines + in: + num: "99" + out: 2 + judge: + type: "exact" + - name: one-zero-zero + in: + num: "100" + out: 1 + judge: + type: "exact" + - name: one-zero-one + in: + num: "101" + out: 1 + judge: + type: "exact" + - name: one-one-zero + in: + num: "110" + out: 2 + judge: + type: "exact" + - name: three-equal + in: + num: "111" + out: 3 + judge: + type: "exact" + - name: example-one + in: + num: "327" + out: 2 + judge: + type: "exact" + - name: increasing-three + in: + num: "123" + out: 3 + judge: + type: "exact" + - name: decreasing-three + in: + num: "321" + out: 2 + judge: + type: "exact" + - name: four-equal + in: + num: "1111" + out: 5 + judge: + type: "exact" + - name: increasing-four + in: + num: "1234" + out: 5 + judge: + type: "exact" + - name: decreasing-four + in: + num: "4321" + out: 2 + judge: + type: "exact" + - name: trailing-zeros + in: + num: "1000" + out: 1 + judge: + type: "exact" + - name: internal-zero + in: + num: "1010" + out: 2 + judge: + type: "exact" + - name: zero-suffix-after-one + in: + num: "1001" + out: 1 + judge: + type: "exact" + - name: mixed-four + in: + num: "1100" + out: 2 + judge: + type: "exact" + - name: palindrome-four + in: + num: "1221" + out: 4 + judge: + type: "exact" + - name: palindrome-five + in: + num: "12321" + out: 5 + judge: + type: "exact" + - name: descending-five + in: + num: "54321" + out: 3 + judge: + type: "exact" + - name: five-equal + in: + num: "11111" + out: 7 + judge: + type: "exact" + - name: five-nines + in: + num: "99999" + out: 7 + judge: + type: "exact" + - name: alternating-six + in: + num: "121212" + out: 8 + judge: + type: "exact" + - name: six-descending + in: + num: "987654" + out: 4 + judge: + type: "exact" + - name: seven-alternating + in: + num: "1010101" + out: 3 + judge: + type: "exact" + - name: seven-increasing + in: + num: "1234567" + out: 15 + judge: + type: "exact" + - name: pi-prefix + in: + num: "31415926" + out: 10 + judge: + type: "exact" + - name: eight-nines + in: + num: "99999999" + out: 22 + judge: + type: "exact" + - name: nine-increasing + in: + num: "123456789" + out: 30 + judge: + type: "exact" + - name: generator-short + in: + num: + gen: "str" + len: 120 + alphabet: "123456789" + judge: + type: "exact" + - name: generator-medium + in: + num: + gen: "str" + len: 500 + alphabet: "0123456789" + judge: + type: "exact" + - name: generator-large-one + in: + num: + gen: "str" + len: 2000 + alphabet: "123456789" + judge: + type: "exact" + - name: generator-large-two + in: + num: + gen: "str" + len: 3000 + alphabet: "0123456789" + judge: + type: "exact" + - name: generator-near-maximum + in: + num: + gen: "str" + len: 3500 + alphabet: "123456789" + judge: + type: "exact" diff --git a/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.cpp b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.cpp new file mode 100644 index 00000000..e5751a0e --- /dev/null +++ b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int numberOfCombinations(string num) { + int n = num.size(); + const int MOD = 1000000007; + vector> dp(n, vector(n + 1, 0)); + for (int i = 0; i < n; ++i) { + if (num[i] != '0') { + for (int j = i + 1; j <= n; ++j) { + if (i == 0) { + dp[i][j] = 1; + } else { + int length = j - i; + dp[i][j] = dp[i][j - 1]; + if (i - length >= 0 && num.substr(i - length, length) <= num.substr(i, length)) { + dp[i][j] += dp[i - length][i]; + } + if (i - length + 1 >= 0 && num.substr(i - length + 1, length - 1) > num.substr(i, length - 1)) { + dp[i][j] += dp[i - length + 1][i]; + } + dp[i][j] %= MOD; + } + } + } + } + long long ans = 0; + for (int i = 0; i < n; ++i) { + ans = (ans + dp[i][n]) % MOD; + } + return (int)ans; + } +}; diff --git a/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.cs b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.cs new file mode 100644 index 00000000..e701ae90 --- /dev/null +++ b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.cs @@ -0,0 +1,31 @@ +public class Solution { + public int NumberOfCombinations(string num) { + int n = num.Length; + const int MOD = 1000000007; + long[,] dp = new long[n, n + 1]; + for (int i = 0; i < n; i++) { + if (num[i] != '0') { + for (int j = i + 1; j <= n; j++) { + if (i == 0) { + dp[i, j] = 1; + } else { + int length = j - i; + dp[i, j] = dp[i, j - 1]; + if (i - length >= 0 && string.CompareOrdinal(num.Substring(i - length, length), num.Substring(i, length)) <= 0) { + dp[i, j] += dp[i - length, i]; + } + if (i - length + 1 >= 0 && string.CompareOrdinal(num.Substring(i - length + 1, length - 1), num.Substring(i, length - 1)) > 0) { + dp[i, j] += dp[i - length + 1, i]; + } + dp[i, j] %= MOD; + } + } + } + } + long ans = 0; + for (int i = 0; i < n; i++) { + ans = (ans + dp[i, n]) % MOD; + } + return (int)ans; + } +} diff --git a/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.dart b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.dart new file mode 100644 index 00000000..4f20afd7 --- /dev/null +++ b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.dart @@ -0,0 +1,30 @@ +class Solution { + int numberOfCombinations(String num) { + int n = num.length; + const int MOD = 1000000007; + List> dp = List.generate(n, (_) => List.filled(n + 1, 0)); + for (int i = 0; i < n; i++) { + if (num[i] != '0') { + for (int j = i + 1; j <= n; j++) { + if (i == 0) { + dp[i][j] = 1; + } else { + int length = j - i; + dp[i][j] = dp[i][j - 1]; + if (i - length >= 0 && num.substring(i - length, i).compareTo(num.substring(i, j)) <= 0) { + dp[i][j] = (dp[i][j] + dp[i - length][i]) % MOD; + } + if (i - length + 1 >= 0 && num.substring(i - length + 1, i).compareTo(num.substring(i, j - 1)) > 0) { + dp[i][j] = (dp[i][j] + dp[i - length + 1][i]) % MOD; + } + } + } + } + } + int ans = 0; + for (int i = 0; i < n; i++) { + ans = (ans + dp[i][n]) % MOD; + } + return ans; + } +} diff --git a/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.go b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.go new file mode 100644 index 00000000..2946054d --- /dev/null +++ b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.go @@ -0,0 +1,32 @@ +func numberOfCombinations(num string) int { + n := len(num) + const MOD = 1000000007 + dp := make([][]int64, n) + for i := range dp { + dp[i] = make([]int64, n+1) + } + for i := 0; i < n; i++ { + if num[i] != '0' { + for j := i + 1; j <= n; j++ { + if i == 0 { + dp[i][j] = 1 + } else { + length := j - i + dp[i][j] = dp[i][j-1] + if i-length >= 0 && num[i-length:i] <= num[i:j] { + dp[i][j] += dp[i-length][i] + } + if i-length+1 >= 0 && num[i-length+1:i] > num[i:j-1] { + dp[i][j] += dp[i-length+1][i] + } + dp[i][j] %= MOD + } + } + } + } + var ans int64 + for i := 0; i < n; i++ { + ans = (ans + dp[i][n]) % MOD + } + return int(ans) +} diff --git a/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.java b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.java new file mode 100644 index 00000000..fff01469 --- /dev/null +++ b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.java @@ -0,0 +1,31 @@ +class Solution { + public int numberOfCombinations(String num) { + int n = num.length(); + long MOD = 1_000_000_007L; + long[][] dp = new long[n][n + 1]; + for (int i = 0; i < n; i++) { + if (num.charAt(i) != '0') { + for (int j = i + 1; j <= n; j++) { + if (i == 0) { + dp[i][j] = 1; + } else { + int length = j - i; + dp[i][j] = dp[i][j - 1]; + if (i - length >= 0 && num.substring(i - length, i).compareTo(num.substring(i, j)) <= 0) { + dp[i][j] += dp[i - length][i]; + } + if (i - length + 1 >= 0 && num.substring(i - length + 1, i).compareTo(num.substring(i, j - 1)) > 0) { + dp[i][j] += dp[i - length + 1][i]; + } + dp[i][j] %= MOD; + } + } + } + } + long ans = 0; + for (int i = 0; i < n; i++) { + ans = (ans + dp[i][n]) % MOD; + } + return (int)ans; + } +} diff --git a/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.kt b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.kt new file mode 100644 index 00000000..9f329bff --- /dev/null +++ b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.kt @@ -0,0 +1,31 @@ +class Solution { + fun numberOfCombinations(num: String): Int { + val n = num.length + val MOD = 1_000_000_007L + val dp = Array(n) { LongArray(n + 1) } + for (i in 0 until n) { + if (num[i] != '0') { + for (j in i + 1..n) { + if (i == 0) { + dp[i][j] = 1 + } else { + val length = j - i + dp[i][j] = dp[i][j - 1] + if (i - length >= 0 && num.substring(i - length, i) <= num.substring(i, j)) { + dp[i][j] += dp[i - length][i] + } + if (i - length + 1 >= 0 && num.substring(i - length + 1, i) > num.substring(i, j - 1)) { + dp[i][j] += dp[i - length + 1][i] + } + dp[i][j] %= MOD + } + } + } + } + var ans = 0L + for (i in 0 until n) { + ans = (ans + dp[i][n]) % MOD + } + return ans.toInt() + } +} diff --git a/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.py b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.py new file mode 100644 index 00000000..9fd61010 --- /dev/null +++ b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.py @@ -0,0 +1,25 @@ +class Solution: + def numberOfCombinations(self, num: str) -> int: + n = len(num) + MOD = 10**9 + 7 + dp = [[0] * (n + 1) for _ in range(n)] + for i in range(n): + if num[i] != "0": + for j in range(i + 1, n + 1): + if i == 0: + dp[i][j] = 1 + else: + length = j - i + # Case 1: j-1 len number would be simply carry forward as that is a solved sub problem + dp[i][j] = dp[i][j - 1] + # Case 2: if equal len num on left of i is <= right of i + if i - length >= 0 and num[i - length : i] <= num[i:j]: + dp[i][j] += dp[i - length][i] + # Case 3: if 1 len smaller num of left of i > 1 len smaller num of right of i that means it wasn't considered in the previous sub problem but can be considered not as the cur number on the right side of i for which we are evaluating has more digits than on the left. + # You only have to check 1 digit because of Case 1 + if ( + i - length + 1 >= 0 + and num[i - length + 1 : i] > num[i : j - 1] + ): + dp[i][j] += dp[i - length + 1][i] + return sum(dp[i][n] for i in range(n)) % MOD diff --git a/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.py2 b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.py2 new file mode 100644 index 00000000..7ac01eff --- /dev/null +++ b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def numberOfCombinations(self, num): + """ + :type num: str + :rtype: int + """ + n = len(num) + MOD = 10**9 + 7 + dp = [[0]*(n+1) for _ in range(n)] + for i in range(n): + if num[i] != "0": + for j in range(i+1, n+1): + if i == 0: + dp[i][j] = 1 + else: + length = j - i + dp[i][j] = dp[i][j-1] + if i - length >= 0 and num[i-length:i] <= num[i:j]: + dp[i][j] += dp[i-length][i] + if i - length + 1 >= 0 and num[i-length+1:i] > num[i:j-1]: + dp[i][j] += dp[i-length+1][i] + dp[i][j] %= MOD + return sum(dp[i][n] for i in range(n)) % MOD diff --git a/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.rb b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.rb new file mode 100644 index 00000000..c2b338c1 --- /dev/null +++ b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.rb @@ -0,0 +1,29 @@ +# @param {String} num +# @return {Integer} +def number_of_combinations(num) + n = num.length + mod = 10**9 + 7 + dp = Array.new(n) { Array.new(n + 1, 0) } + (0...n).each do |i| + if num[i] != '0' + (i + 1..n).each do |j| + if i == 0 + dp[i][j] = 1 + else + length = j - i + dp[i][j] = dp[i][j - 1] + if i - length >= 0 && num[i - length, length] <= num[i, length] + dp[i][j] += dp[i - length][i] + end + if i - length + 1 >= 0 && num[i - length + 1, length - 1] > num[i, length - 1] + dp[i][j] += dp[i - length + 1][i] + end + dp[i][j] %= mod + end + end + end + end + ans = 0 + (0...n).each { |i| ans = (ans + dp[i][n]) % mod } + ans +end diff --git a/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.rs b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.rs new file mode 100644 index 00000000..d5ae53e3 --- /dev/null +++ b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.rs @@ -0,0 +1,31 @@ +impl Solution { + pub fn number_of_combinations(num: String) -> i32 { + let n = num.len(); + let MOD = 1_000_000_007i64; + let bytes = num.as_bytes(); + let mut dp = vec![vec![0i64; n + 1]; n]; + for i in 0..n { + if bytes[i] != b'0' { + for j in i + 1..=n { + if i == 0 { + dp[i][j] = 1; + } else { + let length = j - i; + dp[i][j] = dp[i][j - 1]; + if i >= length && &num[i - length..i] <= &num[i..j] { + dp[i][j] = (dp[i][j] + dp[i - length][i]) % MOD; + } + if i + 1 >= length && &num[i - length + 1..i] > &num[i..j - 1] { + dp[i][j] = (dp[i][j] + dp[i - length + 1][i]) % MOD; + } + } + } + } + } + let mut ans = 0i64; + for i in 0..n { + ans = (ans + dp[i][n]) % MOD; + } + ans as i32 + } +} diff --git a/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.swift b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.swift new file mode 100644 index 00000000..d2527cbd --- /dev/null +++ b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.swift @@ -0,0 +1,50 @@ +class Solution { + func numberOfCombinations(_ num: String) -> Int { + let n = num.count + if n == 0 || num.first == "0" { return 0 } + let mod = 1_000_000_007 + let chars = Array(num) + var lcp = [[Int]](repeating: [Int](repeating: 0, count: n + 1), count: n + 1) + if n > 0 { + for i in stride(from: n - 1, through: 0, by: -1) { + for j in stride(from: n - 1, through: 0, by: -1) where chars[i] == chars[j] { + lcp[i][j] = lcp[i + 1][j + 1] + 1 + } + } + } + + func leq(_ a: Int, _ b: Int, _ length: Int) -> Bool { + let common = min(lcp[a][b], length) + if common == length { return true } + return chars[a + common] < chars[b + common] + } + func greater(_ a: Int, _ b: Int, _ length: Int) -> Bool { + if length == 0 { return false } + let common = min(lcp[a][b], length) + if common == length { return false } + return chars[a + common] > chars[b + common] + } + + var dp = [[Int]](repeating: [Int](repeating: 0, count: n + 1), count: n) + for i in 0..= 0 && leq(i - length, i, length) { + value += dp[i - length][i] + if value >= mod { value -= mod } + } + if i - length + 1 >= 0 && greater(i - length + 1, i, length - 1) { + value += dp[i - length + 1][i] + if value >= mod { value -= mod } + } + dp[i][j] = value + } + } + return dp.reduce(0) { ($0 + $1[n]) % mod } + } +} diff --git a/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.ts b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.ts new file mode 100644 index 00000000..00c52a32 --- /dev/null +++ b/tests/1501-2000/1977. number-of-ways-to-separate-numbers/sol.ts @@ -0,0 +1,34 @@ +function numberOfCombinations(num: string): number { + const n = num.length; + const MOD = 1000000007; + const dp: number[][] = Array.from({ length: n }, () => Array(n + 1).fill(0)); + for (let i = 0; i < n; i++) { + if (num[i] !== "0") { + for (let j = i + 1; j <= n; j++) { + if (i === 0) { + dp[i][j] = 1; + } else { + const length = j - i; + dp[i][j] = dp[i][j - 1]; + if ( + i - length >= 0 && + num.substring(i - length, i) <= num.substring(i, j) + ) { + dp[i][j] = (dp[i][j] + dp[i - length][i]) % MOD; + } + if ( + i - length + 1 >= 0 && + num.substring(i - length + 1, i) > num.substring(i, j - 1) + ) { + dp[i][j] = (dp[i][j] + dp[i - length + 1][i]) % MOD; + } + } + } + } + } + let ans = 0; + for (let i = 0; i < n; i++) { + ans = (ans + dp[i][n]) % MOD; + } + return ans; +} diff --git a/tests/1501-2000/1979. find-greatest-common-divisor-of-array/manifest.yaml b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/manifest.yaml new file mode 100644 index 00000000..30cecf50 --- /dev/null +++ b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/manifest.yaml @@ -0,0 +1,241 @@ +entry: + id: 1979 + title: "find-greatest-common-divisor-of-array" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().findGCD({nums})" + rust: "Solution::find_gcd({nums})" + python3: "Solution().findGCD({nums})" + python2: "Solution().findGCD({nums})" + ruby: "find_gcd({nums})" + java: "new Solution().findGCD({nums})" + csharp: "new Solution().FindGCD({nums})" + kotlin: "Solution().findGCD({nums})" + go: "findGCD({nums})" + dart: "Solution().findGCD({nums})" + swift: "Solution().findGCD({nums})" + typescript: "findGCD({nums})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().findGCD(nums, {result})" + checker: | + from math import gcd + + class Checker: + def findGCD(self, nums, result): + if not isinstance(nums, list) or len(nums) < 2: + return False + if any(not isinstance(x, int) or isinstance(x, bool) or x < 1 or x > 1000 for x in nums): + return False + return isinstance(result, int) and not isinstance(result, bool) and result == gcd(min(nums), max(nums)) + +seed: 1979 + +tests: + - name: "example_one" + in: + nums: [2, 5, 6, 9, 10] + out: 2 + - name: "example_two" + in: + nums: [7, 5, 6, 8, 3] + out: 1 + - name: "example_three" + in: + nums: [3, 3] + out: 3 + - name: "minimum_length_equal" + in: + nums: [1, 1] + out: 1 + - name: "minimum_values" + in: + nums: [1, 2, 1, 2] + out: 1 + - name: "maximum_values" + in: + nums: [1000, 1000, 1000] + out: 1000 + - name: "min_max_coprime" + in: + nums: [1, 1000] + out: 1 + - name: "min_max_equal" + in: + nums: [840, 840, 840, 840] + out: 840 + - name: "duplicates_with_extremes" + in: + nums: [12, 12, 18, 12, 30] + out: 6 + - name: "unordered_input" + in: + nums: [48, 18, 30, 6, 42] + out: 6 + - name: "gcd_two" + in: + nums: [36, 84] + out: 12 + - name: "gcd_three" + in: + nums: [72, 120, 168] + out: 24 + - name: "prime_extremes" + in: + nums: [997, 991, 997] + out: 1 + - name: "same_prime" + in: + nums: [997, 997] + out: 997 + - name: "power_of_two" + in: + nums: [16, 32, 64, 128] + out: 16 + - name: "mixed_even" + in: + nums: [14, 28, 42, 70, 98] + out: 14 + - name: "mixed_odd" + in: + nums: [15, 45, 75, 105] + out: 15 + - name: "large_gcd_four" + in: + nums: [400, 800, 1000, 600] + out: 200 + - name: "large_gcd_six" + in: + nums: [600, 720, 840, 900] + out: 300 + - name: "extreme_range" + in: + nums: [1000, 1, 500, 250] + out: 1 + - name: "range_with_gcd_two" + in: + nums: [998, 2, 250, 500] + out: 2 + - name: "range_with_gcd_three" + in: + nums: [999, 3, 333, 666] + out: 3 + - name: "range_with_gcd_five" + in: + nums: [995, 5, 250, 500] + out: 5 + - name: "range_with_gcd_seven" + in: + nums: [994, 7, 350, 700] + out: 7 + - name: "range_with_gcd_eight" + in: + nums: [992, 8, 256, 512] + out: 8 + - name: "single_outlier_low" + in: + nums: [360, 360, 360, 24] + out: 24 + - name: "single_outlier_high" + in: + nums: [24, 24, 24, 360] + out: 24 + - name: "minimum_and_repeated_max" + in: + nums: [10, 1000, 1000, 1000] + out: 10 + - name: "all_multiples_of_25" + in: + nums: [25, 125, 250, 500, 1000] + out: 25 + - name: "all_multiples_of_37" + in: + nums: [37, 111, 259, 370, 999] + out: 37 + - name: "nontrivial_factor_pair" + in: + nums: [221, 663, 884] + out: 221 + - name: "gcd_twelve" + in: + nums: [12, 120, 600, 996] + out: 12 + - name: "gcd_twentyfour" + in: + nums: [48, 240, 720, 984] + out: 24 + - name: "gcd_thirtysix" + in: + nums: [36, 360, 720, 972] + out: 36 + - name: "gcd_forty" + in: + nums: [40, 200, 400, 1000] + out: 40 + - name: "generated_small" + in: + nums: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + elemType: "int" + - name: "generated_medium" + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + elemType: "int" + - name: "generated_max_a" + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + elemType: "int" + - name: "generated_max_b" + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + elemType: "int" + - name: "generated_max_c" + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000 + distinct: false + elemType: "int" diff --git a/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.cpp b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.cpp new file mode 100644 index 00000000..6714acf0 --- /dev/null +++ b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int findGCD(vector& nums) { + int a = *min_element(nums.begin(), nums.end()); + int b = *max_element(nums.begin(), nums.end()); + return gcd(a, b); + } + +private: + int gcd(int a, int b) { + while (b != 0) { + int temp = b; + b = a % b; + a = temp; + } + return a; + } +}; diff --git a/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.cs b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.cs new file mode 100644 index 00000000..7e4b619d --- /dev/null +++ b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public int FindGCD(int[] nums) { + int a = nums.Min(); + int b = nums.Max(); + return Gcd(a, b); + } + + private int Gcd(int a, int b) { + while (b != 0) { + int temp = b; + b = a % b; + a = temp; + } + return a; + } +} diff --git a/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.dart b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.dart new file mode 100644 index 00000000..0bb3c52d --- /dev/null +++ b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.dart @@ -0,0 +1,16 @@ +class Solution { + int findGCD(List nums) { + int a = nums.reduce((x, y) => x < y ? x : y); + int b = nums.reduce((x, y) => x > y ? x : y); + return _gcd(a, b); + } + + int _gcd(int a, int b) { + while (b != 0) { + int temp = b; + b = a % b; + a = temp; + } + return a; + } +} diff --git a/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.go b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.go new file mode 100644 index 00000000..132fd8c5 --- /dev/null +++ b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.go @@ -0,0 +1,20 @@ +func findGCD(nums []int) int { + a := nums[0] + b := nums[0] + for _, v := range nums { + if v < a { + a = v + } + if v > b { + b = v + } + } + return gcd(a, b) +} + +func gcd(a, b int) int { + for b != 0 { + a, b = b, a%b + } + return a +} diff --git a/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.java b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.java new file mode 100644 index 00000000..2d3bffbc --- /dev/null +++ b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.java @@ -0,0 +1,20 @@ +class Solution { + public int findGCD(int[] nums) { + int a = Integer.MAX_VALUE; + int b = Integer.MIN_VALUE; + for (int num : nums) { + a = Math.min(a, num); + b = Math.max(b, num); + } + return gcd(a, b); + } + + private int gcd(int a, int b) { + while (b != 0) { + int temp = b; + b = a % b; + a = temp; + } + return a; + } +} diff --git a/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.kt b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.kt new file mode 100644 index 00000000..22128eeb --- /dev/null +++ b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.kt @@ -0,0 +1,18 @@ +class Solution { + fun findGCD(nums: IntArray): Int { + val a = nums.min() + val b = nums.max() + return gcd(a, b) + } + + private fun gcd(a: Int, b: Int): Int { + var x = a + var y = b + while (y != 0) { + val temp = y + y = x % y + x = temp + } + return x + } +} diff --git a/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.py b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.py new file mode 100644 index 00000000..4d19f3d9 --- /dev/null +++ b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.py @@ -0,0 +1,6 @@ +from math import gcd + + +class Solution: + def findGCD(self, nums: List[int]) -> int: + return gcd(min(nums), max(nums)) diff --git a/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.py2 b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.py2 new file mode 100644 index 00000000..d1f29ecd --- /dev/null +++ b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.py2 @@ -0,0 +1,12 @@ +class Solution(object): + def findGCD(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + return self.gcd(min(nums), max(nums)) + + def gcd(self, a, b): + while b: + a, b = b, a % b + return a diff --git a/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.rb b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.rb new file mode 100644 index 00000000..1f48f2c1 --- /dev/null +++ b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.rb @@ -0,0 +1,10 @@ +# @param {Integer[]} nums +# @return {Integer} +def find_gcd(nums) + a = nums.min + b = nums.max + while b != 0 + a, b = b, a % b + end + a +end diff --git a/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.rs b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.rs new file mode 100644 index 00000000..8e86a8af --- /dev/null +++ b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn find_gcd(nums: Vec) -> i32 { + let a = *nums.iter().min().unwrap(); + let b = *nums.iter().max().unwrap(); + Self::gcd(a, b) + } + + fn gcd(mut a: i32, mut b: i32) -> i32 { + while b != 0 { + let temp = b; + b = a % b; + a = temp; + } + a + } +} diff --git a/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.swift b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.swift new file mode 100644 index 00000000..72252300 --- /dev/null +++ b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.swift @@ -0,0 +1,18 @@ +class Solution { + func findGCD(_ nums: [Int]) -> Int { + let a = nums.min()! + let b = nums.max()! + return gcd(a, b) + } + + private func gcd(_ a: Int, _ b: Int) -> Int { + var x = a + var y = b + while y != 0 { + let temp = y + y = x % y + x = temp + } + return x + } +} diff --git a/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.ts b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.ts new file mode 100644 index 00000000..5a426cad --- /dev/null +++ b/tests/1501-2000/1979. find-greatest-common-divisor-of-array/sol.ts @@ -0,0 +1,14 @@ +function findGCD(nums: number[]): number { + const a = Math.min(...nums); + const b = Math.max(...nums); + return gcd(a, b); +} + +function gcd(a: number, b: number): number { + while (b !== 0) { + const temp = b; + b = a % b; + a = temp; + } + return a; +} diff --git a/tests/1501-2000/1980. find-unique-binary-string/manifest.yaml b/tests/1501-2000/1980. find-unique-binary-string/manifest.yaml new file mode 100644 index 00000000..06559934 --- /dev/null +++ b/tests/1501-2000/1980. find-unique-binary-string/manifest.yaml @@ -0,0 +1,472 @@ +entry: + id: 1980 + title: "find-unique-binary-string" + params: + nums: + type: array + items: + type: string + call: + cpp: "Solution().findDifferentBinaryString({nums})" + rust: "Solution::find_different_binary_string({nums})" + python3: "Solution().findDifferentBinaryString({nums})" + python2: "Solution().findDifferentBinaryString({nums})" + ruby: "find_different_binary_string({nums})" + java: "new Solution().findDifferentBinaryString({nums})" + csharp: "new Solution().FindDifferentBinaryString({nums})" + kotlin: "Solution().findDifferentBinaryString({nums})" + go: "findDifferentBinaryString({nums})" + dart: "Solution().findDifferentBinaryString({nums})" + swift: "Solution().findDifferentBinaryString({nums})" + typescript: "findDifferentBinaryString({nums})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().findDifferentBinaryString(nums, {result})" + checker: | + class Checker: + def findDifferentBinaryString(self, nums, result): + if not isinstance(result, str): + return False + n = len(nums) + if len(result) != n or any(c not in "01" for c in result): + return False + return result not in set(nums) + +seed: 1980 + +tests: + - name: "single_zero" + in: + nums: ["0"] + - name: "single_one" + in: + nums: ["1"] + - name: "two_mixed" + in: + nums: ["01", "10"] + - name: "two_low" + in: + nums: ["00", "01"] + - name: "two_high" + in: + nums: ["10", "11"] + - name: "three_prefix" + in: + nums: ["000", "001", "010"] + - name: "three_suffix" + in: + nums: ["101", "110", "111"] + - name: "four_even" + in: + nums: ["0000", "0010", "0100", "0110"] + - name: "four_odd" + in: + nums: ["0001", "0011", "0101", "0111"] + - name: "five_low" + in: + nums: ["00000", "00001", "00010", "00011", "00100"] + - name: "five_high" + in: + nums: ["11011", "11100", "11101", "11110", "11111"] + - name: "six_alternating" + in: + nums: ["000000", "010101", "101010", "111111", "001100", "110011"] + - name: "six_blocks" + in: + nums: ["000000", "000111", "111000", "111111", "001111", "110000"] + - name: "seven_low" + in: + nums: + [ + "0000000", + "0000001", + "0000010", + "0000011", + "0000100", + "0000101", + "0000110", + ] + - name: "seven_high" + in: + nums: + [ + "1111001", + "1111010", + "1111011", + "1111100", + "1111101", + "1111110", + "1111111", + ] + - name: "eight_first" + in: + nums: + [ + "00000000", + "00000001", + "00000010", + "00000011", + "00000100", + "00000101", + "00000110", + "00000111", + ] + - name: "eight_last" + in: + nums: + [ + "11111000", + "11111001", + "11111010", + "11111011", + "11111100", + "11111101", + "11111110", + "11111111", + ] + - name: "nine_patterns" + in: + nums: + [ + "000000000", + "010101010", + "101010101", + "111111111", + "001100110", + "110011001", + "000111000", + "111000111", + "100000001", + ] + - name: "ten_low" + in: + nums: + [ + "0000000000", + "0000000001", + "0000000010", + "0000000011", + "0000000100", + "0000000101", + "0000000110", + "0000000111", + "0000001000", + "0000001001", + ] + - name: "ten_high" + in: + nums: + [ + "1111110110", + "1111110111", + "1111111000", + "1111111001", + "1111111010", + "1111111011", + "1111111100", + "1111111101", + "1111111110", + "1111111111", + ] + - name: "eleven_mixed" + in: + nums: + [ + "00000000000", + "11111111111", + "01010101010", + "10101010101", + "00110011001", + "11001100110", + "00011100011", + "11100011100", + "10000000001", + "01111111110", + "00001111000", + ] + - name: "twelve_low" + in: + nums: + [ + "000000000000", + "000000000001", + "000000000010", + "000000000011", + "000000000100", + "000000000101", + "000000000110", + "000000000111", + "000000001000", + "000000001001", + "000000001010", + "000000001011", + ] + - name: "twelve_high" + in: + nums: + [ + "111111111100", + "111111111101", + "111111111110", + "111111111111", + "111111111000", + "111111111001", + "111111111010", + "111111111011", + "111111110100", + "111111110101", + "111111110110", + "111111110111", + ] + - name: "thirteen_mixed" + in: + nums: + [ + "0000000000000", + "1111111111111", + "0101010101010", + "1010101010101", + "0011001100110", + "1100110011001", + "0001110001110", + "1110001110001", + "1000000000001", + "0111111111110", + "0000111100000", + "1111000011111", + "0011111111100", + ] + - name: "fourteen_low" + in: + nums: + [ + "00000000000000", + "00000000000001", + "00000000000010", + "00000000000011", + "00000000000100", + "00000000000101", + "00000000000110", + "00000000000111", + "00000000001000", + "00000000001001", + "00000000001010", + "00000000001011", + "00000000001100", + "00000000001101", + ] + - name: "fourteen_high" + in: + nums: + [ + "11111111111100", + "11111111111101", + "11111111111110", + "11111111111111", + "11111111111000", + "11111111111001", + "11111111111010", + "11111111111011", + "11111111110100", + "11111111110101", + "11111111110110", + "11111111110111", + "11111111110000", + "11111111110001", + ] + - name: "fifteen_mixed" + in: + nums: + [ + "000000000000000", + "111111111111111", + "010101010101010", + "101010101010101", + "001100110011001", + "110011001100110", + "000111000111000", + "111000111000111", + "100000000000001", + "011111111111110", + "000011110000111", + "111100001111000", + "001111111110000", + "110000000001111", + "010000000000010", + ] + - name: "sixteen_low" + in: + nums: + [ + "0000000000000000", + "0000000000000001", + "0000000000000010", + "0000000000000011", + "0000000000000100", + "0000000000000101", + "0000000000000110", + "0000000000000111", + "0000000000001000", + "0000000000001001", + "0000000000001010", + "0000000000001011", + "0000000000001100", + "0000000000001101", + "0000000000001110", + "0000000000001111", + ] + - name: "sixteen_high" + in: + nums: + [ + "1111111111110000", + "1111111111110001", + "1111111111110010", + "1111111111110011", + "1111111111110100", + "1111111111110101", + "1111111111110110", + "1111111111110111", + "1111111111111000", + "1111111111111001", + "1111111111111010", + "1111111111111011", + "1111111111111100", + "1111111111111101", + "1111111111111110", + "1111111111111111", + ] + - name: "sixteen_alternating" + in: + nums: + [ + "0000000000000000", + "1111111111111111", + "0101010101010101", + "1010101010101010", + "0011001100110011", + "1100110011001100", + "0001110001110001", + "1110001110001110", + "1000000000000001", + "0111111111111110", + "0000111100001111", + "1111000011110000", + "0011111111100000", + "1100000000011111", + "0100000000000010", + "1011111111111101", + ] + - name: "sixteen_sparse_ones" + in: + nums: + [ + "0000000000000000", + "0000000000000001", + "0000000000000011", + "0000000000000111", + "0000000000001111", + "0000000000011111", + "0000000000111111", + "0000000001111111", + "0000000011111111", + "0000000111111111", + "0000001111111111", + "0000011111111111", + "0000111111111111", + "0001111111111111", + "0011111111111111", + "0111111111111111", + ] + - name: "sixteen_sparse_zeros" + in: + nums: + [ + "1111111111111111", + "1111111111111110", + "1111111111111100", + "1111111111111000", + "1111111111110000", + "1111111111100000", + "1111111111000000", + "1111111110000000", + "1111111100000000", + "1111111000000000", + "1111110000000000", + "1111100000000000", + "1111000000000000", + "1110000000000000", + "1100000000000000", + "1000000000000000", + ] + - name: "sixteen_single_one_positions" + in: + nums: + [ + "0000000000000001", + "0000000000000010", + "0000000000000100", + "0000000000001000", + "0000000000010000", + "0000000000100000", + "0000000001000000", + "0000000010000000", + "0000000100000000", + "0000001000000000", + "0000010000000000", + "0000100000000000", + "0001000000000000", + "0010000000000000", + "0100000000000000", + "1000000000000000", + ] + - name: "sixteen_complement_pairs" + in: + nums: + [ + "0000000000000000", + "1111111111111111", + "0000000011111111", + "1111111100000000", + "0011001100110011", + "1100110011001100", + "0101010101010101", + "1010101010101010", + "0000111100001111", + "1111000011110000", + "0011110000111100", + "1100001111000011", + "0110011001100110", + "1001100110011001", + "0000001111111100", + "1111110000000011", + ] + - name: "sixteen_reversed_prefixes" + in: + nums: + [ + "0000000000000000", + "1000000000000000", + "0100000000000000", + "1100000000000000", + "0010000000000000", + "1010000000000000", + "0110000000000000", + "1110000000000000", + "0001000000000000", + "1001000000000000", + "0101000000000000", + "1101000000000000", + "0011000000000000", + "1011000000000000", + "0111000000000000", + "1111000000000000", + ] diff --git a/tests/1501-2000/1980. find-unique-binary-string/sol.cpp b/tests/1501-2000/1980. find-unique-binary-string/sol.cpp new file mode 100644 index 00000000..206700cb --- /dev/null +++ b/tests/1501-2000/1980. find-unique-binary-string/sol.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + string findDifferentBinaryString(vector& nums) { + string result; + for (int i = 0; i < nums.size(); i++) { + result += (nums[i][i] == '0') ? '1' : '0'; + } + return result; + } +}; diff --git a/tests/1501-2000/1980. find-unique-binary-string/sol.cs b/tests/1501-2000/1980. find-unique-binary-string/sol.cs new file mode 100644 index 00000000..7e3c54ba --- /dev/null +++ b/tests/1501-2000/1980. find-unique-binary-string/sol.cs @@ -0,0 +1,9 @@ +public class Solution { + public string FindDifferentBinaryString(string[] nums) { + char[] result = new char[nums.Length]; + for (int i = 0; i < nums.Length; i++) { + result[i] = nums[i][i] == '0' ? '1' : '0'; + } + return new string(result); + } +} diff --git a/tests/1501-2000/1980. find-unique-binary-string/sol.dart b/tests/1501-2000/1980. find-unique-binary-string/sol.dart new file mode 100644 index 00000000..784d5584 --- /dev/null +++ b/tests/1501-2000/1980. find-unique-binary-string/sol.dart @@ -0,0 +1,9 @@ +class Solution { + String findDifferentBinaryString(List nums) { + return nums.asMap().entries.map((e) { + int i = e.key; + String s = e.value; + return s[i] == '0' ? '1' : '0'; + }).join(); + } +} diff --git a/tests/1501-2000/1980. find-unique-binary-string/sol.go b/tests/1501-2000/1980. find-unique-binary-string/sol.go new file mode 100644 index 00000000..7b0d1db0 --- /dev/null +++ b/tests/1501-2000/1980. find-unique-binary-string/sol.go @@ -0,0 +1,11 @@ +func findDifferentBinaryString(nums []string) string { + result := make([]byte, len(nums)) + for i, s := range nums { + if s[i] == '0' { + result[i] = '1' + } else { + result[i] = '0' + } + } + return string(result) +} diff --git a/tests/1501-2000/1980. find-unique-binary-string/sol.java b/tests/1501-2000/1980. find-unique-binary-string/sol.java new file mode 100644 index 00000000..4188d284 --- /dev/null +++ b/tests/1501-2000/1980. find-unique-binary-string/sol.java @@ -0,0 +1,10 @@ +class Solution { + public String findDifferentBinaryString(String[] nums) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < nums.length; i++) { + char c = nums[i].charAt(i); + sb.append(c == '0' ? '1' : '0'); + } + return sb.toString(); + } +} diff --git a/tests/1501-2000/1980. find-unique-binary-string/sol.kt b/tests/1501-2000/1980. find-unique-binary-string/sol.kt new file mode 100644 index 00000000..d24be473 --- /dev/null +++ b/tests/1501-2000/1980. find-unique-binary-string/sol.kt @@ -0,0 +1,5 @@ +class Solution { + fun findDifferentBinaryString(nums: Array): String { + return nums.mapIndexed { i, s -> if (s[i] == '0') '1' else '0' }.joinToString("") + } +} diff --git a/tests/1501-2000/1980. find-unique-binary-string/sol.py b/tests/1501-2000/1980. find-unique-binary-string/sol.py new file mode 100644 index 00000000..6a506ccb --- /dev/null +++ b/tests/1501-2000/1980. find-unique-binary-string/sol.py @@ -0,0 +1,3 @@ +class Solution: + def findDifferentBinaryString(self, nums: List[str]) -> str: + return "".join(chr(ord(x[i]) ^ 1) for i, x in enumerate(nums)) diff --git a/tests/1501-2000/1980. find-unique-binary-string/sol.py2 b/tests/1501-2000/1980. find-unique-binary-string/sol.py2 new file mode 100644 index 00000000..b9f8e19a --- /dev/null +++ b/tests/1501-2000/1980. find-unique-binary-string/sol.py2 @@ -0,0 +1,7 @@ +class Solution(object): + def findDifferentBinaryString(self, nums): + """ + :type nums: List[str] + :rtype: str + """ + return "".join(chr(ord(x[i])^1) for i, x in enumerate(nums)) diff --git a/tests/1501-2000/1980. find-unique-binary-string/sol.rb b/tests/1501-2000/1980. find-unique-binary-string/sol.rb new file mode 100644 index 00000000..d437ed70 --- /dev/null +++ b/tests/1501-2000/1980. find-unique-binary-string/sol.rb @@ -0,0 +1,5 @@ +# @param {String[]} nums +# @return {String} +def find_different_binary_string(nums) + nums.each_with_index.map { |x, i| x[i] == '0' ? '1' : '0' }.join +end diff --git a/tests/1501-2000/1980. find-unique-binary-string/sol.rs b/tests/1501-2000/1980. find-unique-binary-string/sol.rs new file mode 100644 index 00000000..496e5961 --- /dev/null +++ b/tests/1501-2000/1980. find-unique-binary-string/sol.rs @@ -0,0 +1,7 @@ +impl Solution { + pub fn find_different_binary_string(nums: Vec) -> String { + nums.iter().enumerate().map(|(i, s)| { + if s.as_bytes()[i] == b'0' { '1' } else { '0' } + }).collect() + } +} diff --git a/tests/1501-2000/1980. find-unique-binary-string/sol.swift b/tests/1501-2000/1980. find-unique-binary-string/sol.swift new file mode 100644 index 00000000..cdb410a3 --- /dev/null +++ b/tests/1501-2000/1980. find-unique-binary-string/sol.swift @@ -0,0 +1,8 @@ +class Solution { + func findDifferentBinaryString(_ nums: [String]) -> String { + return nums.enumerated().map { i, s in + let index = s.index(s.startIndex, offsetBy: i) + return s[index] == "0" ? "1" : "0" + }.joined() + } +} diff --git a/tests/1501-2000/1980. find-unique-binary-string/sol.ts b/tests/1501-2000/1980. find-unique-binary-string/sol.ts new file mode 100644 index 00000000..2d087f1e --- /dev/null +++ b/tests/1501-2000/1980. find-unique-binary-string/sol.ts @@ -0,0 +1,3 @@ +function findDifferentBinaryString(nums: string[]): string { + return nums.map((s, i) => (s[i] === "0" ? "1" : "0")).join(""); +} diff --git a/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/manifest.yaml b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/manifest.yaml new file mode 100644 index 00000000..9e9df9ae --- /dev/null +++ b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/manifest.yaml @@ -0,0 +1,419 @@ +entry: + id: 1981 + title: "minimize-the-difference-between-target-and-chosen-elements" + params: + mat: + type: array + items: + type: array + items: + type: int + target: + type: int + call: + cpp: "Solution().minimizeTheDifference({mat}, {target})" + rust: "Solution::minimize_the_difference({mat}, {target})" + python3: "Solution().minimizeTheDifference({mat}, {target})" + python2: "Solution().minimizeTheDifference({mat}, {target})" + ruby: "minimize_the_difference({mat}, {target})" + java: "new Solution().minimizeTheDifference({mat}, {target})" + csharp: "new Solution().MinimizeTheDifference({mat}, {target})" + kotlin: "Solution().minimizeTheDifference({mat}, {target})" + go: "minimizeTheDifference({mat}, {target})" + dart: "Solution().minimizeTheDifference({mat}, {target})" + swift: "Solution().minimizeTheDifference({mat}, {target})" + typescript: "minimizeTheDifference({mat}, {target})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().minimizeTheDifference(mat, target, {result})" + checker: | + class Checker: + def minimizeTheDifference(self, mat, target, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + sums = {0} + for row in mat: + nxt = set() + for total in sums: + for value in row: + nxt.add(total + value) + sums = nxt + return result == min(abs(total - target) for total in sums) + +seed: 1981 + +tests: + - name: "example_1_exact" + in: + mat: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + target: 13 + out: 0 + - name: "example_2_exact" + in: + mat: + - [1] + - [2] + - [3] + target: 100 + out: 94 + - name: "example_3_exact" + in: + mat: + - [1, 2, 9, 8, 7] + target: 6 + out: 1 + - name: "single_one_exact" + in: + mat: + - [1] + target: 1 + out: 0 + - name: "single_far_below" + in: + mat: + - [70] + target: 1 + out: 69 + - name: "single_far_above" + in: + mat: + - [1] + target: 800 + out: 799 + - name: "one_row_exact_middle" + in: + mat: + - [2, 10, 17, 31] + target: 17 + out: 0 + - name: "one_row_nearest_lower" + in: + mat: + - [4, 12, 20] + target: 15 + out: 3 + - name: "one_row_nearest_upper" + in: + mat: + - [4, 12, 20] + target: 18 + out: 2 + - name: "all_minimums" + in: + mat: + - [1, 1, 1] + - [1, 1, 1] + - [1, 1, 1] + target: 10 + out: 7 + - name: "all_maximums" + in: + mat: + - [70, 70] + - [70, 70] + target: 1 + out: 139 + - name: "duplicates_with_exact_sum" + in: + mat: + - [2, 2, 5] + - [3, 3, 8] + - [4, 4, 9] + target: 14 + out: 0 + - name: "duplicates_without_exact_sum" + in: + mat: + - [2, 2] + - [6, 6] + - [10, 10] + target: 19 + out: 1 + - name: "two_rows_exact" + in: + mat: + - [1, 5, 9] + - [2, 6, 10] + target: 15 + out: 0 + - name: "two_rows_gap" + in: + mat: + - [1, 4] + - [1, 4] + target: 7 + out: 1 + - name: "three_rows_gap" + in: + mat: + - [1, 4] + - [1, 4] + - [1, 4] + target: 8 + out: 1 + - name: "target_zero" + in: + mat: + - [1, 2] + - [3, 4] + target: 1 + out: 3 + - name: "target_maximum" + in: + mat: + - [70, 69] + - [70, 68] + - [70, 67] + target: 800 + out: 590 + - name: "wide_row_exact" + in: + mat: + - [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] + target: 11 + out: 0 + - name: "many_rows_single_column" + in: + mat: + - [3] + - [7] + - [11] + - [15] + - [19] + target: 60 + out: 5 + - name: "many_rows_single_column_exact" + in: + mat: + - [3] + - [7] + - [11] + - [15] + - [19] + target: 55 + out: 0 + - name: "parity_choices" + in: + mat: + - [1, 3] + - [2, 4] + - [5, 7] + target: 12 + out: 0 + - name: "large_target_small_sum" + in: + mat: + - [1, 2, 3] + - [1, 2, 3] + - [1, 2, 3] + - [1, 2, 3] + target: 800 + out: 788 + - name: "large_sum_small_target" + in: + mat: + - [68, 69, 70] + - [68, 69, 70] + - [68, 69, 70] + - [68, 69, 70] + target: 1 + out: 271 + - name: "dense_exact" + in: + mat: + - [1, 6, 11, 16, 21] + - [2, 7, 12, 17, 22] + - [3, 8, 13, 18, 23] + - [4, 9, 14, 19, 24] + target: 50 + out: 0 + - name: "dense_nearest" + in: + mat: + - [1, 6, 11, 16, 21] + - [2, 7, 12, 17, 22] + - [3, 8, 13, 18, 23] + - [4, 9, 14, 19, 24] + target: 51 + out: 1 + - name: "six_rows_mixed" + in: + mat: + - [2, 9, 16] + - [3, 10, 17] + - [4, 11, 18] + - [5, 12, 19] + - [6, 13, 20] + - [7, 14, 21] + target: 75 + out: 1 + - name: "six_rows_mixed_nearest" + in: + mat: + - [2, 9, 16] + - [3, 10, 17] + - [4, 11, 18] + - [5, 12, 19] + - [6, 13, 20] + - [7, 14, 21] + target: 76 + out: 0 + - name: "ten_rows_single" + in: + mat: + - [1] + - [2] + - [3] + - [4] + - [5] + - [6] + - [7] + - [8] + - [9] + - [10] + target: 40 + out: 15 + - name: "ten_rows_exact" + in: + mat: + - [1] + - [2] + - [3] + - [4] + - [5] + - [6] + - [7] + - [8] + - [9] + - [10] + target: 55 + out: 0 + - name: "max_values_exact" + in: + mat: + - [70, 70, 70, 70] + - [70, 70, 70, 70] + - [70, 70, 70, 70] + - [70, 70, 70, 70] + - [70, 70, 70, 70] + target: 350 + out: 0 + - name: "max_dimensions_small_values" + in: + mat: + - [1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1] + target: 70 + out: 62 + - name: "generated_small" + seed: 198101 + in: + mat: + gen: "array" + len: 5 + elemType: "int" + of: + gen: "array" + len: 5 + elemType: "int" + of: + gen: "int" + min: 1 + max: 70 + target: + gen: "int" + min: 1 + max: 100 + - name: "generated_medium" + seed: 198102 + in: + mat: + gen: "array" + len: 15 + elemType: "int" + of: + gen: "array" + len: 10 + elemType: "int" + of: + gen: "int" + min: 1 + max: 70 + target: + gen: "int" + min: 1 + max: 800 + - name: "generated_dense" + seed: 198103 + in: + mat: + gen: "array" + len: 30 + elemType: "int" + of: + gen: "array" + len: 20 + elemType: "int" + of: + gen: "int" + min: 1 + max: 70 + target: + gen: "int" + min: 1 + max: 800 + - name: "generated_large_rows" + seed: 198104 + in: + mat: + gen: "array" + len: 60 + elemType: "int" + of: + gen: "array" + len: 30 + elemType: "int" + of: + gen: "int" + min: 1 + max: 70 + target: + gen: "int" + min: 1 + max: 800 + - name: "generated_maximum_dimensions" + seed: 198105 + in: + mat: + gen: "array" + len: 70 + elemType: "int" + of: + gen: "array" + len: 70 + elemType: "int" + of: + gen: "int" + min: 1 + max: 70 + target: + gen: "int" + min: 1 + max: 800 diff --git a/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.cpp b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.cpp new file mode 100644 index 00000000..0bac49eb --- /dev/null +++ b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int minimizeTheDifference(vector>& mat, int target) { + for (auto& row : mat) { + sort(row.begin(), row.end()); + } + unordered_map dp; + int mini = INT_MAX; + + function dfs = [&](int i, int ans) -> int { + if (i < 0) { + int diff = abs(ans); + mini = min(mini, diff); + return diff; + } + long long key = (long long)i * 100000 + (ans + 100000); + if (dp.find(key) != dp.end()) return dp[key]; + if (ans < 0 && abs(ans) > mini) return INT_MAX / 2; + int take = INT_MAX / 2; + for (int z = 0; z < mat[i].size(); z++) { + if (z > 0 && mat[i][z] == mat[i][z-1]) continue; + take = min(take, dfs(i-1, ans - mat[i][z])); + if (take == 0) break; + } + dp[key] = take; + return take; + }; + + return dfs(mat.size() - 1, target); + } +}; diff --git a/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.cs b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.cs new file mode 100644 index 00000000..f69c704b --- /dev/null +++ b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.cs @@ -0,0 +1,33 @@ +public class Solution { + private int[][] mat; + private Dictionary dp; + private int mini = int.MaxValue; + + public int MinimizeTheDifference(int[][] mat, int target) { + this.mat = mat; + dp = new Dictionary(); + for (int i = 0; i < mat.Length; i++) { + Array.Sort(mat[i]); + } + return Dfs(mat.Length - 1, target); + } + + private int Dfs(int i, int ans) { + if (i < 0) { + int diff = Math.Abs(ans); + if (diff < mini) mini = diff; + return diff; + } + long key = (long)i * 100000 + (ans + 100000); + if (dp.ContainsKey(key)) return dp[key]; + if (ans < 0 && Math.Abs(ans) > mini) return int.MaxValue / 2; + int take = int.MaxValue / 2; + for (int z = 0; z < mat[i].Length; z++) { + if (z > 0 && mat[i][z] == mat[i][z-1]) continue; + take = Math.Min(take, Dfs(i-1, ans - mat[i][z])); + if (take == 0) break; + } + dp[key] = take; + return take; + } +} diff --git a/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.dart b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.dart new file mode 100644 index 00000000..46069cc9 --- /dev/null +++ b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.dart @@ -0,0 +1,31 @@ +class Solution { + int minimizeTheDifference(List> mat, int target) { + for (var row in mat) { + row.sort(); + } + Map dp = {}; + int mini = 1 << 31 - 1; + + int dfs(int i, int ans) { + if (i < 0) { + int diff = ans.abs(); + if (diff < mini) mini = diff; + return diff; + } + String key = '$i,$ans'; + if (dp.containsKey(key)) return dp[key]!; + if (ans < 0 && ans.abs() > mini) return 1 << 30; + int take = 1 << 30; + for (int z = 0; z < mat[i].length; z++) { + if (z > 0 && mat[i][z] == mat[i][z-1]) continue; + int candidate = dfs(i - 1, ans - mat[i][z]); + take = take < candidate ? take : candidate; + if (take == 0) break; + } + dp[key] = take; + return take; + } + + return dfs(mat.length - 1, target); + } +} diff --git a/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.go b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.go new file mode 100644 index 00000000..0ac74f31 --- /dev/null +++ b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.go @@ -0,0 +1,45 @@ +func minimizeTheDifference(mat [][]int, target int) int { + for _, row := range mat { + sort.Ints(row) + } + dp := make(map[[2]int]int) + mini := int(^uint(0) >> 1) // max int + + var dfs func(i, ans int) int + dfs = func(i, ans int) int { + if i < 0 { + diff := ans + if diff < 0 { + diff = -diff + } + if diff < mini { + mini = diff + } + return diff + } + key := [2]int{i, ans} + if val, ok := dp[key]; ok { + return val + } + if ans < 0 && (-ans) > mini { + return int(^uint(0) >> 1) / 2 + } + take := int(^uint(0) >> 1) / 2 + for z := 0; z < len(mat[i]); z++ { + if z > 0 && mat[i][z] == mat[i][z-1] { + continue + } + res := dfs(i-1, ans - mat[i][z]) + if res < take { + take = res + } + if take == 0 { + break + } + } + dp[key] = take + return take + } + + return dfs(len(mat)-1, target) +} diff --git a/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.java b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.java new file mode 100644 index 00000000..1ac7b89b --- /dev/null +++ b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.java @@ -0,0 +1,32 @@ +class Solution { + private int[][] mat; + private java.util.HashMap dp; + private int mini = Integer.MAX_VALUE; + + public int minimizeTheDifference(int[][] mat, int target) { + this.mat = mat; + dp = new java.util.HashMap<>(); + for (int[] row : mat) { + java.util.Arrays.sort(row); + } + return dfs(mat.length - 1, target); + } + + private int dfs(int i, int ans) { + if (i < 0) { + mini = Math.min(mini, Math.abs(ans)); + return Math.abs(ans); + } + long key = (long)i * 100000 + (ans + 100000); + if (dp.containsKey(key)) return dp.get(key); + if (ans < 0 && Math.abs(ans) > mini) return Integer.MAX_VALUE / 2; + int take = Integer.MAX_VALUE / 2; + for (int z = 0; z < mat[i].length; z++) { + if (z > 0 && mat[i][z] == mat[i][z-1]) continue; + take = Math.min(take, dfs(i-1, ans - mat[i][z])); + if (take == 0) break; + } + dp.put(key, take); + return take; + } +} diff --git a/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.kt b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.kt new file mode 100644 index 00000000..4a6616bd --- /dev/null +++ b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.kt @@ -0,0 +1,29 @@ +class Solution { + private lateinit var mat: Array + private val dp = HashMap() + private var mini = Int.MAX_VALUE + + fun minimizeTheDifference(mat: Array, target: Int): Int { + this.mat = mat + for (row in mat) row.sort() + return dfs(mat.size - 1, target) + } + + private fun dfs(i: Int, ans: Int): Int { + if (i < 0) { + mini = minOf(mini, Math.abs(ans)) + return Math.abs(ans) + } + val key = i.toLong() * 100000 + (ans + 100000) + dp[key]?.let { return it } + if (ans < 0 && Math.abs(ans) > mini) return Int.MAX_VALUE / 2 + var take = Int.MAX_VALUE / 2 + for (z in mat[i].indices) { + if (z > 0 && mat[i][z] == mat[i][z-1]) continue + take = minOf(take, dfs(i-1, ans - mat[i][z])) + if (take == 0) break + } + dp[key] = take + return take + } +} diff --git a/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.py b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.py new file mode 100644 index 00000000..3e49ec55 --- /dev/null +++ b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.py @@ -0,0 +1,26 @@ +class Solution: + def minimizeTheDifference(self, mat: List[List[int]], target: int): + dp = {} + self.mini = float("inf") + for row in mat: + row.sort() + + def func(i, ans): + if i < 0: + self.mini = min(self.mini, abs(ans)) + return abs(ans) + if (i, ans) in dp: + return dp[(i, ans)] + if ans < 0 and abs(ans) > self.mini: + return float("inf") + take = float("inf") + for z in range(len(mat[i])): + if z > 0 and mat[i][z] == mat[i][z - 1]: + continue + take = min(take, func(i - 1, ans - mat[i][z])) + if take == 0: + break + dp[(i, ans)] = take + return take + + return func(len(mat) - 1, target) diff --git a/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.py2 b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.py2 new file mode 100644 index 00000000..e78f81f5 --- /dev/null +++ b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.py2 @@ -0,0 +1,31 @@ +class Solution(object): + def minimizeTheDifference(self, mat, target): + """ + :type mat: List[List[int]] + :type target: int + :rtype: int + """ + for row in mat: + row.sort() + dp = {} + mini = [float('inf')] + + def func(i, ans): + if i < 0: + mini[0] = min(mini[0], abs(ans)) + return abs(ans) + if (i, ans) in dp: + return dp[(i, ans)] + if ans < 0 and abs(ans) > mini[0]: + return float('inf') + take = float('inf') + for z in range(len(mat[i])): + if z > 0 and mat[i][z] == mat[i][z-1]: + continue + take = min(take, func(i-1, ans - mat[i][z])) + if take == 0: + break + dp[(i, ans)] = take + return take + + return func(len(mat)-1, target) diff --git a/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.rb b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.rb new file mode 100644 index 00000000..bb27a6d6 --- /dev/null +++ b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.rb @@ -0,0 +1,30 @@ +# @param {Integer[][]} mat +# @param {Integer} target +# @return {Integer} +def minimize_the_difference(mat, target) + mat.each { |row| row.sort! } + dp = {} + mini = [Float::INFINITY] + + func = lambda do |i, ans| + if i < 0 + mini[0] = [mini[0], (ans).abs].min + return (ans).abs + end + key = [i, ans] + return dp[key] if dp.key?(key) + if ans < 0 && (ans).abs > mini[0] + return Float::INFINITY + end + take = Float::INFINITY + mat[i].each_with_index do |val, z| + next if z > 0 && mat[i][z] == mat[i][z-1] + take = [take, func.call(i-1, ans - val)].min + break if take == 0 + end + dp[key] = take + take + end + + func.call(mat.length - 1, target) +end diff --git a/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.rs b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.rs new file mode 100644 index 00000000..88bb7982 --- /dev/null +++ b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.rs @@ -0,0 +1,38 @@ +impl Solution { + pub fn minimize_the_difference(mat: Vec>, target: i32) -> i32 { + let mut mat = mat; + for row in mat.iter_mut() { + row.sort(); + } + let mut dp: std::collections::HashMap<(i32, i32), i32> = std::collections::HashMap::new(); + let mut mini = i32::MAX; + + fn dfs(mat: &Vec>, dp: &mut std::collections::HashMap<(i32, i32), i32>, mini: &mut i32, i: i32, ans: i32) -> i32 { + if i < 0 { + let diff = ans.abs(); + *mini = (*mini).min(diff); + return diff; + } + if let Some(&val) = dp.get(&(i, ans)) { + return val; + } + if ans < 0 && ans.abs() > *mini { + return i32::MAX / 2; + } + let mut take = i32::MAX / 2; + for z in 0..mat[i as usize].len() { + if z > 0 && mat[i as usize][z] == mat[i as usize][z-1] { + continue; + } + take = take.min(dfs(mat, dp, mini, i-1, ans - mat[i as usize][z])); + if take == 0 { + break; + } + } + dp.insert((i, ans), take); + take + } + + dfs(&mat, &mut dp, &mut mini, (mat.len() as i32) - 1, target) + } +} diff --git a/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.swift b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.swift new file mode 100644 index 00000000..35ba4b7a --- /dev/null +++ b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.swift @@ -0,0 +1,39 @@ +class Solution { + func minimizeTheDifference(_ mat: [[Int]], _ target: Int) -> Int { + var mat = mat + for i in 0.. Int { + if i < 0 { + let diff = abs(ans) + mini = min(mini, diff) + return diff + } + let key = "\(i),\(ans)" + if let val = dp[key] { + return val + } + if ans < 0 && abs(ans) > mini { + return Int.max / 2 + } + var take = Int.max / 2 + for z in 0.. 0 && mat[i][z] == mat[i][z-1] { + continue + } + take = min(take, dfs(i-1, ans - mat[i][z])) + if take == 0 { + break + } + } + dp[key] = take + return take + } + + return dfs(mat.count - 1, target) + } +} diff --git a/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.ts b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.ts new file mode 100644 index 00000000..85e341d2 --- /dev/null +++ b/tests/1501-2000/1981. minimize-the-difference-between-target-and-chosen-elements/sol.ts @@ -0,0 +1,28 @@ +function minimizeTheDifference(mat: number[][], target: number): number { + for (let row of mat) { + row.sort((a, b) => a - b); + } + let dp: Map = new Map(); + let mini = Number.MAX_SAFE_INTEGER; + + function dfs(i: number, ans: number): number { + if (i < 0) { + let diff = Math.abs(ans); + if (diff < mini) mini = diff; + return diff; + } + let key = `${i},${ans}`; + if (dp.has(key)) return dp.get(key)!; + if (ans < 0 && Math.abs(ans) > mini) return Number.MAX_SAFE_INTEGER / 2; + let take = Number.MAX_SAFE_INTEGER / 2; + for (let z = 0; z < mat[i].length; z++) { + if (z > 0 && mat[i][z] === mat[i][z - 1]) continue; + take = Math.min(take, dfs(i - 1, ans - mat[i][z])); + if (take === 0) break; + } + dp.set(key, take); + return take; + } + + return dfs(mat.length - 1, target); +} diff --git a/tests/1501-2000/1982. find-array-given-subset-sums/manifest.yaml b/tests/1501-2000/1982. find-array-given-subset-sums/manifest.yaml new file mode 100644 index 00000000..940980ee --- /dev/null +++ b/tests/1501-2000/1982. find-array-given-subset-sums/manifest.yaml @@ -0,0 +1,254 @@ +entry: + id: 1982 + title: "find-array-given-subset-sums" + params: + n: + type: int + sums: + type: array + items: + type: int + call: + cpp: "Solution().recoverArray({n}, {sums})" + rust: "Solution::recover_array({n}, {sums})" + python3: "Solution().recoverArray({n}, {sums})" + python2: "Solution().recoverArray({n}, {sums})" + ruby: "recover_array({n}, {sums})" + java: "new Solution().recoverArray({n}, {sums})" + csharp: "new Solution().RecoverArray({n}, {sums})" + kotlin: "Solution().recoverArray({n}, {sums})" + go: "recoverArray({n}, {sums})" + dart: "Solution().recoverArray({n}, {sums})" + swift: "Solution().recoverArray({n}, {sums})" + typescript: "recoverArray({n}, {sums})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 512 +oracle: + python3: + call: "Checker().recover(n, sums, {result})" + checker: | + from collections import Counter + + class Checker: + def recover(self, n, sums, result): + if not isinstance(result, list) or len(result) != n: + return False + if any(not isinstance(x, int) for x in result): + return False + values = [0] + for x in result: + values += [v + x for v in values] + return Counter(values) == Counter(sums) +seed: 1982 +tests: + - name: one-positive + in: + n: 1 + sums: [0, 7] + - name: one-negative + in: + n: 1 + sums: [-9, 0] + - name: one-zero + in: + n: 1 + sums: [0, 0] + - name: one-min + in: + n: 1 + sums: [-10000, 0] + - name: one-max + in: + n: 1 + sums: [0, 10000] + - name: two-positive + in: + n: 2 + sums: [0, 3, 5, 8] + - name: two-negative + in: + n: 2 + sums: [-11, -4, -7, 0] + - name: two-mixed + in: + n: 2 + sums: [-6, -2, 0, 4] + - name: two-zero + in: + n: 2 + sums: [0, 0, 0, 0] + - name: two-duplicate + in: + n: 2 + sums: [0, 4, 4, 8] + - name: two-cancel + in: + n: 2 + sums: [-5, 0, 0, 5] + - name: two-boundary + in: + n: 2 + sums: [-10000, 0, 0, 10000] + - name: two-large + in: + n: 2 + sums: [0, 1, 10001, 10002] + - name: two-sign-symmetric + in: + n: 2 + sums: [-8, 0, 0, 8] + - name: two-small + in: + n: 2 + sums: [0, 1, 1, 2] + - name: two-opposites + in: + n: 2 + sums: [-12, 0, 0, 12] + - name: three-basic + in: + n: 3 + sums: [0, 1, 2, 3, 3, 4, 5, 6] + - name: three-mixed + in: + n: 3 + sums: [-5, -3, -2, 0, 0, 2, 3, 5] + - name: three-example + in: + n: 3 + sums: [-3, -2, -1, 0, 0, 1, 2, 3] + - name: three-zeros + in: + n: 3 + sums: [0, 0, 0, 0, 0, 0, 0, 0] + - name: three-duplicate + in: + n: 3 + sums: [0, 2, 2, 2, 4, 4, 4, 6] + - name: three-negative + in: + n: 3 + sums: [-8, -6, -2, -1, 0, 1, 5, 7] + - name: three-cancel + in: + n: 3 + sums: [-7, -4, -3, 0, 0, 3, 4, 7] + - name: three-wide + in: + n: 3 + sums: [-10000, -9997, 0, 3, 9997, 10000, 19997, 20000] + - name: three-small + in: + n: 3 + sums: [0, 1, 1, 2, 2, 3, 3, 4] + - name: three-signed-duplicates + in: + n: 3 + sums: [-4, -4, -2, -2, 0, 0, 2, 2] + - name: three-unbalanced + in: + n: 3 + sums: [-3, 0, 1, 3, 4, 6, 7, 10] + - name: four-example + in: + n: 4 + sums: [-1, -1, 0, 0, 3, 3, 4, 4, 4, 4, 5, 5, 8, 8, 9, 9] + - name: four-zeros + in: + n: 4 + sums: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: four-basic + in: + n: 4 + sums: [0, 1, 2, 3, 3, 4, 5, 6, 4, 5, 6, 7, 7, 8, 9, 10] + - name: four-mixed + in: + n: 4 + sums: [-5, -4, -3, -2, -2, -1, -1, 0, 0, 1, 1, 2, 2, 3, 4, 5] + - name: four-duplicates + in: + n: 4 + sums: [0, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 8] + - name: four-canceling + in: + n: 4 + sums: [-5, -3, -3, -2, -2, -1, 0, 0, 0, 0, 1, 2, 2, 3, 3, 5] + - name: five-single-nonzero + in: + n: 5 + sums: + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + 7, + ] + - name: five-balanced + in: + n: 5 + sums: + [ + -7, + -6, + -5, + -4, + -4, + -3, + -2, + -2, + -1, + -1, + 0, + 0, + 1, + 1, + 1, + 2, + 2, + 3, + 3, + 3, + 4, + 4, + 5, + 5, + 6, + 6, + 7, + 8, + 8, + 9, + 10, + 11, + ] diff --git a/tests/1501-2000/1982. find-array-given-subset-sums/sol.cpp b/tests/1501-2000/1982. find-array-given-subset-sums/sol.cpp new file mode 100644 index 00000000..ff050db5 --- /dev/null +++ b/tests/1501-2000/1982. find-array-given-subset-sums/sol.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector recoverArray(int n, vector& sums) { + sort(sums.begin(), sums.end()); + vector res; + + for (int _ = 0; _ < n; ++_) { + int d = sums[1] - sums[0]; + + vector left_part, right_part; + unordered_map count; + for (int s : sums) count[s]++; + + for (int s : sums) { + if (count[s] > 0) { + left_part.push_back(s); + right_part.push_back(s + d); + count[s]--; + count[s + d]--; + } + } + + bool hasZero = false; + for (int s : left_part) if (s == 0) { hasZero = true; break; } + + if (hasZero) { + res.push_back(d); + sums = left_part; + } else { + res.push_back(-d); + sums = right_part; + } + } + return res; + } +}; diff --git a/tests/1501-2000/1982. find-array-given-subset-sums/sol.cs b/tests/1501-2000/1982. find-array-given-subset-sums/sol.cs new file mode 100644 index 00000000..068a8ebb --- /dev/null +++ b/tests/1501-2000/1982. find-array-given-subset-sums/sol.cs @@ -0,0 +1,37 @@ +public class Solution { + public int[] RecoverArray(int n, int[] sums) { + Array.Sort(sums); + int[] res = new int[n]; + + for (int i = 0; i < n; i++) { + int d = sums[1] - sums[0]; + + var left = new List(); + var right = new List(); + var count = new Dictionary(); + foreach (int s in sums) { + if (!count.ContainsKey(s)) count[s] = 0; + count[s]++; + } + + foreach (int s in sums) { + if (count[s] > 0) { + left.Add(s); + right.Add(s + d); + count[s]--; + if (!count.ContainsKey(s + d)) count[s + d] = 0; + count[s + d]--; + } + } + + if (left.Contains(0)) { + res[i] = d; + sums = left.ToArray(); + } else { + res[i] = -d; + sums = right.ToArray(); + } + } + return res; + } +} diff --git a/tests/1501-2000/1982. find-array-given-subset-sums/sol.dart b/tests/1501-2000/1982. find-array-given-subset-sums/sol.dart new file mode 100644 index 00000000..fa7dbbf0 --- /dev/null +++ b/tests/1501-2000/1982. find-array-given-subset-sums/sol.dart @@ -0,0 +1,36 @@ +class Solution { + List recoverArray(int n, List sums) { + sums.sort(); + List res = []; + + for (int i = 0; i < n; i++) { + int d = sums[1] - sums[0]; + + List left = []; + List right = []; + Map count = {}; + for (int s in sums) { + count[s] = (count[s] ?? 0) + 1; + } + + for (int s in sums) { + if (count[s]! > 0) { + left.add(s); + right.add(s + d); + count[s] = count[s]! - 1; + count[s + d] = (count[s + d] ?? 0) - 1; + } + } + + bool hasZero = left.contains(0); + if (hasZero) { + res.add(d); + sums = left; + } else { + res.add(-d); + sums = right; + } + } + return res; + } +} diff --git a/tests/1501-2000/1982. find-array-given-subset-sums/sol.go b/tests/1501-2000/1982. find-array-given-subset-sums/sol.go new file mode 100644 index 00000000..e5807a0c --- /dev/null +++ b/tests/1501-2000/1982. find-array-given-subset-sums/sol.go @@ -0,0 +1,41 @@ +func recoverArray(n int, sums []int) []int { + sort.Ints(sums) + res := make([]int, n) + + for i := 0; i < n; i++ { + d := sums[1] - sums[0] + + left := []int{} + right := []int{} + count := make(map[int]int) + for _, s := range sums { + count[s]++ + } + + for _, s := range sums { + if count[s] > 0 { + left = append(left, s) + right = append(right, s+d) + count[s]-- + count[s+d]-- + } + } + + hasZero := false + for _, s := range left { + if s == 0 { + hasZero = true + break + } + } + + if hasZero { + res[i] = d + sums = left + } else { + res[i] = -d + sums = right + } + } + return res +} diff --git a/tests/1501-2000/1982. find-array-given-subset-sums/sol.java b/tests/1501-2000/1982. find-array-given-subset-sums/sol.java new file mode 100644 index 00000000..61705df4 --- /dev/null +++ b/tests/1501-2000/1982. find-array-given-subset-sums/sol.java @@ -0,0 +1,34 @@ +class Solution { + public int[] recoverArray(int n, int[] sums) { + Arrays.sort(sums); + int[] res = new int[n]; + + for (int i = 0; i < n; i++) { + int d = sums[1] - sums[0]; + + List left = new ArrayList<>(); + List right = new ArrayList<>(); + Map count = new HashMap<>(); + for (int s : sums) count.put(s, count.getOrDefault(s, 0) + 1); + + for (int s : sums) { + if (count.get(s) > 0) { + left.add(s); + right.add(s + d); + count.put(s, count.get(s) - 1); + count.put(s + d, count.getOrDefault(s + d, 0) - 1); + } + } + + boolean hasZero = left.contains(0); + if (hasZero) { + res[i] = d; + sums = left.stream().mapToInt(Integer::intValue).toArray(); + } else { + res[i] = -d; + sums = right.stream().mapToInt(Integer::intValue).toArray(); + } + } + return res; + } +} diff --git a/tests/1501-2000/1982. find-array-given-subset-sums/sol.kt b/tests/1501-2000/1982. find-array-given-subset-sums/sol.kt new file mode 100644 index 00000000..4056e502 --- /dev/null +++ b/tests/1501-2000/1982. find-array-given-subset-sums/sol.kt @@ -0,0 +1,34 @@ +class Solution { + fun recoverArray(n: Int, sums: IntArray): IntArray { + sums.sort() + val res = IntArray(n) + + var cur = sums + for (i in 0 until n) { + val d = cur[1] - cur[0] + + val left = mutableListOf() + val right = mutableListOf() + val count = mutableMapOf() + for (s in cur) count[s] = count.getOrDefault(s, 0) + 1 + + for (s in cur) { + if (count[s]!! > 0) { + left.add(s) + right.add(s + d) + count[s] = count[s]!! - 1 + count[s + d] = count.getOrDefault(s + d, 0) - 1 + } + } + + if (left.contains(0)) { + res[i] = d + cur = left.toIntArray() + } else { + res[i] = -d + cur = right.toIntArray() + } + } + return res + } +} diff --git a/tests/1501-2000/1982. find-array-given-subset-sums/sol.py b/tests/1501-2000/1982. find-array-given-subset-sums/sol.py new file mode 100644 index 00000000..d8e4e9d4 --- /dev/null +++ b/tests/1501-2000/1982. find-array-given-subset-sums/sol.py @@ -0,0 +1,36 @@ +from collections import Counter + + +class Solution: + def recoverArray(self, n: int, sums: List[int]) -> List[int]: + sums.sort() + res = [] + + for _ in range(n): + # The difference between the smallest two sums is a candidate element + d = sums[1] - sums[0] + + # Partition the sums into two halves + left_part = [] + right_part = [] + count = Counter(sums) + + # Greedily pair up sums that differ by exactly 'd' + for s in sums: + if count[s] > 0: + left_part.append(s) + right_part.append(s + d) + count[s] -= 1 + count[s + d] -= 1 + + # Check if 0 is in the left partition to determine the sign of d + # If 0 is in left_part, then 'd' is the original element. + # If not, '-d' is the original element and we use right_part for the next iteration. + if 0 in Counter(left_part): + res.append(d) + sums = left_part + else: + res.append(-d) + sums = right_part + + return res diff --git a/tests/1501-2000/1982. find-array-given-subset-sums/sol.py2 b/tests/1501-2000/1982. find-array-given-subset-sums/sol.py2 new file mode 100644 index 00000000..e38a6af2 --- /dev/null +++ b/tests/1501-2000/1982. find-array-given-subset-sums/sol.py2 @@ -0,0 +1,34 @@ +class Solution(object): + def recoverArray(self, n, sums): + """ + :type n: int + :type sums: List[int] + :rtype: List[int] + """ + sums.sort() + res = [] + + for _ in range(n): + d = sums[1] - sums[0] + + left = [] + right = [] + count = {} + for s in sums: + count[s] = count.get(s, 0) + 1 + + for s in sums: + if count[s] > 0: + left.append(s) + right.append(s + d) + count[s] -= 1 + count[s + d] = count.get(s + d, 0) - 1 + + if 0 in left: + res.append(d) + sums = left + else: + res.append(-d) + sums = right + + return res diff --git a/tests/1501-2000/1982. find-array-given-subset-sums/sol.rb b/tests/1501-2000/1982. find-array-given-subset-sums/sol.rb new file mode 100644 index 00000000..b8ed3762 --- /dev/null +++ b/tests/1501-2000/1982. find-array-given-subset-sums/sol.rb @@ -0,0 +1,34 @@ +# @param {Integer} n +# @param {Integer[]} sums +# @return {Integer[]} +def recover_array(n, sums) + sums.sort! + res = [] + + n.times do + d = sums[1] - sums[0] + + left = [] + right = [] + count = Hash.new(0) + sums.each { |s| count[s] += 1 } + + sums.each do |s| + if count[s] > 0 + left << s + right << s + d + count[s] -= 1 + count[s + d] -= 1 + end + end + + if left.include?(0) + res << d + sums = left + else + res << -d + sums = right + end + end + res +end diff --git a/tests/1501-2000/1982. find-array-given-subset-sums/sol.rs b/tests/1501-2000/1982. find-array-given-subset-sums/sol.rs new file mode 100644 index 00000000..a1fc4ff9 --- /dev/null +++ b/tests/1501-2000/1982. find-array-given-subset-sums/sol.rs @@ -0,0 +1,36 @@ +impl Solution { + pub fn recover_array(n: i32, sums: Vec) -> Vec { + let mut sums = sums; + sums.sort(); + let mut res = Vec::new(); + + for _ in 0..n { + let d = sums[1] - sums[0]; + + let mut left = Vec::new(); + let mut right = Vec::new(); + let mut count = std::collections::HashMap::new(); + for &s in &sums { + *count.entry(s).or_insert(0) += 1; + } + + for &s in &sums { + if count.get(&s).unwrap() > &0 { + left.push(s); + right.push(s + d); + *count.get_mut(&s).unwrap() -= 1; + *count.entry(s + d).or_insert(0) -= 1; + } + } + + if left.contains(&0) { + res.push(d); + sums = left; + } else { + res.push(-d); + sums = right; + } + } + res + } +} diff --git a/tests/1501-2000/1982. find-array-given-subset-sums/sol.swift b/tests/1501-2000/1982. find-array-given-subset-sums/sol.swift new file mode 100644 index 00000000..d3161585 --- /dev/null +++ b/tests/1501-2000/1982. find-array-given-subset-sums/sol.swift @@ -0,0 +1,35 @@ +class Solution { + func recoverArray(_ n: Int, _ sums: [Int]) -> [Int] { + var sums = sums.sorted() + var res: [Int] = [] + + for _ in 0.. 0 { + left.append(s) + right.append(s + d) + count[s]! -= 1 + count[s + d, default: 0] -= 1 + } + } + + if left.contains(0) { + res.append(d) + sums = left + } else { + res.append(-d) + sums = right + } + } + return res + } +} diff --git a/tests/1501-2000/1982. find-array-given-subset-sums/sol.ts b/tests/1501-2000/1982. find-array-given-subset-sums/sol.ts new file mode 100644 index 00000000..a1dece5f --- /dev/null +++ b/tests/1501-2000/1982. find-array-given-subset-sums/sol.ts @@ -0,0 +1,31 @@ +function recoverArray(n: number, sums: number[]): number[] { + sums.sort((a, b) => a - b); + const res: number[] = []; + + for (let i = 0; i < n; i++) { + const d = sums[1] - sums[0]; + + const left: number[] = []; + const right: number[] = []; + const count: Map = new Map(); + for (const s of sums) count.set(s, (count.get(s) || 0) + 1); + + for (const s of sums) { + if (count.get(s)! > 0) { + left.push(s); + right.push(s + d); + count.set(s, count.get(s)! - 1); + count.set(s + d, (count.get(s + d) || 0) - 1); + } + } + + if (left.includes(0)) { + res.push(d); + sums = left; + } else { + res.push(-d); + sums = right; + } + } + return res; +} diff --git a/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/manifest.yaml b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/manifest.yaml new file mode 100644 index 00000000..da7bcc4e --- /dev/null +++ b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/manifest.yaml @@ -0,0 +1,403 @@ +entry: + id: 1984 + title: "minimum-difference-between-highest-and-lowest-of-k-scores" + params: + nums: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().minimumDifference({nums}, {k})" + rust: "Solution::minimum_difference({nums}, {k})" + python3: "Solution().minimumDifference({nums}, {k})" + python2: "Solution().minimumDifference({nums}, {k})" + ruby: "minimum_difference({nums}, {k})" + java: "new Solution().minimumDifference({nums}, {k})" + csharp: "new Solution().MinimumDifference({nums}, {k})" + kotlin: "Solution().minimumDifference({nums}, {k})" + go: "minimumDifference({nums}, {k})" + dart: "Solution().minimumDifference({nums}, {k})" + swift: "Solution().minimumDifference({nums}, {k})" + typescript: "minimumDifference({nums}, {k})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().minimumDifference(nums, k, {result})" + checker: | + class Checker: + def minimumDifference(self, nums, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + a = sorted(nums) + expected = min(a[i + k - 1] - a[i] for i in range(len(a) - k + 1)) + return result == expected +seed: 1984 +tests: + - name: single + in: + nums: [90] + k: 1 + out: 0 + judge: + type: "exact" + - name: example + in: + nums: [9, 4, 1, 7] + k: 2 + out: 2 + judge: + type: "exact" + - name: all-selected + in: + nums: [9, 4, 1, 7] + k: 4 + out: 8 + judge: + type: "exact" + - name: duplicate-zero + in: + nums: [0, 0, 0, 0, 0] + k: 3 + out: 0 + judge: + type: "exact" + - name: duplicate-high + in: + nums: [100000, 100000, 99999, 100000] + k: 2 + out: 0 + judge: + type: "exact" + - name: unsorted-small + in: + nums: [8, 1, 6, 3, 10] + k: 3 + out: 4 + judge: + type: "exact" + - name: k-one + in: + nums: [100000, 0, 54321, 17] + k: 1 + out: 0 + judge: + type: "exact" + - name: adjacent-best + in: + nums: [1, 100, 2, 101, 3] + k: 3 + out: 2 + judge: + type: "exact" + - name: extremes + in: + nums: [0, 100000] + k: 2 + out: 100000 + judge: + type: "exact" + - name: negatives-not-allowed-boundary + in: + nums: [0, 1, 2, 3, 4, 5] + k: 5 + out: 4 + judge: + type: "exact" + - name: repeated-block + in: + nums: [10, 20, 10, 30, 20, 10] + k: 4 + out: 10 + judge: + type: "exact" + - name: sorted-ascending + in: + nums: [2, 5, 8, 11, 14, 17] + k: 2 + out: 3 + judge: + type: "exact" + - name: sorted-descending + in: + nums: [17, 14, 11, 8, 5, 2] + k: 4 + out: 9 + judge: + type: "exact" + - name: narrow-cluster + in: + nums: [0, 99999, 50000, 50001, 50002, 100000] + k: 3 + out: 2 + judge: + type: "exact" + - name: two-pairs + in: + nums: [4, 4, 20, 20] + k: 2 + out: 0 + judge: + type: "exact" + - name: k-three + in: + nums: [100, 1, 50, 51, 52, 1000] + k: 3 + out: 2 + judge: + type: "exact" + - name: k-six + in: + nums: [13, 2, 99, 45, 46, 47, 48] + k: 6 + out: 46 + judge: + type: "exact" + - name: values-at-zero + in: + nums: [0, 0, 1, 100000] + k: 2 + out: 0 + judge: + type: "exact" + - name: values-at-max + in: + nums: [99998, 99999, 100000, 0] + k: 3 + out: 2 + judge: + type: "exact" + - name: alternating + in: + nums: [100, 0, 99, 1, 98, 2, 97, 3] + k: 4 + out: 3 + judge: + type: "exact" + - name: middle-window + in: + nums: [5, 100, 7, 9, 11, 13, 1000] + k: 4 + out: 6 + judge: + type: "exact" + - name: six-equal + in: + nums: [42, 1, 42, 100, 42, 7] + k: 3 + out: 0 + judge: + type: "exact" + - name: wide-with-cluster + in: + nums: [0, 25000, 50000, 50001, 50002, 75000, 100000] + k: 3 + out: 2 + judge: + type: "exact" + - name: k-two-neighbors + in: + nums: [31, 30, 100, 32, 500] + k: 2 + out: 1 + judge: + type: "exact" + - name: k-two-duplicate + in: + nums: [31, 30, 100, 31, 500] + k: 2 + out: 0 + judge: + type: "exact" + - name: all-range + in: + nums: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] + k: 11 + out: 100 + judge: + type: "exact" + - name: four-window + in: + nums: [1000, 2, 8, 4, 6, 100] + k: 4 + out: 6 + judge: + type: "exact" + - name: scattered + in: + nums: [999, 1, 500, 501, 502, 2000, 0] + k: 3 + out: 2 + judge: + type: "exact" + - name: repeated-boundary + in: + nums: [0, 100000, 100000, 100000, 0, 100000] + k: 4 + out: 0 + judge: + type: "exact" + - name: arithmetic + in: + nums: [77, 11, 55, 33, 99, 22, 44, 88, 66] + k: 5 + out: 44 + judge: + type: "exact" + - name: close-large + in: + nums: [100000, 99990, 99980, 99970, 99960, 99950, 0] + k: 5 + out: 40 + judge: + type: "exact" + - name: ten-window + in: + nums: [40, 1, 32, 15, 27, 9, 22, 13, 35, 5, 100] + k: 10 + out: 39 + judge: + type: "exact" + - name: twenty-window + in: + nums: + [ + 0, + 3, + 6, + 9, + 12, + 15, + 18, + 21, + 24, + 27, + 30, + 33, + 36, + 39, + 42, + 45, + 48, + 51, + 54, + 100000, + ] + k: 20 + out: 100000 + judge: + type: "exact" + - name: high-cluster + in: + nums: [99900, 99901, 99902, 99903, 99904, 1, 2, 3] + k: 5 + out: 4 + judge: + type: "exact" + - name: low-cluster + in: + nums: [0, 1, 2, 3, 4, 99996, 99997, 99998] + k: 5 + out: 4 + judge: + type: "exact" + - name: generated-random-small + in: + nums: + gen: "array" + len: 37 + of: + gen: "int" + min: 0 + max: 100000 + distinct: false + sorted: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 37 + judge: + type: "exact" + seed: 198401 + - name: generated-random-medium + in: + nums: + gen: "array" + len: 250 + of: + gen: "int" + min: 0 + max: 100000 + distinct: false + sorted: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 250 + judge: + type: "exact" + seed: 198402 + - name: generated-random-large + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 0 + max: 100000 + distinct: false + sorted: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 1000 + judge: + type: "exact" + seed: 198403 + - name: generated-low-range + in: + nums: + gen: "array" + len: 512 + of: + gen: "int" + min: 0 + max: 12 + distinct: false + sorted: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 512 + judge: + type: "exact" + seed: 198404 + - name: generated-near-max + in: + nums: + gen: "array" + len: 997 + of: + gen: "int" + min: 99900 + max: 100000 + distinct: false + sorted: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 997 + judge: + type: "exact" + seed: 198405 diff --git a/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.cpp b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.cpp new file mode 100644 index 00000000..7fe25ca7 --- /dev/null +++ b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int minimumDifference(vector& nums, int k) { + int n = nums.size(); + sort(nums.begin(), nums.end()); + int ans = nums[k - 1] - nums[0]; + for (int i = 0; i <= n - k; i++) { + ans = min(ans, nums[i + k - 1] - nums[i]); + } + return ans; + } +}; diff --git a/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.cs b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.cs new file mode 100644 index 00000000..a279dfd9 --- /dev/null +++ b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.cs @@ -0,0 +1,11 @@ +public class Solution { + public int MinimumDifference(int[] nums, int k) { + Array.Sort(nums); + int n = nums.Length; + int ans = nums[k - 1] - nums[0]; + for (int i = 0; i <= n - k; i++) { + ans = Math.Min(ans, nums[i + k - 1] - nums[i]); + } + return ans; + } +} diff --git a/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.dart b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.dart new file mode 100644 index 00000000..6d282238 --- /dev/null +++ b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.dart @@ -0,0 +1,11 @@ +class Solution { + int minimumDifference(List nums, int k) { + nums.sort(); + int n = nums.length; + int ans = nums[k - 1] - nums[0]; + for (int i = 0; i <= n - k; i++) { + ans = ans < nums[i + k - 1] - nums[i] ? ans : nums[i + k - 1] - nums[i]; + } + return ans; + } +} diff --git a/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.go b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.go new file mode 100644 index 00000000..ddd50137 --- /dev/null +++ b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.go @@ -0,0 +1,11 @@ +func minimumDifference(nums []int, k int) int { + sort.Ints(nums) + n := len(nums) + ans := nums[k-1] - nums[0] + for i := 0; i <= n-k; i++ { + if nums[i+k-1]-nums[i] < ans { + ans = nums[i+k-1] - nums[i] + } + } + return ans +} diff --git a/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.java b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.java new file mode 100644 index 00000000..4faefeb5 --- /dev/null +++ b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.java @@ -0,0 +1,11 @@ +class Solution { + public int minimumDifference(int[] nums, int k) { + Arrays.sort(nums); + int n = nums.length; + int ans = nums[k - 1] - nums[0]; + for (int i = 0; i <= n - k; i++) { + ans = Math.min(ans, nums[i + k - 1] - nums[i]); + } + return ans; + } +} diff --git a/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.kt b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.kt new file mode 100644 index 00000000..a21cd128 --- /dev/null +++ b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.kt @@ -0,0 +1,11 @@ +class Solution { + fun minimumDifference(nums: IntArray, k: Int): Int { + nums.sort() + val n = nums.size + var ans = nums[k - 1] - nums[0] + for (i in 0..n - k) { + ans = minOf(ans, nums[i + k - 1] - nums[i]) + } + return ans + } +} diff --git a/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.py b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.py new file mode 100644 index 00000000..adb4cf25 --- /dev/null +++ b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.py @@ -0,0 +1,8 @@ +class Solution: + def minimumDifference(self, nums, k): + n = len(nums) + nums.sort() + ans = nums[k - 1] - nums[0] + for i in range(0, n - k + 1): + ans = min(ans, nums[i + k - 1] - nums[i]) + return ans diff --git a/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.py2 b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.py2 new file mode 100644 index 00000000..ead4a064 --- /dev/null +++ b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.py2 @@ -0,0 +1,13 @@ +class Solution(object): + def minimumDifference(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + n = len(nums) + nums.sort() + ans = nums[k - 1] - nums[0] + for i in range(0, n - k + 1): + ans = min(ans, nums[i + k - 1] - nums[i]) + return ans diff --git a/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.rb b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.rb new file mode 100644 index 00000000..fcee1790 --- /dev/null +++ b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.rb @@ -0,0 +1,11 @@ +# @param {Integer[]} nums +# @param {Integer} k +# @return {Integer} +def minimum_difference(nums, k) + nums.sort! + ans = nums[k - 1] - nums[0] + (0..(nums.length - k)).each do |i| + ans = [ans, nums[i + k - 1] - nums[i]].min + end + ans +end diff --git a/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.rs b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.rs new file mode 100644 index 00000000..dab201ac --- /dev/null +++ b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn minimum_difference(nums: Vec, k: i32) -> i32 { + let mut nums = nums; + nums.sort(); + let n = nums.len(); + let k = k as usize; + let mut ans = nums[k - 1] - nums[0]; + for i in 0..=(n - k) { + ans = ans.min(nums[i + k - 1] - nums[i]); + } + ans + } +} diff --git a/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.swift b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.swift new file mode 100644 index 00000000..bd3b4626 --- /dev/null +++ b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.swift @@ -0,0 +1,11 @@ +class Solution { + func minimumDifference(_ nums: [Int], _ k: Int) -> Int { + let sorted = nums.sorted() + let n = sorted.count + var ans = sorted[k - 1] - sorted[0] + for i in 0...(n - k) { + ans = min(ans, sorted[i + k - 1] - sorted[i]) + } + return ans + } +} diff --git a/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.ts b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.ts new file mode 100644 index 00000000..7c85009c --- /dev/null +++ b/tests/1501-2000/1984. minimum-difference-between-highest-and-lowest-of-k-scores/sol.ts @@ -0,0 +1,9 @@ +function minimumDifference(nums: number[], k: number): number { + nums.sort((a, b) => a - b); + const n = nums.length; + let ans = nums[k - 1] - nums[0]; + for (let i = 0; i <= n - k; i++) { + ans = Math.min(ans, nums[i + k - 1] - nums[i]); + } + return ans; +} diff --git a/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/manifest.yaml b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/manifest.yaml new file mode 100644 index 00000000..e0ef008c --- /dev/null +++ b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/manifest.yaml @@ -0,0 +1,684 @@ +entry: + id: 1985 + title: "find-the-kth-largest-integer-in-the-array" + params: + nums: + type: array + items: + type: string + k: + type: int + call: + cpp: "Solution().kthLargestNumber({nums}, {k})" + rust: "Solution::kth_largest_number({nums}, {k})" + python3: "Solution().kthLargestNumber({nums}, {k})" + python2: "Solution().kthLargestNumber({nums}, {k})" + ruby: "kth_largest_number({nums}, {k})" + java: "new Solution().kthLargestNumber({nums}, {k})" + csharp: "new Solution().KthLargestNumber({nums}, {k})" + kotlin: "Solution().kthLargestNumber({nums}, {k})" + go: "kthLargestNumber({nums}, {k})" + dart: "Solution().kthLargestNumber({nums}, {k})" + swift: "Solution().kthLargestNumber({nums}, {k})" + typescript: "kthLargestNumber({nums}, {k})" +judge: + type: "exact" +limits: + time_ms: 2000 + memory_mb: 256 +oracle: + python3: + call: "Checker().kthLargestNumber(nums, k, {result})" + checker: | + class Checker: + def kthLargestNumber(self, nums, k, result): + if not isinstance(result, str): + return False + ordered = sorted(nums, key=lambda value: int(value), reverse=True) + return result == ordered[k - 1] +seed: 1985 +tests: + - name: example-one + in: + nums: ["3", "6", "7", "10"] + k: 4 + judge: + type: "exact" + - name: example-two + in: + nums: ["2", "21", "12", "1"] + k: 3 + judge: + type: "exact" + - name: example-three-duplicates + in: + nums: ["0", "0"] + k: 2 + judge: + type: "exact" + - name: single-zero + in: + nums: ["0"] + k: 1 + judge: + type: "exact" + - name: single-hundred-digit + in: + nums: + [ + "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + ] + k: 1 + judge: + type: "exact" + - name: duplicates-count-distinctly + in: + nums: ["2", "2", "10", "2", "1"] + k: 3 + judge: + type: "exact" + - name: k-one + in: + nums: ["1", "999", "12", "1000", "99"] + k: 1 + judge: + type: "exact" + - name: k-last + in: + nums: ["1", "999", "12", "1000", "99"] + k: 5 + judge: + type: "exact" + - name: length-beats-lexicographic + in: + nums: ["9", "10", "2", "100", "99"] + k: 2 + judge: + type: "exact" + - name: ascending-input + in: + nums: ["1", "2", "3", "4", "5", "6"] + k: 4 + judge: + type: "exact" + - name: descending-input + in: + nums: ["100", "90", "80", "70", "60"] + k: 2 + judge: + type: "exact" + - name: all-equal + in: + nums: ["42", "42", "42", "42", "42", "42"] + k: 5 + judge: + type: "exact" + - name: powers-of-ten + in: + nums: ["1", "10", "100", "1000", "10000", "100000"] + k: 3 + judge: + type: "exact" + - name: long-and-short + in: + nums: + [ + "8", + "99999999999999999999", + "10000000000000000000", + "7", + "100000000000000000000", + ] + k: 2 + judge: + type: "exact" + - name: repeated-long + in: + nums: + [ + "12345678901234567890", + "12345678901234567890", + "1234567890123456789", + "2", + ] + k: 2 + judge: + type: "exact" + - name: near-equal-long + in: + nums: + [ + "100000000000000000000000000000000000001", + "100000000000000000000000000000000000000", + "99999999999999999999999999999999999999", + ] + k: 2 + judge: + type: "exact" + - name: mixed-zero-and-large + in: + nums: + [ + "0", + "1", + "10000000000000000000000000000000000000000000000000", + "10", + "100", + ] + k: 3 + judge: + type: "exact" + - name: alternating-duplicates + in: + nums: ["5", "100", "5", "100", "50", "5", "100"] + k: 4 + judge: + type: "exact" + - name: nine-digit-boundary + in: + nums: ["999999998", "999999999", "1000000000", "1000000001", "1"] + k: 3 + judge: + type: "exact" + - name: hundred-digit-boundary + in: + nums: + [ + "1", + "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999998", + "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "10", + ] + k: 2 + judge: + type: "exact" + - name: fifteen-values + in: + nums: + [ + "15", + "3", + "12", + "8", + "20", + "1", + "19", + "7", + "14", + "2", + "18", + "6", + "13", + "5", + "17", + ] + k: 8 + judge: + type: "exact" + - name: many-ties-middle + in: + nums: ["7", "7", "7", "9", "9", "3", "3", "7", "9", "1"] + k: 6 + judge: + type: "exact" + - name: unsorted-length-groups + in: + nums: ["100", "2", "9999", "50", "1000", "9", "10000", "1"] + k: 5 + judge: + type: "exact" + - name: k-two + in: + nums: ["400", "40", "4", "44", "444", "404"] + k: 2 + judge: + type: "exact" + - name: all-two-digit + in: + nums: ["11", "22", "33", "44", "55", "66", "77", "88", "99"] + k: 7 + judge: + type: "exact" + - name: large-prefix-family + in: + nums: + [ + "10000000000000000001", + "10000000000000000002", + "10000000000000000010", + "10000000000000000011", + "10000000000000000000", + ] + k: 4 + judge: + type: "exact" + - name: twenty-five-values + in: + nums: + [ + "25", + "1", + "24", + "2", + "23", + "3", + "22", + "4", + "21", + "5", + "20", + "6", + "19", + "7", + "18", + "8", + "17", + "9", + "16", + "10", + "15", + "11", + "14", + "12", + "13", + ] + k: 13 + judge: + type: "exact" + - name: zeros-only + in: + nums: ["0", "0", "0", "0", "0", "0", "0", "0"] + k: 8 + judge: + type: "exact" + - name: twenty-five-digit-values + in: + nums: + [ + "9999999999999999999999999", + "1000000000000000000000000", + "5000000000000000000000000", + "9999999999999999999999998", + "2", + ] + k: 3 + judge: + type: "exact" + - name: thirty-values-k-one + in: + nums: + [ + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "10", + "11", + "12", + "13", + "14", + "15", + "16", + "17", + "18", + "19", + "20", + "21", + "22", + "23", + "24", + "25", + "26", + "27", + "28", + "29", + "30", + ] + k: 1 + judge: + type: "exact" + - name: thirty-values-k-last + in: + nums: + [ + "30", + "29", + "28", + "27", + "26", + "25", + "24", + "23", + "22", + "21", + "20", + "19", + "18", + "17", + "16", + "15", + "14", + "13", + "12", + "11", + "10", + "9", + "8", + "7", + "6", + "5", + "4", + "3", + "2", + "1", + ] + k: 30 + judge: + type: "exact" + - name: fifty-values-middle + in: + nums: + [ + "50", + "1", + "49", + "2", + "48", + "3", + "47", + "4", + "46", + "5", + "45", + "6", + "44", + "7", + "43", + "8", + "42", + "9", + "41", + "10", + "40", + "11", + "39", + "12", + "38", + "13", + "37", + "14", + "36", + "15", + "35", + "16", + "34", + "17", + "33", + "18", + "32", + "19", + "31", + "20", + "30", + "21", + "29", + "22", + "28", + "23", + "27", + "24", + "26", + "25", + ] + k: 25 + judge: + type: "exact" + - name: huge-string-order + in: + nums: + [ + "1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", + ] + k: 2 + judge: + type: "exact" + - name: duplicate-huge + in: + nums: + [ + "1234567890123456789012345678901234567890", + "1234567890123456789012345678901234567890", + "1234567890123456789012345678901234567889", + "1", + ] + k: 2 + judge: + type: "exact" + - name: one-hundred-items + in: + nums: + [ + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "10", + "11", + "12", + "13", + "14", + "15", + "16", + "17", + "18", + "19", + "20", + "21", + "22", + "23", + "24", + "25", + "26", + "27", + "28", + "29", + "30", + "31", + "32", + "33", + "34", + "35", + "36", + "37", + "38", + "39", + "40", + "41", + "42", + "43", + "44", + "45", + "46", + "47", + "48", + "49", + "50", + "51", + "52", + "53", + "54", + "55", + "56", + "57", + "58", + "59", + "60", + "61", + "62", + "63", + "64", + "65", + "66", + "67", + "68", + "69", + "70", + "71", + "72", + "73", + "74", + "75", + "76", + "77", + "78", + "79", + "80", + "81", + "82", + "83", + "84", + "85", + "86", + "87", + "88", + "89", + "90", + "91", + "92", + "93", + "94", + "95", + "96", + "97", + "98", + "99", + "100", + ] + k: 50 + judge: + type: "exact" + - name: one-hundred-items-duplicate-blocks + in: + nums: + [ + "100", + "100", + "100", + "99", + "99", + "99", + "98", + "98", + "98", + "97", + "97", + "97", + "96", + "96", + "96", + "95", + "95", + "95", + "94", + "94", + "94", + "93", + "93", + "93", + "92", + "92", + "92", + "91", + "91", + "91", + "90", + "90", + "90", + "89", + "89", + "89", + "88", + "88", + "88", + "87", + "87", + "87", + "86", + "86", + "86", + "85", + "85", + "85", + "84", + "84", + "84", + "83", + "83", + "83", + "82", + "82", + "82", + "81", + "81", + "81", + "80", + "80", + "80", + "79", + "79", + "79", + "78", + "78", + "78", + "77", + "77", + "77", + "76", + "76", + "76", + "75", + "75", + "75", + "74", + "74", + "74", + "73", + "73", + "73", + "72", + "72", + "72", + "71", + "71", + "71", + "70", + "70", + "70", + "69", + "69", + "69", + "68", + "68", + "68", + "67", + "67", + "67", + "66", + "66", + "66", + ] + k: 100 + judge: + type: "exact" diff --git a/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.cpp b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.cpp new file mode 100644 index 00000000..cbd9a997 --- /dev/null +++ b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + string kthLargestNumber(vector& nums, int k) { + sort(nums.begin(), nums.end(), [](const string& a, const string& b) { + if (a.size() != b.size()) return a.size() > b.size(); + return a > b; + }); + return nums[k - 1]; + } +}; diff --git a/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.cs b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.cs new file mode 100644 index 00000000..deebf112 --- /dev/null +++ b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.cs @@ -0,0 +1,9 @@ +public class Solution { + public string KthLargestNumber(string[] nums, int k) { + Array.Sort(nums, (a, b) => { + int byLength = b.Length.CompareTo(a.Length); + return byLength != 0 ? byLength : string.CompareOrdinal(b, a); + }); + return nums[k - 1]; + } +} diff --git a/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.dart b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.dart new file mode 100644 index 00000000..6e386e75 --- /dev/null +++ b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.dart @@ -0,0 +1,9 @@ +class Solution { + String kthLargestNumber(List nums, int k) { + nums.sort((a, b) { + if (a.length != b.length) return b.length.compareTo(a.length); + return b.compareTo(a); + }); + return nums[k - 1]; + } +} diff --git a/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.go b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.go new file mode 100644 index 00000000..3c249ed8 --- /dev/null +++ b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.go @@ -0,0 +1,7 @@ +func kthLargestNumber(nums []string, k int) string { + sort.Slice(nums, func(i, j int) bool { + if len(nums[i]) != len(nums[j]) { return len(nums[i]) > len(nums[j]) } + return nums[i] > nums[j] + }) + return nums[k-1] +} diff --git a/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.java b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.java new file mode 100644 index 00000000..4cb3515d --- /dev/null +++ b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.java @@ -0,0 +1,9 @@ +class Solution { + public String kthLargestNumber(String[] nums, int k) { + Arrays.sort(nums, (a, b) -> { + if (a.length() != b.length()) return Integer.compare(b.length(), a.length()); + return b.compareTo(a); + }); + return nums[k - 1]; + } +} diff --git a/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.kt b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.kt new file mode 100644 index 00000000..f22b3a1c --- /dev/null +++ b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.kt @@ -0,0 +1,6 @@ +class Solution { + fun kthLargestNumber(nums: Array, k: Int): String { + nums.sortWith(compareByDescending { it.length }.thenByDescending { it }) + return nums[k - 1] + } +} diff --git a/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.py b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.py new file mode 100644 index 00000000..5d12f010 --- /dev/null +++ b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.py @@ -0,0 +1,5 @@ +class Solution: + def kthLargestNumber(self, nums: List[str], k: int) -> str: + arr = list(map(int, nums)) + arr.sort(reverse=True) + return str(arr[k - 1]) diff --git a/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.py2 b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.py2 new file mode 100644 index 00000000..a45059c7 --- /dev/null +++ b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.py2 @@ -0,0 +1,9 @@ +class Solution(object): + def kthLargestNumber(self, nums, k): + """ + :type nums: List[str] + :type k: int + :rtype: str + """ + arr = sorted([int(x) for x in nums], reverse=True) + return str(arr[k-1]) diff --git a/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.rb b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.rb new file mode 100644 index 00000000..9749b51d --- /dev/null +++ b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.rb @@ -0,0 +1,7 @@ +# @param {String[]} nums +# @param {Integer} k +# @return {String} +def kth_largest_number(nums, k) + arr = nums.map(&:to_i).sort.reverse + arr[k-1].to_s +end diff --git a/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.rs b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.rs new file mode 100644 index 00000000..6392762c --- /dev/null +++ b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.rs @@ -0,0 +1,7 @@ +impl Solution { + pub fn kth_largest_number(nums: Vec, k: i32) -> String { + let mut arr = nums; + arr.sort_by(|a, b| b.len().cmp(&a.len()).then_with(|| b.cmp(a))); + arr[(k - 1) as usize].clone() + } +} diff --git a/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.swift b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.swift new file mode 100644 index 00000000..a4311f47 --- /dev/null +++ b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.swift @@ -0,0 +1,9 @@ +class Solution { + func kthLargestNumber(_ nums: [String], _ k: Int) -> String { + let arr = nums.sorted { + if $0.count != $1.count { return $0.count > $1.count } + return $0 > $1 + } + return arr[k - 1] + } +} diff --git a/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.ts b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.ts new file mode 100644 index 00000000..0097b59e --- /dev/null +++ b/tests/1501-2000/1985. find-the-kth-largest-integer-in-the-array/sol.ts @@ -0,0 +1,6 @@ +function kthLargestNumber(nums: string[], k: number): string { + nums.sort((a, b) => + a.length !== b.length ? b.length - a.length : a < b ? 1 : a > b ? -1 : 0, + ); + return nums[k - 1]; +} diff --git a/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/manifest.yaml b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/manifest.yaml new file mode 100644 index 00000000..a574d54f --- /dev/null +++ b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/manifest.yaml @@ -0,0 +1,381 @@ +entry: + id: 1986 + title: "minimum-number-of-work-sessions-to-finish-the-tasks" + params: + tasks: + type: array + items: + type: int + sessionTime: + type: int + call: + cpp: "Solution().minSessions({tasks}, {sessionTime})" + rust: "Solution::min_sessions({tasks}, {sessionTime})" + python3: "Solution().minSessions({tasks}, {sessionTime})" + python2: "Solution().minSessions({tasks}, {sessionTime})" + ruby: "min_sessions({tasks}, {sessionTime})" + java: "new Solution().minSessions({tasks}, {sessionTime})" + csharp: "new Solution().MinSessions({tasks}, {sessionTime})" + kotlin: "Solution().minSessions({tasks}, {sessionTime})" + go: "minSessions({tasks}, {sessionTime})" + dart: "Solution().minSessions({tasks}, {sessionTime})" + swift: "Solution().minSessions({tasks}, {sessionTime})" + typescript: "minSessions({tasks}, {sessionTime})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(tasks, sessionTime, {result})" + checker: | + class Checker: + def check(self, tasks, sessionTime, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + n = len(tasks) + sums = [0] * (1 << n) + for mask in range(1, 1 << n): + bit = mask & -mask + i = bit.bit_length() - 1 + sums[mask] = sums[mask ^ bit] + tasks[i] + dp = [n + 1] * (1 << n) + dp[0] = 0 + for mask in range(1, 1 << n): + sub = mask + while sub: + if sums[sub] <= sessionTime: + rest = mask ^ sub + cand = dp[rest] + 1 + if cand < dp[mask]: + dp[mask] = cand + sub = (sub - 1) & mask + return result == dp[-1] + +seed: 1986 + +tests: + - name: example-one + in: + tasks: [1, 2, 3] + sessionTime: 3 + out: 2 + judge: + type: "exact" + - name: example-two + in: + tasks: [3, 1, 3, 1, 1] + sessionTime: 8 + out: 2 + judge: + type: "exact" + - name: example-three + in: + tasks: [1, 2, 3, 4, 5] + sessionTime: 15 + out: 1 + judge: + type: "exact" + - name: single-task + in: + tasks: [7] + sessionTime: 7 + out: 1 + judge: + type: "exact" + - name: two-tasks-fit + in: + tasks: [4, 5] + sessionTime: 9 + out: 1 + judge: + type: "exact" + - name: two-tasks-do-not-fit + in: + tasks: [4, 5] + sessionTime: 5 + out: 2 + judge: + type: "exact" + - name: all-ones + in: + tasks: [1, 1, 1, 1, 1, 1] + sessionTime: 3 + out: 2 + judge: + type: "exact" + - name: all-maximal + in: + tasks: [10, 10, 10, 10] + sessionTime: 10 + out: 4 + judge: + type: "exact" + - name: exact-total + in: + tasks: [2, 3, 4, 6] + sessionTime: 15 + out: 1 + judge: + type: "exact" + - name: tight-pairs + in: + tasks: [6, 6, 6, 6, 4, 4, 4, 4] + sessionTime: 10 + out: 4 + judge: + type: "exact" + - name: mixed-three + in: + tasks: [8, 7, 6, 5, 4, 3] + sessionTime: 10 + out: 4 + judge: + type: "exact" + - name: four-equal-fit + in: + tasks: [3, 3, 3, 3] + sessionTime: 6 + out: 2 + judge: + type: "exact" + - name: awkward-packing + in: + tasks: [9, 5, 5, 5, 4, 4] + sessionTime: 10 + out: 4 + judge: + type: "exact" + - name: many-small-one-large + in: + tasks: [10, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + sessionTime: 10 + out: 2 + judge: + type: "exact" + - name: session-six + in: + tasks: [2, 2, 2, 2, 2, 2, 2] + sessionTime: 6 + out: 3 + judge: + type: "exact" + - name: session-seven + in: + tasks: [1, 2, 3, 4, 5, 6] + sessionTime: 7 + out: 3 + judge: + type: "exact" + - name: duplicate-heavy + in: + tasks: [2, 2, 2, 3, 3, 3, 4, 4] + sessionTime: 8 + out: 3 + judge: + type: "exact" + - name: no-combination + in: + tasks: [5, 6, 7, 8] + sessionTime: 8 + out: 4 + judge: + type: "exact" + - name: exact-packing + in: + tasks: [5, 5, 5, 5, 5, 5] + sessionTime: 10 + out: 3 + judge: + type: "exact" + - name: seven-tasks + in: + tasks: [1, 4, 2, 8, 3, 7, 5] + sessionTime: 10 + out: 3 + judge: + type: "exact" + - name: eight-tasks + in: + tasks: [1, 1, 2, 2, 3, 3, 4, 4] + sessionTime: 7 + out: 3 + judge: + type: "exact" + - name: nine-tasks + in: + tasks: [2, 4, 6, 8, 1, 3, 5, 7, 9] + sessionTime: 15 + out: 3 + judge: + type: "exact" + - name: ten-tasks + in: + tasks: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + sessionTime: 15 + out: 4 + judge: + type: "exact" + - name: eleven-tasks + in: + tasks: [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1] + sessionTime: 5 + out: 4 + judge: + type: "exact" + - name: twelve-tasks + in: + tasks: [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4] + sessionTime: 15 + out: 4 + judge: + type: "exact" + - name: thirteen-varied + in: + tasks: [1, 10, 2, 9, 3, 8, 4, 7, 5, 6, 1, 2, 3] + sessionTime: 15 + out: 5 + judge: + type: "exact" + - name: fourteen-minimum + in: + tasks: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + sessionTime: 3 + out: 5 + judge: + type: "exact" + - name: fourteen-maximal + in: + tasks: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10] + sessionTime: 10 + out: 14 + judge: + type: "exact" + - name: broad-capacity + in: + tasks: [7, 7, 1, 1, 1, 1, 1, 1, 1, 1] + sessionTime: 15 + out: 2 + judge: + type: "exact" + - name: exact-three-bins + in: + tasks: [8, 7, 5, 5, 4, 3, 3, 2] + sessionTime: 15 + out: 3 + judge: + type: "exact" + - name: balanced-four-bins + in: + tasks: [6, 5, 4, 3, 6, 5, 4, 3] + sessionTime: 10 + out: 4 + judge: + type: "exact" + - name: large-balanced + in: + tasks: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4] + sessionTime: 15 + out: 5 + judge: + type: "exact" + - name: large-repeated + in: + tasks: [2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3] + sessionTime: 8 + out: 5 + judge: + type: "exact" + - name: edge-session-two + in: + tasks: [1, 1, 1, 1, 1, 1, 1] + sessionTime: 2 + out: 4 + judge: + type: "exact" + - name: edge-session-fifteen + in: + tasks: [5, 5, 5, 5, 5, 5, 5, 5, 5] + sessionTime: 15 + out: 3 + judge: + type: "exact" + - name: generated-small + in: + tasks: + gen: "array" + len: 14 + of: + gen: "int" + min: 1 + max: 10 + distinct: false + elemType: "int" + sessionTime: 15 + judge: + type: "exact" + seed: 19861 + - name: generated-dense + in: + tasks: + gen: "array" + len: 14 + of: + gen: "int" + min: 6 + max: 10 + distinct: false + elemType: "int" + sessionTime: 15 + judge: + type: "exact" + seed: 19862 + - name: generated-ones-heavy + in: + tasks: + gen: "array" + len: 14 + of: + gen: "int" + min: 1 + max: 4 + distinct: false + elemType: "int" + sessionTime: 7 + judge: + type: "exact" + seed: 19863 + - name: generated-mixed + in: + tasks: + gen: "array" + len: 13 + of: + gen: "int" + min: 1 + max: 10 + distinct: false + elemType: "int" + sessionTime: 10 + judge: + type: "exact" + seed: 19864 + - name: generated-tight + in: + tasks: + gen: "array" + len: 14 + of: + gen: "int" + min: 8 + max: 10 + distinct: false + elemType: "int" + sessionTime: 10 + judge: + type: "exact" + seed: 19865 diff --git a/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.cpp b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.cpp new file mode 100644 index 00000000..2cb1bb71 --- /dev/null +++ b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + int minSessions(vector& tasks, int sessionTime) { + sort(tasks.rbegin(), tasks.rend()); + + auto feasibility = [&](int n) -> bool { + vector sessions(n, 0); + + function dfs = [&](int i) -> bool { + for (int v : sessions) if (v > sessionTime) return false; + if (i == (int)tasks.size()) return true; + + for (int s = 0; s < n; s++) { + sessions[s] += tasks[i]; + if (dfs(i+1)) return true; + sessions[s] -= tasks[i]; + if (sessions[s] == 0) return false; + } + return false; + }; + + return dfs(0); + }; + + int lo = 1, hi = tasks.size(); + int res = hi; + while (lo <= hi) { + int mid = (lo + hi) / 2; + if (feasibility(mid)) { + res = mid; + hi = mid - 1; + } else { + lo = mid + 1; + } + } + return res; + } +}; diff --git a/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.cs b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.cs new file mode 100644 index 00000000..b87ff626 --- /dev/null +++ b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.cs @@ -0,0 +1,38 @@ +public class Solution { + public int MinSessions(int[] tasks, int sessionTime) { + Array.Sort(tasks, (a, b) => b.CompareTo(a)); + + Func feasibility = (n) => { + int[] sessions = new int[n]; + + Func dfs = null; + dfs = (i) => { + foreach (int v in sessions) if (v > sessionTime) return false; + if (i == tasks.Length) return true; + + for (int s = 0; s < n; s++) { + sessions[s] += tasks[i]; + if (dfs(i+1)) return true; + sessions[s] -= tasks[i]; + if (sessions[s] == 0) return false; + } + return false; + }; + + return dfs(0); + }; + + int lo = 1, hi = tasks.Length; + int res = hi; + while (lo <= hi) { + int mid = (lo + hi) / 2; + if (feasibility(mid)) { + res = mid; + hi = mid - 1; + } else { + lo = mid + 1; + } + } + return res; + } +} diff --git a/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.dart b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.dart new file mode 100644 index 00000000..7aa76ae4 --- /dev/null +++ b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.dart @@ -0,0 +1,39 @@ +class Solution { + int minSessions(List tasks, int sessionTime) { + tasks.sort((a, b) => b.compareTo(a)); + + bool feasibility(int n) { + List sessions = List.filled(n, 0); + + bool dfs(int i) { + for (int v in sessions) { + if (v > sessionTime) return false; + } + if (i == tasks.length) return true; + + for (int s = 0; s < n; s++) { + sessions[s] += tasks[i]; + if (dfs(i+1)) return true; + sessions[s] -= tasks[i]; + if (sessions[s] == 0) return false; + } + return false; + } + + return dfs(0); + } + + int lo = 1, hi = tasks.length; + int res = hi; + while (lo <= hi) { + int mid = (lo + hi) ~/ 2; + if (feasibility(mid)) { + res = mid; + hi = mid - 1; + } else { + lo = mid + 1; + } + } + return res; + } +} diff --git a/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.go b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.go new file mode 100644 index 00000000..41cfa7f2 --- /dev/null +++ b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.go @@ -0,0 +1,46 @@ +func minSessions(tasks []int, sessionTime int) int { + sort.Sort(sort.Reverse(sort.IntSlice(tasks))) + + feasibility := func(n int) bool { + sessions := make([]int, n) + + var dfs func(i int) bool + dfs = func(i int) bool { + for _, v := range sessions { + if v > sessionTime { + return false + } + } + if i == len(tasks) { + return true + } + + for s := 0; s < n; s++ { + sessions[s] += tasks[i] + if dfs(i+1) { + return true + } + sessions[s] -= tasks[i] + if sessions[s] == 0 { + return false + } + } + return false + } + + return dfs(0) + } + + lo, hi := 1, len(tasks) + res := hi + for lo <= hi { + mid := (lo + hi) / 2 + if feasibility(mid) { + res = mid + hi = mid - 1 + } else { + lo = mid + 1 + } + } + return res +} diff --git a/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.java b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.java new file mode 100644 index 00000000..a29b1f38 --- /dev/null +++ b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.java @@ -0,0 +1,41 @@ +import java.util.*; + +class Solution { + public int minSessions(int[] tasks, int sessionTime) { + Integer[] arr = Arrays.stream(tasks).boxed().toArray(Integer[]::new); + Arrays.sort(arr, Collections.reverseOrder()); + int[] sorted = Arrays.stream(arr).mapToInt(Integer::intValue).toArray(); + tasks = sorted; + + int lo = 1, hi = tasks.length; + int res = hi; + while (lo <= hi) { + int mid = (lo + hi) / 2; + if (feasibility(tasks, sessionTime, mid)) { + res = mid; + hi = mid - 1; + } else { + lo = mid + 1; + } + } + return res; + } + + private boolean feasibility(int[] tasks, int sessionTime, int n) { + int[] sessions = new int[n]; + return dfs(tasks, sessionTime, 0, sessions); + } + + private boolean dfs(int[] tasks, int sessionTime, int i, int[] sessions) { + for (int v : sessions) if (v > sessionTime) return false; + if (i == tasks.length) return true; + + for (int s = 0; s < sessions.length; s++) { + sessions[s] += tasks[i]; + if (dfs(tasks, sessionTime, i+1, sessions)) return true; + sessions[s] -= tasks[i]; + if (sessions[s] == 0) return false; + } + return false; + } +} diff --git a/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.kt b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.kt new file mode 100644 index 00000000..62a0c2af --- /dev/null +++ b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.kt @@ -0,0 +1,38 @@ +class Solution { + fun minSessions(tasks: IntArray, sessionTime: Int): Int { + tasks.sortDescending() + + fun feasibility(n: Int): Boolean { + val sessions = IntArray(n) + + fun dfs(i: Int): Boolean { + if (sessions.max()!! > sessionTime) return false + if (i == tasks.size) return true + + for (s in 0 until n) { + sessions[s] += tasks[i] + if (dfs(i+1)) return true + sessions[s] -= tasks[i] + if (sessions[s] == 0) return false + } + return false + } + + return dfs(0) + } + + var lo = 1 + var hi = tasks.size + var res = hi + while (lo <= hi) { + val mid = (lo + hi) / 2 + if (feasibility(mid)) { + res = mid + hi = mid - 1 + } else { + lo = mid + 1 + } + } + return res + } +} diff --git a/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.py b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.py new file mode 100644 index 00000000..2a13828f --- /dev/null +++ b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.py @@ -0,0 +1,45 @@ +class Solution: + def minSessions(self, tasks: List[int], sessionTime: int) -> int: + # feasibility: + # for T tasks, can we fit them in N sessions? + # partition array s.t. max sum is T. + + tasks.sort(reverse=True) + + def feasibility(N): + sessions = [0] * N + + def dfs(i): + if max(sessions) > sessionTime: + return False + if i == len(tasks): + return True + + for s in range(N): + sessions[s] += tasks[i] + + if dfs(i + 1): + return True + + sessions[s] -= tasks[i] + if sessions[s] == 0: + return False + + return False + + return dfs(0) + + lo = 1 # all tasks fit in 1 session + hi = len(tasks) # each task takes 1 session + res = hi + + while lo <= hi: + mid = (lo + hi) // 2 + + if feasibility(mid): + res = mid + hi = mid - 1 + else: + lo = mid + 1 + + return res diff --git a/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.py2 b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.py2 new file mode 100644 index 00000000..5723323f --- /dev/null +++ b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.py2 @@ -0,0 +1,39 @@ +class Solution(object): + def minSessions(self, tasks, sessionTime): + """ + :type tasks: List[int] + :type sessionTime: int + :rtype: int + """ + tasks.sort(reverse=True) + + def feasibility(N): + sessions = [0] * N + + def dfs(i): + if max(sessions) > sessionTime: + return False + if i == len(tasks): + return True + + for s in range(N): + sessions[s] += tasks[i] + if dfs(i+1): + return True + sessions[s] -= tasks[i] + if sessions[s] == 0: + return False + return False + + return dfs(0) + + lo, hi = 1, len(tasks) + res = hi + while lo <= hi: + mid = (lo + hi) // 2 + if feasibility(mid): + res = mid + hi = mid - 1 + else: + lo = mid + 1 + return res diff --git a/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.rb b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.rb new file mode 100644 index 00000000..a0ff740e --- /dev/null +++ b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.rb @@ -0,0 +1,39 @@ +# @param {Integer[]} tasks +# @param {Integer} session_time +# @return {Integer} +def min_sessions(tasks, session_time) + tasks.sort! { |a, b| b <=> a } + + feasibility = ->(n) { + sessions = Array.new(n, 0) + + dfs = nil + dfs = ->(i) { + return false if sessions.max > session_time + return true if i == tasks.length + + (0...n).each do |s| + sessions[s] += tasks[i] + return true if dfs.call(i+1) + sessions[s] -= tasks[i] + return false if sessions[s] == 0 + end + false + } + + dfs.call(0) + } + + lo, hi = 1, tasks.length + res = hi + while lo <= hi + mid = (lo + hi) / 2 + if feasibility.call(mid) + res = mid + hi = mid - 1 + else + lo = mid + 1 + end + end + res +end diff --git a/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.rs b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.rs new file mode 100644 index 00000000..7446c193 --- /dev/null +++ b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.rs @@ -0,0 +1,39 @@ +impl Solution { + pub fn min_sessions(tasks: Vec, session_time: i32) -> i32 { + let mut tasks = tasks; + tasks.sort_by(|a, b| b.cmp(a)); + + fn feasibility(tasks: &Vec, session_time: i32, n: usize) -> bool { + let mut sessions = vec![0i32; n]; + + fn dfs(tasks: &Vec, session_time: i32, i: usize, sessions: &mut Vec) -> bool { + if sessions.iter().any(|&v| v > session_time) { return false; } + if i == tasks.len() { return true; } + + for s in 0..sessions.len() { + sessions[s] += tasks[i]; + if dfs(tasks, session_time, i+1, sessions) { return true; } + sessions[s] -= tasks[i]; + if sessions[s] == 0 { return false; } + } + false + } + + dfs(tasks, session_time, 0, &mut sessions) + } + + let mut lo = 1usize; + let mut hi = tasks.len(); + let mut res = hi as i32; + while lo <= hi { + let mid = (lo + hi) / 2; + if feasibility(&tasks, session_time, mid) { + res = mid as i32; + hi = mid - 1; + } else { + lo = mid + 1; + } + } + res + } +} diff --git a/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.swift b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.swift new file mode 100644 index 00000000..adb5574c --- /dev/null +++ b/tests/1501-2000/1986. minimum-number-of-work-sessions-to-finish-the-tasks/sol.swift @@ -0,0 +1,37 @@ +class Solution { + func minSessions(_ tasks: [Int], _ sessionTime: Int) -> Int { + var tasks = tasks.sorted(by: >) + + func feasibility(_ n: Int) -> Bool { + var sessions = [Int](repeating: 0, count: n) + + func dfs(_ i: Int) -> Bool { + if sessions.max()! > sessionTime { return false } + if i == tasks.count { return true } + + for s in 0.. b - a); + + function feasibility(n: number): boolean { + const sessions = new Array(n).fill(0); + + function dfs(i: number): boolean { + for (const v of sessions) { + if (v > sessionTime) return false; + } + if (i === tasks.length) return true; + + for (let s = 0; s < n; s++) { + sessions[s] += tasks[i]; + if (dfs(i + 1)) return true; + sessions[s] -= tasks[i]; + if (sessions[s] === 0) return false; + } + return false; + } + + return dfs(0); + } + + let lo = 1, + hi = tasks.length; + let res = hi; + while (lo <= hi) { + const mid = Math.floor((lo + hi) / 2); + if (feasibility(mid)) { + res = mid; + hi = mid - 1; + } else { + lo = mid + 1; + } + } + return res; +} diff --git a/tests/1501-2000/1987. number-of-unique-good-subsequences/manifest.yaml b/tests/1501-2000/1987. number-of-unique-good-subsequences/manifest.yaml new file mode 100644 index 00000000..d21b2d75 --- /dev/null +++ b/tests/1501-2000/1987. number-of-unique-good-subsequences/manifest.yaml @@ -0,0 +1,229 @@ +entry: + id: 1987 + title: "number-of-unique-good-subsequences" + params: + binary: + type: string + call: + cpp: "Solution().numberOfUniqueGoodSubsequences({binary})" + rust: "Solution::number_of_unique_good_subsequences({binary})" + python3: "Solution().numberOfUniqueGoodSubsequences({binary})" + python2: "Solution().numberOfUniqueGoodSubsequences({binary})" + ruby: "number_of_unique_good_subsequences({binary})" + java: "new Solution().numberOfUniqueGoodSubsequences({binary})" + csharp: "new Solution().NumberOfUniqueGoodSubsequences({binary})" + kotlin: "Solution().numberOfUniqueGoodSubsequences({binary})" + go: "numberOfUniqueGoodSubsequences({binary})" + dart: "Solution().numberOfUniqueGoodSubsequences({binary})" + swift: "Solution().numberOfUniqueGoodSubsequences({binary})" + typescript: "numberOfUniqueGoodSubsequences({binary})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().check(binary, {result})" + checker: | + class Checker: + def check(self, binary, result): + mod = 1000000007 + end0 = 0 + end1 = 0 + has_zero = False + for ch in binary: + if ch == "0": + end0 = (end0 + end1) % mod + has_zero = True + else: + end1 = (end0 + end1 + 1) % mod + expected = (end0 + end1 + (1 if has_zero else 0)) % mod + return result == expected + +seed: 1987 + +tests: + - name: single-zero + in: + binary: "0" + out: 1 + - name: single-one + in: + binary: "1" + out: 1 + - name: zero-zero + in: + binary: "00" + out: 1 + - name: one-one + in: + binary: "11" + out: 2 + - name: example-001 + in: + binary: "001" + out: 2 + - name: example-101 + in: + binary: "101" + out: 5 + - name: alternating-short + in: + binary: "0101" + out: 5 + - name: alternating-long + in: + binary: "101010" + out: 21 + - name: one-zero + in: + binary: "10" + out: 3 + - name: zero-one + in: + binary: "01" + out: 2 + - name: one-zero-zero + in: + binary: "100" + out: 4 + - name: zero-one-zero + in: + binary: "010" + out: 3 + - name: one-zero-one-one + in: + binary: "1011" + out: 7 + - name: zero-prefix-one-run + in: + binary: "000111" + out: 4 + - name: one-prefix-zero-run + in: + binary: "111000" + out: 13 + - name: all-ones-five + in: + binary: "11111" + out: 5 + - name: all-zeros-five + in: + binary: "00000" + out: 1 + - name: one-zero-one-zero-one + in: + binary: "10101" + out: 13 + - name: zero-one-one-zero-zero + in: + binary: "01100" + out: 7 + - name: repeated-block + in: + binary: "11001100" + out: 41 + - name: leading-zeros + in: + binary: "000010101" + out: 13 + - name: trailing-zeros + in: + binary: "1010000" + out: 17 + - name: sparse-ones + in: + binary: "1000001" + out: 13 + - name: sparse-zeros + in: + binary: "0111110" + out: 11 + - name: balanced-eight + in: + binary: "01011010" + out: 31 + - name: mixed-nine + in: + binary: "110101001" + out: 81 + - name: mixed-ten + in: + binary: "0011010110" + out: 50 + - name: one-zero-cycle + in: + binary: "1001001001" + out: 97 + - name: zero-one-cycle + in: + binary: "0110110110" + out: 71 + - name: long-ones + in: + binary: "11111111111111111111" + out: 20 + - name: long-zeros + in: + binary: "00000000000000000000" + out: 1 + - name: alternating-twenty + in: + binary: "10101010101010101010" + out: 17711 + - name: dense-mixed + in: + binary: "11101110111011101110" + out: 3742 + - name: sparse-mixed + in: + binary: "10001000100010001000" + out: 2640 + - name: large-periodic + in: + binary: "00110011001100110011001100110011" + out: 665857 + - name: generated-short + in: + binary: + gen: "str" + len: 37 + alphabet: "01" + judge: + type: "exact" + - name: generated-medium + in: + binary: + gen: "str" + len: 257 + alphabet: "01" + judge: + type: "exact" + - name: generated-long + in: + binary: + gen: "str" + len: 4096 + alphabet: "01" + judge: + type: "exact" + - name: generated-near-limit + in: + binary: + gen: "str" + len: 50000 + alphabet: "01" + judge: + type: "exact" + - name: generated-maximum + in: + binary: + gen: "str" + len: 100000 + alphabet: "01" + judge: + type: "exact" diff --git a/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.cpp b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.cpp new file mode 100644 index 00000000..443d14d2 --- /dev/null +++ b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int numberOfUniqueGoodSubsequences(string binary) { + long long a = 0, b = 0; + int z = 0; + const long long MOD = 1000000007; + for (char c : binary) { + if (c == '1') { + b = (a + b + 1) % MOD; + } else { + a = (a + b) % MOD; + z = 1; + } + } + return (int)((a + b + z) % MOD); + } +}; diff --git a/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.cs b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.cs new file mode 100644 index 00000000..08729f0f --- /dev/null +++ b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.cs @@ -0,0 +1,16 @@ +public class Solution { + public int NumberOfUniqueGoodSubsequences(string binary) { + long a = 0, b = 0; + int z = 0; + const long MOD = 1000000007; + foreach (char c in binary) { + if (c == '1') { + b = (a + b + 1) % MOD; + } else { + a = (a + b) % MOD; + z = 1; + } + } + return (int)((a + b + z) % MOD); + } +} diff --git a/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.dart b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.dart new file mode 100644 index 00000000..13358bf8 --- /dev/null +++ b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.dart @@ -0,0 +1,15 @@ +class Solution { + int numberOfUniqueGoodSubsequences(String binary) { + int a = 0, b = 0, z = 0; + const mod = 1000000007; + for (int i = 0; i < binary.length; i++) { + if (binary[i] == '1') { + b = (a + b + 1) % mod; + } else { + a = (a + b) % mod; + z = 1; + } + } + return (a + b + z) % mod; + } +} diff --git a/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.go b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.go new file mode 100644 index 00000000..00a0ab9d --- /dev/null +++ b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.go @@ -0,0 +1,14 @@ +func numberOfUniqueGoodSubsequences(binary string) int { + a, b := 0, 0 + z := 0 + mod := 1000000007 + for _, c := range binary { + if c == '1' { + b = (a + b + 1) % mod + } else { + a = (a + b) % mod + z = 1 + } + } + return (a + b + z) % mod +} diff --git a/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.java b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.java new file mode 100644 index 00000000..0f788b87 --- /dev/null +++ b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.java @@ -0,0 +1,15 @@ +class Solution { + public int numberOfUniqueGoodSubsequences(String binary) { + long a = 0, b = 0; + int z = 0; + for (char c : binary.toCharArray()) { + if (c == '1') { + b = (a + b + 1) % 1000000007L; + } else { + a = (a + b) % 1000000007L; + z = 1; + } + } + return (int)((a + b + z) % 1000000007L); + } +} diff --git a/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.kt b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.kt new file mode 100644 index 00000000..75cf104a --- /dev/null +++ b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun numberOfUniqueGoodSubsequences(binary: String): Int { + var a = 0L + var b = 0L + var z = 0 + for (c in binary) { + if (c == '1') { + b = (a + b + 1) % 1000000007L + } else { + a = (a + b) % 1000000007L + z = 1 + } + } + return ((a + b + z) % 1000000007L).toInt() + } +} diff --git a/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.py b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.py new file mode 100644 index 00000000..e5cf6402 --- /dev/null +++ b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.py @@ -0,0 +1,11 @@ +class Solution: + def numberOfUniqueGoodSubsequences(self, binary: str) -> int: + a, b = 0, 0 + z = 0 + for c in binary: + if c == "1": + b = (a + b + 1) % (10**9 + 7) + else: + a = (a + b) % (10**9 + 7) + z = 1 + return (a + b + z) % (10**9 + 7) diff --git a/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.py2 b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.py2 new file mode 100644 index 00000000..d1feed90 --- /dev/null +++ b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.py2 @@ -0,0 +1,15 @@ +class Solution(object): + def numberOfUniqueGoodSubsequences(self, binary): + """ + :type binary: str + :rtype: int + """ + a, b = 0, 0 + z = 0 + for c in binary: + if c == '1': + b = (a + b + 1) % (10**9 + 7) + else: + a = (a + b) % (10**9 + 7) + z = 1 + return (a + b + z) % (10**9 + 7) diff --git a/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.rb b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.rb new file mode 100644 index 00000000..e97b4862 --- /dev/null +++ b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.rb @@ -0,0 +1,16 @@ +# @param {String} binary +# @return {Integer} +def number_of_unique_good_subsequences(binary) + a = 0 + b = 0 + z = 0 + binary.each_char do |c| + if c == '1' + b = (a + b + 1) % (10**9 + 7) + else + a = (a + b) % (10**9 + 7) + z = 1 + end + end + (a + b + z) % (10**9 + 7) +end diff --git a/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.rs b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.rs new file mode 100644 index 00000000..ab987356 --- /dev/null +++ b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn number_of_unique_good_subsequences(binary: String) -> i32 { + let mut a: i64 = 0; + let mut b: i64 = 0; + let mut z: i64 = 0; + let modulo: i64 = 1_000_000_007; + for c in binary.chars() { + if c == '1' { + b = (a + b + 1) % modulo; + } else { + a = (a + b) % modulo; + z = 1; + } + } + ((a + b + z) % modulo) as i32 + } +} diff --git a/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.swift b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.swift new file mode 100644 index 00000000..d16f3411 --- /dev/null +++ b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.swift @@ -0,0 +1,17 @@ +class Solution { + func numberOfUniqueGoodSubsequences(_ binary: String) -> Int { + var a = 0 + var b = 0 + var z = 0 + let mod = 1000000007 + for c in binary { + if c == "1" { + b = (a + b + 1) % mod + } else { + a = (a + b) % mod + z = 1 + } + } + return (a + b + z) % mod + } +} diff --git a/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.ts b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.ts new file mode 100644 index 00000000..e19b0528 --- /dev/null +++ b/tests/1501-2000/1987. number-of-unique-good-subsequences/sol.ts @@ -0,0 +1,15 @@ +function numberOfUniqueGoodSubsequences(binary: string): number { + let a = 0, + b = 0, + z = 0; + const mod = 1000000007; + for (const c of binary) { + if (c === "1") { + b = (a + b + 1) % mod; + } else { + a = (a + b) % mod; + z = 1; + } + } + return (a + b + z) % mod; +} diff --git a/tests/1501-2000/1991. find-the-middle-index-in-array/manifest.yaml b/tests/1501-2000/1991. find-the-middle-index-in-array/manifest.yaml new file mode 100644 index 00000000..0844fc14 --- /dev/null +++ b/tests/1501-2000/1991. find-the-middle-index-in-array/manifest.yaml @@ -0,0 +1,323 @@ +entry: + id: 1991 + title: "find-the-middle-index-in-array" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().findMiddleIndex({nums})" + rust: "Solution::find_middle_index({nums})" + python3: "Solution().findMiddleIndex({nums})" + python2: "Solution().findMiddleIndex({nums})" + ruby: "find_middle_index({nums})" + java: "new Solution().findMiddleIndex({nums})" + csharp: "new Solution().FindMiddleIndex({nums})" + kotlin: "Solution().findMiddleIndex({nums})" + go: "findMiddleIndex({nums})" + dart: "Solution().findMiddleIndex({nums})" + swift: "Solution().findMiddleIndex({nums})" + typescript: "findMiddleIndex({nums})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().findMiddleIndex(nums, {result})" + checker: | + class Checker: + def findMiddleIndex(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + total = sum(nums) + left = 0 + expected = -1 + for i, value in enumerate(nums): + if left == total - left - value: + expected = i + break + left += value + return result == expected + +seed: 1991 + +tests: + - name: example-one + in: + nums: [2, 3, -1, 8, 4] + out: 3 + judge: + type: "exact" + - name: example-two + in: + nums: [1, -1, 4] + out: 2 + judge: + type: "exact" + - name: example-three + in: + nums: [2, 5] + out: -1 + judge: + type: "exact" + - name: single-zero + in: + nums: [0] + out: 0 + judge: + type: "exact" + - name: single-positive + in: + nums: [7] + out: 0 + judge: + type: "exact" + - name: single-negative + in: + nums: [-7] + out: 0 + judge: + type: "exact" + - name: two-zeros + in: + nums: [0, 0] + out: 0 + judge: + type: "exact" + - name: two-balanced-at-right + in: + nums: [0, 5] + out: 1 + judge: + type: "exact" + - name: two-balanced-at-left + in: + nums: [5, 0] + out: 0 + judge: + type: "exact" + - name: two-unbalanced + in: + nums: [-3, 4] + out: -1 + judge: + type: "exact" + - name: leftmost-among-many + in: + nums: [0, 0, 0, 0] + out: 0 + judge: + type: "exact" + - name: repeated-positive + in: + nums: [1, 1, 1, 1, 1] + out: 2 + judge: + type: "exact" + - name: repeated-negative + in: + nums: [-1, -1, -1, -1, -1] + out: 2 + judge: + type: "exact" + - name: negative-total + in: + nums: [-2, -3, 5, -1, -4] + out: 2 + judge: + type: "exact" + - name: mixed-sign-center + in: + nums: [-1, 2, 3, -2, -2] + out: 1 + judge: + type: "exact" + - name: pivot-at-first + in: + nums: [0, 1, -1, 2, -2] + out: 0 + judge: + type: "exact" + - name: pivot-at-last + in: + nums: [1, -1, 2, -2, 0] + out: 4 + judge: + type: "exact" + - name: first-candidate-not-last + in: + nums: [0, 2, -2, 0] + out: 0 + judge: + type: "exact" + - name: later-candidate + in: + nums: [4, -2, -2, 0] + out: 3 + judge: + type: "exact" + - name: alternating-signs + in: + nums: [5, -5, 5, -5, 5, -5] + out: -1 + judge: + type: "exact" + - name: all-max-values + in: + nums: [1000, 1000, 1000] + out: 1 + judge: + type: "exact" + - name: all-min-values + in: + nums: [-1000, -1000, -1000] + out: 1 + judge: + type: "exact" + - name: max-range-balanced + in: + nums: [1000, -1000, 1000, -1000, 0] + out: 4 + judge: + type: "exact" + - name: min-range-balanced + in: + nums: [-1000, 1000, -1000, 1000, 0] + out: 4 + judge: + type: "exact" + - name: six-elements + in: + nums: [3, 1, -4, 2, 2, -1] + out: 0 + judge: + type: "exact" + - name: seven-elements + in: + nums: [10, -5, -5, 0, 4, -2, -2] + out: 3 + judge: + type: "exact" + - name: no-zero-values + in: + nums: [8, -3, 6, -4, 2] + out: -1 + judge: + type: "exact" + - name: zero-sum-prefix + in: + nums: [2, -2, 5, -5, 9] + out: 4 + judge: + type: "exact" + - name: large-cancellation + in: + nums: [1000, 1000, -1000, -1000, 7] + out: 4 + judge: + type: "exact" + - name: negative-pivot-value + in: + nums: [4, -1, 2, -5, 0] + out: 4 + judge: + type: "exact" + - name: pivot-value-does-not-matter + in: + nums: [3, 1, 9, -4, -9, 0] + out: 5 + judge: + type: "exact" + - name: length-ten + in: + nums: [1, 2, 3, 4, 5, -5, -4, -3, -2, -1] + out: -1 + judge: + type: "exact" + - name: length-eleven + in: + nums: [-5, 3, 2, 1, 0, 4, -2, -1, -1, 0, 0] + out: 3 + judge: + type: "exact" + - name: many-leading-zeros + in: + nums: [0, 0, 0, 5, -5, 0] + out: 0 + judge: + type: "exact" + - name: long-symmetric + in: + nums: [1, 2, 3, 4, 5, 6, 0, -6, -5, -4, -3, -2, -1] + out: -1 + judge: + type: "exact" + - name: generated-random-moderate + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: "int" + - name: generated-random-short + in: + nums: + gen: "array" + len: 37 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: "int" + - name: generated-all-boundary + in: + nums: + gen: "array" + len: 100 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: "int" + seed: 199101 + - name: generated-random-long + in: + nums: + gen: "array" + len: 99 + of: + gen: "int" + min: -1000 + max: 1000 + distinct: false + sorted: false + elemType: "int" + seed: 199102 + - name: generated-zero-heavy-range + in: + nums: + gen: "array" + len: 64 + of: + gen: "int" + min: -10 + max: 10 + distinct: false + sorted: false + elemType: "int" + seed: 199103 diff --git a/tests/1501-2000/1991. find-the-middle-index-in-array/sol.cpp b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.cpp new file mode 100644 index 00000000..381422c4 --- /dev/null +++ b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int findMiddleIndex(vector& nums) { + int total = 0; + for (int num : nums) total += num; + + int leftSum = 0; + int rightSum = total; + + for (int i = 0; i < nums.size(); i++) { + rightSum -= nums[i]; + if (leftSum == rightSum) return i; + leftSum += nums[i]; + } + + return -1; + } +}; diff --git a/tests/1501-2000/1991. find-the-middle-index-in-array/sol.cs b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.cs new file mode 100644 index 00000000..5faab2d5 --- /dev/null +++ b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.cs @@ -0,0 +1,15 @@ +public class Solution { + public int FindMiddleIndex(int[] nums) { + int total = nums.Sum(); + int leftSum = 0; + int rightSum = total; + + for (int i = 0; i < nums.Length; i++) { + rightSum -= nums[i]; + if (leftSum == rightSum) return i; + leftSum += nums[i]; + } + + return -1; + } +} diff --git a/tests/1501-2000/1991. find-the-middle-index-in-array/sol.dart b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.dart new file mode 100644 index 00000000..e91af004 --- /dev/null +++ b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.dart @@ -0,0 +1,15 @@ +class Solution { + int findMiddleIndex(List nums) { + int total = nums.reduce((a, b) => a + b); + int leftSum = 0; + int rightSum = total; + + for (int i = 0; i < nums.length; i++) { + rightSum -= nums[i]; + if (leftSum == rightSum) return i; + leftSum += nums[i]; + } + + return -1; + } +} diff --git a/tests/1501-2000/1991. find-the-middle-index-in-array/sol.go b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.go new file mode 100644 index 00000000..2f83d4ad --- /dev/null +++ b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.go @@ -0,0 +1,19 @@ +func findMiddleIndex(nums []int) int { + total := 0 + for _, num := range nums { + total += num + } + + leftSum := 0 + rightSum := total + + for i, num := range nums { + rightSum -= num + if leftSum == rightSum { + return i + } + leftSum += num + } + + return -1 +} diff --git a/tests/1501-2000/1991. find-the-middle-index-in-array/sol.java b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.java new file mode 100644 index 00000000..a1257eda --- /dev/null +++ b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.java @@ -0,0 +1,17 @@ +class Solution { + public int findMiddleIndex(int[] nums) { + int total = 0; + for (int num : nums) total += num; + + int leftSum = 0; + int rightSum = total; + + for (int i = 0; i < nums.length; i++) { + rightSum -= nums[i]; + if (leftSum == rightSum) return i; + leftSum += nums[i]; + } + + return -1; + } +} diff --git a/tests/1501-2000/1991. find-the-middle-index-in-array/sol.kt b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.kt new file mode 100644 index 00000000..f9db15b8 --- /dev/null +++ b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun findMiddleIndex(nums: IntArray): Int { + val total = nums.sum() + var leftSum = 0 + var rightSum = total + + for (i in nums.indices) { + rightSum -= nums[i] + if (leftSum == rightSum) return i + leftSum += nums[i] + } + + return -1 + } +} diff --git a/tests/1501-2000/1991. find-the-middle-index-in-array/sol.py b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.py new file mode 100644 index 00000000..fcb6a3bc --- /dev/null +++ b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.py @@ -0,0 +1,17 @@ +class Solution: + def findMiddleIndex(self, nums): + + total = sum(nums) + + leftSum = 0 + rightSum = total + + for i in range(len(nums)): + rightSum -= nums[i] + + if leftSum == rightSum: + return i + + leftSum += nums[i] + + return -1 diff --git a/tests/1501-2000/1991. find-the-middle-index-in-array/sol.py2 b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.py2 new file mode 100644 index 00000000..d3689da2 --- /dev/null +++ b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.py2 @@ -0,0 +1,17 @@ +class Solution(object): + def findMiddleIndex(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + total = sum(nums) + left_sum = 0 + right_sum = total + + for i in range(len(nums)): + right_sum -= nums[i] + if left_sum == right_sum: + return i + left_sum += nums[i] + + return -1 diff --git a/tests/1501-2000/1991. find-the-middle-index-in-array/sol.rb b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.rb new file mode 100644 index 00000000..b0a4e1d6 --- /dev/null +++ b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.rb @@ -0,0 +1,15 @@ +# @param {Integer[]} nums +# @return {Integer} +def find_middle_index(nums) + total = nums.sum + left_sum = 0 + right_sum = total + + nums.each_with_index do |num, i| + right_sum -= num + return i if left_sum == right_sum + left_sum += num + end + + -1 +end diff --git a/tests/1501-2000/1991. find-the-middle-index-in-array/sol.rs b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.rs new file mode 100644 index 00000000..23b2e55f --- /dev/null +++ b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn find_middle_index(nums: Vec) -> i32 { + let total: i32 = nums.iter().sum(); + let mut left_sum = 0; + let mut right_sum = total; + + for (i, &num) in nums.iter().enumerate() { + right_sum -= num; + if left_sum == right_sum { + return i as i32; + } + left_sum += num; + } + + -1 + } +} diff --git a/tests/1501-2000/1991. find-the-middle-index-in-array/sol.swift b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.swift new file mode 100644 index 00000000..9896aeb2 --- /dev/null +++ b/tests/1501-2000/1991. find-the-middle-index-in-array/sol.swift @@ -0,0 +1,17 @@ +class Solution { + func findMiddleIndex(_ nums: [Int]) -> Int { + let total = nums.reduce(0, +) + var leftSum = 0 + var rightSum = total + + for i in 0.. a + b, 0); + let leftSum = 0; + let rightSum = total; + + for (let i = 0; i < nums.length; i++) { + rightSum -= nums[i]; + if (leftSum === rightSum) return i; + leftSum += nums[i]; + } + + return -1; +} diff --git a/tests/1501-2000/1992. find-all-groups-of-farmland/manifest.yaml b/tests/1501-2000/1992. find-all-groups-of-farmland/manifest.yaml new file mode 100644 index 00000000..3b825ee8 --- /dev/null +++ b/tests/1501-2000/1992. find-all-groups-of-farmland/manifest.yaml @@ -0,0 +1,372 @@ +entry: + id: 1992 + title: "find-all-groups-of-farmland" + params: + land: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().findFarmland({land})" + rust: "Solution::find_farmland({land})" + python3: "Solution().findFarmland({land})" + python2: "Solution().findFarmland({land})" + ruby: "find_farmland({land})" + java: "new Solution().findFarmland({land})" + csharp: "new Solution().FindFarmland({land})" + kotlin: "Solution().findFarmland({land})" + go: "findFarmland({land})" + dart: "Solution().findFarmland({land})" + swift: "Solution().findFarmland({land})" + typescript: "findFarmland({land})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().findFarmland(land, {result})" + checker: | + class Checker: + def findFarmland(self, land, result): + if not isinstance(result, list): + return False + rows = len(land) + cols = len(land[0]) + seen = [[False] * cols for _ in range(rows)] + expected = [] + for r in range(rows): + for c in range(cols): + if land[r][c] == 1 and not seen[r][c]: + stack = [(r, c)] + seen[r][c] = True + cells = [] + while stack: + x, y = stack.pop() + cells.append((x, y)) + for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)): + nx, ny = x + dx, y + dy + if 0 <= nx < rows and 0 <= ny < cols and land[nx][ny] == 1 and not seen[nx][ny]: + seen[nx][ny] = True + stack.append((nx, ny)) + top = min(x for x, y in cells) + left = min(y for x, y in cells) + bottom = max(x for x, y in cells) + right = max(y for x, y in cells) + expected.append((top, left, bottom, right)) + actual = [] + for item in result: + if not isinstance(item, list) or len(item) != 4 or not all(isinstance(x, int) and not isinstance(x, bool) for x in item): + return False + r1, c1, r2, c2 = item + if not (0 <= r1 <= r2 < rows and 0 <= c1 <= c2 < cols): + return False + for r in range(r1, r2 + 1): + for c in range(c1, c2 + 1): + if land[r][c] != 1: + return False + actual.append(tuple(item)) + return sorted(actual) == sorted(expected) + +seed: 1992 + +tests: + - name: "example_single_and_square" + in: + land: + - [1, 0, 0] + - [0, 1, 1] + - [0, 1, 1] + - name: "example_full" + in: + land: + - [1, 1] + - [1, 1] + - name: "example_empty" + in: + land: + - [0] + - name: "single_one" + in: + land: + - [0, 0, 0, 0] + - [0, 0, 1, 0] + - [0, 0, 0, 0] + - name: "single_row_alternating" + in: + land: + - [1, 0, 1, 0, 1, 0, 1] + - name: "single_column_alternating" + in: + land: + - [1] + - [0] + - [1] + - [0] + - [1] + - name: "two_horizontal_groups" + in: + land: + - [1, 1, 0, 0, 1] + - [1, 1, 0, 0, 1] + - name: "two_vertical_groups" + in: + land: + - [1, 0, 1] + - [1, 0, 1] + - [0, 0, 1] + - [1, 0, 0] + - name: "corner_points" + in: + land: + - [1, 0, 0, 1] + - [0, 0, 0, 0] + - [0, 0, 0, 0] + - [1, 0, 0, 1] + - name: "three_rectangles" + in: + land: + - [1, 1, 0, 0, 0, 1] + - [1, 1, 0, 0, 0, 1] + - [0, 0, 1, 1, 0, 0] + - [0, 0, 1, 1, 0, 0] + - name: "thin_top_and_bottom" + in: + land: + - [1, 1, 1, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0] + - [0, 1, 1, 1, 0] + - name: "nested_gaps" + in: + land: + - [1, 1, 0, 1, 1] + - [1, 1, 0, 1, 1] + - [0, 0, 0, 0, 0] + - [1, 0, 1, 0, 1] + - name: "checkerboard_4" + in: + land: + - [1, 0, 1, 0] + - [0, 1, 0, 1] + - [1, 0, 1, 0] + - [0, 1, 0, 1] + - name: "left_large_right_points" + in: + land: + - [1, 1, 0, 0, 1, 0] + - [1, 1, 0, 0, 0, 0] + - [1, 1, 0, 0, 1, 0] + - [0, 0, 0, 0, 0, 0] + - name: "diagonal_components" + in: + land: + - [1, 0, 0, 0, 0] + - [0, 1, 0, 0, 0] + - [0, 0, 1, 0, 0] + - [0, 0, 0, 1, 0] + - [0, 0, 0, 0, 1] + - name: "middle_block" + in: + land: + - [0, 0, 0, 0, 0] + - [0, 1, 1, 0, 0] + - [0, 1, 1, 0, 0] + - [0, 0, 0, 0, 0] + - name: "four_singletons" + in: + land: + - [1, 0, 0, 0, 1] + - [0, 0, 0, 0, 0] + - [0, 0, 1, 0, 0] + - [0, 0, 0, 0, 0] + - [1, 0, 0, 0, 1] + - name: "wide_middle_group" + in: + land: + - [0, 0, 0, 0, 0, 0, 0] + - [1, 1, 1, 1, 1, 1, 1] + - [0, 0, 0, 0, 0, 0, 0] + - name: "tall_middle_group" + in: + land: + - [0, 1, 0] + - [0, 1, 0] + - [0, 1, 0] + - [0, 1, 0] + - [0, 1, 0] + - name: "border_strips" + in: + land: + - [1, 1, 1, 1, 1, 1] + - [0, 0, 0, 0, 0, 0] + - [1, 1, 1, 1, 1, 1] + - name: "four_by_six_blocks" + in: + land: + - [1, 1, 0, 0, 1, 1] + - [1, 1, 0, 0, 1, 1] + - [0, 0, 0, 0, 0, 0] + - [1, 1, 1, 0, 0, 0] + - name: "isolated_cross_corners" + in: + land: + - [1, 0, 1] + - [0, 0, 0] + - [1, 0, 1] + - name: "dense_left_sparse_right" + in: + land: + - [1, 1, 1, 0, 1] + - [1, 1, 1, 0, 0] + - [1, 1, 1, 0, 1] + - [0, 0, 0, 0, 0] + - name: "alternating_rows" + in: + land: + - [1, 1, 1, 1, 1] + - [0, 0, 0, 0, 0] + - [1, 1, 1, 1, 1] + - [0, 0, 0, 0, 0] + - [1, 1, 1, 1, 1] + - name: "two_by_ten" + in: + land: + - [1, 1, 0, 0, 1, 1, 0, 0, 1, 1] + - [1, 1, 0, 0, 1, 1, 0, 0, 1, 1] + - name: "ten_by_two" + in: + land: + - [1, 1] + - [1, 1] + - [0, 0] + - [1, 1] + - [1, 1] + - [0, 0] + - [1, 1] + - [1, 1] + - [0, 0] + - [1, 1] + - name: "hollow_zero_frame" + in: + land: + - [1, 1, 0, 0, 1] + - [1, 1, 0, 0, 1] + - [0, 0, 0, 0, 1] + - [0, 0, 1, 1, 0] + - name: "separated_corner_blocks" + in: + land: + - [1, 1, 0, 0, 0, 1, 1] + - [1, 1, 0, 0, 0, 1, 1] + - [0, 0, 0, 0, 0, 0, 0] + - [0, 0, 1, 1, 0, 0, 0] + - name: "five_singletons_row" + in: + land: + - [1, 0, 1, 0, 1, 0, 1, 0, 1] + - name: "large_empty_12" + in: + land: + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - name: "large_full_12" + in: + land: + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: "six_by_six_quadrants" + in: + land: + - [1, 1, 0, 0, 1, 1] + - [1, 1, 0, 0, 1, 1] + - [0, 0, 0, 0, 0, 0] + - [0, 0, 1, 1, 0, 0] + - [0, 0, 1, 1, 0, 0] + - [0, 0, 0, 0, 0, 0] + - name: "long_isolated_runs" + in: + land: + - [1, 1, 1, 1, 0, 0, 0, 1, 1, 1] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [1, 1, 0, 0, 1, 1, 1, 0, 0, 1] + - name: "mixed_8x8" + in: + land: + - [1, 1, 0, 0, 0, 0, 1, 1] + - [1, 1, 0, 0, 0, 0, 1, 1] + - [0, 0, 0, 1, 1, 0, 0, 0] + - [0, 0, 0, 1, 1, 0, 0, 0] + - [1, 0, 0, 0, 0, 1, 1, 0] + - [1, 0, 0, 0, 0, 1, 1, 0] + - [0, 0, 1, 1, 0, 0, 0, 0] + - [0, 0, 1, 1, 0, 0, 0, 0] + - name: "single_row_full" + in: + land: + - [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: "single_column_full" + in: + land: + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - [1] + - name: "two_diagonal_rectangles" + in: + land: + - [1, 1, 0, 0, 0, 0] + - [1, 1, 0, 0, 0, 0] + - [0, 0, 0, 0, 1, 1] + - [0, 0, 0, 0, 1, 1] + - name: "maxish_sparse" + in: + land: + - [1, 0, 0, 0, 0, 0, 0, 0, 0, 1] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [0, 0, 1, 1, 0, 0, 1, 0, 0, 0] + - [0, 0, 1, 1, 0, 0, 1, 0, 0, 0] + - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + - [1, 1, 1, 0, 0, 0, 0, 1, 1, 1] + - [1, 1, 1, 0, 0, 0, 0, 1, 1, 1] + - name: "all_singletons_6x6" + in: + land: + - [1, 0, 1, 0, 1, 0] + - [0, 0, 0, 0, 0, 0] + - [1, 0, 1, 0, 1, 0] + - [0, 0, 0, 0, 0, 0] + - [1, 0, 1, 0, 1, 0] + - [0, 0, 0, 0, 0, 0] diff --git a/tests/1501-2000/1992. find-all-groups-of-farmland/sol.cpp b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.cpp new file mode 100644 index 00000000..e3be01a2 --- /dev/null +++ b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.cpp @@ -0,0 +1,40 @@ +class Solution { +public: + vector> findFarmland(vector>& land) { + int n = land.size(); + int m = land[0].size(); + vector> visited(n, vector(m, false)); + vector> directions = {{-1,0},{0,1},{1,0},{0,-1}}; + + vector maxr(1); + vector maxc(1); + + function dfs = [&](int r, int c) { + visited[r][c] = true; + maxr[0] = max(maxr[0], r); + maxc[0] = max(maxc[0], c); + for (auto& d : directions) { + int nr = r + d.first; + int nc = c + d.second; + if (nr >= 0 && nr < n && nc >= 0 && nc < m) { + if (!visited[nr][nc] && land[nr][nc] == 1) { + dfs(nr, nc); + } + } + } + }; + + vector> res; + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (land[i][j] == 1 && !visited[i][j]) { + maxr[0] = i; + maxc[0] = j; + dfs(i, j); + res.push_back({i, j, maxr[0], maxc[0]}); + } + } + } + return res; + } +}; diff --git a/tests/1501-2000/1992. find-all-groups-of-farmland/sol.cs b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.cs new file mode 100644 index 00000000..862413c9 --- /dev/null +++ b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.cs @@ -0,0 +1,40 @@ +public class Solution { + public int[][] FindFarmland(int[][] land) { + int n = land.Length; + int m = land[0].Length; + bool[][] visited = new bool[n][]; + for (int i = 0; i < n; i++) visited[i] = new bool[m]; + int[][] directions = new int[][] { new int[]{-1,0}, new int[]{0,1}, new int[]{1,0}, new int[]{0,-1} }; + + int[] maxr = new int[1]; + int[] maxc = new int[1]; + + void Dfs(int r, int c) { + visited[r][c] = true; + maxr[0] = Math.Max(maxr[0], r); + maxc[0] = Math.Max(maxc[0], c); + foreach (var d in directions) { + int nr = r + d[0]; + int nc = c + d[1]; + if (nr >= 0 && nr < n && nc >= 0 && nc < m) { + if (!visited[nr][nc] && land[nr][nc] == 1) { + Dfs(nr, nc); + } + } + } + } + + var res = new List(); + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (land[i][j] == 1 && !visited[i][j]) { + maxr[0] = i; + maxc[0] = j; + Dfs(i, j); + res.Add(new int[]{i, j, maxr[0], maxc[0]}); + } + } + } + return res.ToArray(); + } +} diff --git a/tests/1501-2000/1992. find-all-groups-of-farmland/sol.dart b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.dart new file mode 100644 index 00000000..89b4b6c1 --- /dev/null +++ b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.dart @@ -0,0 +1,39 @@ +class Solution { + List> findFarmland(List> land) { + int n = land.length; + int m = land[0].length; + List> visited = List.generate(n, (_) => List.filled(m, false)); + List> directions = [[-1,0],[0,1],[1,0],[0,-1]]; + + List maxr = [0]; + List maxc = [0]; + + void dfs(int r, int c) { + visited[r][c] = true; + if (r > maxr[0]) maxr[0] = r; + if (c > maxc[0]) maxc[0] = c; + for (var d in directions) { + int nr = r + d[0]; + int nc = c + d[1]; + if (nr >= 0 && nr < n && nc >= 0 && nc < m) { + if (!visited[nr][nc] && land[nr][nc] == 1) { + dfs(nr, nc); + } + } + } + } + + List> res = []; + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (land[i][j] == 1 && !visited[i][j]) { + maxr[0] = i; + maxc[0] = j; + dfs(i, j); + res.add([i, j, maxr[0], maxc[0]]); + } + } + } + return res; + } +} diff --git a/tests/1501-2000/1992. find-all-groups-of-farmland/sol.go b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.go new file mode 100644 index 00000000..ac044184 --- /dev/null +++ b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.go @@ -0,0 +1,40 @@ +func findFarmland(land [][]int) [][]int { + n := len(land) + m := len(land[0]) + visited := make([][]bool, n) + for i := range visited { + visited[i] = make([]bool, m) + } + directions := [][]int{{-1,0},{0,1},{1,0},{0,-1}} + + maxr := []int{0} + maxc := []int{0} + + var dfs func(r, c int) + dfs = func(r, c int) { + visited[r][c] = true + if r > maxr[0] { maxr[0] = r } + if c > maxc[0] { maxc[0] = c } + for _, d := range directions { + nr, nc := r + d[0], c + d[1] + if nr >= 0 && nr < n && nc >= 0 && nc < m { + if !visited[nr][nc] && land[nr][nc] == 1 { + dfs(nr, nc) + } + } + } + } + + res := make([][]int, 0) + for i := 0; i < n; i++ { + for j := 0; j < m; j++ { + if land[i][j] == 1 && !visited[i][j] { + maxr[0] = i + maxc[0] = j + dfs(i, j) + res = append(res, []int{i, j, maxr[0], maxc[0]}) + } + } + } + return res +} diff --git a/tests/1501-2000/1992. find-all-groups-of-farmland/sol.java b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.java new file mode 100644 index 00000000..c9f3c1ec --- /dev/null +++ b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.java @@ -0,0 +1,40 @@ +class Solution { + public int[][] findFarmland(int[][] land) { + int n = land.length; + int m = land[0].length; + boolean[][] visited = new boolean[n][m]; + int[][] directions = {{-1,0},{0,1},{1,0},{0,-1}}; + + int[] maxr = new int[1]; + int[] maxc = new int[1]; + + java.util.List res = new java.util.ArrayList<>(); + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (land[i][j] == 1 && !visited[i][j]) { + maxr[0] = i; + maxc[0] = j; + dfs(land, visited, directions, i, j, maxr, maxc); + res.add(new int[]{i, j, maxr[0], maxc[0]}); + } + } + } + return res.toArray(new int[0][]); + } + + private void dfs(int[][] land, boolean[][] visited, int[][] directions, int r, int c, int[] maxr, int[] maxc) { + visited[r][c] = true; + maxr[0] = Math.max(maxr[0], r); + maxc[0] = Math.max(maxc[0], c); + for (int[] d : directions) { + int nr = r + d[0]; + int nc = c + d[1]; + if (nr >= 0 && nr < land.length && nc >= 0 && nc < land[0].length) { + if (!visited[nr][nc] && land[nr][nc] == 1) { + dfs(land, visited, directions, nr, nc, maxr, maxc); + } + } + } + } +} diff --git a/tests/1501-2000/1992. find-all-groups-of-farmland/sol.kt b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.kt new file mode 100644 index 00000000..72ac07ed --- /dev/null +++ b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.kt @@ -0,0 +1,40 @@ +class Solution { + fun findFarmland(land: Array): Array { + val n = land.size + val m = land[0].size + val visited = Array(n) { BooleanArray(m) } + val directions = arrayOf(intArrayOf(-1,0), intArrayOf(0,1), intArrayOf(1,0), intArrayOf(0,-1)) + + val maxr = IntArray(1) + val maxc = IntArray(1) + + val res = mutableListOf() + + fun dfs(r: Int, c: Int) { + visited[r][c] = true + maxr[0] = maxOf(maxr[0], r) + maxc[0] = maxOf(maxc[0], c) + for (d in directions) { + val nr = r + d[0] + val nc = c + d[1] + if (nr >= 0 && nr < n && nc >= 0 && nc < m) { + if (!visited[nr][nc] && land[nr][nc] == 1) { + dfs(nr, nc) + } + } + } + } + + for (i in 0 until n) { + for (j in 0 until m) { + if (land[i][j] == 1 && !visited[i][j]) { + maxr[0] = i + maxc[0] = j + dfs(i, j) + res.add(intArrayOf(i, j, maxr[0], maxc[0])) + } + } + } + return res.toTypedArray() + } +} diff --git a/tests/1501-2000/1992. find-all-groups-of-farmland/sol.py b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.py new file mode 100644 index 00000000..51fe8359 --- /dev/null +++ b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.py @@ -0,0 +1,78 @@ +# posted its solution + + +class Solution: + def findFarmland(self, land: List[List[int]]) -> List[List[int]]: + grid = land + n = len(grid) + m = len(grid[0]) + + visi = [[False] * m for _ in range(n)] + + direct = [[-1, 0], [0, 1], [1, 0], [0, -1]] + + # NORMAL APPROACH------------------------------------------------------------------------------------- + def dfs(r, c, temp): + visi[r][c] = True + temp.append((r, c)) + + for dr, dc in direct: + nr, nc = r + dr, c + dc + if 0 <= nr < n and 0 <= nc < m: + if visi[nr][nc] == False and grid[nr][nc] == 1: + dfs(nr, nc, temp) + return temp + + # -------------------------------------------- + res = [] + for i in range(n): + for j in range(m): + if grid[i][j] == 1 and visi[i][j] == False: + temp = dfs(i, j, []) + + temp.sort() # O(log(n*m))this temp lenth can be + res.append((temp[0][0], temp[0][1], temp[-1][0], temp[-1][1])) + + return res + # total n*m log(n*m) + # ================================================================================================== + + # MOST OPTIMAL + """------------------------------------------------------------------------------------- + 🚀 APPROACH 2: DFS TRACKING BOUNDARIES (Optimal O(N*M)) + 1. Top-left corner is always the starting I, J of the DFS. + + 2. Bottom-right corner is simply the absolute MAX_R and MAX_C found during traversal. + becasue it is siad in question there will be in reectangle shape only + 3. By tracking MAX_COORDS dynamically, we completely avoid appending and sorting, reducing time to pure O(N*M). + #------------------------------------------------------------------- + """ + + def dfs(r, c, maxr, maxc): + visi[r][c] = True + + # ⭐ OPTIMIZATION: Just track the absolute max row and col found becasue it is siad in question there will be in reectangle shape only + maxr = max(maxr, r) + maxc = max(maxc, r) + + for dr, dc in direct: + nr, nc = r + dr, c + dc + if 0 <= nr < n and 0 <= nc < m: + if visi[nr][nc] == False and grid[nr][nc] == 1: + dfs(nr, nc, maxr, maxc) + + # -------------------------------------------- + res = [] + for i in range(n): + for j in range(m): + if grid[i][j] == 1 and visi[i][j] == False: + maxr, maxc = i, j # initially + dfs(i, j, maxr, maxc) + + res.append((i, j, maxr, maxc)) + + return res + # OPTIMAL SOLUTION time: O(N*M)) + + +# ================================================================================================== diff --git a/tests/1501-2000/1992. find-all-groups-of-farmland/sol.py2 b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.py2 new file mode 100644 index 00000000..0b275a23 --- /dev/null +++ b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.py2 @@ -0,0 +1,30 @@ +class Solution(object): + def findFarmland(self, land): + """ + :type land: List[List[int]] + :rtype: List[List[int]] + """ + n = len(land) + m = len(land[0]) + visited = [[False]*m for _ in range(n)] + directions = [[-1,0],[0,1],[1,0],[0,-1]] + + def dfs(r, c, maxr, maxc): + visited[r][c] = True + maxr[0] = max(maxr[0], r) + maxc[0] = max(maxc[0], c) + for dr, dc in directions: + nr, nc = r+dr, c+dc + if 0 <= nr < n and 0 <= nc < m: + if not visited[nr][nc] and land[nr][nc] == 1: + dfs(nr, nc, maxr, maxc) + + res = [] + for i in range(n): + for j in range(m): + if land[i][j] == 1 and not visited[i][j]: + maxr = [i] + maxc = [j] + dfs(i, j, maxr, maxc) + res.append([i, j, maxr[0], maxc[0]]) + return res diff --git a/tests/1501-2000/1992. find-all-groups-of-farmland/sol.rb b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.rb new file mode 100644 index 00000000..4fd07ca3 --- /dev/null +++ b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.rb @@ -0,0 +1,35 @@ +# @param {Integer[][]} land +# @return {Integer[][]} +def find_farmland(land) + n = land.length + m = land[0].length + visited = Array.new(n) { Array.new(m, false) } + directions = [[-1,0],[0,1],[1,0],[0,-1]] + + dfs = lambda do |r, c, maxr, maxc| + visited[r][c] = true + maxr[0] = [maxr[0], r].max + maxc[0] = [maxc[0], c].max + directions.each do |dr, dc| + nr, nc = r + dr, c + dc + if nr >= 0 && nr < n && nc >= 0 && nc < m + if !visited[nr][nc] && land[nr][nc] == 1 + dfs.call(nr, nc, maxr, maxc) + end + end + end + end + + res = [] + (0...n).each do |i| + (0...m).each do |j| + if land[i][j] == 1 && !visited[i][j] + maxr = [i] + maxc = [j] + dfs.call(i, j, maxr, maxc) + res << [i, j, maxr[0], maxc[0]] + end + end + end + res +end diff --git a/tests/1501-2000/1992. find-all-groups-of-farmland/sol.rs b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.rs new file mode 100644 index 00000000..c8781bc4 --- /dev/null +++ b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.rs @@ -0,0 +1,41 @@ +impl Solution { + pub fn find_farmland(land: Vec>) -> Vec> { + let n = land.len(); + let m = land[0].len(); + let mut visited = vec![vec![false; m]; n]; + let directions = [[-1,0],[0,1],[1,0],[0,-1]]; + + let mut maxr = vec![0]; + let mut maxc = vec![0]; + + fn dfs(land: &Vec>, visited: &mut Vec>, directions: &[[i32;2]], r: usize, c: usize, maxr: &mut Vec, maxc: &mut Vec) { + visited[r][c] = true; + maxr[0] = maxr[0].max(r as i32); + maxc[0] = maxc[0].max(c as i32); + for d in directions { + let nr = r as i32 + d[0]; + let nc = c as i32 + d[1]; + if nr >= 0 && nr < land.len() as i32 && nc >= 0 && nc < land[0].len() as i32 { + let nr = nr as usize; + let nc = nc as usize; + if !visited[nr][nc] && land[nr][nc] == 1 { + dfs(land, visited, directions, nr, nc, maxr, maxc); + } + } + } + } + + let mut res: Vec> = Vec::new(); + for i in 0..n { + for j in 0..m { + if land[i][j] == 1 && !visited[i][j] { + maxr[0] = i as i32; + maxc[0] = j as i32; + dfs(&land, &mut visited, &directions, i, j, &mut maxr, &mut maxc); + res.push(vec![i as i32, j as i32, maxr[0], maxc[0]]); + } + } + } + res + } +} diff --git a/tests/1501-2000/1992. find-all-groups-of-farmland/sol.swift b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.swift new file mode 100644 index 00000000..fdbb8f22 --- /dev/null +++ b/tests/1501-2000/1992. find-all-groups-of-farmland/sol.swift @@ -0,0 +1,39 @@ +class Solution { + func findFarmland(_ land: [[Int]]) -> [[Int]] { + let n = land.count + let m = land[0].count + var visited = Array(repeating: Array(repeating: false, count: m), count: n) + let directions = [[-1,0],[0,1],[1,0],[0,-1]] + + var maxr = [0] + var maxc = [0] + + func dfs(_ r: Int, _ c: Int) { + visited[r][c] = true + maxr[0] = max(maxr[0], r) + maxc[0] = max(maxc[0], c) + for d in directions { + let nr = r + d[0] + let nc = c + d[1] + if nr >= 0 && nr < n && nc >= 0 && nc < m { + if !visited[nr][nc] && land[nr][nc] == 1 { + dfs(nr, nc) + } + } + } + } + + var res: [[Int]] = [] + for i in 0.. + Array(m).fill(false), + ); + const directions = [ + [-1, 0], + [0, 1], + [1, 0], + [0, -1], + ]; + + const maxr: number[] = [0]; + const maxc: number[] = [0]; + + const dfs = (r: number, c: number): void => { + visited[r][c] = true; + maxr[0] = Math.max(maxr[0], r); + maxc[0] = Math.max(maxc[0], c); + for (const d of directions) { + const nr = r + d[0]; + const nc = c + d[1]; + if (nr >= 0 && nr < n && nc >= 0 && nc < m) { + if (!visited[nr][nc] && land[nr][nc] === 1) { + dfs(nr, nc); + } + } + } + }; + + const res: number[][] = []; + for (let i = 0; i < n; i++) { + for (let j = 0; j < m; j++) { + if (land[i][j] === 1 && !visited[i][j]) { + maxr[0] = i; + maxc[0] = j; + dfs(i, j); + res.push([i, j, maxr[0], maxc[0]]); + } + } + } + return res; +} diff --git a/tests/1501-2000/1994. the-number-of-good-subsets/manifest.yaml b/tests/1501-2000/1994. the-number-of-good-subsets/manifest.yaml new file mode 100644 index 00000000..99c8190d --- /dev/null +++ b/tests/1501-2000/1994. the-number-of-good-subsets/manifest.yaml @@ -0,0 +1,292 @@ +entry: + id: 1994 + title: "the-number-of-good-subsets" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().numberOfGoodSubsets({nums})" + rust: "Solution::number_of_good_subsets({nums})" + python3: "Solution().numberOfGoodSubsets({nums})" + python2: "Solution().numberOfGoodSubsets({nums})" + ruby: "number_of_good_subsets({nums})" + java: "new Solution().numberOfGoodSubsets({nums})" + csharp: "new Solution().NumberOfGoodSubsets({nums})" + kotlin: "Solution().numberOfGoodSubsets({nums})" + go: "numberOfGoodSubsets({nums})" + dart: "Solution().numberOfGoodSubsets({nums})" + swift: "Solution().numberOfGoodSubsets({nums})" + typescript: "numberOfGoodSubsets({nums})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().numberOfGoodSubsets(nums, {result})" + checker: | + class Checker: + def numberOfGoodSubsets(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not isinstance(nums, list) or any(not isinstance(x, int) or x < 1 or x > 30 for x in nums): + return False + good = {6, 10, 14, 22, 26, 15, 21} + masks = {} + for x in range(2, 31): + mask = 0 + y = x + for bit, p in enumerate((2, 3, 5, 7, 11, 13, 17, 19, 23, 29)): + if y % (p * p) == 0: + mask = -1 + break + if y % p == 0: + mask |= 1 << bit + if mask >= 0: + masks[x] = mask + dp = [0] * 1024 + dp[0] = 1 + for x in nums: + if x == 1 or x not in masks: + continue + bit = masks[x] + for state in range(1024 - 1, -1, -1): + if state & bit == 0: + dp[state | bit] += dp[state] + expected = (sum(dp[1:]) * pow(2, nums.count(1), 1000000007)) % 1000000007 + return result == expected + +seed: 1994 + +tests: + - name: "example_one" + in: + nums: [1, 2, 3, 4] + out: 6 + - name: "example_two" + in: + nums: [4, 2, 3, 15] + out: 5 + - name: "single_one" + in: + nums: [1] + out: 0 + - name: "single_prime" + in: + nums: [2] + out: 1 + - name: "single_composite_square" + in: + nums: [4] + out: 0 + - name: "single_valid_composite" + in: + nums: [6] + out: 1 + - name: "all_ones" + in: + nums: [1, 1, 1, 1, 1] + out: 0 + - name: "ones_with_prime" + in: + nums: [1, 1, 2] + out: 4 + - name: "repeated_prime" + in: + nums: [2, 2, 2] + out: 3 + - name: "repeated_valid_value" + in: + nums: [6, 6] + out: 2 + - name: "all_invalid_composites" + in: + nums: [4, 8, 9, 12, 16, 18, 20, 25, 27, 30] + out: 1 + - name: "all_distinct_primes" + in: + nums: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + out: 1023 + - name: "valid_pairs" + in: + nums: [6, 10, 14, 15, 21, 22, 26] + out: 13 + - name: "disjoint_valid_products" + in: + nums: [6, 10, 21] + out: 4 + - name: "overlapping_products" + in: + nums: [6, 15, 21] + out: 3 + - name: "prime_and_square" + in: + nums: [2, 4, 3, 9, 5, 25] + out: 7 + - name: "thirty_values" + in: + nums: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + ] + out: 6654 + - name: "large_one_count" + in: + nums: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3] + out: 3072 + - name: "large_repeated_prime" + in: + nums: [2, 2, 2, 2, 2, 3, 3, 3] + out: 23 + - name: "mixed_valid_invalid" + in: + nums: [1, 4, 6, 8, 10, 12, 14, 15, 16, 18, 21, 22, 24, 25, 26, 27, 28, 30] + out: 28 + - name: "two_coprime_pairs" + in: + nums: [10, 21] + out: 3 + - name: "same_prime_factor_pairs" + in: + nums: [6, 10, 14] + out: 3 + - name: "ones_and_all_primes" + in: + nums: [1, 1, 2, 3, 5, 7] + out: 60 + - name: "prime_thirty_boundary" + in: + nums: [29, 30] + out: 3 + - name: "valid_numbers_only" + in: + nums: [2, 3, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29] + out: 1983 + - name: "many_ones_and_invalid" + in: + nums: [1, 1, 1, 1, 1, 1, 4, 8, 9, 12] + out: 0 + - name: "singletons_with_one" + in: + nums: [1, 2, 4, 8, 16] + out: 2 + - name: "three_disjoint_masks" + in: + nums: [2, 3, 5] + out: 7 + - name: "four_disjoint_masks" + in: + nums: [6, 5, 22, 13] + out: 11 + - name: "duplicate_valid_with_ones" + in: + nums: [1, 1, 6, 6, 10] + out: 12 + - name: "all_valid_pairs_with_ones" + in: + nums: [1, 6, 10, 14, 15, 21, 22, 26] + out: 26 + - name: "maximum_length_small_values" + in: + nums: + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] + out: 1054 + - name: "prime_multiplicities" + in: + nums: [2, 2, 3, 3, 5, 5, 7, 7] + out: 80 + - name: "generator_small" + in: + nums: + gen: "array" + len: 12 + of: + gen: "int" + min: 1 + max: 30 + distinct: false + sorted: false + elemType: "int" + - name: "generator_medium" + in: + nums: + gen: "array" + len: 20 + of: + gen: "int" + min: 1 + max: 30 + distinct: false + sorted: false + elemType: "int" + - name: "generator_primes_range" + in: + nums: + gen: "array" + len: 18 + of: + gen: "int" + min: 2 + max: 29 + distinct: false + sorted: false + elemType: "int" + - name: "generator_ones_heavy" + in: + nums: + gen: "array" + len: 20 + of: + gen: "int" + min: 1 + max: 6 + distinct: false + sorted: false + elemType: "int" + - name: "generator_boundary_values" + in: + nums: + gen: "array" + len: 20 + of: + gen: "int" + min: 25 + max: 30 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/1501-2000/1994. the-number-of-good-subsets/sol.cpp b/tests/1501-2000/1994. the-number-of-good-subsets/sol.cpp new file mode 100644 index 00000000..6cad062c --- /dev/null +++ b/tests/1501-2000/1994. the-number-of-good-subsets/sol.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int numberOfGoodSubsets(vector& nums) { + const long long MOD = 1000000007; + const int primes[10] = {2,3,5,7,11,13,17,19,23,29}; + int freq[31] = {}; + for (int x : nums) ++freq[x]; + int masks[31] = {}; + for (int x = 2; x <= 30; ++x) { + int y = x, mask = 0; bool ok = true; + for (int b = 0; b < 10; ++b) { + int p = primes[b]; + if (y % (p * p) == 0) { ok = false; break; } + if (y % p == 0) mask |= 1 << b; + } + if (ok) masks[x] = mask; + } + long long dp[1024] = {}; dp[0] = 1; + for (int x = 2; x <= 30; ++x) { + int mask = masks[x]; + if (mask == 0 || freq[x] == 0) continue; + for (int state = 1023; state >= 0; --state) + if ((state & mask) == 0) + dp[state | mask] = (dp[state | mask] + dp[state] * freq[x]) % MOD; + } + long long ans = 0; + for (int state = 1; state < 1024; ++state) ans = (ans + dp[state]) % MOD; + for (int i = 0; i < freq[1]; ++i) ans = ans * 2 % MOD; + return (int)ans; + } +}; diff --git a/tests/1501-2000/1994. the-number-of-good-subsets/sol.cs b/tests/1501-2000/1994. the-number-of-good-subsets/sol.cs new file mode 100644 index 00000000..afa20a75 --- /dev/null +++ b/tests/1501-2000/1994. the-number-of-good-subsets/sol.cs @@ -0,0 +1,30 @@ +public class Solution { + public int NumberOfGoodSubsets(int[] nums) { + const long MOD = 1000000007; + int[] primes = {2,3,5,7,11,13,17,19,23,29}; + int[] freq = new int[31]; + foreach (int x in nums) freq[x]++; + int[] masks = new int[31]; + for (int x = 2; x <= 30; x++) { + int y = x, mask = 0; bool ok = true; + for (int b = 0; b < 10; b++) { + int p = primes[b]; + if (y % (p * p) == 0) { ok = false; break; } + if (y % p == 0) mask |= 1 << b; + } + if (ok) masks[x] = mask; + } + long[] dp = new long[1024]; dp[0] = 1; + for (int x = 2; x <= 30; x++) { + int mask = masks[x]; + if (mask == 0 || freq[x] == 0) continue; + for (int state = 1023; state >= 0; state--) + if ((state & mask) == 0) + dp[state | mask] = (dp[state | mask] + dp[state] * freq[x]) % MOD; + } + long ans = 0; + for (int state = 1; state < 1024; state++) ans = (ans + dp[state]) % MOD; + for (int i = 0; i < freq[1]; i++) ans = ans * 2 % MOD; + return (int)ans; + } +} diff --git a/tests/1501-2000/1994. the-number-of-good-subsets/sol.dart b/tests/1501-2000/1994. the-number-of-good-subsets/sol.dart new file mode 100644 index 00000000..fc335f5f --- /dev/null +++ b/tests/1501-2000/1994. the-number-of-good-subsets/sol.dart @@ -0,0 +1,33 @@ +class Solution { + int numberOfGoodSubsets(List nums) { + const mod = 1000000007; + const primes = [2,3,5,7,11,13,17,19,23,29]; + final freq = List.filled(31, 0); + for (final x in nums) freq[x]++; + final masks = List.filled(31, 0); + for (int x = 2; x <= 30; x++) { + int y = x, mask = 0; bool ok = true; + for (int b = 0; b < 10; b++) { + final p = primes[b]; + if (y % (p * p) == 0) { ok = false; break; } + if (y % p == 0) mask |= 1 << b; + } + if (ok) masks[x] = mask; + } + final dp = List.filled(1024, 0); dp[0] = 1; + for (int x = 2; x <= 30; x++) { + final mask = masks[x]; + if (mask == 0 || freq[x] == 0) continue; + for (int state = 1023; state >= 0; state--) { + if ((state & mask) == 0) { + final next = state | mask; + dp[next] = (dp[next] + dp[state] * freq[x]) % mod; + } + } + } + int ans = 0; + for (int state = 1; state < 1024; state++) ans = (ans + dp[state]) % mod; + for (int i = 0; i < freq[1]; i++) ans = ans * 2 % mod; + return ans; + } +} diff --git a/tests/1501-2000/1994. the-number-of-good-subsets/sol.go b/tests/1501-2000/1994. the-number-of-good-subsets/sol.go new file mode 100644 index 00000000..0615baf8 --- /dev/null +++ b/tests/1501-2000/1994. the-number-of-good-subsets/sol.go @@ -0,0 +1,30 @@ +func numberOfGoodSubsets(nums []int) int { + const mod int64 = 1000000007 + primes := [10]int{2,3,5,7,11,13,17,19,23,29} + freq := [31]int{} + for _, x := range nums { freq[x]++ } + masks := [31]int{} + for x := 2; x <= 30; x++ { + y, mask := x, 0; ok := true + for b, p := range primes { + if y%(p*p) == 0 { ok = false; break } + if y%p == 0 { mask |= 1 << b } + } + if ok { masks[x] = mask } + } + dp := [1024]int64{}; dp[0] = 1 + for x := 2; x <= 30; x++ { + mask := masks[x] + if mask == 0 || freq[x] == 0 { continue } + for state := 1023; state >= 0; state-- { + if state&mask == 0 { + next := state | mask + dp[next] = (dp[next] + dp[state] * int64(freq[x])) % mod + } + } + } + var ans int64 + for state := 1; state < 1024; state++ { ans = (ans + dp[state]) % mod } + for i := 0; i < freq[1]; i++ { ans = ans * 2 % mod } + return int(ans) +} diff --git a/tests/1501-2000/1994. the-number-of-good-subsets/sol.java b/tests/1501-2000/1994. the-number-of-good-subsets/sol.java new file mode 100644 index 00000000..fa7779e1 --- /dev/null +++ b/tests/1501-2000/1994. the-number-of-good-subsets/sol.java @@ -0,0 +1,30 @@ +class Solution { + public int numberOfGoodSubsets(int[] nums) { + final long MOD = 1_000_000_007L; + int[] primes = {2,3,5,7,11,13,17,19,23,29}; + int[] freq = new int[31]; + for (int x : nums) freq[x]++; + int[] masks = new int[31]; + for (int x = 2; x <= 30; x++) { + int y = x, mask = 0; boolean ok = true; + for (int b = 0; b < 10; b++) { + int p = primes[b]; + if (y % (p * p) == 0) { ok = false; break; } + if (y % p == 0) mask |= 1 << b; + } + if (ok) masks[x] = mask; + } + long[] dp = new long[1024]; dp[0] = 1; + for (int x = 2; x <= 30; x++) { + int mask = masks[x]; + if (mask == 0 || freq[x] == 0) continue; + for (int state = 1023; state >= 0; state--) + if ((state & mask) == 0) + dp[state | mask] = (dp[state | mask] + dp[state] * freq[x]) % MOD; + } + long ans = 0; + for (int state = 1; state < 1024; state++) ans = (ans + dp[state]) % MOD; + for (int i = 0; i < freq[1]; i++) ans = ans * 2 % MOD; + return (int)ans; + } +} diff --git a/tests/1501-2000/1994. the-number-of-good-subsets/sol.kt b/tests/1501-2000/1994. the-number-of-good-subsets/sol.kt new file mode 100644 index 00000000..8f04074a --- /dev/null +++ b/tests/1501-2000/1994. the-number-of-good-subsets/sol.kt @@ -0,0 +1,33 @@ +class Solution { + fun numberOfGoodSubsets(nums: IntArray): Int { + val mod = 1_000_000_007L + val primes = intArrayOf(2,3,5,7,11,13,17,19,23,29) + val freq = IntArray(31) + for (x in nums) freq[x]++ + val masks = IntArray(31) + for (x in 2..30) { + var y = x; var mask = 0; var ok = true + for (b in 0 until 10) { + val p = primes[b] + if (y % (p * p) == 0) { ok = false; break } + if (y % p == 0) mask = mask or (1 shl b) + } + if (ok) masks[x] = mask + } + val dp = LongArray(1024); dp[0] = 1 + for (x in 2..30) { + val mask = masks[x] + if (mask == 0 || freq[x] == 0) continue + for (state in 1023 downTo 0) { + if (state and mask == 0) { + val next = state or mask + dp[next] = (dp[next] + dp[state] * freq[x]) % mod + } + } + } + var ans = 0L + for (state in 1 until 1024) ans = (ans + dp[state]) % mod + repeat(freq[1]) { ans = ans * 2 % mod } + return ans.toInt() + } +} diff --git a/tests/1501-2000/1994. the-number-of-good-subsets/sol.py b/tests/1501-2000/1994. the-number-of-good-subsets/sol.py new file mode 100644 index 00000000..c62ed2d6 --- /dev/null +++ b/tests/1501-2000/1994. the-number-of-good-subsets/sol.py @@ -0,0 +1,43 @@ +""" +primes - 2 3 5 7 11 13 17 19 23 29 +valid prods - 6 10 14 22 26 15 21 +""" + +MOD = 10**9 + 7 +primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] # 10 + + +class Solution: + def numberOfGoodSubsets(self, nums: List[int]) -> int: + freq = Counter(nums) + # consider only unique elements from nums greater than 1 + arr = list(x for x in set(nums) if 1 < x) + N = len(arr) # N < 30 + + @cache + def rec(i, prod): + if i == N: + return prod != 1 + + # not pick + cnt = rec(i + 1, prod) + + # check and pick + next_prod = prod * arr[i] + is_distinct_prime_product = all( + next_prod % (prime * prime) for prime in primes + ) + if is_distinct_prime_product: + cnt += freq[arr[i]] * rec(i + 1, next_prod) + # print(i, prod, next_prod, is_distinct_prime_product) + + return cnt % MOD + + ans = rec(0, 1) + + # include contribution of `1`s to all the subsets + ones = freq[1] + ones_contribution = pow(2, ones, MOD) + ans *= ones_contribution + + return ans % MOD diff --git a/tests/1501-2000/1994. the-number-of-good-subsets/sol.py2 b/tests/1501-2000/1994. the-number-of-good-subsets/sol.py2 new file mode 100644 index 00000000..eebd33a6 --- /dev/null +++ b/tests/1501-2000/1994. the-number-of-good-subsets/sol.py2 @@ -0,0 +1,32 @@ +class Solution(object): + def numberOfGoodSubsets(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + from collections import Counter + MOD = 10**9 + 7 + primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + freq = Counter(nums) + arr = [x for x in set(nums) if x > 1] + n = len(arr) + + memo = {} + def rec(i, prod): + key = (i, prod) + if key in memo: + return memo[key] + if i == n: + return 1 if prod != 1 else 0 + cnt = rec(i+1, prod) + next_prod = prod * arr[i] + ok = all(next_prod % (p*p) for p in primes) + if ok: + cnt += freq[arr[i]] * rec(i+1, next_prod) + memo[key] = cnt % MOD + return memo[key] + + ans = rec(0, 1) + ones = freq[1] + ans *= pow(2, ones, MOD) + return ans % MOD diff --git a/tests/1501-2000/1994. the-number-of-good-subsets/sol.rb b/tests/1501-2000/1994. the-number-of-good-subsets/sol.rb new file mode 100644 index 00000000..c119dcf3 --- /dev/null +++ b/tests/1501-2000/1994. the-number-of-good-subsets/sol.rb @@ -0,0 +1,31 @@ +# @param {Integer[]} nums +# @return {Integer} +def number_of_good_subsets(nums) + mod = 10**9 + 7 + primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + freq = nums.tally + # tally creates hash, need to get default 0 + default_freq = Hash.new(0) + freq.each { |k, v| default_freq[k] = v } + freq = default_freq + arr = nums.uniq.select { |x| x > 1 } + n = arr.length + memo = {} + + rec = lambda do |i, prod| + return prod != 1 ? 1 : 0 if i == n + key = [i, prod] + return memo[key] if memo.key?(key) + cnt = rec.call(i+1, prod) + next_prod = prod * arr[i] + ok = primes.all? { |p| next_prod % (p*p) != 0 } + cnt += freq[arr[i]] * rec.call(i+1, next_prod) if ok + memo[key] = cnt % mod + end + + ans = rec.call(0, 1) + ones = freq[1] + ones_contribution = 2.pow(ones, mod) rescue (2**ones) % mod + ans = (ans * ones_contribution) % mod + return ans +end diff --git a/tests/1501-2000/1994. the-number-of-good-subsets/sol.rs b/tests/1501-2000/1994. the-number-of-good-subsets/sol.rs new file mode 100644 index 00000000..1eabd803 --- /dev/null +++ b/tests/1501-2000/1994. the-number-of-good-subsets/sol.rs @@ -0,0 +1,31 @@ +impl Solution { + pub fn number_of_good_subsets(nums: Vec) -> i32 { + const MOD: i64 = 1_000_000_007; + let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]; + let mut freq = [0i64; 31]; + for x in nums { freq[x as usize] += 1; } + let mut masks = [0usize; 31]; + for x in 2..=30 { + let mut y = x; let mut mask = 0usize; let mut ok = true; + for (bit, &p) in primes.iter().enumerate() { + if y % (p * p) == 0 { ok = false; break; } + if y % p == 0 { mask |= 1usize << bit; } + } + if ok { masks[x as usize] = mask; } + } + let mut dp = [0i64; 1024]; dp[0] = 1; + for x in 2..=30 { + let mask = masks[x as usize]; + if mask == 0 || freq[x as usize] == 0 { continue; } + for state in (0..1024).rev() { + if state & mask == 0 { + let next = state | mask; + dp[next] = (dp[next] + dp[state] * freq[x as usize]) % MOD; + } + } + } + let mut ans = dp[1..].iter().sum::() % MOD; + for _ in 0..freq[1] { ans = ans * 2 % MOD; } + ans as i32 + } +} diff --git a/tests/1501-2000/1994. the-number-of-good-subsets/sol.swift b/tests/1501-2000/1994. the-number-of-good-subsets/sol.swift new file mode 100644 index 00000000..9ecb0e1a --- /dev/null +++ b/tests/1501-2000/1994. the-number-of-good-subsets/sol.swift @@ -0,0 +1,30 @@ +class Solution { + func numberOfGoodSubsets(_ nums: [Int]) -> Int { + let mod = 1_000_000_007 + let primes = [2,3,5,7,11,13,17,19,23,29] + var freq = Array(repeating: 0, count: 31) + for x in nums { freq[x] += 1 } + var masks = Array(repeating: 0, count: 31) + for x in 2...30 { + var y = x, mask = 0, ok = true + for b in 0..<10 { + let p = primes[b] + if y % (p * p) == 0 { ok = false; break } + if y % p == 0 { mask |= 1 << b } + } + if ok { masks[x] = mask } + } + var dp = Array(repeating: 0, count: 1024); dp[0] = 1 + for x in 2...30 { + let mask = masks[x] + if mask == 0 || freq[x] == 0 { continue } + for state in stride(from: 1023, through: 0, by: -1) where state & mask == 0 { + let next = state | mask + dp[next] = (dp[next] + dp[state] * freq[x]) % mod + } + } + var ans = dp.dropFirst().reduce(0) { ($0 + $1) % mod } + for _ in 0..= 0; state--) { + if ((state & mask) === 0) { + const next = state | mask; + dp[next] = (dp[next] + dp[state] * freq[x]) % mod; + } + } + } + let ans = 0; + for (let state = 1; state < 1024; state++) ans = (ans + dp[state]) % mod; + for (let i = 0; i < freq[1]; i++) ans = (ans * 2) % mod; + return ans; +} diff --git a/tests/1501-2000/1995. count-special-quadruplets/manifest.yaml b/tests/1501-2000/1995. count-special-quadruplets/manifest.yaml new file mode 100644 index 00000000..c77f0a8a --- /dev/null +++ b/tests/1501-2000/1995. count-special-quadruplets/manifest.yaml @@ -0,0 +1,242 @@ +entry: + id: 1995 + title: "count-special-quadruplets" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().countQuadruplets({nums})" + rust: "Solution::count_quadruplets({nums})" + python3: "Solution().countQuadruplets({nums})" + python2: "Solution().countQuadruplets({nums})" + ruby: "count_quadruplets({nums})" + java: "new Solution().countQuadruplets({nums})" + csharp: "new Solution().CountQuadruplets({nums})" + kotlin: "Solution().countQuadruplets({nums})" + go: "countQuadruplets({nums})" + dart: "Solution().countQuadruplets({nums})" + swift: "Solution().countQuadruplets({nums})" + typescript: "countQuadruplets({nums})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().countQuadruplets(nums, {result})" + checker: | + class Checker: + def countQuadruplets(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not isinstance(nums, list) or not (4 <= len(nums) <= 50): + return False + expected = 0 + for a in range(len(nums)): + for b in range(a + 1, len(nums)): + for c in range(b + 1, len(nums)): + for d in range(c + 1, len(nums)): + if nums[a] + nums[b] + nums[c] == nums[d]: + expected += 1 + return result == expected + +seed: 1995 + +tests: + - name: "example-one" + in: + nums: [1, 2, 3, 6] + out: 1 + - name: "example-two" + in: + nums: [3, 3, 6, 4, 5] + out: 0 + - name: "example-three" + in: + nums: [1, 1, 1, 3, 5] + out: 4 + - name: "minimum-length-no-match" + in: + nums: [1, 1, 1, 1] + out: 0 + - name: "minimum-length-match" + in: + nums: [1, 2, 3, 6] + out: 1 + - name: "all-ones" + in: + nums: [1, 1, 1, 1, 1, 1, 1] + out: 0 + - name: "all-fours" + in: + nums: [4, 4, 4, 4, 4, 4] + out: 0 + - name: "all-hundreds" + in: + nums: [100, 100, 100, 100, 100] + out: 0 + - name: "repeated-one-three" + in: + nums: [1, 1, 1, 3, 3, 3] + out: 3 + - name: "repeated-one-four" + in: + nums: [1, 1, 1, 1, 4, 4] + out: 0 + - name: "several-prefix-matches" + in: + nums: [1, 2, 3, 6, 6, 6] + out: 3 + - name: "matches-at-late-positions" + in: + nums: [1, 2, 3, 10, 20, 30, 6] + out: 1 + - name: "increasing-no-match" + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8] + out: 4 + - name: "increasing-match" + in: + nums: [1, 2, 3, 6, 10, 15, 21, 28] + out: 5 + - name: "one-match-middle" + in: + nums: [2, 4, 1, 7, 3, 8] + out: 2 + - name: "two-disjoint-matches" + in: + nums: [1, 1, 1, 3, 2, 2, 2, 6] + out: 11 + - name: "zeros-not-allowed-but-positive-pattern" + in: + nums: [1, 1, 2, 4, 1, 1, 2, 4] + out: 13 + - name: "large-first-values" + in: + nums: [90, 90, 90, 100, 99, 99, 99, 100] + out: 0 + - name: "many-equal-targets" + in: + nums: [1, 2, 3, 6, 6, 6, 6, 6] + out: 5 + - name: "duplicate-prefix-values" + in: + nums: [1, 1, 2, 4, 4, 4, 4] + out: 4 + - name: "late-single-target" + in: + nums: [2, 2, 2, 2, 2, 2, 6] + out: 20 + - name: "mixed-small-values" + in: + nums: [1, 3, 2, 6, 4, 12, 7, 13] + out: 5 + - name: "ascending-prefix-sums" + in: + nums: [1, 1, 2, 4, 3, 7, 5, 12] + out: 8 + - name: "no-targets-after-prefix" + in: + nums: [1, 2, 3, 100, 100, 100] + out: 0 + - name: "target-equals-single-sum" + in: + nums: [5, 5, 5, 15, 15, 15] + out: 3 + - name: "many-four-sums" + in: + nums: [1, 1, 1, 3, 3, 3, 3, 3] + out: 5 + - name: "late-combinations" + in: + nums: [1, 1, 1, 1, 1, 1, 3, 3, 3] + out: 60 + - name: "alternating-values" + in: + nums: [1, 10, 1, 11, 1, 12, 1, 13] + out: 9 + - name: "fourteen-ones-and-targets" + in: + nums: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3] + out: 286 + - name: "four-ones-target-four" + in: + nums: [1, 1, 1, 1, 4, 4, 4, 4] + out: 0 + - name: "structured-small" + in: + nums: [1, 2, 3, 6, 1, 2, 3, 6, 1, 2, 3, 6] + out: 38 + - name: "max-length-no-match" + in: + nums: + gen: "array" + len: 50 + of: + gen: "int" + min: 100 + max: 100 + out: 0 + - name: "generated-small" + seed: 2001 + in: + nums: + gen: "array" + len: + gen: "int" + min: 4 + max: 12 + of: + gen: "int" + min: 1 + max: 20 + + - name: "generated-medium" + seed: 2002 + in: + nums: + gen: "array" + len: + gen: "int" + min: 20 + max: 30 + of: + gen: "int" + min: 1 + max: 100 + - name: "generated-large-values" + seed: 2003 + in: + nums: + gen: "array" + len: 50 + of: + gen: "int" + min: 1 + max: 100 + - name: "generated-large-uniform" + seed: 2004 + in: + nums: + gen: "array" + len: 50 + of: + gen: "int" + min: 1 + max: 2 + - name: "generated-large-bounded" + seed: 2005 + in: + nums: + gen: "array" + len: 45 + of: + gen: "int" + min: 1 + max: 10 diff --git a/tests/1501-2000/1995. count-special-quadruplets/sol.cpp b/tests/1501-2000/1995. count-special-quadruplets/sol.cpp new file mode 100644 index 00000000..67ad5788 --- /dev/null +++ b/tests/1501-2000/1995. count-special-quadruplets/sol.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int countQuadruplets(vector& nums) { + int res = 0, n = nums.size(); + for (int w = 0; w < n; w++) { + for (int x = w + 1; x < n; x++) { + for (int y = x + 1; y < n; y++) { + for (int z = y + 1; z < n; z++) { + res += (nums[w] + nums[x] + nums[y] == nums[z]); + } + } + } + } + return res; + } +}; diff --git a/tests/1501-2000/1995. count-special-quadruplets/sol.cs b/tests/1501-2000/1995. count-special-quadruplets/sol.cs new file mode 100644 index 00000000..f2660eb8 --- /dev/null +++ b/tests/1501-2000/1995. count-special-quadruplets/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public int CountQuadruplets(int[] nums) { + int res = 0; + int n = nums.Length; + for (int w = 0; w < n; w++) { + for (int x = w + 1; x < n; x++) { + for (int y = x + 1; y < n; y++) { + for (int z = y + 1; z < n; z++) { + if (nums[w] + nums[x] + nums[y] == nums[z]) { + res++; + } + } + } + } + } + return res; + } +} diff --git a/tests/1501-2000/1995. count-special-quadruplets/sol.dart b/tests/1501-2000/1995. count-special-quadruplets/sol.dart new file mode 100644 index 00000000..abbefe34 --- /dev/null +++ b/tests/1501-2000/1995. count-special-quadruplets/sol.dart @@ -0,0 +1,18 @@ +class Solution { + int countQuadruplets(List nums) { + int res = 0; + int n = nums.length; + for (int w = 0; w < n; w++) { + for (int x = w + 1; x < n; x++) { + for (int y = x + 1; y < n; y++) { + for (int z = y + 1; z < n; z++) { + if (nums[w] + nums[x] + nums[y] == nums[z]) { + res++; + } + } + } + } + } + return res; + } +} diff --git a/tests/1501-2000/1995. count-special-quadruplets/sol.go b/tests/1501-2000/1995. count-special-quadruplets/sol.go new file mode 100644 index 00000000..509ae4e8 --- /dev/null +++ b/tests/1501-2000/1995. count-special-quadruplets/sol.go @@ -0,0 +1,16 @@ +func countQuadruplets(nums []int) int { + res := 0 + n := len(nums) + for w := 0; w < n; w++ { + for x := w + 1; x < n; x++ { + for y := x + 1; y < n; y++ { + for z := y + 1; z < n; z++ { + if nums[w] + nums[x] + nums[y] == nums[z] { + res++ + } + } + } + } + } + return res +} diff --git a/tests/1501-2000/1995. count-special-quadruplets/sol.java b/tests/1501-2000/1995. count-special-quadruplets/sol.java new file mode 100644 index 00000000..4610910f --- /dev/null +++ b/tests/1501-2000/1995. count-special-quadruplets/sol.java @@ -0,0 +1,15 @@ +class Solution { + public int countQuadruplets(int[] nums) { + int res = 0, n = nums.length; + for (int w = 0; w < n; w++) { + for (int x = w + 1; x < n; x++) { + for (int y = x + 1; y < n; y++) { + for (int z = y + 1; z < n; z++) { + if (nums[w] + nums[x] + nums[y] == nums[z]) res++; + } + } + } + } + return res; + } +} diff --git a/tests/1501-2000/1995. count-special-quadruplets/sol.kt b/tests/1501-2000/1995. count-special-quadruplets/sol.kt new file mode 100644 index 00000000..b310655a --- /dev/null +++ b/tests/1501-2000/1995. count-special-quadruplets/sol.kt @@ -0,0 +1,16 @@ +class Solution { + fun countQuadruplets(nums: IntArray): Int { + var res = 0 + val n = nums.size + for (w in 0 until n) { + for (x in w + 1 until n) { + for (y in x + 1 until n) { + for (z in y + 1 until n) { + if (nums[w] + nums[x] + nums[y] == nums[z]) res++ + } + } + } + } + return res + } +} diff --git a/tests/1501-2000/1995. count-special-quadruplets/sol.py b/tests/1501-2000/1995. count-special-quadruplets/sol.py new file mode 100644 index 00000000..8561c985 --- /dev/null +++ b/tests/1501-2000/1995. count-special-quadruplets/sol.py @@ -0,0 +1,10 @@ +class Solution: + def countQuadruplets(self, nums: List[int]) -> int: + A = nums + res, n = 0, len(A) + for w in range(n): + for x in range(w + 1, n): + for y in range(x + 1, n): + for z in range(y + 1, n): + res += int(A[w] + A[x] + A[y] == A[z]) + return res diff --git a/tests/1501-2000/1995. count-special-quadruplets/sol.py2 b/tests/1501-2000/1995. count-special-quadruplets/sol.py2 new file mode 100644 index 00000000..4d8e44c1 --- /dev/null +++ b/tests/1501-2000/1995. count-special-quadruplets/sol.py2 @@ -0,0 +1,13 @@ +class Solution(object): + def countQuadruplets(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + res, n = 0, len(nums) + for w in range(n): + for x in range(w + 1, n): + for y in range(x + 1, n): + for z in range(y + 1, n): + res += 1 if nums[w] + nums[x] + nums[y] == nums[z] else 0 + return res diff --git a/tests/1501-2000/1995. count-special-quadruplets/sol.rb b/tests/1501-2000/1995. count-special-quadruplets/sol.rb new file mode 100644 index 00000000..0d2bc902 --- /dev/null +++ b/tests/1501-2000/1995. count-special-quadruplets/sol.rb @@ -0,0 +1,16 @@ +# @param {Integer[]} nums +# @return {Integer} +def count_quadruplets(nums) + res = 0 + n = nums.length + (0...n).each do |w| + (w+1...n).each do |x| + (x+1...n).each do |y| + (y+1...n).each do |z| + res += 1 if nums[w] + nums[x] + nums[y] == nums[z] + end + end + end + end + res +end diff --git a/tests/1501-2000/1995. count-special-quadruplets/sol.rs b/tests/1501-2000/1995. count-special-quadruplets/sol.rs new file mode 100644 index 00000000..86506867 --- /dev/null +++ b/tests/1501-2000/1995. count-special-quadruplets/sol.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn count_quadruplets(nums: Vec) -> i32 { + let mut res = 0; + let n = nums.len(); + for w in 0..n { + for x in (w+1)..n { + for y in (x+1)..n { + for z in (y+1)..n { + if nums[w] + nums[x] + nums[y] == nums[z] { + res += 1; + } + } + } + } + } + res + } +} diff --git a/tests/1501-2000/1995. count-special-quadruplets/sol.swift b/tests/1501-2000/1995. count-special-quadruplets/sol.swift new file mode 100644 index 00000000..966d6dd9 --- /dev/null +++ b/tests/1501-2000/1995. count-special-quadruplets/sol.swift @@ -0,0 +1,18 @@ +class Solution { + func countQuadruplets(_ nums: [Int]) -> Int { + var res = 0 + let n = nums.count + for w in 0.. attack and d > defense for a, d in properties): + weak += 1 + return result == weak + +seed: 1996 + +tests: + - name: example-1 + in: + properties: + - [5, 5] + - [6, 3] + - [3, 6] + out: 0 + judge: + type: exact + - name: example-2 + in: + properties: + - [2, 2] + - [3, 3] + out: 1 + judge: + type: exact + - name: example-3 + in: + properties: + - [1, 5] + - [10, 4] + - [4, 3] + out: 1 + judge: + type: exact + - name: increasing-diagonal + in: + properties: + - [1, 1] + - [2, 2] + - [3, 3] + - [4, 4] + out: 3 + judge: + type: exact + - name: equal-defense + in: + properties: + - [1, 10] + - [2, 10] + - [3, 10] + out: 0 + judge: + type: exact + - name: equal-attack + in: + properties: + - [10, 1] + - [10, 2] + - [10, 3] + out: 0 + judge: + type: exact + - name: duplicate-pairs + in: + properties: + - [1, 1] + - [1, 1] + - [2, 2] + - [2, 2] + out: 2 + judge: + type: exact + - name: descending-defense + in: + properties: + - [1, 5] + - [2, 4] + - [3, 3] + - [4, 2] + - [5, 1] + out: 0 + judge: + type: exact + - name: mixed-crossing + in: + properties: + - [1, 1] + - [2, 3] + - [3, 2] + - [4, 4] + out: 3 + judge: + type: exact + - name: maximum-pair + in: + properties: + - [100000, 100000] + - [1, 1] + out: 1 + judge: + type: exact + - name: opposite-extremes + in: + properties: + - [1, 100000] + - [100000, 1] + - [50000, 50000] + out: 0 + judge: + type: exact + - name: strict-chain + in: + properties: + - [2, 1] + - [3, 2] + - [4, 3] + - [5, 4] + - [6, 5] + out: 4 + judge: + type: exact + - name: attack-decreases-defense-increases + in: + properties: + - [5, 5] + - [4, 6] + - [3, 7] + - [2, 8] + out: 0 + judge: + type: exact + - name: repeated-attacks + in: + properties: + - [1, 2] + - [2, 1] + - [3, 3] + - [4, 2] + - [5, 5] + out: 4 + judge: + type: exact + - name: tied-groups + in: + properties: + - [1, 1] + - [2, 2] + - [2, 3] + - [3, 2] + - [3, 4] + out: 3 + judge: + type: exact + - name: descending-defense-large-values + in: + properties: + - [1, 100] + - [2, 99] + - [3, 98] + - [4, 97] + - [5, 96] + out: 0 + judge: + type: exact + - name: plateau-defense + in: + properties: + - [1, 1] + - [2, 1] + - [3, 1] + - [4, 2] + - [5, 2] + out: 3 + judge: + type: exact + - name: maximum-attack-with-low-defense + in: + properties: + - [7, 7] + - [6, 6] + - [5, 5] + - [8, 8] + - [9, 1] + out: 3 + judge: + type: exact + - name: one-dominating-maximum + in: + properties: + - [1, 50] + - [2, 40] + - [3, 30] + - [4, 20] + - [5, 10] + - [6, 60] + out: 5 + judge: + type: exact + - name: reverse-chain + in: + properties: + - [10, 10] + - [9, 9] + - [8, 8] + - [7, 7] + - [6, 6] + - [5, 5] + out: 5 + judge: + type: exact + - name: single-dominator + in: + properties: + - [1, 1] + - [2, 5] + - [3, 4] + - [4, 3] + - [5, 2] + - [6, 1] + out: 1 + judge: + type: exact + - name: anti-chain-reversed + in: + properties: + - [100, 1] + - [99, 2] + - [98, 3] + - [97, 4] + - [96, 5] + out: 0 + judge: + type: exact + - name: nine-element-antichain + in: + properties: + - [1, 9] + - [2, 8] + - [3, 7] + - [4, 6] + - [5, 5] + - [6, 4] + - [7, 3] + - [8, 2] + - [9, 1] + out: 0 + judge: + type: exact + - name: layered-dominance + in: + properties: + - [1, 3] + - [2, 2] + - [3, 1] + - [4, 4] + - [5, 3] + - [6, 2] + - [7, 5] + out: 6 + judge: + type: exact + - name: pure-chain-seven + in: + properties: + - [2, 2] + - [3, 3] + - [4, 4] + - [5, 5] + - [6, 6] + - [7, 7] + - [8, 8] + out: 6 + judge: + type: exact + - name: nonmonotonic-defense + in: + properties: + - [1, 100] + - [2, 50] + - [3, 75] + - [4, 25] + - [5, 125] + out: 4 + judge: + type: exact + - name: high-attack-tail + in: + properties: + - [10, 5] + - [11, 4] + - [12, 3] + - [13, 2] + - [14, 1] + - [15, 6] + out: 5 + judge: + type: exact + - name: shuffled-chain + in: + properties: + - [1, 1] + - [3, 3] + - [2, 2] + - [4, 4] + - [5, 5] + out: 4 + judge: + type: exact + - name: near-maximum-values + in: + properties: + - [50000, 50000] + - [50000, 49999] + - [49999, 50000] + - [1, 1] + out: 1 + judge: + type: exact + - name: increasing-offsets + in: + properties: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + - [6, 7] + - [7, 8] + out: 6 + judge: + type: exact + - name: generated-random-medium + in: + properties: + gen: array + len: 1000 + of: + gen: array + len: 2 + of: + gen: int + min: 1 + max: 100000 + judge: + type: exact + - name: generated-random-large + in: + properties: + gen: array + len: 10000 + of: + gen: array + len: 2 + of: + gen: int + min: 1 + max: 100000 + judge: + type: exact + - name: generated-small-values + in: + properties: + gen: array + len: 5000 + of: + gen: array + len: 2 + of: + gen: int + min: 1 + max: 20 + judge: + type: exact + - name: generated-wide-values + in: + properties: + gen: array + len: 50000 + of: + gen: array + len: 2 + of: + gen: int + min: 99980 + max: 100000 + judge: + type: exact + - name: generated-maximum-size + in: + properties: + gen: array + len: 100000 + of: + gen: array + len: 2 + of: + gen: int + min: 1 + max: 100000 + judge: + type: exact diff --git a/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.cpp b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.cpp new file mode 100644 index 00000000..21faf54b --- /dev/null +++ b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int numberOfWeakCharacters(vector>& properties) { + sort(properties.begin(), properties.end(), [](const vector& a, const vector& b) { + if (a[0] != b[0]) return a[0] > b[0]; + return a[1] < b[1]; + }); + + int maxDefense = 0; + int weakCount = 0; + + for (const auto& prop : properties) { + if (prop[1] < maxDefense) { + weakCount++; + } else { + maxDefense = prop[1]; + } + } + + return weakCount; + } +}; diff --git a/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.cs b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.cs new file mode 100644 index 00000000..815398ef --- /dev/null +++ b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public int NumberOfWeakCharacters(int[][] properties) { + Array.Sort(properties, (a, b) => a[0] != b[0] ? b[0] - a[0] : a[1] - b[1]); + + int maxDefense = 0; + int weakCount = 0; + + foreach (var prop in properties) { + if (prop[1] < maxDefense) { + weakCount++; + } else { + maxDefense = prop[1]; + } + } + + return weakCount; + } +} diff --git a/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.dart b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.dart new file mode 100644 index 00000000..c207bb26 --- /dev/null +++ b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.dart @@ -0,0 +1,18 @@ +class Solution { + int numberOfWeakCharacters(List> properties) { + properties.sort((a, b) => a[0] != b[0] ? b[0] - a[0] : a[1] - b[1]); + + int maxDefense = 0; + int weakCount = 0; + + for (var prop in properties) { + if (prop[1] < maxDefense) { + weakCount++; + } else { + maxDefense = prop[1]; + } + } + + return weakCount; + } +} diff --git a/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.go b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.go new file mode 100644 index 00000000..94b14741 --- /dev/null +++ b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.go @@ -0,0 +1,21 @@ +func numberOfWeakCharacters(properties [][]int) int { + sort.Slice(properties, func(i, j int) bool { + if properties[i][0] != properties[j][0] { + return properties[i][0] > properties[j][0] + } + return properties[i][1] < properties[j][1] + }) + + maxDefense := 0 + weakCount := 0 + + for _, prop := range properties { + if prop[1] < maxDefense { + weakCount++ + } else { + maxDefense = prop[1] + } + } + + return weakCount +} diff --git a/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.java b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.java new file mode 100644 index 00000000..56cfea35 --- /dev/null +++ b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.java @@ -0,0 +1,18 @@ +class Solution { + public int numberOfWeakCharacters(int[][] properties) { + Arrays.sort(properties, (a, b) -> a[0] != b[0] ? b[0] - a[0] : a[1] - b[1]); + + int maxDefense = 0; + int weakCount = 0; + + for (int[] prop : properties) { + if (prop[1] < maxDefense) { + weakCount++; + } else { + maxDefense = prop[1]; + } + } + + return weakCount; + } +} diff --git a/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.kt b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.kt new file mode 100644 index 00000000..4a15c194 --- /dev/null +++ b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.kt @@ -0,0 +1,18 @@ +class Solution { + fun numberOfWeakCharacters(properties: Array): Int { + properties.sortWith(compareBy({ -it[0] }, { it[1] })) + + var maxDefense = 0 + var weakCount = 0 + + for (prop in properties) { + if (prop[1] < maxDefense) { + weakCount++ + } else { + maxDefense = prop[1] + } + } + + return weakCount + } +} diff --git a/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.py b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.py new file mode 100644 index 00000000..04a742eb --- /dev/null +++ b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.py @@ -0,0 +1,18 @@ +class Solution(object): + def numberOfWeakCharacters(self, properties): + """ + :type properties: List[List[int]] + :rtype: int + """ + properties.sort(key=lambda x: (-x[0], x[1])) + + max_defense = 0 + weak_count = 0 + + for attack, defense in properties: + if defense < max_defense: + weak_count += 1 + else: + max_defense = defense + + return weak_count diff --git a/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.py2 b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.py2 new file mode 100644 index 00000000..6636f766 --- /dev/null +++ b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def numberOfWeakCharacters(self, properties): + """ + :type properties: List[List[int]] + :rtype: int + """ + properties.sort(key=lambda x: (-x[0], x[1])) + + max_defense = 0 + weak_count = 0 + + for attack, defense in properties: + if defense < max_defense: + weak_count += 1 + else: + max_defense = defense + + return weak_count diff --git a/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.rb b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.rb new file mode 100644 index 00000000..4ebba96f --- /dev/null +++ b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.rb @@ -0,0 +1,18 @@ +# @param {Integer[][]} properties +# @return {Integer} +def number_of_weak_characters(properties) + properties.sort_by! { |x| [-x[0], x[1]] } + + max_defense = 0 + weak_count = 0 + + properties.each do |attack, defense| + if defense < max_defense + weak_count += 1 + else + max_defense = defense + end + end + + weak_count +end diff --git a/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.rs b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.rs new file mode 100644 index 00000000..a5fcf749 --- /dev/null +++ b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn number_of_weak_characters(properties: Vec>) -> i32 { + let mut sorted = properties; + sorted.sort_by(|a, b| { + if a[0] != b[0] { b[0].cmp(&a[0]) } else { a[1].cmp(&b[1]) } + }); + + let mut max_defense = 0; + let mut weak_count = 0; + + for prop in sorted { + if prop[1] < max_defense { + weak_count += 1; + } else { + max_defense = prop[1]; + } + } + + weak_count + } +} diff --git a/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.swift b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.swift new file mode 100644 index 00000000..cad52a7a --- /dev/null +++ b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.swift @@ -0,0 +1,21 @@ +class Solution { + func numberOfWeakCharacters(_ properties: [[Int]]) -> Int { + let sorted = properties.sorted { + if $0[0] != $1[0] { return $0[0] > $1[0] } + return $0[1] < $1[1] + } + + var maxDefense = 0 + var weakCount = 0 + + for prop in sorted { + if prop[1] < maxDefense { + weakCount += 1 + } else { + maxDefense = prop[1] + } + } + + return weakCount + } +} diff --git a/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.ts b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.ts new file mode 100644 index 00000000..8cf97572 --- /dev/null +++ b/tests/1501-2000/1996. the-number-of-weak-characters-in-the-game/sol.ts @@ -0,0 +1,16 @@ +function numberOfWeakCharacters(properties: number[][]): number { + properties.sort((a, b) => (a[0] !== b[0] ? b[0] - a[0] : a[1] - b[1])); + + let maxDefense = 0; + let weakCount = 0; + + for (const prop of properties) { + if (prop[1] < maxDefense) { + weakCount++; + } else { + maxDefense = prop[1]; + } + } + + return weakCount; +} diff --git a/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/manifest.yaml b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/manifest.yaml new file mode 100644 index 00000000..9675fbc6 --- /dev/null +++ b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/manifest.yaml @@ -0,0 +1,397 @@ +entry: + id: 1997 + title: "first-day-where-you-have-been-in-all-the-rooms" + params: + nextVisit: + type: array + items: + type: int + call: + cpp: "Solution().firstDayBeenInAllRooms({nextVisit})" + rust: "Solution::first_day_been_in_all_rooms({nextVisit})" + python3: "Solution().firstDayBeenInAllRooms({nextVisit})" + python2: "Solution().firstDayBeenInAllRooms({nextVisit})" + ruby: "first_day_been_in_all_rooms({nextVisit})" + java: "new Solution().firstDayBeenInAllRooms({nextVisit})" + csharp: "new Solution().FirstDayBeenInAllRooms({nextVisit})" + kotlin: "Solution().firstDayBeenInAllRooms({nextVisit})" + go: "firstDayBeenInAllRooms({nextVisit})" + dart: "Solution().firstDayBeenInAllRooms({nextVisit})" + swift: "Solution().firstDayBeenInAllRooms({nextVisit})" + typescript: "firstDayBeenInAllRooms({nextVisit})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 300 + +oracle: + python3: + call: "Checker().firstDayBeenInAllRooms(nextVisit, {result})" + checker: | + class Checker: + def firstDayBeenInAllRooms(self, nextVisit, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + mod = 1000000007 + dp = [0] * len(nextVisit) + for i in range(1, len(nextVisit)): + dp[i] = (2 * dp[i - 1] - dp[nextVisit[i - 1]] + 2) % mod + return result == dp[-1] + +seed: 1997 + +tests: + - name: "example_two_rooms" + in: + nextVisit: [0, 0] + out: 2 + - name: "example_three_rooms" + in: + nextVisit: [0, 0, 2] + out: 6 + - name: "example_four_rooms" + in: + nextVisit: [0, 1, 2, 0] + out: 6 + - name: "all_zero_n3" + in: + nextVisit: [0, 0, 0] + out: 6 + - name: "all_zero_n4" + in: + nextVisit: [0, 0, 0, 0] + out: 14 + - name: "all_zero_n5" + in: + nextVisit: [0, 0, 0, 0, 0] + out: 30 + - name: "all_zero_n6" + in: + nextVisit: [0, 0, 0, 0, 0, 0] + out: 62 + - name: "all_zero_n7" + in: + nextVisit: [0, 0, 0, 0, 0, 0, 0] + out: 126 + - name: "identity_n3" + in: + nextVisit: [0, 1, 2] + out: 4 + - name: "identity_n4" + in: + nextVisit: [0, 1, 2, 3] + out: 6 + - name: "identity_n5" + in: + nextVisit: [0, 1, 2, 3, 4] + out: 8 + - name: "identity_n6" + in: + nextVisit: [0, 1, 2, 3, 4, 5] + out: 10 + - name: "identity_n10" + in: + nextVisit: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + out: 18 + - name: "self_loops_n5" + in: + nextVisit: [0, 1, 2, 3, 4] + out: 8 + - name: "near_previous_n5" + in: + nextVisit: [0, 0, 1, 2, 3] + out: 20 + - name: "near_previous_n6" + in: + nextVisit: [0, 0, 1, 2, 3, 4] + out: 30 + - name: "mixed_small_a" + in: + nextVisit: [0, 0, 1, 0, 2] + out: 26 + - name: "mixed_small_b" + in: + nextVisit: [0, 0, 0, 2, 1] + out: 24 + - name: "mixed_small_c" + in: + nextVisit: [0, 0, 1, 1, 2, 0] + out: 44 + - name: "mixed_small_d" + in: + nextVisit: [0, 0, 1, 2, 0, 3] + out: 42 + - name: "mixed_small_e" + in: + nextVisit: [0, 0, 0, 1, 1, 2, 3] + out: 108 + - name: "mixed_small_f" + in: + nextVisit: [0, 0, 1, 0, 3, 2, 1] + out: 80 + - name: "mixed_small_g" + in: + nextVisit: [0, 0, 0, 2, 2, 4, 1, 5] + out: 132 + - name: "mixed_small_h" + in: + nextVisit: [0, 0, 1, 1, 3, 0, 2, 6] + out: 152 + - name: "mixed_small_i" + in: + nextVisit: [0, 0, 0, 1, 2, 3, 4, 5, 6] + out: 266 + - name: "mixed_small_j" + in: + nextVisit: [0, 0, 1, 2, 3, 1, 4, 2, 6, 0] + out: 342 + - name: "mostly_zero_n10" + in: + nextVisit: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + out: 1022 + - name: "mostly_identity_n10" + in: + nextVisit: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + out: 18 + - name: "periodic_three_n10" + in: + nextVisit: [0, 0, 1, 0, 1, 2, 0, 1, 2, 0] + out: 804 + - name: "periodic_two_n12" + in: + nextVisit: [0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0] + out: 3412 + - name: "descending_targets_n12" + in: + nextVisit: [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + out: 1192 + - name: "zero_prefix_n15" + in: + nextVisit: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + out: 32766 + - name: "identity_n15" + in: + nextVisit: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] + out: 28 + - name: "mixed_n15" + in: + nextVisit: [0, 0, 1, 1, 0, 3, 2, 5, 1, 7, 4, 8, 0, 10, 6] + out: 14252 + - name: "zero_prefix_n20" + in: + nextVisit: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + out: 1048574 + - name: "identity_n20" + in: + nextVisit: + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] + out: 38 + - name: "alternating_n20" + in: + nextVisit: + [0, 0, 1, 0, 3, 2, 1, 4, 0, 6, 2, 8, 4, 10, 6, 12, 8, 14, 10, 16] + out: 425264 + - name: "balanced_n25" + in: + nextVisit: + [ + 0, + 0, + 1, + 1, + 2, + 2, + 3, + 3, + 4, + 4, + 5, + 5, + 6, + 6, + 7, + 7, + 8, + 8, + 9, + 9, + 10, + 10, + 11, + 11, + 12, + ] + out: 17977584 + - name: "deep_prefix_n30" + in: + nextVisit: + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + out: 73741815 + - name: "modulo_relevant_n100" + in: + nextVisit: + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + out: 279632275 diff --git a/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.cpp b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.cpp new file mode 100644 index 00000000..74578bc0 --- /dev/null +++ b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int firstDayBeenInAllRooms(vector& nextVisit) { + const int MOD = 1'000'000'007; + int n = nextVisit.size(); + vector dp(n, 0); + + for (int i = 1; i < n; i++) { + dp[i] = (2 * dp[i-1] - dp[nextVisit[i-1]] + 2 + MOD) % MOD; + } + + return (int) dp[n-1]; + } +}; diff --git a/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.cs b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.cs new file mode 100644 index 00000000..4a5fdf97 --- /dev/null +++ b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public int FirstDayBeenInAllRooms(int[] nextVisit) { + const int MOD = 1000000007; + int n = nextVisit.Length; + long[] dp = new long[n]; + + for (int i = 1; i < n; i++) { + dp[i] = (2 * dp[i-1] - dp[nextVisit[i-1]] + 2 + MOD) % MOD; + } + + return (int) dp[n-1]; + } +} diff --git a/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.dart b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.dart new file mode 100644 index 00000000..9e888b53 --- /dev/null +++ b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.dart @@ -0,0 +1,13 @@ +class Solution { + int firstDayBeenInAllRooms(List nextVisit) { + const MOD = 1000000007; + int n = nextVisit.length; + List dp = List.filled(n, 0); + + for (int i = 1; i < n; i++) { + dp[i] = (2 * dp[i-1] - dp[nextVisit[i-1]] + 2 + MOD) % MOD; + } + + return dp[n-1]; + } +} diff --git a/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.go b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.go new file mode 100644 index 00000000..b7157b5a --- /dev/null +++ b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.go @@ -0,0 +1,11 @@ +func firstDayBeenInAllRooms(nextVisit []int) int { + const MOD = 1000000007 + n := len(nextVisit) + dp := make([]int64, n) + + for i := 1; i < n; i++ { + dp[i] = (2*dp[i-1] - dp[nextVisit[i-1]] + 2 + MOD) % MOD + } + + return int(dp[n-1]) +} diff --git a/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.java b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.java new file mode 100644 index 00000000..b500cc20 --- /dev/null +++ b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int firstDayBeenInAllRooms(int[] nextVisit) { + final int MOD = 1_000_000_007; + int n = nextVisit.length; + long[] dp = new long[n]; + + for (int i = 1; i < n; i++) { + dp[i] = (2 * dp[i-1] - dp[nextVisit[i-1]] + 2 + MOD) % MOD; + } + + return (int) dp[n-1]; + } +} diff --git a/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.kt b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.kt new file mode 100644 index 00000000..0b75e071 --- /dev/null +++ b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.kt @@ -0,0 +1,13 @@ +class Solution { + fun firstDayBeenInAllRooms(nextVisit: IntArray): Int { + val MOD = 1_000_000_007 + val n = nextVisit.size + val dp = LongArray(n) + + for (i in 1 until n) { + dp[i] = (2 * dp[i-1] - dp[nextVisit[i-1]] + 2 + MOD) % MOD + } + + return dp[n-1].toInt() + } +} diff --git a/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.py b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.py new file mode 100644 index 00000000..4bbdd371 --- /dev/null +++ b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.py @@ -0,0 +1,14 @@ +class Solution(object): + def firstDayBeenInAllRooms(self, nextVisit): + """ + :type nextVisit: List[int] + :rtype: int + """ + MOD = 10**9 + 7 + n = len(nextVisit) + dp = [0] * n + + for i in range(1, n): + dp[i] = (2 * dp[i - 1] - dp[nextVisit[i - 1]] + 2 + MOD) % MOD + + return dp[n - 1] diff --git a/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.py2 b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.py2 new file mode 100644 index 00000000..15750b56 --- /dev/null +++ b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def firstDayBeenInAllRooms(self, nextVisit): + """ + :type nextVisit: List[int] + :rtype: int + """ + MOD = 10**9 + 7 + n = len(nextVisit) + dp = [0] * n + + for i in range(1, n): + dp[i] = (2 * dp[i-1] - dp[nextVisit[i-1]] + 2 + MOD) % MOD + + return dp[n-1] diff --git a/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.rb b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.rb new file mode 100644 index 00000000..07c1a34a --- /dev/null +++ b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.rb @@ -0,0 +1,13 @@ +# @param {Integer[]} next_visit +# @return {Integer} +def first_day_been_in_all_rooms(next_visit) + mod = 10**9 + 7 + n = next_visit.length + dp = Array.new(n, 0) + + (1...n).each do |i| + dp[i] = (2 * dp[i-1] - dp[next_visit[i-1]] + 2 + mod) % mod + end + + dp[n-1] +end diff --git a/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.rs b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.rs new file mode 100644 index 00000000..fedbf895 --- /dev/null +++ b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn first_day_been_in_all_rooms(next_visit: Vec) -> i32 { + const MOD: i64 = 1_000_000_007; + let n = next_visit.len(); + let mut dp = vec![0i64; n]; + + for i in 1..n { + dp[i] = (2 * dp[i-1] - dp[next_visit[i-1] as usize] + 2 + MOD) % MOD; + } + + dp[n-1] as i32 + } +} diff --git a/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.swift b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.swift new file mode 100644 index 00000000..4a6e035f --- /dev/null +++ b/tests/1501-2000/1997. first-day-where-you-have-been-in-all-the-rooms/sol.swift @@ -0,0 +1,13 @@ +class Solution { + func firstDayBeenInAllRooms(_ nextVisit: [Int]) -> Int { + let MOD = 1_000_000_007 + let n = nextVisit.count + var dp = [Int](repeating: 0, count: n) + + for i in 1.. 1: + if x in first: + union(i, first[x]) + else: + first[x] = i + expected = True + sorted_values = sorted(nums) + positions = {} + for i, value in enumerate(nums): + positions.setdefault(value, []).append(i) + used = {} + for destination, value in enumerate(sorted_values): + k = used.get(value, 0) + original = positions[value][k] + used[value] = k + 1 + if find(destination) != find(original): + expected = False + break + return result == expected + +seed: 1998 + +tests: + - name: "example_chain" + in: + nums: [7, 21, 3] + out: true + - name: "example_isolated_prime" + in: + nums: [5, 2, 6, 2] + out: false + - name: "example_mixed_components" + in: + nums: [10, 5, 9, 3, 15] + out: true + - name: "single_value" + in: + nums: [2] + out: true + - name: "already_sorted_primes" + in: + nums: [2, 3, 5, 7, 11] + out: true + - name: "reverse_primes" + in: + nums: [11, 7, 5, 3, 2] + out: false + - name: "equal_values" + in: + nums: [37, 37, 37, 37] + out: true + - name: "two_coprime_swap_needed" + in: + nums: [3, 2] + out: false + - name: "two_shared_factor" + in: + nums: [6, 10] + out: true + - name: "transitive_factor_chain" + in: + nums: [77, 22, 6] + out: true + - name: "large_prime_isolated" + in: + nums: [99991, 2, 3] + out: false + - name: "large_prime_sorted" + in: + nums: [2, 3, 99991] + out: true + - name: "duplicate_component" + in: + nums: [12, 7, 18, 5, 30] + out: true + - name: "all_even_reverse" + in: + nums: [100, 50, 10, 2] + out: true + - name: "all_odd_shared_three" + in: + nums: [45, 15, 75, 105] + out: true + - name: "separate_blocks_sorted" + in: + nums: [6, 10, 7, 11] + out: false + - name: "separate_blocks_crossed" + in: + nums: [10, 6, 11, 7] + out: false + - name: "one_component_with_singletons" + in: + nums: [35, 14, 22, 13, 26] + out: true + - name: "prime_duplicates_can_move" + in: + nums: [13, 2, 13, 2] + out: false + - name: "duplicate_prime_crossed" + in: + nums: [13, 2, 2, 13] + out: false + - name: "many_small_factors" + in: + nums: [30, 42, 70, 105, 66] + out: true + - name: "coprime_permutation" + in: + nums: [17, 19, 23, 29] + out: true + - name: "sorted_with_zero_swaps" + in: + nums: [2, 6, 15, 35, 77] + out: true + - name: "one_bad_position" + in: + nums: [2, 6, 35, 15, 77] + out: true + - name: "factor_one_bridge" + in: + nums: [143, 11, 22, 6, 3] + out: true + - name: "large_values_shared_factor" + in: + nums: [99990, 99980, 99970, 99960] + out: true + - name: "large_values_coprime_order" + in: + nums: [99991, 99989, 99971] + out: false + - name: "mixed_duplicates" + in: + nums: [8, 15, 8, 21, 15, 35] + out: false + - name: "component_boundary_failure" + in: + nums: [2, 9, 6, 25] + out: true + - name: "long_factor_chain" + in: + nums: [231, 77, 35, 15, 6] + out: true + - name: "all_singletons_already_sorted" + in: + nums: [2, 3, 5, 7, 11, 13] + out: true + - name: "all_singletons_reversed" + in: + nums: [13, 11, 7, 5, 3, 2] + out: false + - name: "stress_even_component" + seed: 2101 + in: + nums: + gen: "array" + len: 30000 + of: + gen: "int" + min: 2 + max: 100000 + - name: "stress_small_values" + seed: 2102 + in: + nums: + gen: "array" + len: 25000 + of: + gen: "int" + min: 2 + max: 200 + - name: "stress_large_values" + seed: 2103 + in: + nums: + gen: "array" + len: 30000 + of: + gen: "int" + min: 90000 + max: 100000 + - name: "stress_medium_values" + seed: 2104 + in: + nums: + gen: "array" + len: 20000 + of: + gen: "int" + min: 2 + max: 10000 + - name: "stress_repeated_values" + seed: 2105 + in: + nums: + gen: "array" + len: 30000 + of: + gen: "int" + min: 99990 + max: 100000 diff --git a/tests/1501-2000/1998. gcd-sort-of-an-array/sol.cpp b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.cpp new file mode 100644 index 00000000..c71b3200 --- /dev/null +++ b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.cpp @@ -0,0 +1,30 @@ +class Solution { + int find(vector& p, int x) { while (p[x] != x) { p[x] = p[p[x]]; x = p[x]; } return x; } + void unite(vector& p, vector& sz, int a, int b) { + a = find(p, a); b = find(p, b); if (a == b) return; + if (sz[a] < sz[b]) swap(a, b); p[b] = a; sz[a] += sz[b]; + } +public: + bool gcdSort(vector& nums) { + int mx = 0; for (int x : nums) mx = max(mx, x); + vector p(mx + 1), sz(mx + 1, 1); + for (int i = 0; i <= mx; i++) p[i] = i; + for (int value : nums) { + int x = value; + for (int f = 2; f * f <= x; f++) if (x % f == 0) { + unite(p, sz, f, value); + while (x % f == 0) x /= f; + } + if (x > 1) unite(p, sz, x, value); + } + vector sorted = nums; + for (int i = 1; i < (int)sorted.size(); i++) { + int x = sorted[i], j = i - 1; + while (j >= 0 && sorted[j] > x) { sorted[j + 1] = sorted[j]; j--; } + sorted[j + 1] = x; + } + for (int i = 0; i < (int)nums.size(); i++) + if (find(p, nums[i]) != find(p, sorted[i])) return false; + return true; + } +}; diff --git a/tests/1501-2000/1998. gcd-sort-of-an-array/sol.cs b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.cs new file mode 100644 index 00000000..7658b805 --- /dev/null +++ b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.cs @@ -0,0 +1,18 @@ +public class GcdSortUnionFind { + private readonly int[] p; + private readonly int[] size; + public GcdSortUnionFind(int n) { p = new int[n]; size = new int[n]; for (int i=0;i Find(a) == Find(b); +} +public class Solution { + public bool GcdSort(int[] nums) { + int max = 0; foreach (int x in nums) if (x > max) max = x; + var uf = new GcdSortUnionFind(max + 1); + foreach (int value in nums) { int n=value; for(int f=2;f*f<=n;f++) if(n%f==0){uf.Join(f,value);while(n%f==0)n/=f;} if(n>1)uf.Join(n,value); } + int[] sorted=(int[])nums.Clone(); System.Array.Sort(sorted); + for(int i=0;i p = [], size = []; + _DSU(int n) { for (int i = 0; i < n; i++) { p.add(i); size.add(1); } } + int find(int x) { while (p[x] != x) { p[x] = p[p[x]]; x = p[x]; } return x; } + void union(int a, int b) { a = find(a); b = find(b); if (a == b) return; if (size[a] < size[b]) { final t = a; a = b; b = t; } p[b] = a; size[a] += size[b]; } +} +class Solution { + bool gcdSort(List nums) { + int mx = 0; for (final x in nums) { if (x > mx) mx = x; } + final d = _DSU(mx + 1); + for (final value in nums) { + int x = value; + for (int f = 2; f * f <= x; f++) if (x % f == 0) { + d.union(f, value); while (x % f == 0) x ~/= f; + } + if (x > 1) d.union(x, value); + } + final sorted = List.from(nums)..sort(); + for (int i = 0; i < nums.length; i++) if (d.find(nums[i]) != d.find(sorted[i])) return false; + return true; + } +} diff --git a/tests/1501-2000/1998. gcd-sort-of-an-array/sol.go b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.go new file mode 100644 index 00000000..8e17491a --- /dev/null +++ b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.go @@ -0,0 +1,17 @@ +type gcdDSU struct { p, sz []int } +func newGcdDSU(n int) *gcdDSU { p := make([]int,n); sz := make([]int,n); for i := range p { p[i] = i; sz[i] = 1 }; return &gcdDSU{p,sz} } +func (d *gcdDSU) find(x int) int { for d.p[x] != x { d.p[x] = d.p[d.p[x]]; x = d.p[x] }; return x } +func (d *gcdDSU) unite(a,b int) { a,b = d.find(a),d.find(b); if a == b { return }; if d.sz[a] < d.sz[b] { a,b = b,a }; d.p[b] = a; d.sz[a] += d.sz[b] } +func gcdSort(nums []int) bool { + mx := 0; for _, x := range nums { if x > mx { mx = x } } + d := newGcdDSU(mx + 1) + for _, value := range nums { + x := value + for f := 2; f*f <= x; f++ { if x%f == 0 { d.unite(f,value); for x%f == 0 { x /= f } } } + if x > 1 { d.unite(x,value) } + } + sorted := append([]int(nil), nums...) + for i := 1; i < len(sorted); i++ { x,j := sorted[i],i-1; for j >= 0 && sorted[j] > x { sorted[j+1] = sorted[j]; j-- }; sorted[j+1] = x } + for i := range nums { if d.find(nums[i]) != d.find(sorted[i]) { return false } } + return true +} diff --git a/tests/1501-2000/1998. gcd-sort-of-an-array/sol.java b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.java new file mode 100644 index 00000000..88fe44e5 --- /dev/null +++ b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.java @@ -0,0 +1,68 @@ +class Solution { + public boolean gcdSort(int[] nums) { + class UnionFind { + int[] parent; + int[] size; + UnionFind(int n) { + parent = new int[n]; + size = new int[n]; + for (int i = 0; i < n; i++) { + parent[i] = i; + size[i] = 1; + } + } + int find(int x) { + if (parent[x] != x) { + parent[x] = find(parent[x]); + } + return parent[x]; + } + boolean connected(int x, int y) { + return find(x) == find(y); + } + void union(int x, int y) { + int px = find(x); + int py = find(y); + if (px != py) { + if (size[px] < size[py]) { + parent[px] = py; + size[py] += size[px]; + } else { + parent[py] = px; + size[px] += size[py]; + } + } + } + } + + int maxVal = 0; + for (int num : nums) { + maxVal = Math.max(maxVal, num); + } + UnionFind uf = new UnionFind(maxVal + 1); + for (int num : nums) { + int n = num; + int i = 2; + while (i * i <= n) { + if (n % i == 0) { + uf.union(i, num); + while (n % i == 0) { + n /= i; + } + } + i++; + } + if (n > 1) { + uf.union(n, num); + } + } + int[] sorted = nums.clone(); + java.util.Arrays.sort(sorted); + for (int i = 0; i < nums.length; i++) { + if (!uf.connected(nums[i], sorted[i])) { + return false; + } + } + return true; + } +} diff --git a/tests/1501-2000/1998. gcd-sort-of-an-array/sol.kt b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.kt new file mode 100644 index 00000000..b0c3ea29 --- /dev/null +++ b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.kt @@ -0,0 +1,55 @@ +class Solution { + fun gcdSort(nums: IntArray): Boolean { + class UnionFind(val n: Int) { + val parent = IntArray(n) { it } + val size = IntArray(n) { 1 } + fun find(x: Int): Int { + if (parent[x] != x) { + parent[x] = find(parent[x]) + } + return parent[x] + } + fun union(x: Int, y: Int) { + val px = find(x) + val py = find(y) + if (px != py) { + if (size[px] < size[py]) { + parent[px] = py + size[py] += size[px] + } else { + parent[py] = px + size[px] += size[py] + } + } + } + fun connected(x: Int, y: Int): Boolean { + return find(x) == find(y) + } + } + val maxVal = nums.maxOrNull() ?: 0 + val uf = UnionFind(maxVal + 1) + for (num in nums) { + var n = num + var i = 2 + while (i * i <= n) { + if (n % i == 0) { + uf.union(i, num) + while (n % i == 0) { + n /= i + } + } + i++ + } + if (n > 1) { + uf.union(n, num) + } + } + val sorted = nums.sorted() + for (i in nums.indices) { + if (!uf.connected(nums[i], sorted[i])) { + return false + } + } + return true + } +} diff --git a/tests/1501-2000/1998. gcd-sort-of-an-array/sol.py b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.py new file mode 100644 index 00000000..e4619877 --- /dev/null +++ b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.py @@ -0,0 +1,46 @@ +class UnionFind: + def __init__(self, n): + self.P = [i for i in range(n)] + self.S = [1] * n + + def Find(self, node): + if self.P[node] != node: + self.P[node] = self.Find(self.P[node]) + return self.P[node] + + def Connected(self, x, y): + return self.Find(x) == self.Find(y) + + def Union(self, x, y): + pX, pY = self.Find(x), self.Find(y) + + if pX != pY: + if self.S[pX] < self.S[pY]: + self.P[pX] = pY + self.S[pY] += self.S[pX] + else: + self.P[pY] = pX + self.S[pX] += self.S[pY] + + +class Solution: + def gcdSort(self, nums): + A = nums + + G = UnionFind(max(A) + 1) + + for num in A: + n, i = num, 2 + while i * i <= n: + if not n % i: + G.Union(i, num) + while not n % i: + n //= i + i += 1 + if n > 1: + G.Union(n, num) + + for a, b in zip(A, sorted(A)): + if not G.Connected(a, b): + return False + return True diff --git a/tests/1501-2000/1998. gcd-sort-of-an-array/sol.py2 b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.py2 new file mode 100644 index 00000000..4197752f --- /dev/null +++ b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.py2 @@ -0,0 +1,42 @@ +class Solution(object): + def gcdSort(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + class UnionFind: + def __init__(self, n): + self.parent = list(range(n)) + self.size = [1]*n + def find(self, x): + if self.parent[x] != x: + self.parent[x] = self.find(self.parent[x]) + return self.parent[x] + def union(self, x, y): + px, py = self.find(x), self.find(y) + if px != py: + if self.size[px] < self.size[py]: + self.parent[px] = py + self.size[py] += self.size[px] + else: + self.parent[py] = px + self.size[px] += self.size[py] + + max_val = max(nums) + uf = UnionFind(max_val+1) + for num in nums: + n = num + i = 2 + while i*i <= n: + if n % i == 0: + uf.union(i, num) + while n % i == 0: + n //= i + i += 1 + if n > 1: + uf.union(n, num) + + for a, b in zip(nums, sorted(nums)): + if uf.find(a) != uf.find(b): + return False + return True diff --git a/tests/1501-2000/1998. gcd-sort-of-an-array/sol.rb b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.rb new file mode 100644 index 00000000..57cf11e3 --- /dev/null +++ b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.rb @@ -0,0 +1,37 @@ +class GcdSortUnionFind + def initialize(n) + @parent = (0...n).to_a + @size = Array.new(n, 1) + end + def find(x) + while @parent[x] != x + @parent[x] = @parent[@parent[x]] + x = @parent[x] + end + x + end + def union(a, b) + a = find(a); b = find(b); return if a == b + a, b = b, a if @size[a] < @size[b] + @parent[b] = a; @size[a] += @size[b] + end + def connected?(a, b); find(a) == find(b); end +end + +def gcd_sort(nums) + uf = GcdSortUnionFind.new(nums.max + 1) + nums.each do |value| + x = value; factor = 2 + while factor * factor <= x + if x % factor == 0 + uf.union(factor, value) + x /= factor while x % factor == 0 + end + factor += 1 + end + uf.union(x, value) if x > 1 + end + sorted = nums.sort + nums.each_index { |i| return false unless uf.connected?(nums[i], sorted[i]) } + true +end diff --git a/tests/1501-2000/1998. gcd-sort-of-an-array/sol.rs b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.rs new file mode 100644 index 00000000..d0faebe6 --- /dev/null +++ b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.rs @@ -0,0 +1,66 @@ +impl Solution { + pub fn gcd_sort(nums: Vec) -> bool { + struct UnionFind { + parent: Vec, + size: Vec, + } + impl UnionFind { + fn new(n: usize) -> Self { + UnionFind { + parent: (0..n).collect(), + size: vec![1; n], + } + } + fn find(&mut self, x: usize) -> usize { + if self.parent[x] != x { + let root = self.find(self.parent[x]); + self.parent[x] = root; + } + self.parent[x] + } + fn union(&mut self, x: usize, y: usize) { + let px = self.find(x); + let py = self.find(y); + if px != py { + if self.size[px] < self.size[py] { + self.parent[px] = py; + self.size[py] += self.size[px]; + } else { + self.parent[py] = px; + self.size[px] += self.size[py]; + } + } + } + fn connected(&mut self, x: usize, y: usize) -> bool { + self.find(x) == self.find(y) + } + } + + let max_val = *nums.iter().max().unwrap_or(&0) as usize; + let mut uf = UnionFind::new(max_val + 1); + for &num in nums.iter() { + let mut n = num as usize; + let mut i = 2; + while i * i <= n { + if n % i == 0 { + uf.union(i, num as usize); + while n % i == 0 { + n /= i; + } + } + i += 1; + } + if n > 1 { + uf.union(n, num as usize); + } + } + let mut sorted = nums.clone(); + sorted.sort_unstable(); + for i in 0..nums.len() { + if !uf.connected(nums[i] as usize, sorted[i] as usize) { + return false; + } + } + true + } +} diff --git a/tests/1501-2000/1998. gcd-sort-of-an-array/sol.swift b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.swift new file mode 100644 index 00000000..e5d39f6f --- /dev/null +++ b/tests/1501-2000/1998. gcd-sort-of-an-array/sol.swift @@ -0,0 +1,60 @@ +class Solution { + func gcdSort(_ nums: [Int]) -> Bool { + class UnionFind { + var parent: [Int] + var size: [Int] + init(_ n: Int) { + parent = Array(0.. Int { + if parent[x] != x { + parent[x] = find(parent[x]) + } + return parent[x] + } + func union(_ x: Int, _ y: Int) { + let px = find(x) + let py = find(y) + if px != py { + if size[px] < size[py] { + parent[px] = py + size[py] += size[px] + } else { + parent[py] = px + size[px] += size[py] + } + } + } + func connected(_ x: Int, _ y: Int) -> Bool { + return find(x) == find(y) + } + } + + let maxVal = nums.max() ?? 0 + let uf = UnionFind(maxVal + 1) + for num in nums { + var n = num + var i = 2 + while i * i <= n { + if n % i == 0 { + uf.union(i, num) + while n % i == 0 { + n /= i + } + } + i += 1 + } + if n > 1 { + uf.union(n, num) + } + } + let sorted = nums.sorted() + for i in 0.. i); + this.size = new Array(n).fill(1); + } + find(x: number): number { + if (this.parent[x] !== x) { + this.parent[x] = this.find(this.parent[x]); + } + return this.parent[x]; + } + union(x: number, y: number): void { + const px = this.find(x); + const py = this.find(y); + if (px !== py) { + if (this.size[px] < this.size[py]) { + this.parent[px] = py; + this.size[py] += this.size[px]; + } else { + this.parent[py] = px; + this.size[px] += this.size[py]; + } + } + } + connected(x: number, y: number): boolean { + return this.find(x) === this.find(y); + } + } + + const maxVal = Math.max(...nums, 0); + const uf = new UnionFind(maxVal + 1); + for (const num of nums) { + let n = num; + let i = 2; + while (i * i <= n) { + if (n % i === 0) { + uf.union(i, num); + while (n % i === 0) { + n = Math.floor(n / i); + } + } + i++; + } + if (n > 1) { + uf.union(n, num); + } + } + const sorted = [...nums].sort((a, b) => a - b); + for (let i = 0; i < nums.length; i++) { + if (!uf.connected(nums[i], sorted[i])) { + return false; + } + } + return true; +} diff --git a/tests/1501-2000/2000. reverse-prefix-of-word/manifest.yaml b/tests/1501-2000/2000. reverse-prefix-of-word/manifest.yaml new file mode 100644 index 00000000..779db049 --- /dev/null +++ b/tests/1501-2000/2000. reverse-prefix-of-word/manifest.yaml @@ -0,0 +1,325 @@ +entry: + id: 2000 + title: "reverse-prefix-of-word" + params: + word: + type: string + ch: + type: char + call: + cpp: "Solution().reversePrefix({word}, {ch})" + rust: "Solution::reverse_prefix({word}, {ch})" + python3: "Solution().reversePrefix({word}, {ch})" + python2: "Solution().reversePrefix({word}, {ch})" + ruby: "reverse_prefix({word}, {ch})" + java: "new Solution().reversePrefix({word}, {ch})" + csharp: "new Solution().ReversePrefix({word}, {ch})" + kotlin: "Solution().reversePrefix({word}, {ch})" + go: "reversePrefix({word}, {ch})" + dart: "Solution().reversePrefix({word}, {ch})" + swift: "Solution().reversePrefix({word}, {ch})" + typescript: "reversePrefix({word}, {ch})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().reversePrefix(word, ch, {result})" + checker: | + class Checker: + def reversePrefix(self, word, ch, result): + if not isinstance(word, str) or not isinstance(ch, str) or len(ch) != 1: + return False + if not isinstance(result, str): + return False + pos = word.find(ch) + expected = word if pos < 0 else word[:pos + 1][::-1] + word[pos + 1:] + return result == expected + +seed: 2000 + +tests: + - name: "example_1" + in: + word: "abcdefd" + ch: "d" + out: "dcbaefd" + + - name: "example_2" + in: + word: "xyxzxe" + ch: "z" + out: "zxyxxe" + + - name: "example_3_missing" + in: + word: "abcd" + ch: "z" + out: "abcd" + + - name: "one_character_match" + in: + word: "a" + ch: "a" + out: "a" + + - name: "one_character_missing" + in: + word: "a" + ch: "b" + out: "a" + + - name: "match_at_start" + in: + word: "apple" + ch: "a" + out: "apple" + + - name: "match_at_end" + in: + word: "hello" + ch: "o" + out: "olleh" + + - name: "first_occurrence_only" + in: + word: "abcaad" + ch: "a" + out: "abcaad" + + - name: "repeated_match_after_prefix" + in: + word: "zzzzabc" + ch: "z" + out: "zzzzabc" + + - name: "repeated_match_middle" + in: + word: "cabacaba" + ch: "a" + out: "acbacaba" + + - name: "all_same" + in: + word: "bbbbbb" + ch: "b" + out: "bbbbbb" + + - name: "missing_z" + in: + word: "abcdefghijklmnopqrstuvwxy" + ch: "z" + out: "abcdefghijklmnopqrstuvwxy" + + - name: "reverse_two" + in: + word: "abcd" + ch: "b" + out: "bacd" + + - name: "reverse_three" + in: + word: "abcdef" + ch: "c" + out: "cbadef" + + - name: "prefix_with_duplicates" + in: + word: "aabcaef" + ch: "c" + out: "cbaaaef" + + - name: "late_first_match" + in: + word: "mnopqrmnop" + ch: "r" + out: "rqponmmnop" + + - name: "match_near_end" + in: + word: "qwertyuiop" + ch: "i" + out: "iuytrewqop" + + - name: "vowels" + in: + word: "aeiouae" + ch: "u" + out: "uoieaae" + + - name: "letter_x" + in: + word: "xylophone" + ch: "o" + out: "olyxphone" + + - name: "letter_m" + in: + word: "programming" + ch: "m" + out: "margorpming" + + - name: "missing_first_letter" + in: + word: "leetcode" + ch: "a" + out: "leetcode" + + - name: "match_at_index_one" + in: + word: "baaaaa" + ch: "a" + out: "abaaaa" + + - name: "match_at_index_two" + in: + word: "cbaabc" + ch: "a" + out: "abcabc" + + - name: "palindromic_prefix" + in: + word: "abccbaef" + ch: "c" + out: "cbacbaef" + + - name: "palindrome_whole" + in: + word: "racecar" + ch: "r" + out: "racecar" + + - name: "alternating_letters" + in: + word: "abababab" + ch: "b" + out: "baababab" + + - name: "long_prefix_1" + in: + word: "abcdefghijklmnopqrst" + ch: "t" + out: "tsrqponmlkjihgfedcba" + + - name: "long_prefix_2" + in: + word: "abcdefghijklmnopqrst" + ch: "k" + out: "kjihgfedcbalmnopqrst" + + - name: "first_match_does_not_skip" + in: + word: "cbacada" + ch: "a" + out: "abccada" + + - name: "suffix_preserved" + in: + word: "helloworld" + ch: "l" + out: "lehloworld" + + - name: "digits_not_allowed_but_letters_dense" + in: + word: "zzzyyyxxxwww" + ch: "x" + out: "xyyyzzzxxwww" + + - name: "near_max_static" + in: + word: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + ch: "a" + out: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + + - name: "missing_middle_letter" + in: + word: "abcdefghijklmnop" + ch: "z" + out: "abcdefghijklmnop" + + - name: "first_match_after_run" + in: + word: "bbbbbcdef" + ch: "d" + out: "dcbbbbbef" + + - name: "first_match_is_last_character" + in: + word: "vwxyz" + ch: "z" + out: "zyxwv" + + - name: "short_missing" + in: + word: "abc" + ch: "c" + out: "cba" + + - name: "generated_small" + seed: 20001 + in: + word: + gen: "str" + len: + gen: "int" + min: 1 + max: 20 + alphabet: "abcxz" + ch: + gen: "char" + variety: ["a", "b", "c", "x", "z"] + + - name: "generated_medium" + seed: 20002 + in: + word: + gen: "str" + len: + gen: "int" + min: 21 + max: 80 + alphabet: "admpz" + ch: + gen: "char" + variety: ["a", "d", "m", "p", "z"] + + - name: "generated_large" + seed: 20003 + in: + word: + gen: "str" + len: + gen: "int" + min: 200 + max: 250 + alphabet: "abcdef" + ch: + gen: "char" + variety: ["a", "b", "c", "d", "e", "f", "z"] + + - name: "generated_binary_alphabet" + seed: 20004 + in: + word: + gen: "str" + len: 250 + alphabet: "ab" + ch: + gen: "char" + variety: ["a", "b", "c"] + + - name: "generated_uniform_stress" + seed: 20005 + in: + word: + gen: "str" + len: 250 + alphabet: "abcdefghijklmnopqrstuvwxyz" + ch: + gen: "char" + variety: ["a", "m", "z"] diff --git a/tests/1501-2000/2000. reverse-prefix-of-word/sol.cpp b/tests/1501-2000/2000. reverse-prefix-of-word/sol.cpp new file mode 100644 index 00000000..9e44480a --- /dev/null +++ b/tests/1501-2000/2000. reverse-prefix-of-word/sol.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + string reversePrefix(string word, char ch) { + size_t pos = word.find(ch); + if (pos == string::npos) { + return word; + } + reverse(word.begin(), word.begin() + pos + 1); + return word; + } +}; diff --git a/tests/1501-2000/2000. reverse-prefix-of-word/sol.cs b/tests/1501-2000/2000. reverse-prefix-of-word/sol.cs new file mode 100644 index 00000000..b332b602 --- /dev/null +++ b/tests/1501-2000/2000. reverse-prefix-of-word/sol.cs @@ -0,0 +1,11 @@ +public class Solution { + public string ReversePrefix(string word, char ch) { + int idx = word.IndexOf(ch); + if (idx == -1) { + return word; + } + char[] chars = word.ToCharArray(); + Array.Reverse(chars, 0, idx + 1); + return new string(chars); + } +} diff --git a/tests/1501-2000/2000. reverse-prefix-of-word/sol.dart b/tests/1501-2000/2000. reverse-prefix-of-word/sol.dart new file mode 100644 index 00000000..78263f56 --- /dev/null +++ b/tests/1501-2000/2000. reverse-prefix-of-word/sol.dart @@ -0,0 +1,11 @@ +class Solution { + String reversePrefix(String word, String ch) { + int idx = word.indexOf(ch); + if (idx == -1) { + return word; + } + String prefix = word.substring(0, idx + 1); + String reversed = prefix.split('').reversed.join(); + return reversed + word.substring(idx + 1); + } +} diff --git a/tests/1501-2000/2000. reverse-prefix-of-word/sol.go b/tests/1501-2000/2000. reverse-prefix-of-word/sol.go new file mode 100644 index 00000000..e5be66a6 --- /dev/null +++ b/tests/1501-2000/2000. reverse-prefix-of-word/sol.go @@ -0,0 +1,17 @@ +func reversePrefix(word string, ch byte) string { + idx := -1 + for i := 0; i < len(word); i++ { + if word[i] == ch { + idx = i + break + } + } + if idx == -1 { + return word + } + runes := []byte(word) + for i, j := 0, idx; i < j; i, j = i+1, j-1 { + runes[i], runes[j] = runes[j], runes[i] + } + return string(runes) +} diff --git a/tests/1501-2000/2000. reverse-prefix-of-word/sol.java b/tests/1501-2000/2000. reverse-prefix-of-word/sol.java new file mode 100644 index 00000000..1b8ee4c4 --- /dev/null +++ b/tests/1501-2000/2000. reverse-prefix-of-word/sol.java @@ -0,0 +1,13 @@ +class Solution { + public String reversePrefix(String word, char ch) { + int idx = word.indexOf(ch); + if (idx == -1) { + return word; + } + StringBuilder sb = new StringBuilder(); + sb.append(word.substring(0, idx + 1)); + sb.reverse(); + sb.append(word.substring(idx + 1)); + return sb.toString(); + } +} diff --git a/tests/1501-2000/2000. reverse-prefix-of-word/sol.kt b/tests/1501-2000/2000. reverse-prefix-of-word/sol.kt new file mode 100644 index 00000000..79197456 --- /dev/null +++ b/tests/1501-2000/2000. reverse-prefix-of-word/sol.kt @@ -0,0 +1,12 @@ +class Solution { + fun reversePrefix(word: String, ch: Char): String { + val idx = word.indexOf(ch) + if (idx == -1) { + return word + } + val sb = StringBuilder() + sb.append(word.substring(0, idx + 1)).reverse() + sb.append(word.substring(idx + 1)) + return sb.toString() + } +} diff --git a/tests/1501-2000/2000. reverse-prefix-of-word/sol.py b/tests/1501-2000/2000. reverse-prefix-of-word/sol.py new file mode 100644 index 00000000..06006f13 --- /dev/null +++ b/tests/1501-2000/2000. reverse-prefix-of-word/sol.py @@ -0,0 +1,17 @@ +class Solution: + def reversePrefix(self, word: str, ch: str) -> str: + if ch not in word: + return word + + stack = [] + answer = [] + + for i, c in enumerate(word): + stack.append(c) + + if c == ch: + answer.extend(reversed(stack)) + answer.extend(word[i + 1 :]) + break + + return "".join(answer) diff --git a/tests/1501-2000/2000. reverse-prefix-of-word/sol.py2 b/tests/1501-2000/2000. reverse-prefix-of-word/sol.py2 new file mode 100644 index 00000000..d49170b0 --- /dev/null +++ b/tests/1501-2000/2000. reverse-prefix-of-word/sol.py2 @@ -0,0 +1,11 @@ +class Solution(object): + def reversePrefix(self, word, ch): + """ + :type word: str + :type ch: str + :rtype: str + """ + if ch not in word: + return word + idx = word.index(ch) + return word[:idx+1][::-1] + word[idx+1:] diff --git a/tests/1501-2000/2000. reverse-prefix-of-word/sol.rb b/tests/1501-2000/2000. reverse-prefix-of-word/sol.rb new file mode 100644 index 00000000..f34ea98b --- /dev/null +++ b/tests/1501-2000/2000. reverse-prefix-of-word/sol.rb @@ -0,0 +1,5 @@ +def reverse_prefix(word, ch) + idx = word.index(ch) + return word if idx.nil? + word[0..idx].reverse + word[(idx + 1)..] +end diff --git a/tests/1501-2000/2000. reverse-prefix-of-word/sol.rs b/tests/1501-2000/2000. reverse-prefix-of-word/sol.rs new file mode 100644 index 00000000..b416bcfd --- /dev/null +++ b/tests/1501-2000/2000. reverse-prefix-of-word/sol.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn reverse_prefix(word: String, ch: char) -> String { + let idx = word.find(ch); + match idx { + Some(i) => { + let mut chars: Vec = word.chars().collect(); + let mut left = 0; + let mut right = i; + while left < right { + chars.swap(left, right); + left += 1; + right -= 1; + } + chars.into_iter().collect() + } + None => word, + } + } +} diff --git a/tests/1501-2000/2000. reverse-prefix-of-word/sol.swift b/tests/1501-2000/2000. reverse-prefix-of-word/sol.swift new file mode 100644 index 00000000..56def3a8 --- /dev/null +++ b/tests/1501-2000/2000. reverse-prefix-of-word/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func reversePrefix(_ word: String, _ ch: Character) -> String { + guard let idx = word.firstIndex(of: ch) else { return word } + var chars = Array(word) + let endIdx = word.distance(from: word.startIndex, to: idx) + var left = 0 + var right = endIdx + while left < right { + chars.swapAt(left, right) + left += 1 + right -= 1 + } + return String(chars) + } +} diff --git a/tests/1501-2000/2000. reverse-prefix-of-word/sol.ts b/tests/1501-2000/2000. reverse-prefix-of-word/sol.ts new file mode 100644 index 00000000..72cc7905 --- /dev/null +++ b/tests/1501-2000/2000. reverse-prefix-of-word/sol.ts @@ -0,0 +1,9 @@ +function reversePrefix(word: string, ch: string): string { + const idx = word.indexOf(ch); + if (idx === -1) { + return word; + } + const prefix = word.substring(0, idx + 1); + const reversed = prefix.split("").reverse().join(""); + return reversed + word.substring(idx + 1); +} diff --git a/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/manifest.yaml b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/manifest.yaml new file mode 100644 index 00000000..d203ab91 --- /dev/null +++ b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/manifest.yaml @@ -0,0 +1,504 @@ +entry: + id: 2001 + title: "number-of-pairs-of-interchangeable-rectangles" + params: + rectangles: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().interchangeableRectangles({rectangles})" + rust: "Solution::interchangeable_rectangles({rectangles})" + python3: "Solution().interchangeableRectangles({rectangles})" + python2: "Solution().interchangeableRectangles({rectangles})" + ruby: "interchangeable_rectangles({rectangles})" + java: "new Solution().interchangeableRectangles({rectangles})" + csharp: "new Solution().InterchangeableRectangles({rectangles})" + kotlin: "Solution().interchangeableRectangles({rectangles})" + go: "interchangeableRectangles({rectangles})" + dart: "Solution().interchangeableRectangles({rectangles})" + swift: "Solution().interchangeableRectangles({rectangles})" + typescript: "interchangeableRectangles({rectangles})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().interchangeableRectangles(rectangles, {result})" + checker: | + from collections import defaultdict + from math import gcd + + class Checker: + def interchangeableRectangles(self, rectangles, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + counts = defaultdict(int) + expected = 0 + for pair in rectangles: + if not isinstance(pair, list) or len(pair) != 2: + return False + w, h = pair + if not isinstance(w, int) or not isinstance(h, int) or w <= 0 or h <= 0: + return False + g = gcd(w, h) + key = (w // g, h // g) + expected += counts[key] + counts[key] += 1 + return result == expected + +seed: 2001 + +tests: + - name: "example_all_same" + in: + rectangles: + elemType: "int" + value: + - [4, 8] + - [3, 6] + - [10, 20] + - [15, 30] + out: 6 + - name: "example_no_match" + in: + rectangles: + elemType: "int" + value: + - [4, 5] + - [7, 8] + out: 0 + - name: "two_equal" + in: + rectangles: + elemType: "int" + value: + - [1, 1] + - [2, 2] + out: 1 + - name: "single" + in: + rectangles: + elemType: "int" + value: + - [100000, 1] + out: 0 + - name: "same_width_different_ratio" + in: + rectangles: + elemType: "int" + value: + - [5, 1] + - [5, 2] + - [5, 5] + - [5, 10] + out: 0 + - name: "reduced_fraction_duplicates" + in: + rectangles: + elemType: "int" + value: + - [6, 9] + - [2, 3] + - [100, 150] + - [4, 6] + - [3, 2] + out: 6 + - name: "two_groups" + in: + rectangles: + elemType: "int" + value: + - [1, 2] + - [2, 4] + - [3, 9] + - [1, 3] + - [10, 30] + - [4, 8] + out: 6 + - name: "three_groups" + in: + rectangles: + elemType: "int" + value: + - [1, 1] + - [2, 2] + - [1, 2] + - [2, 4] + - [1, 3] + - [3, 9] + - [7, 5] + out: 3 + - name: "coprime_pairs" + in: + rectangles: + elemType: "int" + value: + - [1, 2] + - [2, 3] + - [3, 4] + - [4, 5] + - [5, 6] + out: 0 + - name: "max_values_same_ratio" + in: + rectangles: + elemType: "int" + value: + - [100000, 100000] + - [50000, 50000] + - [99999, 99999] + out: 3 + - name: "one_pair_among_noise" + in: + rectangles: + elemType: "int" + value: + - [2, 5] + - [3, 7] + - [4, 10] + - [6, 11] + - [7, 13] + out: 1 + - name: "four_equal_ratio" + in: + rectangles: + elemType: "int" + value: + - [8, 12] + - [2, 3] + - [10, 15] + - [14, 21] + out: 6 + - name: "two_equal_groups" + in: + rectangles: + elemType: "int" + value: + - [2, 3] + - [4, 6] + - [3, 4] + - [6, 8] + - [5, 7] + out: 2 + - name: "order_independent" + in: + rectangles: + elemType: "int" + value: + - [9, 6] + - [1, 4] + - [3, 2] + - [5, 20] + - [2, 1] + out: 2 + - name: "large_coprime_values" + in: + rectangles: + elemType: "int" + value: + - [99991, 99989] + - [99989, 99991] + - [99991, 99991] + out: 0 + - name: "five_same" + in: + rectangles: + elemType: "int" + value: + - [1, 7] + - [2, 14] + - [3, 21] + - [4, 28] + - [5, 35] + out: 10 + - name: "six_same" + in: + rectangles: + elemType: "int" + value: + - [7, 1] + - [14, 2] + - [21, 3] + - [28, 4] + - [35, 5] + - [42, 6] + out: 15 + - name: "mixed_reduced_forms" + in: + rectangles: + elemType: "int" + value: + - [12, 18] + - [8, 12] + - [20, 30] + - [15, 10] + - [3, 2] + - [9, 6] + - [1, 1] + out: 6 + - name: "all_distinct_reversed" + in: + rectangles: + elemType: "int" + value: + - [1, 5] + - [2, 4] + - [3, 3] + - [4, 2] + - [5, 1] + out: 0 + - name: "ratio_one_and_two" + in: + rectangles: + elemType: "int" + value: + - [1, 1] + - [2, 2] + - [3, 3] + - [1, 2] + - [2, 4] + - [3, 6] + - [4, 8] + out: 9 + - name: "eight_same" + in: + rectangles: + elemType: "int" + value: + - [11, 13] + - [22, 26] + - [33, 39] + - [44, 52] + - [55, 65] + - [66, 78] + - [77, 91] + - [88, 104] + out: 28 + - name: "alternating_groups" + in: + rectangles: + elemType: "int" + value: + - [1, 2] + - [1, 3] + - [2, 4] + - [2, 6] + - [3, 6] + - [3, 9] + out: 6 + - name: "three_ratio_groups" + in: + rectangles: + elemType: "int" + value: + - [2, 5] + - [4, 10] + - [6, 15] + - [3, 7] + - [6, 14] + - [9, 21] + - [5, 2] + - [10, 4] + out: 7 + - name: "boundary_widths" + in: + rectangles: + elemType: "int" + value: + - [1, 100000] + - [2, 100000] + - [3, 100000] + - [100000, 1] + - [50000, 1] + out: 0 + - name: "duplicate_input_rows" + in: + rectangles: + elemType: "int" + value: + - [17, 19] + - [17, 19] + - [17, 19] + - [19, 17] + out: 3 + - name: "seven_same" + in: + rectangles: + elemType: "int" + value: + - [9, 10] + - [18, 20] + - [27, 30] + - [36, 40] + - [45, 50] + - [54, 60] + - [63, 70] + out: 21 + - name: "large_reduced_ratio" + in: + rectangles: + elemType: "int" + value: + - [99999, 66666] + - [3, 2] + - [99996, 66664] + - [6, 4] + out: 6 + - name: "two_pairs_two_singletons" + in: + rectangles: + elemType: "int" + value: + - [4, 7] + - [8, 14] + - [5, 8] + - [10, 16] + - [6, 11] + - [7, 12] + out: 2 + - name: "nine_same" + in: + rectangles: + elemType: "int" + value: + - [1, 9] + - [2, 18] + - [3, 27] + - [4, 36] + - [5, 45] + - [6, 54] + - [7, 63] + - [8, 72] + - [9, 81] + out: 36 + - name: "ten_all_distinct" + in: + rectangles: + elemType: "int" + value: + - [1, 2] + - [2, 3] + - [3, 5] + - [5, 8] + - [8, 13] + - [13, 21] + - [21, 34] + - [34, 55] + - [55, 89] + - [89, 144] + out: 0 + - name: "ten_same_max_pair_count" + in: + rectangles: + elemType: "int" + value: + - [10000, 100000] + - [1000, 10000] + - [100, 1000] + - [10, 100] + - [1, 10] + - [20000, 100000] + - [2000, 10000] + - [200, 1000] + - [20, 100] + - [2, 10] + out: 20 + - name: "mixed_many_groups" + in: + rectangles: + elemType: "int" + value: + - [2, 3] + - [4, 6] + - [3, 5] + - [6, 10] + - [5, 7] + - [10, 14] + - [7, 11] + - [14, 22] + - [11, 13] + - [22, 26] + out: 5 + - name: "stress_same_ratio" + in: + rectangles: + gen: "array" + len: 100000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + elemType: "int" + seed: 2101 + - name: "stress_random_rectangles" + in: + rectangles: + gen: "array" + len: 100000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + elemType: "int" + seed: 2102 + - name: "stress_small_values" + in: + rectangles: + gen: "array" + len: 100000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 20 + elemType: "int" + elemType: "int" + seed: 2103 + - name: "stress_max_boundary" + in: + rectangles: + gen: "array" + len: 99999 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 99980 + max: 100000 + elemType: "int" + elemType: "int" + seed: 2104 + - name: "stress_moderate" + in: + rectangles: + gen: "array" + len: 50000 + of: + gen: "array" + len: 2 + of: + gen: "int" + min: 1 + max: 100000 + elemType: "int" + elemType: "int" + seed: 2105 diff --git a/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.cpp b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.cpp new file mode 100644 index 00000000..9e8e793f --- /dev/null +++ b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + long long interchangeableRectangles(vector>& rectangles) { + auto gcd = [](int a, int b) { + while (b != 0) { + int temp = a % b; + a = b; + b = temp; + } + return a; + }; + + unordered_map, long long, hash_pair> ratioCount; + long long result = 0; + + for (const auto& rect : rectangles) { + int width = rect[0], height = rect[1]; + int g = gcd(width, height); + auto reduced = make_pair(width / g, height / g); + result += ratioCount[reduced]; + ratioCount[reduced]++; + } + + return result; + } + +private: + struct hash_pair { + size_t operator()(const pair& p) const { + return ((size_t)p.first << 32) ^ p.second; + } + }; +}; diff --git a/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.cs b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.cs new file mode 100644 index 00000000..82a5bd6b --- /dev/null +++ b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.cs @@ -0,0 +1,25 @@ +public class Solution { + public long InterchangeableRectangles(int[][] rectangles) { + int Gcd(int a, int b) { + while (b != 0) { + int temp = a % b; + a = b; + b = temp; + } + return a; + } + + var ratioCount = new Dictionary<(int, int), long>(); + long result = 0; + + foreach (var rect in rectangles) { + int width = rect[0], height = rect[1]; + int g = Gcd(width, height); + var reduced = (width / g, height / g); + result += ratioCount.GetValueOrDefault(reduced); + ratioCount[reduced] = ratioCount.GetValueOrDefault(reduced) + 1; + } + + return result; + } +} diff --git a/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.dart b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.dart new file mode 100644 index 00000000..ab64d091 --- /dev/null +++ b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.dart @@ -0,0 +1,37 @@ +class Solution { + int interchangeableRectangles(List> rectangles) { + int gcd(int a, int b) { + while (b != 0) { + int temp = a % b; + a = b; + b = temp; + } + return a; + } + + Map, int> ratioCount = {}; + int result = 0; + + for (var rect in rectangles) { + int width = rect[0], height = rect[1]; + int g = gcd(width, height); + var reduced = Pair(width ~/ g, height ~/ g); + result += ratioCount[reduced] ?? 0; + ratioCount[reduced] = (ratioCount[reduced] ?? 0) + 1; + } + + return result; + } +} + +class Pair { + final A a; + final B b; + Pair(this.a, this.b); + + @override + bool operator ==(Object other) => other is Pair && other.a == a && other.b == b; + + @override + int get hashCode => a.hashCode ^ b.hashCode; +} diff --git a/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.go b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.go new file mode 100644 index 00000000..5f7e22f6 --- /dev/null +++ b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.go @@ -0,0 +1,21 @@ +func interchangeableRectangles(rectangles [][]int) int64 { + gcd := func(a, b int) int { + for b != 0 { + a, b = b, a%b + } + return a + } + + ratioCount := make(map[[2]int]int64) + var result int64 = 0 + + for _, rect := range rectangles { + width, height := rect[0], rect[1] + g := gcd(width, height) + reduced := [2]int{width / g, height / g} + result += ratioCount[reduced] + ratioCount[reduced]++ + } + + return result +} diff --git a/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.java b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.java new file mode 100644 index 00000000..a348fcbf --- /dev/null +++ b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.java @@ -0,0 +1,25 @@ +class Solution { + public long interchangeableRectangles(int[][] rectangles) { + java.util.HashMap, Integer> ratioCount = new java.util.HashMap<>(); + long result = 0; + + for (int[] rect : rectangles) { + int width = rect[0], height = rect[1]; + int g = gcd(width, height); + Pair reduced = new Pair<>(width / g, height / g); + result += ratioCount.getOrDefault(reduced, 0); + ratioCount.put(reduced, ratioCount.getOrDefault(reduced, 0) + 1); + } + + return result; + } + + private int gcd(int a, int b) { + while (b != 0) { + int temp = a % b; + a = b; + b = temp; + } + return a; + } +} diff --git a/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.kt b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.kt new file mode 100644 index 00000000..38a3dde0 --- /dev/null +++ b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.kt @@ -0,0 +1,28 @@ +class Solution { + fun interchangeableRectangles(rectangles: Array): Long { + fun gcd(a: Int, b: Int): Int { + var x = a + var y = b + while (y != 0) { + val temp = x % y + x = y + y = temp + } + return x + } + + val ratioCount = mutableMapOf, Int>() + var result = 0L + + for (rect in rectangles) { + val width = rect[0] + val height = rect[1] + val g = gcd(width, height) + val reduced = Pair(width / g, height / g) + result += ratioCount[reduced] ?: 0 + ratioCount[reduced] = (ratioCount[reduced] ?: 0) + 1 + } + + return result + } +} diff --git a/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.py b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.py new file mode 100644 index 00000000..de3e2256 --- /dev/null +++ b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.py @@ -0,0 +1,25 @@ +from collections import defaultdict + + +def gcd(a, b): + while b: + a, b = b, a % b + return a + + +class Solution(object): + def interchangeableRectangles(self, rectangles): + """ + :type rectangles: List[List[int]] + :rtype: int + """ + ratio_count = defaultdict(int) + result = 0 + + for width, height in rectangles: + g = gcd(width, height) + reduced = (width // g, height // g) + result += ratio_count[reduced] + ratio_count[reduced] += 1 + + return result diff --git a/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.py2 b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.py2 new file mode 100644 index 00000000..c2a29a74 --- /dev/null +++ b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def interchangeableRectangles(self, rectangles): + """ + :type rectangles: List[List[int]] + :rtype: int + """ + from collections import defaultdict + + def gcd(a, b): + while b: + a, b = b, a % b + return a + + ratio_count = defaultdict(int) + result = 0 + + for width, height in rectangles: + g = gcd(width, height) + reduced = (width // g, height // g) + result += ratio_count[reduced] + ratio_count[reduced] += 1 + + return result diff --git a/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.rb b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.rb new file mode 100644 index 00000000..b04f5ca3 --- /dev/null +++ b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.rb @@ -0,0 +1,22 @@ +# @param {Integer[][]} rectangles +# @return {Integer} +def interchangeable_rectangles(rectangles) + def gcd(a, b) + while b != 0 + a, b = b, a % b + end + a + end + + ratio_count = Hash.new(0) + result = 0 + + rectangles.each do |width, height| + g = gcd(width, height) + reduced = [width / g, height / g] + result += ratio_count[reduced] + ratio_count[reduced] += 1 + end + + result +end diff --git a/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.rs b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.rs new file mode 100644 index 00000000..3126a58a --- /dev/null +++ b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.rs @@ -0,0 +1,28 @@ +impl Solution { + pub fn interchangeable_rectangles(rectangles: Vec>) -> i64 { + fn gcd(a: i32, b: i32) -> i32 { + let (mut a, mut b) = (a, b); + while b != 0 { + let temp = a % b; + a = b; + b = temp; + } + a + } + + use std::collections::HashMap; + let mut ratio_count: HashMap<(i32, i32), i64> = HashMap::new(); + let mut result: i64 = 0; + + for rect in &rectangles { + let width = rect[0]; + let height = rect[1]; + let g = gcd(width, height); + let reduced = (width / g, height / g); + result += *ratio_count.get(&reduced).unwrap_or(&0); + *ratio_count.entry(reduced).or_insert(0) += 1; + } + + result + } +} diff --git a/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.swift b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.swift new file mode 100644 index 00000000..f7a4053a --- /dev/null +++ b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.swift @@ -0,0 +1,32 @@ +class Solution { + func interchangeableRectangles(_ rectangles: [[Int]]) -> Int { + func gcd(_ a: Int, _ b: Int) -> Int { + var x = a + var y = b + while y != 0 { + let temp = x % y + x = y + y = temp + } + return x + } + + var ratioCount: [Pair: Int] = [:] + var result = 0 + + for rect in rectangles { + let width = rect[0], height = rect[1] + let g = gcd(width, height) + let reduced = Pair(a: width / g, b: height / g) + result += ratioCount[reduced] ?? 0 + ratioCount[reduced] = (ratioCount[reduced] ?? 0) + 1 + } + + return result + } +} + +struct Pair: Hashable { + let a: A + let b: B +} diff --git a/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.ts b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.ts new file mode 100644 index 00000000..0f2114a6 --- /dev/null +++ b/tests/2001-2500/2001. number-of-pairs-of-interchangeable-rectangles/sol.ts @@ -0,0 +1,20 @@ +function interchangeableRectangles(rectangles: number[][]): number { + function gcd(a: number, b: number): number { + while (b !== 0) { + [a, b] = [b, a % b]; + } + return a; + } + + const ratioCount = new Map(); + let result = 0; + + for (const [width, height] of rectangles) { + const g = gcd(width, height); + const reduced = `${width / g},${height / g}`; + result += ratioCount.get(reduced) || 0; + ratioCount.set(reduced, (ratioCount.get(reduced) || 0) + 1); + } + + return result; +} diff --git a/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/manifest.yaml b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/manifest.yaml new file mode 100644 index 00000000..6b1dea73 --- /dev/null +++ b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/manifest.yaml @@ -0,0 +1,226 @@ +entry: + id: 2002 + title: "maximum-product-of-the-length-of-two-palindromic-subsequences" + params: + s: + type: string + call: + cpp: "Solution().maxProduct({s})" + rust: "Solution::max_product({s})" + python3: "Solution().maxProduct({s})" + python2: "Solution().maxProduct({s})" + ruby: "max_product({s})" + java: "new Solution().maxProduct({s})" + csharp: "new Solution().MaxProduct({s})" + kotlin: "Solution().maxProduct({s})" + go: "maxProduct({s})" + dart: "Solution().maxProduct({s})" + swift: "Solution().maxProduct({s})" + typescript: "maxProduct({s})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().maxProduct(s, {result})" + checker: | + class Checker: + def maxProduct(self, s, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + n = len(s) + best = 0 + pal = [] + for mask in range(1, 1 << n): + text = ''.join(s[i] for i in range(n) if mask & (1 << i)) + if text == text[::-1]: + pal.append((mask, mask.bit_count())) + for i, (left, left_len) in enumerate(pal): + for right, right_len in pal[i + 1:]: + if not (left & right): + best = max(best, left_len * right_len) + return result == best + +seed: 2002 + +tests: + - name: "example_leetcodecom" + in: + s: "leetcodecom" + out: 9 + - name: "example_bb" + in: + s: "bb" + out: 1 + - name: "example_accbcaxxcxx" + in: + s: "accbcaxxcxx" + out: 25 + - name: "minimum_distinct" + in: + s: "abc" + out: 1 + - name: "all_equal_four" + in: + s: "aaaa" + out: 4 + - name: "whole_even_palindrome" + in: + s: "abba" + out: 4 + - name: "four_distinct" + in: + s: "abcd" + out: 1 + - name: "two_pairs" + in: + s: "aabb" + out: 4 + - name: "outer_pair" + in: + s: "abca" + out: 3 + - name: "odd_center_palindrome" + in: + s: "abcba" + out: 6 + - name: "nested_even_palindrome" + in: + s: "aabbaa" + out: 9 + - name: "symmetric_six" + in: + s: "abccba" + out: 9 + - name: "six_distinct" + in: + s: "abcdef" + out: 1 + - name: "long_single_palindrome" + in: + s: "racecar" + out: 12 + - name: "three_pairs" + in: + s: "aabbcc" + out: 4 + - name: "alternating_pairs" + in: + s: "abab" + out: 4 + - name: "offset_palindrome" + in: + s: "cabba" + out: 4 + - name: "six_equal" + in: + s: "zzzzzz" + out: 9 + - name: "eight_symmetric" + in: + s: "abcddcba" + out: 16 + - name: "overlapping_letters" + in: + s: "aabcaa" + out: 9 + - name: "two_long_halves" + in: + s: "baccab" + out: 9 + - name: "repeated_triple_pattern" + in: + s: "abcabc" + out: 9 + - name: "four_pairs" + in: + s: "aabbccdd" + out: 4 + - name: "mississippi" + in: + s: "mississippi" + out: 24 + - name: "palindrome_prefix" + in: + s: "xyzyxabc" + out: 6 + - name: "nested_aba" + in: + s: "aabccbaa" + out: 16 + - name: "large_odd_palindrome" + in: + s: "abacaba" + out: 12 + - name: "mixed_runs" + in: + s: "cccbbaaa" + out: 9 + - name: "twelve_distinct" + in: + s: "abcdefghijkl" + out: 1 + - name: "six_distinct_pairs" + in: + s: "aabbccddeeff" + out: 4 + - name: "short_odd_palindrome" + in: + s: "aba" + out: 2 + - name: "twelve_symmetric" + in: + s: "abcdeffedcba" + out: 36 + - name: "duplicate_case_repeat" + in: + s: "aabbcc" + out: 4 + - name: "three_repeated_blocks" + in: + s: "abcabcabc" + out: 15 + - name: "near_symmetric_run" + in: + s: "aabbba" + out: 9 + - name: "generated_binary_short" + seed: 2101 + in: + s: + gen: "str" + len: 12 + alphabet: "ab" + - name: "generated_ternary_short" + seed: 2102 + in: + s: + gen: "str" + len: 12 + alphabet: "abc" + - name: "generated_four_letters" + seed: 2103 + in: + s: + gen: "str" + len: 12 + alphabet: "acmz" + - name: "generated_repeated_alphabet" + seed: 2104 + in: + s: + gen: "str" + len: 12 + alphabet: "abcde" + - name: "generated_full_lowercase" + seed: 2105 + in: + s: + gen: "str" + len: 12 + alphabet: "abcdefghijklmnopqrstuvwxyz" diff --git a/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.cpp b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.cpp new file mode 100644 index 00000000..74aa94a8 --- /dev/null +++ b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int maxProduct(string s) { + int n = s.size(); + vector> palin_masks; + + for (int mask = 1; mask < (1 << n); mask++) { + string seq; + for (int i = 0; i < n; i++) { + if ((mask >> i) & 1) { + seq += s[i]; + } + } + string rev = seq; + reverse(rev.begin(), rev.end()); + if (seq == rev) { + int count = __builtin_popcount(mask); + palin_masks.push_back({mask, count}); + } + } + + int max_product = 0; + for (int i = 0; i < palin_masks.size(); i++) { + for (int j = i + 1; j < palin_masks.size(); j++) { + int m1 = palin_masks[i].first; + int m2 = palin_masks[j].first; + int l1 = palin_masks[i].second; + int l2 = palin_masks[j].second; + if ((m1 & m2) == 0) { + max_product = max(max_product, l1 * l2); + } + } + } + + return max_product; + } +}; diff --git a/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.cs b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.cs new file mode 100644 index 00000000..5f2ca377 --- /dev/null +++ b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.cs @@ -0,0 +1,41 @@ +public class Solution { + public int MaxProduct(string s) { + int n = s.Length; + var palinMasks = new List<(int mask, int len)>(); + + for (int mask = 1; mask < (1 << n); mask++) { + var sb = new StringBuilder(); + for (int i = 0; i < n; i++) { + if (((mask >> i) & 1) == 1) { + sb.Append(s[i]); + } + } + string seq = sb.ToString(); + char[] arr = seq.ToCharArray(); + Array.Reverse(arr); + string rev = new string(arr); + if (seq == rev) { + int count = 0; + for (int i = 0; i < n; i++) { + if (((mask >> i) & 1) == 1) count++; + } + palinMasks.Add((mask, count)); + } + } + + int maxProduct = 0; + for (int i = 0; i < palinMasks.Count; i++) { + for (int j = i + 1; j < palinMasks.Count; j++) { + int m1 = palinMasks[i].mask; + int m2 = palinMasks[j].mask; + int l1 = palinMasks[i].len; + int l2 = palinMasks[j].len; + if ((m1 & m2) == 0) { + maxProduct = Math.Max(maxProduct, l1 * l2); + } + } + } + + return maxProduct; + } +} diff --git a/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.dart b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.dart new file mode 100644 index 00000000..fef13acd --- /dev/null +++ b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.dart @@ -0,0 +1,36 @@ +class Solution { + int maxProduct(String s) { + int n = s.length; + List> palinMasks = []; + + for (int mask = 1; mask < (1 << n); mask++) { + StringBuffer sb = StringBuffer(); + for (int i = 0; i < n; i++) { + if (((mask >> i) & 1) == 1) { + sb.write(s[i]); + } + } + String seq = sb.toString(); + if (seq == seq.split('').reversed.join()) { + palinMasks.add([mask, mask.toRadixString(2).split('1').length - 1]); + } + } + + int maxProduct = 0; + for (int i = 0; i < palinMasks.length; i++) { + for (int j = i + 1; j < palinMasks.length; j++) { + int m1 = palinMasks[i][0]; + int m2 = palinMasks[j][0]; + int l1 = palinMasks[i][1]; + int l2 = palinMasks[j][1]; + if ((m1 & m2) == 0) { + maxProduct = max(maxProduct, l1 * l2); + } + } + } + + return maxProduct; + } + + int max(int a, int b) => a > b ? a : b; +} diff --git a/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.go b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.go new file mode 100644 index 00000000..0c49db2e --- /dev/null +++ b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.go @@ -0,0 +1,48 @@ +func maxProduct(s string) int { + n := len(s) + type palin struct { + mask int + len int + } + palins := []palin{} + + for mask := 1; mask < (1 << n); mask++ { + var sb []byte + for i := 0; i < n; i++ { + if ((mask >> i) & 1) == 1 { + sb = append(sb, s[i]) + } + } + // check palindrome + valid := true + for i, j := 0, len(sb)-1; i < j; i, j = i+1, j-1 { + if sb[i] != sb[j] { + valid = false + break + } + } + if valid { + count := 0 + for i := 0; i < n; i++ { + if ((mask >> i) & 1) == 1 { + count++ + } + } + palins = append(palins, palin{mask, count}) + } + } + + maxProd := 0 + for i := 0; i < len(palins); i++ { + for j := i + 1; j < len(palins); j++ { + if (palins[i].mask & palins[j].mask) == 0 { + prod := palins[i].len * palins[j].len + if prod > maxProd { + maxProd = prod + } + } + } + } + + return maxProd +} diff --git a/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.java b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.java new file mode 100644 index 00000000..f0d7e9eb --- /dev/null +++ b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.java @@ -0,0 +1,34 @@ +class Solution { + public int maxProduct(String s) { + int n = s.length(); + List palinMasks = new ArrayList<>(); + + for (int mask = 1; mask < (1 << n); mask++) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < n; i++) { + if (((mask >> i) & 1) == 1) { + sb.append(s.charAt(i)); + } + } + String seq = sb.toString(); + if (seq.equals(sb.reverse().toString())) { + palinMasks.add(new int[]{mask, Integer.bitCount(mask)}); + } + } + + int maxProduct = 0; + for (int i = 0; i < palinMasks.size(); i++) { + for (int j = i + 1; j < palinMasks.size(); j++) { + int m1 = palinMasks.get(i)[0]; + int m2 = palinMasks.get(j)[0]; + int l1 = palinMasks.get(i)[1]; + int l2 = palinMasks.get(j)[1]; + if ((m1 & m2) == 0) { + maxProduct = Math.max(maxProduct, l1 * l2); + } + } + } + + return maxProduct; + } +} diff --git a/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.kt b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.kt new file mode 100644 index 00000000..0f39d80b --- /dev/null +++ b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.kt @@ -0,0 +1,32 @@ +class Solution { + fun maxProduct(s: String): Int { + val n = s.length + val palinMasks = mutableListOf>() + + for (mask in 1 until (1 shl n)) { + val sb = StringBuilder() + for (i in 0 until n) { + if (((mask shr i) and 1) == 1) { + sb.append(s[i]) + } + } + val seq = sb.toString() + if (seq == sb.reverse().toString()) { + palinMasks.add(Pair(mask, Integer.bitCount(mask))) + } + } + + var maxProduct = 0 + for (i in palinMasks.indices) { + for (j in i + 1 until palinMasks.size) { + val (m1, l1) = palinMasks[i] + val (m2, l2) = palinMasks[j] + if ((m1 and m2) == 0) { + maxProduct = maxOf(maxProduct, l1 * l2) + } + } + } + + return maxProduct + } +} diff --git a/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.py b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.py new file mode 100644 index 00000000..eebb1471 --- /dev/null +++ b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.py @@ -0,0 +1,29 @@ +class Solution(object): + def maxProduct(self, s): + """ + :type s: str + :rtype: int + """ + n = len(s) + palin_masks = [] + + def is_palindrome(mask): + seq = [] + for i in range(n): + if (mask >> i) & 1: + seq.append(s[i]) + return seq == seq[::-1] + + for mask in range(1, 1 << n): + if is_palindrome(mask): + palin_masks.append((mask, bin(mask).count("1"))) + + max_product = 0 + for i in range(len(palin_masks)): + for j in range(i + 1, len(palin_masks)): + m1, l1 = palin_masks[i] + m2, l2 = palin_masks[j] + if m1 & m2 == 0: + max_product = max(max_product, l1 * l2) + + return max_product diff --git a/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.py2 b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.py2 new file mode 100644 index 00000000..320cd434 --- /dev/null +++ b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.py2 @@ -0,0 +1,29 @@ +class Solution(object): + def maxProduct(self, s): + """ + :type s: str + :rtype: int + """ + n = len(s) + palin_masks = [] + + def is_palindrome(mask): + seq = [] + for i in range(n): + if (mask >> i) & 1: + seq.append(s[i]) + return seq == seq[::-1] + + for mask in range(1, 1 << n): + if is_palindrome(mask): + palin_masks.append((mask, bin(mask).count("1"))) + + max_product = 0 + for i in range(len(palin_masks)): + for j in range(i + 1, len(palin_masks)): + m1, l1 = palin_masks[i] + m2, l2 = palin_masks[j] + if m1 & m2 == 0: + max_product = max(max_product, l1 * l2) + + return max_product diff --git a/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.rb b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.rb new file mode 100644 index 00000000..6e0c96e9 --- /dev/null +++ b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.rb @@ -0,0 +1,35 @@ +# @param {String} s +# @return {Integer} +def max_product(s) + n = s.length + palin_masks = [] + + is_palindrome = lambda do |mask| + seq = [] + (0...n).each do |i| + if (mask >> i) & 1 == 1 + seq << s[i] + end + end + seq == seq.reverse + end + + (1... (1 << n)).each do |mask| + if is_palindrome.call(mask) + palin_masks << [mask, mask.to_s(2).count("1")] + end + end + + max_product = 0 + (0...palin_masks.length).each do |i| + (i+1...palin_masks.length).each do |j| + m1, l1 = palin_masks[i] + m2, l2 = palin_masks[j] + if (m1 & m2) == 0 + max_product = [max_product, l1 * l2].max + end + end + end + + max_product +end diff --git a/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.rs b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.rs new file mode 100644 index 00000000..e5779d25 --- /dev/null +++ b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.rs @@ -0,0 +1,34 @@ +impl Solution { + pub fn max_product(s: String) -> i32 { + let n = s.len(); + let chars: Vec = s.chars().collect(); + let mut palin_masks: Vec<(i32, i32)> = Vec::new(); + + for mask in 1u32..(1u32 << n) { + let mut seq = String::new(); + for i in 0..n { + if ((mask >> i) & 1) == 1 { + seq.push(chars[i]); + } + } + let rev: String = seq.chars().rev().collect(); + if seq == rev { + let count = mask.count_ones() as i32; + palin_masks.push((mask as i32, count)); + } + } + + let mut max_product = 0; + for i in 0..palin_masks.len() { + for j in (i+1)..palin_masks.len() { + let (m1, l1) = palin_masks[i]; + let (m2, l2) = palin_masks[j]; + if (m1 & m2) == 0 { + max_product = max_product.max(l1 * l2); + } + } + } + + max_product + } +} diff --git a/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.swift b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.swift new file mode 100644 index 00000000..1f023fc3 --- /dev/null +++ b/tests/2001-2500/2002. maximum-product-of-the-length-of-two-palindromic-subsequences/sol.swift @@ -0,0 +1,35 @@ +class Solution { + func maxProduct(_ s: String) -> Int { + let n = s.count + let chars = Array(s) + var palinMasks: [(mask: Int, len: Int)] = [] + + for mask in 1..<(1 << n) { + var seq = "" + for i in 0..> i) & 1) == 1 { + seq.append(chars[i]) + } + } + if seq == String(seq.reversed()) { + let count = mask.nonzeroBitCount + palinMasks.append((mask, count)) + } + } + + var maxProduct = 0 + for i in 0..> i) & 1) { + seq += s[i]; + } + } + if (seq === seq.split("").reverse().join("")) { + let count = 0; + for (let i = 0; i < n; i++) { + if ((mask >> i) & 1) count++; + } + palinMasks.push([mask, count]); + } + } + + let maxProduct = 0; + for (let i = 0; i < palinMasks.length; i++) { + for (let j = i + 1; j < palinMasks.length; j++) { + const [m1, l1] = palinMasks[i]; + const [m2, l2] = palinMasks[j]; + if ((m1 & m2) === 0) { + maxProduct = Math.max(maxProduct, l1 * l2); + } + } + } + + return maxProduct; +} diff --git a/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/manifest.yaml b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/manifest.yaml new file mode 100644 index 00000000..1677ec51 --- /dev/null +++ b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/manifest.yaml @@ -0,0 +1,290 @@ +entry: + id: 2003 + title: "smallest-missing-genetic-value-in-each-subtree" + params: + parents: + type: array + items: + type: int + nums: + type: array + items: + type: int + call: + cpp: "Solution().smallestMissingValueSubtree({parents}, {nums})" + rust: "Solution::smallest_missing_value_subtree({parents}, {nums})" + python3: "Solution().smallestMissingValueSubtree({parents}, {nums})" + python2: "Solution().smallestMissingValueSubtree({parents}, {nums})" + ruby: "smallest_missing_value_subtree({parents}, {nums})" + java: "new Solution().smallestMissingValueSubtree({parents}, {nums})" + csharp: "new Solution().SmallestMissingValueSubtree({parents}, {nums})" + kotlin: "Solution().smallestMissingValueSubtree({parents}, {nums})" + go: "smallestMissingValueSubtree({parents}, {nums})" + dart: "Solution().smallestMissingValueSubtree({parents}, {nums})" + swift: "Solution().smallestMissingValueSubtree({parents}, {nums})" + typescript: "smallestMissingValueSubtree({parents}, {nums})" +judge: + type: exact +limits: + time_ms: 2000 + memory_mb: 512 +oracle: + python3: + call: "Checker().check(parents, nums, {result})" + checker: | + class Checker: + def check(self, parents, nums, result): + n = len(parents) + if not isinstance(result, list) or len(result) != n: + return False + children = [[] for _ in range(n)] + for i in range(1, n): + if not isinstance(parents[i], int) or parents[i] < 0 or parents[i] >= n: + return False + children[parents[i]].append(i) + expected = [1] * n + def visit(v): + values = {nums[v]} + for child in children[v]: + values.update(visit(child)) + missing = 1 + while missing in values: + missing += 1 + expected[v] = missing + return values + visit(0) + return result == expected +seed: 2003 +tests: + - name: example-one + in: + parents: [-1, 0, 0, 2] + nums: [1, 2, 3, 4] + out: [5, 1, 1, 1] + - name: example-two + in: + parents: [-1, 0, 1, 0, 3, 3] + nums: [5, 4, 6, 2, 1, 3] + out: [7, 1, 1, 4, 2, 1] + - name: example-three + in: + parents: [-1, 2, 3, 0, 2, 4, 1] + nums: [2, 3, 4, 5, 6, 7, 8] + out: [1, 1, 1, 1, 1, 1, 1] + - name: root-and-child + in: + parents: [-1, 0, 0] + nums: [1, 2, 3] + out: [4, 1, 1] + - name: root-missing-one + in: + parents: [-1, 0, 1] + nums: [2, 1, 3] + out: [4, 2, 1] + - name: chain-one-to-five + in: + parents: [-1, 0, 1, 2, 3, 4] + nums: [1, 2, 3, 4, 5, 6] + out: [7, 1, 1, 1, 1, 1] + - name: chain-reversed-values + in: + parents: [-1, 0, 1, 2, 3, 4] + nums: [6, 5, 4, 3, 2, 1] + out: [7, 6, 5, 4, 3, 2] + - name: star-with-one + in: + parents: [-1, 0, 0, 0, 0, 0, 0] + nums: [4, 1, 2, 3, 6, 7, 5] + out: [8, 2, 1, 1, 1, 1, 1] + - name: one-deep-branch + in: + parents: [-1, 0, 0, 1, 3, 4, 2] + nums: [9, 1, 8, 2, 3, 4, 5] + out: [6, 5, 1, 1, 1, 1, 1] + - name: one-at-leaf + in: + parents: [-1, 0, 0, 1, 1, 3, 2, 6] + nums: [8, 4, 6, 2, 7, 1, 5, 3] + out: [9, 3, 1, 3, 1, 2, 1, 1] + - name: one-at-root + in: + parents: [-1, 0, 0, 1, 1, 2, 2, 5] + nums: [1, 9, 8, 7, 6, 5, 4, 3] + out: [2, 1, 1, 1, 1, 1, 1, 1] + - name: missing-middle-root + in: + parents: [-1, 0, 0, 1, 1, 2, 2, 6, 6] + nums: [1, 2, 4, 3, 8, 9, 7, 6, 5] + out: [10, 1, 1, 1, 1, 1, 1, 1, 1] + - name: sparse-values + in: + parents: [-1, 0, 1, 0, 3, 3, 5, 5] + nums: [100000, 99999, 50000, 1, 2, 4, 3, 100] + out: [5, 1, 1, 5, 1, 1, 1, 1] + - name: high-values-no-one + in: + parents: [-1, 0, 0, 1, 1, 2, 2] + nums: [100000, 99998, 99997, 99996, 99995, 99994, 99993] + out: [1, 1, 1, 1, 1, 1, 1] + - name: complete-seven + in: + parents: [-1, 0, 0, 1, 1, 2, 2] + nums: [1, 2, 3, 4, 5, 6, 7] + out: [8, 1, 1, 1, 1, 1, 1] + - name: complete-seven-one-leaf + in: + parents: [-1, 0, 0, 1, 1, 2, 2] + nums: [8, 7, 6, 5, 4, 3, 1] + out: [2, 1, 2, 1, 1, 1, 2] + - name: branching-nine + in: + parents: [-1, 0, 0, 0, 1, 1, 2, 2, 3] + nums: [7, 1, 9, 2, 3, 4, 5, 6, 8] + out: [10, 2, 1, 1, 1, 1, 1, 1, 1] + - name: one-under-heavy-branch + in: + parents: [-1, 0, 0, 1, 1, 3, 3, 6, 6, 2] + nums: [9, 8, 7, 6, 5, 4, 3, 2, 1, 10] + out: [11, 7, 1, 5, 1, 1, 4, 1, 2, 1] + - name: one-and-two-in-subtree + in: + parents: [-1, 0, 0, 1, 1, 4, 2, 6, 6] + nums: [9, 8, 7, 6, 5, 1, 4, 2, 3] + out: [10, 2, 1, 1, 2, 2, 1, 1, 1] + - name: chain-ten + in: + parents: [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8] + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + out: [11, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: chain-ten-one-last + in: + parents: [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8] + nums: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + out: [11, 10, 9, 8, 7, 6, 5, 4, 3, 2] + - name: ten-star + in: + parents: [-1, 0, 0, 0, 0, 0, 0, 0, 0, 0] + nums: [1, 2, 4, 6, 8, 10, 3, 5, 7, 9] + out: [11, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: alternating-branches + in: + parents: [-1, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8] + nums: [11, 1, 2, 3, 5, 4, 7, 6, 9, 8, 10] + out: [12, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: value-one-middle + in: + parents: [-1, 0, 0, 1, 1, 2, 2, 4, 4, 5, 5] + nums: [11, 10, 9, 8, 1, 7, 6, 5, 4, 3, 2] + out: [12, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1] + - name: root-values-one-to-eleven + in: + parents: [-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4] + nums: [11, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + out: [12, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: two-large-gaps + in: + parents: [-1, 0, 0, 0, 1, 1, 2, 2, 3, 3] + nums: [1, 100000, 99999, 99998, 2, 4, 3, 5, 6, 7] + out: [8, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: deep-one-branch + in: + parents: [-1, 0, 0, 1, 3, 4, 5, 6, 7, 8, 2, 10] + nums: [20, 19, 18, 17, 16, 15, 14, 13, 12, 1, 11, 2] + out: [3, 2, 1, 2, 2, 2, 2, 2, 2, 2, 1, 1] + - name: twelve-complete-values + in: + parents: [-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5] + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + out: [13, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: twelve-no-one + in: + parents: [-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5] + nums: + [ + 100000, + 99999, + 99998, + 99997, + 99996, + 99995, + 99994, + 99993, + 99992, + 99991, + 99990, + 99989, + ] + out: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: thirteen-one-in-small-subtree + in: + parents: [-1, 0, 0, 1, 1, 2, 2, 3, 4, 5, 6, 10, 10] + nums: [50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 1, 2] + out: [3, 1, 3, 1, 1, 1, 3, 1, 1, 1, 3, 2, 1] + - name: fourteen-mixed + in: + parents: [-1, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 5, 6, 7] + nums: [1, 2, 4, 6, 3, 5, 8, 7, 9, 10, 11, 12, 13, 14] + out: [15, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: one-at-deep-leaf-fourteen + in: + parents: [-1, 0, 0, 1, 1, 3, 3, 5, 5, 7, 7, 2, 2, 12] + nums: [30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 1] + out: [2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2] + - name: fifteen-low-values + in: + parents: [-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6] + nums: [1, 2, 3, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 4, 7] + out: [16, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: fifteen-one-in-right + in: + parents: [-1, 0, 0, 1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10] + nums: [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + out: [16, 1, 3, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2] + - name: sixteen-root-gap + in: + parents: [-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7] + nums: [1, 3, 5, 7, 9, 11, 13, 15, 2, 4, 6, 8, 10, 12, 14, 16] + out: [17, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: sixteen-high-with-one + in: + parents: [-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7] + nums: + [ + 100000, + 99999, + 99998, + 99997, + 99996, + 99995, + 99994, + 99993, + 99992, + 99991, + 99990, + 99989, + 99988, + 99987, + 99986, + 1, + ] + out: [2, 2, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2] + - name: seventeen-chain-prefix + in: + parents: [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17] + out: [18, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: seventeen-chain-one-last + in: + parents: [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + nums: [17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + out: [18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2] + - name: eighteen-star-values + in: + parents: [-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + nums: [1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 3, 5, 7, 9, 11, 13, 15, 17] + out: [19, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + - name: nineteen-mixed-tree + in: + parents: [-1, 0, 0, 1, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 9, 10, 11, 12] + nums: [19, 1, 18, 2, 3, 17, 16, 4, 5, 6, 15, 14, 13, 7, 8, 9, 10, 11, 12] + out: [20, 10, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] diff --git a/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.cpp b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.cpp new file mode 100644 index 00000000..4258b59a --- /dev/null +++ b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + vector smallestMissingValueSubtree(vector& parents, vector& nums) { + int n = parents.size(); + vector> graph(n); + int nodeOne = -1; + int root = -1; + + for (int child = 0; child < n; child++) { + if (parents[child] == -1) { + root = child; + } else { + graph[parents[child]].push_back(child); + } + if (nums[child] == 1) nodeOne = child; + } + + vector results(n, 1); + if (nodeOne == -1) return results; + + vector seen(100002, false); + int current = nodeOne; + int missing = 1; + + while (current != -1) { + markSeen(current, graph, seen, nums); + while (missing < 100002 && seen[missing]) missing++; + results[current] = missing; + current = parents[current]; + } + + return results; + } + +private: + void markSeen(int node, vector>& graph, vector& seen, vector& nums) { + if (!seen[nums[node]]) { + seen[nums[node]] = true; + for (int child : graph[node]) { + markSeen(child, graph, seen, nums); + } + } + } +}; diff --git a/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.cs b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.cs new file mode 100644 index 00000000..3b5c49f0 --- /dev/null +++ b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.cs @@ -0,0 +1,49 @@ +public class Solution { + private bool[] seen; + private int[] nums; + private List[] graph; + + public int[] SmallestMissingValueSubtree(int[] parents, int[] nums) { + int n = parents.Length; + graph = new List[n]; + for (int i = 0; i < n; i++) graph[i] = new List(); + this.nums = nums; + + int nodeOne = -1; + int root = -1; + for (int child = 0; child < n; child++) { + if (parents[child] == -1) { + root = child; + } else { + graph[parents[child]].Add(child); + } + if (nums[child] == 1) nodeOne = child; + } + + int[] results = new int[n]; + Array.Fill(results, 1); + if (nodeOne == -1) return results; + + seen = new bool[100002]; + int current = nodeOne; + int missing = 1; + + while (current != -1) { + MarkSeen(current); + while (missing < 100002 && seen[missing]) missing++; + results[current] = missing; + current = parents[current]; + } + + return results; + } + + private void MarkSeen(int node) { + if (!seen[nums[node]]) { + seen[nums[node]] = true; + foreach (int child in graph[node]) { + MarkSeen(child); + } + } + } +} diff --git a/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.dart b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.dart new file mode 100644 index 00000000..e48bf91c --- /dev/null +++ b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.dart @@ -0,0 +1,42 @@ +class Solution { + List smallestMissingValueSubtree(List parents, List nums) { + int n = parents.length; + List> graph = List.generate(n, (i) => []); + int nodeOne = -1; + int root = -1; + + for (int child = 0; child < n; child++) { + if (parents[child] == -1) { + root = child; + } else { + graph[parents[child]].add(child); + } + if (nums[child] == 1) nodeOne = child; + } + + List results = List.filled(n, 1); + if (nodeOne == -1) return results; + + List seen = List.filled(100002, false); + int current = nodeOne; + int missing = 1; + + while (current != -1) { + markSeen(current, graph, seen, nums); + while (missing < 100002 && seen[missing]) missing++; + results[current] = missing; + current = parents[current]; + } + + return results; + } + + void markSeen(int node, List> graph, List seen, List nums) { + if (!seen[nums[node]]) { + seen[nums[node]] = true; + for (int child in graph[node]) { + markSeen(child, graph, seen, nums); + } + } + } +} diff --git a/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.go b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.go new file mode 100644 index 00000000..9dea287c --- /dev/null +++ b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.go @@ -0,0 +1,46 @@ +func smallestMissingValueSubtree(parents []int, nums []int) []int { + n := len(parents) + graph := make([][]int, n) + nodeOne := -1 + + for child := 0; child < n; child++ { + if parents[child] != -1 { + graph[parents[child]] = append(graph[parents[child]], child) + } + if nums[child] == 1 { + nodeOne = child + } + } + + results := make([]int, n) + for i := range results { + results[i] = 1 + } + if nodeOne == -1 { + return results + } + + seen := make([]bool, 100002) + current := nodeOne + missing := 1 + + for current != -1 { + markSeen(current, graph, seen, nums) + for missing < 100002 && seen[missing] { + missing++ + } + results[current] = missing + current = parents[current] + } + + return results +} + +func markSeen(node int, graph [][]int, seen []bool, nums []int) { + if !seen[nums[node]] { + seen[nums[node]] = true + for _, child := range graph[node] { + markSeen(child, graph, seen, nums) + } + } +} diff --git a/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.java b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.java new file mode 100644 index 00000000..854ea920 --- /dev/null +++ b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.java @@ -0,0 +1,47 @@ +class Solution { + private boolean[] seen; + private int[] nums; + private HashMap> graph; + + public int[] smallestMissingValueSubtree(int[] parents, int[] nums) { + int n = parents.length; + graph = new HashMap<>(); + for (int i = 0; i < n; i++) graph.put(i, new ArrayList<>()); + this.nums = nums; + + int nodeOne = -1; + int root = -1; + for (int child = 0; child < n; child++) { + if (parents[child] == -1) { + root = child; + } else { + graph.get(parents[child]).add(child); + } + if (nums[child] == 1) nodeOne = child; + } + + int[] results = new int[n]; + Arrays.fill(results, 1); + if (nodeOne == -1) return results; + + seen = new boolean[100002]; + int current = nodeOne; + int missing = 1; + + while (current != -1) { + markSeen(current); + while (missing < 100002 && seen[missing]) missing++; + results[current] = missing; + current = parents[current]; + } + + return results; + } + + private void markSeen(int node) { + if (!seen[nums[node]]) { + seen[nums[node]] = true; + for (int child : graph.get(node)) markSeen(child); + } + } +} diff --git a/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.kt b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.kt new file mode 100644 index 00000000..d90f8539 --- /dev/null +++ b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.kt @@ -0,0 +1,45 @@ +class Solution { + private lateinit var seen: BooleanArray + private lateinit var nums: IntArray + private lateinit var graph: Array> + + fun smallestMissingValueSubtree(parents: IntArray, nums: IntArray): IntArray { + val n = parents.size + this.nums = nums + graph = Array(n) { mutableListOf() } + + var nodeOne = -1 + var root = -1 + for (child in 0 until n) { + if (parents[child] == -1) { + root = child + } else { + graph[parents[child]].add(child) + } + if (nums[child] == 1) nodeOne = child + } + + val results = IntArray(n) { 1 } + if (nodeOne == -1) return results + + seen = BooleanArray(100002) + var current = nodeOne + var missing = 1 + + while (current != -1) { + markSeen(current) + while (missing < 100002 && seen[missing]) missing++ + results[current] = missing + current = parents[current] + } + + return results + } + + private fun markSeen(node: Int) { + if (!seen[nums[node]]) { + seen[nums[node]] = true + for (child in graph[node]) markSeen(child) + } + } +} diff --git a/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.py b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.py new file mode 100644 index 00000000..b7d7c09e --- /dev/null +++ b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.py @@ -0,0 +1,45 @@ +class Solution: + def smallestMissingValueSubtree( + self, parents: List[int], nums: List[int] + ) -> List[int]: + n = len(parents) + graph = defaultdict(list) + node_one = None + + # Build the tree structure and find the root and node with genetic value 1 + for child, parent in enumerate(parents): + if parent == -1: + root = child # Root node identified + else: + graph[parent].append(child) + if nums[child] == 1: + node_one = child # Node with genetic value 1 found + + # Initialize results and seen values + results = [1] * n + if node_one is None: + return results # Return early if there is no node with genetic value 1 + + seen = [False] * 100002 # Boolean array to track seen genetic values + current_node = node_one + previous_missing = 1 + + # Traverse upwards from the node with genetic value 1 + while current_node != -1: + self._markSeen(current_node, graph, seen, nums) + # Find the first missing genetic value + while previous_missing < 100002 and seen[previous_missing]: + previous_missing += 1 + results[current_node] = previous_missing # Assign the missing value + current_node = parents[current_node] # Move to the parent node + + return results + + def _markSeen( + self, node: int, graph: defaultdict, seen: List[bool], nums: List[int] + ): + """DFS to mark genetic values seen in the subtree rooted at 'node'.""" + if not seen[nums[node]]: + seen[nums[node]] = True # Mark the current node's genetic value as seen + for child in graph[node]: + self._markSeen(child, graph, seen, nums) # Recursively mark children diff --git a/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.py2 b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.py2 new file mode 100644 index 00000000..df29f686 --- /dev/null +++ b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.py2 @@ -0,0 +1,43 @@ +class Solution(object): + def smallestMissingValueSubtree(self, parents, nums): + """ + :type parents: List[int] + :type nums: List[int] + :rtype: List[int] + """ + n = len(parents) + graph = {} + for child in range(n): + graph.setdefault(child, []) + node_one = None + root = None + for child, parent in enumerate(parents): + if parent == -1: + root = child + else: + graph[parent].append(child) + if nums[child] == 1: + node_one = child + + results = [1] * n + if node_one is None: + return results + + seen = [False] * 100002 + current_node = node_one + previous_missing = 1 + + while current_node != -1: + self._markSeen(current_node, graph, seen, nums) + while previous_missing < 100002 and seen[previous_missing]: + previous_missing += 1 + results[current_node] = previous_missing + current_node = parents[current_node] + + return results + + def _markSeen(self, node, graph, seen, nums): + if not seen[nums[node]]: + seen[nums[node]] = True + for child in graph[node]: + self._markSeen(child, graph, seen, nums) diff --git a/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.rb b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.rb new file mode 100644 index 00000000..e640c459 --- /dev/null +++ b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.rb @@ -0,0 +1,41 @@ +# @param {Integer[]} parents +# @param {Integer[]} nums +# @return {Integer[]} +def smallest_missing_value_subtree(parents, nums) + n = parents.length + graph = Hash.new { |h, k| h[k] = [] } + node_one = nil + root = nil + + parents.each_with_index do |parent, child| + if parent == -1 + root = child + else + graph[parent] << child + end + node_one = child if nums[child] == 1 + end + + results = Array.new(n, 1) + return results unless node_one + + seen = Array.new(100002, false) + current_node = node_one + previous_missing = 1 + + while current_node != -1 + mark_seen(current_node, graph, seen, nums) + previous_missing += 1 while previous_missing < 100002 && seen[previous_missing] + results[current_node] = previous_missing + current_node = parents[current_node] + end + + results +end + +def mark_seen(node, graph, seen, nums) + unless seen[nums[node]] + seen[nums[node]] = true + graph[node].each { |child| mark_seen(child, graph, seen, nums) } + end +end diff --git a/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.rs b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.rs new file mode 100644 index 00000000..8eac6ed5 --- /dev/null +++ b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.rs @@ -0,0 +1,48 @@ +impl Solution { + pub fn smallest_missing_value_subtree(parents: Vec, nums: Vec) -> Vec { + let n = parents.len(); + let mut graph = vec![Vec::new(); n]; + let mut node_one = -1; + let mut root = -1; + + for child in 0..n { + if parents[child] == -1 { + root = child as i32; + } else { + graph[parents[child] as usize].push(child); + } + if nums[child] == 1 { + node_one = child as i32; + } + } + + let mut results = vec![1; n]; + if node_one == -1 { + return results; + } + + let mut seen = vec![false; 100002]; + let mut current = node_one; + let mut missing = 1; + + while current != -1 { + Self::mark_seen(current as usize, &graph, &mut seen, &nums); + while missing < 100002 && seen[missing] { + missing += 1; + } + results[current as usize] = missing as i32; + current = parents[current as usize]; + } + + results + } + + fn mark_seen(node: usize, graph: &Vec>, seen: &mut Vec, nums: &Vec) { + if !seen[nums[node] as usize] { + seen[nums[node] as usize] = true; + for &child in &graph[node] { + Self::mark_seen(child, graph, seen, nums); + } + } + } +} diff --git a/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.swift b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.swift new file mode 100644 index 00000000..d8579612 --- /dev/null +++ b/tests/2001-2500/2003. smallest-missing-genetic-value-in-each-subtree/sol.swift @@ -0,0 +1,48 @@ +class Solution { + func smallestMissingValueSubtree(_ parents: [Int], _ nums: [Int]) -> [Int] { + let n = parents.count + var graph = [[Int]](repeating: [], count: n) + var nodeOne = -1 + var root = -1 + + for child in 0.. []); + let nodeOne = -1; + let root = -1; + + for (let child = 0; child < n; child++) { + if (parents[child] === -1) { + root = child; + } else { + graph[parents[child]].push(child); + } + if (nums[child] === 1) nodeOne = child; + } + + const results = new Array(n).fill(1); + if (nodeOne === -1) return results; + + const seen = new Array(100002).fill(false); + let current = nodeOne; + let missing = 1; + + while (current !== -1) { + markSeen(current, graph, seen, nums); + while (missing < 100002 && seen[missing]) missing++; + results[current] = missing; + current = parents[current]; + } + + return results; +} + +function markSeen( + node: number, + graph: number[][], + seen: boolean[], + nums: number[], +) { + if (!seen[nums[node]]) { + seen[nums[node]] = true; + for (const child of graph[node]) { + markSeen(child, graph, seen, nums); + } + } +} diff --git a/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/manifest.yaml b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/manifest.yaml new file mode 100644 index 00000000..9be0218d --- /dev/null +++ b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/manifest.yaml @@ -0,0 +1,403 @@ +entry: + id: 2006 + title: count-number-of-pairs-with-absolute-difference-k + params: + nums: + type: array + items: + type: int + k: + type: int + call: + cpp: "Solution().countKDifference({nums}, {k})" + rust: "Solution::count_k_difference({nums}, {k})" + python3: "Solution().countKDifference({nums}, {k})" + python2: "Solution().countKDifference({nums}, {k})" + ruby: "count_k_difference({nums}, {k})" + java: "new Solution().countKDifference({nums}, {k})" + csharp: "new Solution().CountKDifference({nums}, {k})" + kotlin: "Solution().countKDifference({nums}, {k})" + go: "countKDifference({nums}, {k})" + dart: "Solution().countKDifference({nums}, {k})" + swift: "Solution().countKDifference({nums}, {k})" + typescript: "countKDifference({nums}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().countKDifference(nums, k, {result})" + checker: | + from collections import Counter + + class Checker: + def countKDifference(self, nums, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + counts = Counter(nums) + expected = sum(counts[x] * counts.get(x + k, 0) for x in counts) + return result == expected + +seed: 2006 + +tests: + - name: example-one + in: + nums: [1, 2, 2, 1] + k: 1 + out: 4 + judge: + type: "exact" + - name: example-two-no-pair + in: + nums: [1, 3] + k: 3 + out: 0 + judge: + type: "exact" + - name: example-three + in: + nums: [3, 2, 1, 5, 4] + k: 2 + out: 3 + judge: + type: "exact" + - name: singleton + in: + nums: [7] + k: 1 + out: 0 + judge: + type: "exact" + - name: two-equal-k-one + in: + nums: [5, 5] + k: 1 + out: 0 + judge: + type: "exact" + - name: two-consecutive + in: + nums: [1, 2] + k: 1 + out: 1 + judge: + type: "exact" + - name: reversed-consecutive + in: + nums: [2, 1] + k: 1 + out: 1 + judge: + type: "exact" + - name: maximum-k + in: + nums: [1, 100] + k: 99 + out: 1 + judge: + type: "exact" + - name: maximum-k-no-match + in: + nums: [1, 99] + k: 99 + out: 0 + judge: + type: "exact" + - name: all-equal + in: + nums: [8, 8, 8, 8, 8] + k: 1 + out: 0 + judge: + type: "exact" + - name: repeated-adjacent-values + in: + nums: [1, 1, 2, 2, 3, 3] + k: 1 + out: 8 + judge: + type: "exact" + - name: repeated-gap-two + in: + nums: [1, 1, 1, 3, 3, 3] + k: 2 + out: 9 + judge: + type: "exact" + - name: three-value-chain + in: + nums: [1, 2, 3] + k: 1 + out: 2 + judge: + type: "exact" + - name: no-values-in-range + in: + nums: [1, 100, 50] + k: 50 + out: 1 + judge: + type: "exact" + - name: values-at-lower-bound + in: + nums: [1, 1, 2, 2, 100] + k: 1 + out: 4 + judge: + type: "exact" + - name: values-at-upper-bound + in: + nums: [98, 98, 99, 100, 100] + k: 1 + out: 4 + judge: + type: "exact" + - name: alternating-order + in: + nums: [10, 1, 10, 1, 10, 1] + k: 9 + out: 9 + judge: + type: "exact" + - name: one-sided-frequency + in: + nums: [4, 4, 4, 5, 6] + k: 1 + out: 4 + judge: + type: "exact" + - name: disjoint-value-groups + in: + nums: [2, 2, 2, 5, 5, 5, 8, 8] + k: 3 + out: 15 + judge: + type: "exact" + - name: k-skips-middle + in: + nums: [1, 2, 4, 5, 7] + k: 3 + out: 3 + judge: + type: "exact" + - name: duplicate-cross-groups + in: + nums: [12, 15, 12, 15, 12, 15, 12] + k: 3 + out: 12 + judge: + type: "exact" + - name: k-larger-than-span + in: + nums: [20, 21, 22, 23] + k: 10 + out: 0 + judge: + type: "exact" + - name: k-one-long-run + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8] + k: 1 + out: 7 + judge: + type: "exact" + - name: k-two-long-run + in: + nums: [1, 2, 3, 4, 5, 6, 7, 8] + k: 2 + out: 6 + judge: + type: "exact" + - name: duplicate-every-value + in: + nums: [1, 1, 2, 2, 3, 3, 4, 4] + k: 1 + out: 12 + judge: + type: "exact" + - name: sparse-values + in: + nums: [7, 20, 33, 46, 59, 72] + k: 13 + out: 5 + judge: + type: "exact" + - name: sparse-values-no-match + in: + nums: [7, 20, 33, 46, 59, 72] + k: 12 + out: 0 + judge: + type: "exact" + - name: mixed-frequency + in: + nums: [1, 1, 1, 2, 3, 3, 4, 5, 5, 5] + k: 2 + out: 13 + judge: + type: "exact" + - name: boundary-chain + in: + nums: [1, 2, 99, 100, 1, 100] + k: 1 + out: 4 + judge: + type: "exact" + - name: ten-copies-two-values + in: + nums: [10, 10, 10, 10, 10, 20, 20, 20, 20, 20] + k: 10 + out: 25 + judge: + type: "exact" + - name: twenty-identical + in: + nums: + [ + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + ] + k: 1 + out: 0 + judge: + type: "exact" + - name: full-range-pairs + in: + nums: [1, 100, 1, 100, 1, 100, 1, 100] + k: 99 + out: 16 + judge: + type: "exact" + - name: repeated-three-step + in: + nums: [2, 5, 8, 11, 14, 17, 20, 23, 26, 29] + k: 6 + out: 8 + judge: + type: "exact" + - name: large-uniform + in: + nums: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] + k: 1 + out: 100 + judge: + type: "exact" + - name: generator-small-values + in: + nums: + gen: "array" + len: 200 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 99 + judge: + type: "exact" + seed: 200601 + - name: generator-small-k + in: + nums: + gen: "array" + len: 200 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 5 + judge: + type: "exact" + seed: 200602 + - name: generator-large-k + in: + nums: + gen: "array" + len: 200 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + k: + gen: "int" + min: 95 + max: 99 + judge: + type: "exact" + seed: 200603 + - name: generator-max-duplicates + in: + nums: + gen: "array" + len: 200 + of: + gen: "int" + min: 1 + max: 3 + distinct: false + sorted: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 2 + judge: + type: "exact" + seed: 200604 + - name: generator-full-domain + in: + nums: + gen: "array" + len: 200 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false + elemType: "int" + k: + gen: "int" + min: 1 + max: 99 + judge: + type: "exact" + seed: 200605 diff --git a/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.cpp b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.cpp new file mode 100644 index 00000000..0272892d --- /dev/null +++ b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int countKDifference(vector& nums, int k) { + unordered_map c; + for (int num : nums) { + c[num]++; + } + int ans = 0; + for (const auto& entry : c) { + auto it = c.find(entry.first + k); + if (it != c.end()) ans += entry.second * it->second; + } + return ans; + } +}; diff --git a/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.cs b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.cs new file mode 100644 index 00000000..53a3f4dc --- /dev/null +++ b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.cs @@ -0,0 +1,13 @@ +public class Solution { + public int CountKDifference(int[] nums, int k) { + var c = new Dictionary(); + foreach (int num in nums) { + c[num] = c.GetValueOrDefault(num) + 1; + } + int ans = 0; + foreach (var kv in c) { + ans += kv.Value * c.GetValueOrDefault(kv.Key + k); + } + return ans; + } +} diff --git a/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.dart b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.dart new file mode 100644 index 00000000..af1f923c --- /dev/null +++ b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.dart @@ -0,0 +1,13 @@ +class Solution { + int countKDifference(List nums, int k) { + final c = {}; + for (var num in nums) { + c[num] = (c[num] ?? 0) + 1; + } + var ans = 0; + c.forEach((x, cnt) { + ans += cnt * (c[x + k] ?? 0); + }); + return ans; + } +} diff --git a/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.go b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.go new file mode 100644 index 00000000..23ec468b --- /dev/null +++ b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.go @@ -0,0 +1,11 @@ +func countKDifference(nums []int, k int) int { + c := make(map[int]int) + for _, num := range nums { + c[num]++ + } + ans := 0 + for x, cnt := range c { + ans += cnt * c[x+k] + } + return ans +} diff --git a/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.java b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.java new file mode 100644 index 00000000..3b6fc6e1 --- /dev/null +++ b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.java @@ -0,0 +1,13 @@ +class Solution { + public int countKDifference(int[] nums, int k) { + Map c = new HashMap<>(); + for (int num : nums) { + c.put(num, c.getOrDefault(num, 0) + 1); + } + int ans = 0; + for (int x : c.keySet()) { + ans += c.get(x) * c.getOrDefault(x + k, 0); + } + return ans; + } +} diff --git a/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.kt b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.kt new file mode 100644 index 00000000..2fa11f81 --- /dev/null +++ b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.kt @@ -0,0 +1,9 @@ +class Solution { + fun countKDifference(nums: IntArray, k: Int): Int { + val c = HashMap() + for (value in nums) c[value] = (c[value] ?: 0) + 1 + var result = 0 + for ((x, cnt) in c) result += cnt * (c[x + k] ?: 0) + return result + } +} diff --git a/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.py b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.py new file mode 100644 index 00000000..73827c68 --- /dev/null +++ b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.py @@ -0,0 +1,4 @@ +class Solution: + def countKDifference(self, nums: List[int], k: int) -> int: + c = Counter(nums) + return sum(c[x] * c[x + k] for x in c) diff --git a/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.py2 b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.py2 new file mode 100644 index 00000000..eb2602a5 --- /dev/null +++ b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.py2 @@ -0,0 +1,10 @@ +class Solution(object): + def countKDifference(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + from collections import Counter + c = Counter(nums) + return sum(c[x] * c[x + k] for x in c) diff --git a/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.rb b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.rb new file mode 100644 index 00000000..2b2c6143 --- /dev/null +++ b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.rb @@ -0,0 +1,7 @@ +# @param {Integer[]} nums +# @param {Integer} k +# @return {Integer} +def count_k_difference(nums, k) + c = nums.tally + c.sum { |x, cnt| cnt * (c[x + k] || 0) } +end diff --git a/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.rs b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.rs new file mode 100644 index 00000000..2b5e556e --- /dev/null +++ b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.rs @@ -0,0 +1,10 @@ +impl Solution { + pub fn count_k_difference(nums: Vec, k: i32) -> i32 { + use std::collections::HashMap; + let mut c = HashMap::new(); + for &num in &nums { + *c.entry(num).or_insert(0) += 1; + } + c.iter().map(|(&x, &cnt)| cnt * c.get(&(x + k)).unwrap_or(&0)).sum() + } +} diff --git a/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.swift b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.swift new file mode 100644 index 00000000..d620d158 --- /dev/null +++ b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.swift @@ -0,0 +1,13 @@ +class Solution { + func countKDifference(_ nums: [Int], _ k: Int) -> Int { + var c: [Int: Int] = [:] + for num in nums { + c[num, default: 0] += 1 + } + var ans = 0 + for (x, cnt) in c { + ans += cnt * (c[x + k] ?? 0) + } + return ans + } +} diff --git a/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.ts b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.ts new file mode 100644 index 00000000..d6b1a4a2 --- /dev/null +++ b/tests/2001-2500/2006. count-number-of-pairs-with-absolute-difference-k/sol.ts @@ -0,0 +1,11 @@ +function countKDifference(nums: number[], k: number): number { + const c: Map = new Map(); + for (const num of nums) { + c.set(num, (c.get(num) || 0) + 1); + } + let ans = 0; + c.forEach((cnt, x) => { + ans += cnt * (c.get(x + k) || 0); + }); + return ans; +} diff --git a/tests/2001-2500/2007. find-original-array-from-doubled-array/manifest.yaml b/tests/2001-2500/2007. find-original-array-from-doubled-array/manifest.yaml new file mode 100644 index 00000000..a7744401 --- /dev/null +++ b/tests/2001-2500/2007. find-original-array-from-doubled-array/manifest.yaml @@ -0,0 +1,288 @@ +entry: + id: 2007 + title: "find-original-array-from-doubled-array" + params: + changed: + type: array + items: + type: int + call: + cpp: "Solution().findOriginalArray({changed})" + rust: "Solution::find_original_array({changed})" + python3: "Solution().findOriginalArray({changed})" + python2: "Solution().findOriginalArray({changed})" + ruby: "find_original_array({changed})" + java: "new Solution().findOriginalArray({changed})" + csharp: "new Solution().FindOriginalArray({changed})" + kotlin: "Solution().findOriginalArray({changed})" + go: "findOriginalArray({changed})" + dart: "Solution().findOriginalArray({changed})" + swift: "Solution().findOriginalArray({changed})" + typescript: "findOriginalArray({changed})" + +judge: + type: exact + +limits: + time_ms: 3000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().findOriginalArray(changed, {result})" + checker: | + from collections import Counter + + class Checker: + def findOriginalArray(self, changed, result): + if not isinstance(result, list): + return False + if len(changed) % 2 == 1: + return result == [] + remaining = Counter(changed) + for value in result: + if not isinstance(value, int) or value < 0: + return False + if remaining[value] <= 0: + return False + remaining[value] -= 1 + doubled = value * 2 + if remaining[doubled] <= 0: + return False + remaining[doubled] -= 1 + if len(result) != len(changed) // 2: + return False + return not any(remaining.values()) + +seed: 2007 + +tests: + - name: example-valid + in: + changed: [1, 3, 4, 2, 6, 8] + - name: example-invalid + in: + changed: [6, 3, 0, 1] + out: [] + - name: example-odd + in: + changed: [1] + out: [] + - name: empty-not-allowed-but-represented + in: + changed: [0, 0] + - name: all-zero-four + in: + changed: [0, 0, 0, 0] + - name: zero-and-one + in: + changed: [0, 1, 0, 2] + - name: zero-and-large + in: + changed: [0, 0, 100000, 0] + out: [] + - name: one-chain + in: + changed: [1, 2, 2, 4, 4, 8] + - name: duplicate-chain + in: + changed: [2, 4, 8, 16, 2, 4, 8, 16] + - name: duplicate-single + in: + changed: [7, 14, 7, 14] + - name: unsorted-valid + in: + changed: [10, 1, 6, 2, 3, 20, 12, 4] + out: [] + - name: unsorted-invalid + in: + changed: [8, 4, 2, 1, 16, 5] + out: [] + - name: missing-double + in: + changed: [2, 3, 4, 6] + - name: extra-unpaired + in: + changed: [1, 2, 2, 4, 9, 18, 10, 11] + out: [] + - name: odd-three + in: + changed: [0, 0, 0] + out: [] + - name: odd-five + in: + changed: [1, 2, 2, 4, 4] + out: [] + - name: minimum-positive + in: + changed: [1, 2] + - name: minimum-invalid + in: + changed: [2, 3] + out: [] + - name: maximum-value-pair + in: + changed: [50000, 100000] + - name: maximum-unmatched + in: + changed: [100000, 100000] + out: [] + - name: many-zeros-and-pair + in: + changed: [0, 0, 0, 0, 0, 0, 5, 10] + - name: repeated-zero-valid + in: + changed: [0, 5, 0, 10, 0, 0] + - name: repeated-zero-invalid + in: + changed: [0, 0, 0, 5, 10, 11] + out: [] + - name: powers-of-two + in: + changed: [32, 1, 16, 2, 4, 8, 64, 128] + - name: powers-invalid-tail + in: + changed: [1, 2, 2, 4, 4, 8, 8, 32] + out: [] + - name: repeated-mixed-valid + in: + changed: [3, 6, 3, 6, 12, 24, 0, 0, 10, 20] + - name: repeated-mixed-invalid + in: + changed: [3, 6, 3, 6, 12, 12, 0, 0, 10, 21] + out: [] + - name: adjacent-values + in: + changed: [11, 22, 12, 24, 13, 26, 14, 28] + - name: close-invalid-values + in: + changed: [11, 22, 12, 24, 13, 26, 14, 29] + out: [] + - name: zero-heavy-valid + in: + changed: [0, 0, 0, 0, 0, 0, 0, 0, 25, 50, 1, 2] + - name: zero-heavy-invalid + in: + changed: [0, 0, 0, 0, 0, 0, 0, 0, 25, 50, 1, 3] + out: [] + - name: broad-valid + in: + changed: [99, 198, 100, 200, 101, 202, 102, 204, 103, 206, 104, 208] + - name: broad-invalid + in: + changed: [99, 198, 100, 200, 101, 202, 102, 204, 103, 206, 104, 209] + out: [] + - name: many-duplicate-pairs + in: + changed: [6, 12, 6, 12, 6, 12, 6, 12, 7, 14, 7, 14, 0, 0, 0, 0] + - name: large-static-valid + in: + changed: + [ + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 2, + 2, + 4, + 3, + 6, + 4, + 8, + 5, + 10, + 6, + 12, + 7, + 14, + 8, + 16, + 9, + 18, + 10, + 20, + 11, + 22, + 12, + 24, + 13, + 26, + 14, + 28, + 15, + 30, + 16, + 32, + 17, + 34, + 18, + 36, + 19, + 38, + 20, + 40, + 21, + 42, + 22, + 44, + 23, + 46, + 24, + 48, + 25, + 50, + 26, + 52, + 27, + 54, + 28, + 56, + 29, + 58, + 30, + 60, + 31, + 62, + 32, + 64, + 33, + 66, + 34, + 68, + 35, + 70, + 36, + 72, + 37, + 74, + 38, + 76, + 39, + 78, + 40, + 80, + 41, + 82, + 42, + 84, + 43, + 86, + 44, + 88, + 45, + 90, + 46, + 92, + 47, + 94, + 48, + 96, + 49, + 98, + 50, + 100, + ] diff --git a/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.cpp b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.cpp new file mode 100644 index 00000000..88a87a64 --- /dev/null +++ b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + vector findOriginalArray(vector& changed) { + if (changed.size() % 2 != 0) return {}; + + unordered_map count; + for (int num : changed) { + count[num]++; + } + sort(changed.begin(), changed.end()); + vector original; + + for (int num : changed) { + if (count[num] == 0) continue; + if (count[2 * num] == 0) return {}; + original.push_back(num); + count[num]--; + count[2 * num]--; + } + + return original; + } +}; diff --git a/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.cs b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.cs new file mode 100644 index 00000000..5fdf8ebd --- /dev/null +++ b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.cs @@ -0,0 +1,22 @@ +public class Solution { + public int[] FindOriginalArray(int[] changed) { + if (changed.Length % 2 != 0) return new int[0]; + + var count = new Dictionary(); + foreach (int num in changed) { + count[num] = count.GetValueOrDefault(num) + 1; + } + Array.Sort(changed); + var original = new List(); + + foreach (int num in changed) { + if (count[num] == 0) continue; + if (count.GetValueOrDefault(2 * num) == 0) return new int[0]; + original.Add(num); + count[num]--; + count[2 * num]--; + } + + return original.ToArray(); + } +} diff --git a/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.dart b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.dart new file mode 100644 index 00000000..29e1c698 --- /dev/null +++ b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.dart @@ -0,0 +1,22 @@ +class Solution { + List findOriginalArray(List changed) { + if (changed.length % 2 != 0) return []; + + Map count = {}; + for (int num in changed) { + count[num] = (count[num] ?? 0) + 1; + } + changed.sort(); + List original = []; + + for (int num in changed) { + if (count[num] == 0) continue; + if ((count[2 * num] ?? 0) == 0) return []; + original.add(num); + count[num] = count[num]! - 1; + count[2 * num] = count[2 * num]! - 1; + } + + return original; + } +} diff --git a/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.go b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.go new file mode 100644 index 00000000..781f9ef3 --- /dev/null +++ b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.go @@ -0,0 +1,26 @@ +func findOriginalArray(changed []int) []int { + if len(changed)%2 != 0 { + return []int{} + } + + count := make(map[int]int) + for _, num := range changed { + count[num]++ + } + sort.Ints(changed) + original := []int{} + + for _, num := range changed { + if count[num] == 0 { + continue + } + if count[2*num] == 0 { + return []int{} + } + original = append(original, num) + count[num]-- + count[2*num]-- + } + + return original +} diff --git a/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.java b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.java new file mode 100644 index 00000000..53916544 --- /dev/null +++ b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.java @@ -0,0 +1,26 @@ +class Solution { + public int[] findOriginalArray(int[] changed) { + if (changed.length % 2 != 0) return new int[0]; + + Map count = new HashMap<>(); + for (int num : changed) { + count.put(num, count.getOrDefault(num, 0) + 1); + } + Arrays.sort(changed); + List original = new ArrayList<>(); + + for (int num : changed) { + if (count.get(num) == 0) continue; + if (count.getOrDefault(2 * num, 0) == 0) return new int[0]; + original.add(num); + count.put(num, count.get(num) - 1); + count.put(2 * num, count.get(2 * num) - 1); + } + + int[] result = new int[original.size()]; + for (int i = 0; i < original.size(); i++) { + result[i] = original.get(i); + } + return result; + } +} diff --git a/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.kt b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.kt new file mode 100644 index 00000000..8569d45a --- /dev/null +++ b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.kt @@ -0,0 +1,22 @@ +class Solution { + fun findOriginalArray(changed: IntArray): IntArray { + if (changed.size % 2 != 0) return intArrayOf() + + val count = mutableMapOf() + for (num in changed) { + count[num] = (count[num] ?: 0) + 1 + } + changed.sort() + val original = mutableListOf() + + for (num in changed) { + if (count[num] == 0) continue + if ((count[2 * num] ?: 0) == 0) return intArrayOf() + original.add(num) + count[num] = count[num]!! - 1 + count[2 * num] = count[2 * num]!! - 1 + } + + return original.toIntArray() + } +} diff --git a/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.py b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.py new file mode 100644 index 00000000..e8adea7a --- /dev/null +++ b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.py @@ -0,0 +1,23 @@ +class Solution(object): + def findOriginalArray(self, changed): + """ + :type changed: List[int] + :rtype: List[int] + """ + if len(changed) % 2 != 0: + return [] + + count = Counter(changed) + changed.sort() + original = [] + + for num in changed: + if count[num] == 0: + continue + if count[2 * num] == 0: + return [] + original.append(num) + count[num] -= 1 + count[2 * num] -= 1 + + return original diff --git a/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.py2 b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.py2 new file mode 100644 index 00000000..c5c5657b --- /dev/null +++ b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.py2 @@ -0,0 +1,23 @@ +class Solution(object): + def findOriginalArray(self, changed): + """ + :type changed: List[int] + :rtype: List[int] + """ + if len(changed) % 2 != 0: + return [] + + count = Counter(changed) + changed.sort() + original = [] + + for num in changed: + if count[num] == 0: + continue + if count[2 * num] == 0: + return [] + original.append(num) + count[num] -= 1 + count[2 * num] -= 1 + + return original diff --git a/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.rb b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.rb new file mode 100644 index 00000000..c011b669 --- /dev/null +++ b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.rb @@ -0,0 +1,20 @@ +# @param {Integer[]} changed +# @return {Integer[]} +def find_original_array(changed) + return [] if changed.length.odd? + + count = Hash.new(0) + changed.each { |num| count[num] += 1 } + changed.sort! + original = [] + + changed.each do |num| + next if count[num] == 0 + return [] if count[2 * num] == 0 + original << num + count[num] -= 1 + count[2 * num] -= 1 + end + + original +end diff --git a/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.rs b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.rs new file mode 100644 index 00000000..944154e1 --- /dev/null +++ b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.rs @@ -0,0 +1,29 @@ +impl Solution { + pub fn find_original_array(changed: Vec) -> Vec { + if changed.len() % 2 != 0 { + return vec![]; + } + + use std::collections::HashMap; + let mut count = HashMap::new(); + for &num in &changed { + *count.entry(num).or_insert(0) += 1; + } + let mut sorted = changed.clone(); + sorted.sort(); + let mut original = Vec::new(); + + for &num in &sorted { + if count[&num] == 0 { continue; } + let double = 2 * num; + if !count.contains_key(&double) || count[&double] == 0 { + return vec![]; + } + original.push(num); + *count.get_mut(&num).unwrap() -= 1; + *count.get_mut(&double).unwrap() -= 1; + } + + original + } +} diff --git a/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.swift b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.swift new file mode 100644 index 00000000..c10b84ef --- /dev/null +++ b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.swift @@ -0,0 +1,22 @@ +class Solution { + func findOriginalArray(_ changed: [Int]) -> [Int] { + if changed.count % 2 != 0 { return [] } + + var count = [Int: Int]() + for num in changed { + count[num, default: 0] += 1 + } + let sorted = changed.sorted() + var original = [Int]() + + for num in sorted { + if count[num] == 0 { continue } + if count[2 * num] == nil || count[2 * num] == 0 { return [] } + original.append(num) + count[num]! -= 1 + count[2 * num]! -= 1 + } + + return original + } +} diff --git a/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.ts b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.ts new file mode 100644 index 00000000..7912b42a --- /dev/null +++ b/tests/2001-2500/2007. find-original-array-from-doubled-array/sol.ts @@ -0,0 +1,20 @@ +function findOriginalArray(changed: number[]): number[] { + if (changed.length % 2 !== 0) return []; + + let count = new Map(); + for (let num of changed) { + count.set(num, (count.get(num) || 0) + 1); + } + changed.sort((a, b) => a - b); + let original: number[] = []; + + for (let num of changed) { + if (count.get(num) === 0) continue; + if (!count.get(2 * num) || count.get(2 * num) === 0) return []; + original.push(num); + count.set(num, count.get(num)! - 1); + count.set(2 * num, count.get(2 * num)! - 1); + } + + return original; +} diff --git a/tests/2001-2500/2008. maximum-earnings-from-taxi/manifest.yaml b/tests/2001-2500/2008. maximum-earnings-from-taxi/manifest.yaml new file mode 100644 index 00000000..9f76462a --- /dev/null +++ b/tests/2001-2500/2008. maximum-earnings-from-taxi/manifest.yaml @@ -0,0 +1,380 @@ +entry: + id: 2008 + title: "maximum-earnings-from-taxi" + params: + n: + type: int + rides: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().maxTaxiEarnings({n}, {rides})" + rust: "Solution::max_taxi_earnings({n}, {rides})" + python3: "Solution().maxTaxiEarnings({n}, {rides})" + python2: "Solution().maxTaxiEarnings({n}, {rides})" + ruby: "max_taxi_earnings({n}, {rides})" + java: "new Solution().maxTaxiEarnings({n}, {rides})" + csharp: "new Solution().MaxTaxiEarnings({n}, {rides})" + kotlin: "Solution().maxTaxiEarnings({n}, {rides})" + go: "maxTaxiEarnings({n}, {rides})" + dart: "Solution().maxTaxiEarnings({n}, {rides})" + swift: "Solution().maxTaxiEarnings({n}, {rides})" + typescript: "maxTaxiEarnings({n}, {rides})" + +judge: + type: "exact" + +limits: + time_ms: 1000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().maxTaxiEarnings(n, rides, {result})" + checker: | + class Checker: + def maxTaxiEarnings(self, n, rides, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + best = [0] * (n + 1) + by_end = [[] for _ in range(n + 1)] + for start, end, tip in rides: + if not (1 <= start < end <= n and tip >= 1): + return False + by_end[end].append((start, end - start + tip)) + for end in range(1, n + 1): + best[end] = best[end - 1] + for start, profit in by_end[end]: + best[end] = max(best[end], best[start] + profit) + return result == best[n] + +seed: 2008 + +tests: + - name: "example_1" + in: + n: 5 + rides: + - [2, 5, 4] + - [1, 5, 1] + out: 7 + - name: "example_2" + in: + n: 20 + rides: + - [1, 6, 1] + - [3, 10, 2] + - [10, 12, 3] + - [11, 12, 2] + - [12, 15, 2] + - [13, 18, 1] + out: 20 + - name: "single_minimal" + in: + n: 2 + rides: + - [1, 2, 1] + out: 2 + - name: "single_large_tip" + in: + n: 2 + rides: + - [1, 2, 100] + out: 101 + - name: "adjacent_rides" + in: + n: 3 + rides: + - [1, 2, 1] + - [2, 3, 1] + out: 4 + - name: "overlap_selects_two" + in: + n: 3 + rides: + - [1, 3, 1] + - [1, 2, 100] + - [2, 3, 100] + out: 202 + - name: "no_overlap_longer" + in: + n: 10 + rides: + - [1, 2, 1] + - [2, 3, 1] + - [3, 4, 1] + - [4, 5, 1] + - [5, 6, 1] + - [6, 7, 1] + - [7, 8, 1] + - [8, 9, 1] + - [9, 10, 1] + out: 18 + - name: "many_short_beats_long" + in: + n: 10 + rides: + - [1, 10, 1] + - [1, 2, 100] + - [2, 3, 100] + - [3, 4, 100] + - [4, 5, 100] + - [5, 6, 100] + - [6, 7, 100] + - [7, 8, 100] + - [8, 9, 100] + out: 808 + - name: "overlapping_windows" + in: + n: 10 + rides: + - [1, 5, 10] + - [2, 6, 10] + - [3, 7, 10] + - [4, 8, 10] + - [5, 9, 10] + - [6, 10, 10] + out: 28 + - name: "touching_zero_tip" + in: + n: 8 + rides: + - [1, 4, 1] + - [4, 8, 1] + out: 9 + - name: "long_ride_with_tip" + in: + n: 8 + rides: + - [1, 4, 1] + - [4, 8, 1] + - [1, 8, 100] + out: 107 + - name: "same_start" + in: + n: 6 + rides: + - [1, 2, 1] + - [1, 3, 2] + - [1, 4, 3] + - [1, 5, 4] + - [1, 6, 5] + out: 10 + - name: "same_end" + in: + n: 6 + rides: + - [1, 6, 1] + - [2, 6, 100] + - [3, 6, 100] + - [4, 6, 100] + - [5, 6, 100] + out: 104 + - name: "three_chain" + in: + n: 7 + rides: + - [1, 3, 5] + - [3, 5, 5] + - [5, 7, 5] + - [1, 7, 1] + out: 21 + - name: "unsorted_input" + in: + n: 7 + rides: + - [2, 4, 10] + - [4, 6, 10] + - [1, 2, 1] + - [6, 7, 1] + out: 28 + - name: "best_chain_vs_direct" + in: + n: 10 + rides: + - [1, 3, 1] + - [3, 6, 2] + - [6, 10, 3] + - [1, 10, 2] + out: 15 + - name: "duplicate_rides" + in: + n: 10 + rides: + - [1, 2, 1] + - [1, 2, 2] + - [1, 2, 3] + - [2, 5, 4] + - [2, 5, 5] + - [5, 10, 6] + out: 23 + - name: "dense_overlaps" + in: + n: 15 + rides: + - [1, 5, 1] + - [2, 6, 2] + - [3, 7, 3] + - [4, 8, 4] + - [5, 9, 5] + - [6, 10, 6] + - [7, 11, 7] + - [8, 12, 8] + - [9, 13, 9] + - [10, 14, 10] + - [11, 15, 11] + out: 33 + - name: "large_direct" + in: + n: 100 + rides: + - [1, 100, 1] + out: 100 + - name: "large_two_segments" + in: + n: 100 + rides: + - [1, 2, 100000] + - [2, 100, 100000] + out: 200099 + - name: "two_touching_segments" + in: + n: 100 + rides: + - [1, 50, 1] + - [50, 100, 1] + out: 101 + - name: "four_equal_segments" + in: + n: 100 + rides: + - [1, 25, 10] + - [25, 50, 10] + - [50, 75, 10] + - [75, 100, 10] + out: 139 + - name: "nested_high_tip" + in: + n: 10 + rides: + - [1, 10, 1] + - [2, 9, 100] + - [3, 8, 100] + - [4, 7, 100] + out: 107 + - name: "mixed_six" + in: + n: 12 + rides: + - [1, 4, 2] + - [4, 7, 3] + - [7, 12, 4] + - [1, 6, 1] + - [6, 12, 1] + out: 20 + - name: "unit_chain_ten" + in: + n: 12 + rides: + - [2, 3, 1] + - [3, 4, 1] + - [4, 5, 1] + - [5, 6, 1] + - [6, 7, 1] + - [7, 8, 1] + - [8, 9, 1] + - [9, 10, 1] + - [10, 11, 1] + - [11, 12, 1] + out: 20 + - name: "three_equal_blocks" + in: + n: 9 + rides: + - [1, 3, 10] + - [3, 6, 10] + - [6, 9, 10] + - [1, 9, 1] + out: 38 + - name: "alternative_paths" + in: + n: 9 + rides: + - [1, 2, 1] + - [2, 9, 1] + - [1, 4, 5] + - [4, 9, 5] + out: 18 + - name: "two_high_routes" + in: + n: 20 + rides: + - [1, 2, 1] + - [2, 20, 1] + - [1, 10, 50] + - [10, 20, 50] + out: 119 + - name: "five_medium_routes" + in: + n: 30 + rides: + - [1, 10, 1] + - [10, 20, 2] + - [20, 30, 3] + - [1, 15, 10] + - [15, 30, 10] + out: 49 + - name: "late_big_tip" + in: + n: 50 + rides: + - [1, 2, 1] + - [2, 3, 1] + - [3, 4, 1] + - [4, 5, 1] + - [5, 6, 1] + - [6, 7, 1] + - [7, 8, 1] + - [8, 9, 1] + - [9, 10, 1] + - [10, 50, 100] + out: 158 + - name: "three_quarters" + in: + n: 50 + rides: + - [1, 25, 1] + - [25, 50, 1] + - [1, 50, 20] + out: 69 + - name: "maximum_single_ride" + in: + n: 1000 + rides: + - [1, 1000, 100000] + out: 100999 + - name: "large_composed" + in: + n: 1000 + rides: + - [1, 500, 1] + - [500, 1000, 1] + - [1, 250, 100] + - [250, 750, 100] + - [750, 1000, 100] + out: 1299 + - name: "final_short_ride" + in: + n: 10 + rides: + - [1, 2, 1] + out: 2 + - name: "final_full_ride" + in: + n: 5 + rides: + - [1, 5, 1] + out: 5 diff --git a/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.cpp b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.cpp new file mode 100644 index 00000000..9580b5b9 --- /dev/null +++ b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.cpp @@ -0,0 +1,36 @@ +#include +#include + +class Solution { +public: + long long maxTaxiEarnings(int n, vector>& rides) { + sort(rides.begin(), rides.end(), [](const vector& a, const vector& b) { + return a[1] < b[1]; + }); + + vector> dp; + dp.push_back({0, 0}); + + for (const auto& ride : rides) { + long long start = ride[0], end = ride[1], tip = ride[2]; + + long long lo = 0, hi = dp.size(); + while (lo < hi) { + long long mid = lo + (hi - lo) / 2; + if (dp[mid].first <= start) { + lo = mid + 1; + } else { + hi = mid; + } + } + long long i = lo - 1; + long long profit = dp[i].second + end - start + tip; + + if (profit > dp.back().second) { + dp.push_back({end, profit}); + } + } + + return dp.back().second; + } +}; diff --git a/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.cs b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.cs new file mode 100644 index 00000000..2c1f802e --- /dev/null +++ b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; + +public class Solution { + public long MaxTaxiEarnings(int n, int[][] rides) { + Array.Sort(rides, (a, b) => a[1].CompareTo(b[1])); + List dp = new List { new long[] {0, 0} }; + + foreach (var ride in rides) { + long start = ride[0], end = ride[1], tip = ride[2]; + + int lo = 0, hi = dp.Count; + while (lo < hi) { + int mid = lo + (hi - lo) / 2; + if (dp[mid][0] <= start) { + lo = mid + 1; + } else { + hi = mid; + } + } + int i = lo - 1; + long profit = dp[i][1] + end - start + tip; + + if (profit > dp[dp.Count - 1][1]) { + dp.Add(new long[] {end, profit}); + } + } + + return dp[dp.Count - 1][1]; + } +} diff --git a/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.dart b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.dart new file mode 100644 index 00000000..7fc8ba9f --- /dev/null +++ b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.dart @@ -0,0 +1,28 @@ +class Solution { + int maxTaxiEarnings(int n, List> rides) { + rides.sort((a, b) => a[1].compareTo(b[1])); + List> dp = [[0, 0]]; + + for (var ride in rides) { + int start = ride[0], end = ride[1], tip = ride[2]; + + int lo = 0, hi = dp.length; + while (lo < hi) { + int mid = lo + (hi - lo) ~/ 2; + if (dp[mid][0] <= start) { + lo = mid + 1; + } else { + hi = mid; + } + } + int i = lo - 1; + int profit = dp[i][1] + end - start + tip; + + if (profit > dp.last[1]) { + dp.add([end, profit]); + } + } + + return dp.last[1]; + } +} diff --git a/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.go b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.go new file mode 100644 index 00000000..bfddc48d --- /dev/null +++ b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.go @@ -0,0 +1,29 @@ +func maxTaxiEarnings(n int, rides [][]int) int64 { + sort.Slice(rides, func(i, j int) bool { + return rides[i][1] < rides[j][1] + }) + + dp := [][]int64{{0, 0}} + + for _, ride := range rides { + start, end, tip := int64(ride[0]), int64(ride[1]), int64(ride[2]) + + lo, hi := 0, len(dp) + for lo < hi { + mid := lo + (hi-lo)/2 + if dp[mid][0] <= start { + lo = mid + 1 + } else { + hi = mid + } + } + i := lo - 1 + profit := dp[i][1] + end - start + tip + + if profit > dp[len(dp)-1][1] { + dp = append(dp, []int64{end, profit}) + } + } + + return dp[len(dp)-1][1] +} diff --git a/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.java b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.java new file mode 100644 index 00000000..e58ec680 --- /dev/null +++ b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.java @@ -0,0 +1,34 @@ +import java.util.*; + +class Solution { + public long maxTaxiEarnings(int n, int[][] rides) { + Arrays.sort(rides, (a, b) -> Integer.compare(a[1], b[1])); + List dp = new ArrayList<>(); + dp.add(new long[]{0, 0}); + + for (int[] ride : rides) { + int start = ride[0], end = ride[1], tip = ride[2]; + int i = binarySearch(dp, start) - 1; + long profit = dp.get(i)[1] + end - start + tip; + + if (profit > dp.get(dp.size()-1)[1]) { + dp.add(new long[]{end, profit}); + } + } + + return dp.get(dp.size()-1)[1]; + } + + private int binarySearch(List dp, int start) { + int lo = 0, hi = dp.size(); + while (lo < hi) { + int mid = lo + (hi - lo) / 2; + if (dp.get(mid)[0] <= start) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; + } +} diff --git a/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.kt b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.kt new file mode 100644 index 00000000..fee6dbe2 --- /dev/null +++ b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.kt @@ -0,0 +1,31 @@ +class Solution { + fun maxTaxiEarnings(n: Int, rides: Array): Long { + rides.sortBy { it[1] } + val dp = mutableListOf(longArrayOf(0, 0)) + + for (ride in rides) { + val start = ride[0].toLong() + val end = ride[1].toLong() + val tip = ride[2].toLong() + + var lo = 0 + var hi = dp.size + while (lo < hi) { + val mid = lo + (hi - lo) / 2 + if (dp[mid][0] <= start) { + lo = mid + 1 + } else { + hi = mid + } + } + val i = lo - 1 + val profit = dp[i][1] + end - start + tip + + if (profit > dp.last()[1]) { + dp.add(longArrayOf(end, profit)) + } + } + + return dp.last()[1] + } +} diff --git a/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.py b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.py new file mode 100644 index 00000000..89bf3436 --- /dev/null +++ b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.py @@ -0,0 +1,21 @@ +from bisect import bisect_right + + +class Solution(object): + def maxTaxiEarnings(self, n, rides): + """ + :type n: int + :type rides: List[List[int]] + :rtype: int + """ + rides.sort(key=lambda x: x[1]) + dp = [(0, 0)] + + for start, end, tip in rides: + i = bisect_right(dp, (start, float("inf"))) - 1 + profit = dp[i][1] + end - start + tip + + if profit > dp[-1][1]: + dp.append((end, profit)) + + return dp[-1][1] diff --git a/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.py2 b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.py2 new file mode 100644 index 00000000..7534fdf5 --- /dev/null +++ b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def maxTaxiEarnings(self, n, rides): + """ + :type n: int + :type rides: List[List[int]] + :rtype: int + """ + from bisect import bisect_right + + rides.sort(key=lambda x: x[1]) + dp = [(0, 0)] + + for start, end, tip in rides: + i = bisect_right(dp, (start, float('inf'))) - 1 + profit = dp[i][1] + end - start + tip + + if profit > dp[-1][1]: + dp.append((end, profit)) + + return dp[-1][1] diff --git a/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.rb b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.rb new file mode 100644 index 00000000..a5319f7d --- /dev/null +++ b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.rb @@ -0,0 +1,19 @@ +# @param {Integer} n +# @param {Integer[][]} rides +# @return {Integer} +def max_taxi_earnings(n, rides) + rides.sort_by! { |r| r[1] } + dp = [[0, 0]] + + rides.each do |start, ending, tip| + i = dp.bsearch_index { |(end_time, _)| end_time > start } || dp.length + i -= 1 + profit = dp[i][1] + ending - start + tip + + if profit > dp[-1][1] + dp << [ending, profit] + end + end + + dp[-1][1] +end diff --git a/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.rs b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.rs new file mode 100644 index 00000000..43686c95 --- /dev/null +++ b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.rs @@ -0,0 +1,32 @@ +impl Solution { + pub fn max_taxi_earnings(n: i32, rides: Vec>) -> i64 { + let mut rides = rides; + rides.sort_by_key(|r| r[1]); + let mut dp: Vec<(i64, i64)> = vec![(0, 0)]; + + for ride in &rides { + let start = ride[0] as i64; + let end = ride[1] as i64; + let tip = ride[2] as i64; + + let mut lo = 0; + let mut hi = dp.len(); + while lo < hi { + let mid = lo + (hi - lo) / 2; + if dp[mid].0 <= start { + lo = mid + 1; + } else { + hi = mid; + } + } + let i = lo - 1; + let profit = dp[i].1 + end - start + tip; + + if profit > dp.last().unwrap().1 { + dp.push((end, profit)); + } + } + + dp.last().unwrap().1 + } +} diff --git a/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.swift b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.swift new file mode 100644 index 00000000..1c584fef --- /dev/null +++ b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.swift @@ -0,0 +1,29 @@ +class Solution { + func maxTaxiEarnings(_ n: Int, _ rides: [[Int]]) -> Int { + let sortedRides = rides.sorted { $0[1] < $1[1] } + var dp: [(end: Int, profit: Int)] = [(0, 0)] + + for ride in sortedRides { + let start = ride[0], end = ride[1], tip = ride[2] + + var lo = 0 + var hi = dp.count + while lo < hi { + let mid = lo + (hi - lo) / 2 + if dp[mid].end <= start { + lo = mid + 1 + } else { + hi = mid + } + } + let i = lo - 1 + let profit = dp[i].profit + end - start + tip + + if profit > dp.last!.profit { + dp.append((end, profit)) + } + } + + return dp.last!.profit + } +} diff --git a/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.ts b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.ts new file mode 100644 index 00000000..04e98f1c --- /dev/null +++ b/tests/2001-2500/2008. maximum-earnings-from-taxi/sol.ts @@ -0,0 +1,13 @@ +function maxTaxiEarnings(n: number, rides: number[][]): number { + const ending = Array.from({ length: n + 1 }, () => [] as [number, number][]); + for (const [start, end, tip] of rides) ending[end].push([start, tip]); + const dp = new Array(n + 1).fill(0); + + for (let time = 1; time <= n; time++) { + dp[time] = dp[time - 1]; + for (const [start, tip] of ending[time]) { + dp[time] = Math.max(dp[time], dp[start] + time - start + tip); + } + } + return dp[n]; +} diff --git a/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/manifest.yaml b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/manifest.yaml new file mode 100644 index 00000000..6702828b --- /dev/null +++ b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/manifest.yaml @@ -0,0 +1,231 @@ +entry: + id: 2009 + title: "minimum-number-of-operations-to-make-array-continuous" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().minOperations({nums})" + rust: "Solution::min_operations({nums})" + python3: "Solution().minOperations({nums})" + python2: "Solution().minOperations({nums})" + ruby: "min_operations({nums})" + java: "new Solution().minOperations({nums})" + csharp: "new Solution().MinOperations({nums})" + kotlin: "Solution().minOperations({nums})" + go: "minOperations({nums})" + dart: "Solution().minOperations({nums})" + swift: "Solution().minOperations({nums})" + typescript: "minOperations({nums})" +judge: + type: exact +limits: + time_ms: 3000 + memory_mb: 256 +oracle: + python3: + call: "Checker().minOperations(nums, {result})" + checker: | + class Checker: + def minOperations(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + n = len(nums) + values = sorted(set(nums)) + best = 0 + right = 0 + for left, value in enumerate(values): + while right < len(values) and values[right] < value + n: + right += 1 + best = max(best, right - left) + return result == n - best +seed: 2009 +tests: + - name: example-one + in: + nums: [4, 2, 5, 3] + out: 0 + - name: example-two + in: + nums: [1, 2, 3, 5, 6] + out: 1 + - name: example-three + in: + nums: [1, 10, 100, 1000] + out: 3 + - name: single + in: + nums: [42] + out: 0 + - name: two-equal + in: + nums: [7, 7] + out: 1 + - name: two-adjacent + in: + nums: [100, 99] + out: 0 + - name: consecutive-unsorted + in: + nums: [5, 1, 4, 2, 3] + out: 0 + - name: consecutive-with-duplicate + in: + nums: [1, 2, 2, 3, 4] + out: 1 + - name: one-gap + in: + nums: [1, 2, 3, 5] + out: 1 + - name: duplicate-cluster + in: + nums: [1, 1, 1, 1, 2, 3] + out: 3 + - name: all-equal + in: + nums: [9, 9, 9, 9, 9] + out: 4 + - name: far-apart + in: + nums: [1, 100, 1000, 10000, 100000] + out: 4 + - name: negative-not-allowed-boundary + in: + nums: [1, 2, 1000000000] + out: 1 + - name: max-values-consecutive + in: + nums: [999999996, 1000000000, 999999998, 999999997, 999999999] + out: 0 + - name: max-values-duplicate + in: + nums: [1000000000, 1000000000, 999999999, 999999998] + out: 1 + - name: five-window-best + in: + nums: [1, 2, 4, 5, 7] + out: 1 + - name: six-window-best + in: + nums: [10, 11, 12, 20, 21, 22] + out: 3 + - name: duplicate-and-gap + in: + nums: [1, 1, 3, 3, 5, 5] + out: 3 + - name: dense-low-values + in: + nums: [1, 2, 3, 4, 6, 7, 8, 10] + out: 1 + - name: scattered-even + in: + nums: [2, 4, 6, 8, 10, 12, 14] + out: 3 + - name: nearly-continuous-left + in: + nums: [2, 3, 4, 5, 6, 8, 9] + out: 1 + - name: nearly-continuous-right + in: + nums: [1, 2, 3, 4, 6, 7, 8] + out: 1 + - name: repeated-endpoints + in: + nums: [1, 1, 2, 3, 4, 5, 5] + out: 2 + - name: best-window-middle + in: + nums: [1, 2, 50, 51, 52, 53, 100] + out: 3 + - name: many-duplicates + in: + nums: [3, 3, 3, 4, 4, 5, 6, 6] + out: 4 + - name: powers-of-ten + in: + nums: [1, 10, 100, 1000, 10000, 100000] + out: 5 + - name: arithmetic-step-three + in: + nums: [1, 4, 7, 10, 13, 16, 19, 22] + out: 5 + - name: shifted-blocks + in: + nums: [20, 21, 22, 23, 30, 31, 32, 33, 34] + out: 4 + - name: duplicate-heavy-block + in: + nums: [10, 10, 11, 11, 12, 13, 14, 14, 15, 16] + out: 3 + - name: large-span-small-n + in: + nums: [1, 500000000, 700000000, 900000000] + out: 3 + - name: ten-almost-continuous + in: + nums: [1, 2, 3, 4, 5, 6, 8, 9, 10, 11] + out: 1 + - name: ten-with-duplicates + in: + nums: [1, 2, 2, 3, 4, 6, 6, 7, 8, 9] + out: 2 + - name: twelve-spread + in: + nums: [2, 3, 5, 6, 8, 9, 11, 12, 14, 15, 17, 18] + out: 4 + - name: twelve-dense-with-outlier + in: + nums: [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 1000] + out: 1 + - name: generator-random-small + in: + nums: + gen: array + len: 50 + of: + gen: int + min: 1 + max: 200 + elemType: int + - name: generator-random-medium + in: + nums: + gen: array + len: 1000 + of: + gen: int + min: 1 + max: 1000000 + elemType: int + - name: generator-large-random + in: + nums: + gen: array + len: 100000 + of: + gen: int + min: 1 + max: 1000000000 + elemType: int + - name: generator-large-dense-domain + in: + nums: + gen: array + len: 100000 + of: + gen: int + min: 1 + max: 100000 + elemType: int + - name: generator-large-wide-domain + in: + nums: + gen: array + len: 100000 + of: + gen: int + min: 900000000 + max: 1000000000 + elemType: int diff --git a/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.cpp b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.cpp new file mode 100644 index 00000000..987b81f9 --- /dev/null +++ b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int minOperations(vector& nums) { + int length = nums.size(); + int minOps = length; + vector uniqueNums(nums.begin(), nums.end()); + sort(uniqueNums.begin(), uniqueNums.end()); + uniqueNums.erase(unique(uniqueNums.begin(), uniqueNums.end()), uniqueNums.end()); + int right = 0; + + for (int left = 0; left < uniqueNums.size(); left++) { + while (right < uniqueNums.size() && uniqueNums[right] < uniqueNums[left] + length) { + right++; + } + + minOps = min(minOps, length - (right - left)); + } + + return minOps; + } +}; diff --git a/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.cs b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.cs new file mode 100644 index 00000000..ef3db7ea --- /dev/null +++ b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public int MinOperations(int[] nums) { + int length = nums.Length; + int minOps = length; + int[] uniqueNums = nums.Distinct().OrderBy(x => x).ToArray(); + int right = 0; + + for (int left = 0; left < uniqueNums.Length; left++) { + while (right < uniqueNums.Length && uniqueNums[right] < uniqueNums[left] + length) { + right++; + } + + minOps = Math.Min(minOps, length - (right - left)); + } + + return minOps; + } +} diff --git a/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.dart b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.dart new file mode 100644 index 00000000..f2c07cad --- /dev/null +++ b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.dart @@ -0,0 +1,18 @@ +class Solution { + int minOperations(List nums) { + int length = nums.length; + int minOps = length; + List uniqueNums = nums.toSet().toList()..sort(); + int right = 0; + + for (int left = 0; left < uniqueNums.length; left++) { + while (right < uniqueNums.length && uniqueNums[right] < uniqueNums[left] + length) { + right++; + } + + minOps = minOps < length - (right - left) ? minOps : length - (right - left); + } + + return minOps; + } +} diff --git a/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.go b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.go new file mode 100644 index 00000000..e699d0fc --- /dev/null +++ b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.go @@ -0,0 +1,26 @@ +func minOperations(nums []int) int { + length := len(nums) + minOps := length + uniqueNums := make([]int, 0) + seen := make(map[int]bool) + for _, num := range nums { + if !seen[num] { + seen[num] = true + uniqueNums = append(uniqueNums, num) + } + } + sort.Ints(uniqueNums) + right := 0 + + for left := 0; left < len(uniqueNums); left++ { + for right < len(uniqueNums) && uniqueNums[right] < uniqueNums[left] + length { + right++ + } + + if length-(right-left) < minOps { + minOps = length - (right - left) + } + } + + return minOps +} diff --git a/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.java b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.java new file mode 100644 index 00000000..3a392a3d --- /dev/null +++ b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.java @@ -0,0 +1,18 @@ +class Solution { + public int minOperations(int[] nums) { + int length = nums.length; + int minOps = length; + int[] uniqueNums = java.util.Arrays.stream(nums).distinct().sorted().toArray(); + int right = 0; + + for (int left = 0; left < uniqueNums.length; left++) { + while (right < uniqueNums.length && uniqueNums[right] < uniqueNums[left] + length) { + right++; + } + + minOps = Math.min(minOps, length - (right - left)); + } + + return minOps; + } +} diff --git a/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.kt b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.kt new file mode 100644 index 00000000..8d14e6a5 --- /dev/null +++ b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.kt @@ -0,0 +1,18 @@ +class Solution { + fun minOperations(nums: IntArray): Int { + val length = nums.size + var minOps = length + val uniqueNums = nums.distinct().sorted() + var right = 0 + + for (left in uniqueNums.indices) { + while (right < uniqueNums.size && uniqueNums[right] < uniqueNums[left] + length) { + right++ + } + + minOps = minOf(minOps, length - (right - left)) + } + + return minOps + } +} diff --git a/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.py b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.py new file mode 100644 index 00000000..92318599 --- /dev/null +++ b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.py @@ -0,0 +1,17 @@ +class Solution: + def minOperations(self, nums: List[int]) -> int: + length = len(nums) + min_operations = length + unique_nums = sorted(set(nums)) + right = 0 + + for left in range(len(unique_nums)): + while ( + right < len(unique_nums) + and unique_nums[right] < unique_nums[left] + length + ): + right += 1 + + min_operations = min(min_operations, length - (right - left)) + + return min_operations diff --git a/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.py2 b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.py2 new file mode 100644 index 00000000..83f86a80 --- /dev/null +++ b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.py2 @@ -0,0 +1,18 @@ +class Solution(object): + def minOperations(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + length = len(nums) + min_ops = length + unique_nums = sorted(set(nums)) + right = 0 + + for left in range(len(unique_nums)): + while right < len(unique_nums) and unique_nums[right] < unique_nums[left] + length: + right += 1 + + min_ops = min(min_ops, length - (right - left)) + + return min_ops diff --git a/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.rb b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.rb new file mode 100644 index 00000000..d6162862 --- /dev/null +++ b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.rb @@ -0,0 +1,18 @@ +# @param {Integer[]} nums +# @return {Integer} +def min_operations(nums) + length = nums.length + min_ops = length + unique_nums = nums.uniq.sort + right = 0 + + (0...unique_nums.length).each do |left| + while right < unique_nums.length && unique_nums[right] < unique_nums[left] + length + right += 1 + end + + min_ops = [min_ops, length - (right - left)].min + end + + min_ops +end diff --git a/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.rs b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.rs new file mode 100644 index 00000000..6f138094 --- /dev/null +++ b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn min_operations(nums: Vec) -> i32 { + let length = nums.len() as i32; + let mut min_ops = length; + let mut unique_nums: Vec = nums.iter().cloned().collect::>().into_iter().collect(); + unique_nums.sort(); + let mut right = 0; + + for left in 0..unique_nums.len() { + while right < unique_nums.len() && unique_nums[right] < unique_nums[left] + length { + right += 1; + } + + min_ops = min_ops.min(length - (right as i32 - left as i32)); + } + + min_ops + } +} diff --git a/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.swift b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.swift new file mode 100644 index 00000000..88ffe1ed --- /dev/null +++ b/tests/2001-2500/2009. minimum-number-of-operations-to-make-array-continuous/sol.swift @@ -0,0 +1,18 @@ +class Solution { + func minOperations(_ nums: [Int]) -> Int { + let length = nums.count + var minOps = length + let uniqueNums = Array(Set(nums)).sorted() + var right = 0 + + for left in 0.. a - b); + let right = 0; + + for (let left = 0; left < uniqueNums.length; left++) { + while ( + right < uniqueNums.length && + uniqueNums[right] < uniqueNums[left] + length + ) { + right++; + } + + minOps = Math.min(minOps, length - (right - left)); + } + + return minOps; +} diff --git a/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/manifest.yaml b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/manifest.yaml new file mode 100644 index 00000000..058a1c8d --- /dev/null +++ b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/manifest.yaml @@ -0,0 +1,587 @@ +entry: + id: 2011 + title: "final-value-of-variable-after-performing-operations" + params: + operations: + type: array + items: + type: string + call: + cpp: "Solution().finalValueAfterOperations({operations})" + rust: "Solution::final_value_after_operations({operations})" + python3: "Solution().finalValueAfterOperations({operations})" + python2: "Solution().finalValueAfterOperations({operations})" + ruby: "final_value_after_operations({operations})" + java: "new Solution().finalValueAfterOperations({operations})" + csharp: "new Solution().FinalValueAfterOperations({operations})" + kotlin: "Solution().finalValueAfterOperations({operations})" + go: "finalValueAfterOperations({operations})" + dart: "Solution().finalValueAfterOperations({operations})" + swift: "Solution().finalValueAfterOperations({operations})" + typescript: "finalValueAfterOperations({operations})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().finalValueAfterOperations(operations, {result})" + checker: | + class Checker: + def finalValueAfterOperations(self, operations, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + if not isinstance(operations, list) or not operations: + return False + if any(op not in ("++X", "X++", "--X", "X--") for op in operations): + return False + expected = sum(1 if op[1] == "+" else -1 for op in operations) + return result == expected + +seed: 2011 + +tests: + - name: "example_mixed" + in: + operations: ["--X", "X++", "X++"] + out: 1 + - name: "example_all_increment" + in: + operations: ["++X", "++X", "X++"] + out: 3 + - name: "example_balanced" + in: + operations: ["X++", "++X", "--X", "X--"] + out: 0 + - name: "single_prefix_increment" + in: + operations: ["++X"] + out: 1 + - name: "single_postfix_increment" + in: + operations: ["X++"] + out: 1 + - name: "single_prefix_decrement" + in: + operations: ["--X"] + out: -1 + - name: "single_postfix_decrement" + in: + operations: ["X--"] + out: -1 + - name: "two_same_prefix_increments" + in: + operations: ["++X", "++X"] + out: 2 + - name: "two_same_postfix_decrements" + in: + operations: ["X--", "X--"] + out: -2 + - name: "one_of_each" + in: + operations: ["++X", "X++", "--X", "X--"] + out: 0 + - name: "alternating_increments_decrements" + in: + operations: ["++X", "--X", "X++", "X--", "++X", "X--"] + out: 0 + - name: "mostly_increments" + in: + operations: ["++X", "X++", "++X", "X++", "--X"] + out: 3 + - name: "mostly_decrements" + in: + operations: ["--X", "X--", "--X", "X--", "X++"] + out: -3 + - name: "prefix_only_balanced" + in: + operations: ["++X", "--X", "++X", "--X", "++X", "--X"] + out: 0 + - name: "postfix_only_positive" + in: + operations: ["X++", "X++", "X++", "X++", "X++"] + out: 5 + - name: "postfix_only_negative" + in: + operations: ["X--", "X--", "X--", "X--", "X--"] + out: -5 + - name: "alternating_prefixes" + in: + operations: ["++X", "--X", "++X", "--X", "++X", "--X", "++X"] + out: 1 + - name: "alternating_postfixes" + in: + operations: ["X++", "X--", "X++", "X--", "X++", "X--", "X++", "X--"] + out: 0 + - name: "negative_then_recover" + in: + operations: ["--X", "X--", "--X", "++X", "X++", "++X", "X++"] + out: 1 + - name: "positive_then_fall" + in: + operations: ["++X", "X++", "++X", "X--", "--X", "X--"] + out: 0 + - name: "long_cycle" + in: + operations: + ["++X", "X++", "--X", "X--", "X++", "++X", "X--", "--X", "++X", "X++"] + out: 2 + - name: "all_four_repeated_twice" + in: + operations: ["++X", "X++", "--X", "X--", "++X", "X++", "--X", "X--"] + out: 0 + - name: "three_increments_one_decrement" + in: + operations: ["++X", "X++", "++X", "X--"] + out: 2 + - name: "one_increment_three_decrements" + in: + operations: ["--X", "X--", "--X", "X++"] + out: -2 + - name: "prefix_increment_postfix_decrement" + in: + operations: ["++X", "X--", "++X", "X--", "++X"] + out: 1 + - name: "prefix_decrement_postfix_increment" + in: + operations: ["--X", "X++", "--X", "X++", "--X"] + out: -1 + - name: "ten_balanced" + in: + operations: + ["++X", "--X", "X++", "X--", "++X", "--X", "X++", "X--", "++X", "--X"] + out: 0 + - name: "ten_positive" + in: + operations: + ["++X", "X++", "++X", "X++", "++X", "X++", "++X", "X++", "++X", "X++"] + out: 10 + - name: "ten_negative" + in: + operations: + ["--X", "X--", "--X", "X--", "--X", "X--", "--X", "X--", "--X", "X--"] + out: -10 + - name: "eleven_positive_one_negative" + in: + operations: + [ + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "--X", + "++X", + ] + out: 10 + - name: "eleven_negative_one_positive" + in: + operations: + [ + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "X++", + "--X", + ] + out: -10 + - name: "twenty_mixed" + in: + operations: + [ + "++X", + "X++", + "--X", + "X--", + "++X", + "++X", + "X--", + "X++", + "--X", + "++X", + "X++", + "X++", + "--X", + "X--", + "++X", + "X++", + "--X", + "--X", + "++X", + "X++", + ] + out: 4 + - name: "twenty_one_balanced" + in: + operations: + [ + "++X", + "X++", + "--X", + "X--", + "++X", + "X++", + "--X", + "X--", + "++X", + "X++", + "--X", + "X--", + "++X", + "X++", + "--X", + "X--", + "++X", + "X++", + "--X", + "X--", + "++X", + "--X", + ] + out: 0 + - name: "twenty_five_positive" + in: + operations: + [ + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + ] + out: 25 + - name: "twenty_five_negative" + in: + operations: + [ + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + ] + out: -25 + - name: "fifty_balanced" + in: + operations: + [ + "++X", + "--X", + "X++", + "X--", + "++X", + "--X", + "X++", + "X--", + "++X", + "--X", + "X++", + "X--", + "++X", + "--X", + "X++", + "X--", + "++X", + "--X", + "X++", + "X--", + "++X", + "--X", + "X++", + "X--", + "++X", + "--X", + "X++", + "X--", + "++X", + "--X", + "X++", + "X--", + "++X", + "--X", + "X++", + "X--", + "++X", + "--X", + "X++", + "X--", + "++X", + "--X", + "X++", + "X--", + "++X", + "--X", + "X++", + "X--", + "++X", + "--X", + ] + out: 0 + - name: "ninety_nine_positive" + in: + operations: + [ + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + "++X", + "X++", + ] + out: 96 + - name: "one_hundred_maximum_all_decrements" + in: + operations: + [ + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + "--X", + "X--", + ] + out: -104 diff --git a/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.cpp b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.cpp new file mode 100644 index 00000000..05be4260 --- /dev/null +++ b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + int finalValueAfterOperations(vector& operations) { + int result = 0; + for (const string& op : operations) { + result += (op[1] == '+') ? 1 : -1; + } + return result; + } +}; diff --git a/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.cs b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.cs new file mode 100644 index 00000000..51ac7f7f --- /dev/null +++ b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.cs @@ -0,0 +1,9 @@ +public class Solution { + public int FinalValueAfterOperations(string[] operations) { + int result = 0; + foreach (string op in operations) { + result += (op[1] == '+') ? 1 : -1; + } + return result; + } +} diff --git a/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.dart b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.dart new file mode 100644 index 00000000..afb1752a --- /dev/null +++ b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.dart @@ -0,0 +1,5 @@ +class Solution { + int finalValueAfterOperations(List operations) { + return operations.fold(0, (sum, op) => sum + (op[1] == '+' ? 1 : -1)); + } +} diff --git a/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.go b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.go new file mode 100644 index 00000000..fb483780 --- /dev/null +++ b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.go @@ -0,0 +1,11 @@ +func finalValueAfterOperations(operations []string) int { + result := 0 + for _, op := range operations { + if op[1] == '+' { + result++ + } else { + result-- + } + } + return result +} diff --git a/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.java b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.java new file mode 100644 index 00000000..e398aaca --- /dev/null +++ b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.java @@ -0,0 +1,9 @@ +class Solution { + public int finalValueAfterOperations(String[] operations) { + int result = 0; + for (String op : operations) { + result += (op.charAt(1) == '+') ? 1 : -1; + } + return result; + } +} diff --git a/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.kt b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.kt new file mode 100644 index 00000000..3028a3f9 --- /dev/null +++ b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.kt @@ -0,0 +1,7 @@ +class Solution { + fun finalValueAfterOperations(operations: Array): Int { + var result = 0 + for (operation in operations) result += if (operation[1] == '+') 1 else -1 + return result + } +} diff --git a/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.py b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.py new file mode 100644 index 00000000..8b69cee4 --- /dev/null +++ b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.py @@ -0,0 +1,3 @@ +class Solution(object): + def finalValueAfterOperations(self, operations): + return sum(1 if op[1] == "+" else -1 for op in operations) diff --git a/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.py2 b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.py2 new file mode 100644 index 00000000..d7e0620f --- /dev/null +++ b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.py2 @@ -0,0 +1,7 @@ +class Solution(object): + def finalValueAfterOperations(self, operations): + """ + :type operations: List[str] + :rtype: int + """ + return sum(1 if op[1] == '+' else -1 for op in operations) diff --git a/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.rb b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.rb new file mode 100644 index 00000000..66508889 --- /dev/null +++ b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.rb @@ -0,0 +1,5 @@ +# @param {String[]} operations +# @return {Integer} +def final_value_after_operations(operations) + operations.sum { |op| op[1] == '+' ? 1 : -1 } +end diff --git a/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.rs b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.rs new file mode 100644 index 00000000..306f90e2 --- /dev/null +++ b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.rs @@ -0,0 +1,5 @@ +impl Solution { + pub fn final_value_after_operations(operations: Vec) -> i32 { + operations.iter().map(|op| if op.chars().nth(1).unwrap() == '+' { 1 } else { -1 }).sum() + } +} diff --git a/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.swift b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.swift new file mode 100644 index 00000000..91ea3957 --- /dev/null +++ b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.swift @@ -0,0 +1,5 @@ +class Solution { + func finalValueAfterOperations(_ operations: [String]) -> Int { + return operations.reduce(0) { $0 + ($1[$1.index($1.startIndex, offsetBy: 1)] == "+" ? 1 : -1) } + } +} diff --git a/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.ts b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.ts new file mode 100644 index 00000000..616aa3ef --- /dev/null +++ b/tests/2001-2500/2011. final-value-of-variable-after-performing-operations/sol.ts @@ -0,0 +1,3 @@ +function finalValueAfterOperations(operations: string[]): number { + return operations.reduce((sum, op) => sum + (op[1] === "+" ? 1 : -1), 0); +} diff --git a/tests/2001-2500/2012. sum-of-beauty-in-the-array/manifest.yaml b/tests/2001-2500/2012. sum-of-beauty-in-the-array/manifest.yaml new file mode 100644 index 00000000..4175406f --- /dev/null +++ b/tests/2001-2500/2012. sum-of-beauty-in-the-array/manifest.yaml @@ -0,0 +1,266 @@ +entry: + id: 2012 + title: "sum-of-beauty-in-the-array" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().sumOfBeauties({nums})" + rust: "Solution::sum_of_beauties({nums})" + python3: "Solution().sumOfBeauties({nums})" + python2: "Solution().sumOfBeauties({nums})" + ruby: "sum_of_beauties({nums})" + java: "new Solution().sumOfBeauties({nums})" + csharp: "new Solution().SumOfBeauties({nums})" + kotlin: "Solution().sumOfBeauties({nums})" + go: "sumOfBeauties({nums})" + dart: "Solution().sumOfBeauties({nums})" + swift: "Solution().sumOfBeauties({nums})" + typescript: "sumOfBeauties({nums})" +judge: + type: "exact" +limits: + time_ms: 1000 + memory_mb: 300 +oracle: + python3: + call: "Checker().sumOfBeauties(nums, {result})" + checker: | + class Checker: + def sumOfBeauties(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + n = len(nums) + prefix = [0] * n + suffix = [0] * n + prefix[0] = nums[0] + suffix[n - 1] = nums[n - 1] + for i in range(1, n): + prefix[i] = max(prefix[i - 1], nums[i - 1]) + for i in range(n - 2, -1, -1): + suffix[i] = min(suffix[i + 1], nums[i + 1]) + total = 0 + for i in range(1, len(nums) - 1): + if prefix[i] < nums[i] < suffix[i]: + total += 2 + elif nums[i - 1] < nums[i] < nums[i + 1]: + total += 1 + return result == total +seed: 2012 +tests: + - name: "ex1" + in: + nums: [1, 2, 3] + out: 2 + - name: "ex2" + in: + nums: [2, 4, 6, 4] + out: 1 + - name: "ex3" + in: + nums: [3, 2, 1] + out: 0 + - name: "all_equal" + in: + nums: [1, 1, 1] + out: 0 + - name: "equal_breaks_increase" + in: + nums: [1, 2, 2, 3] + out: 0 + - name: "strict_decrease" + in: + nums: [5, 4, 3, 2, 1] + out: 0 + - name: "mixed_beauty" + in: + nums: [1, 3, 2, 4, 5] + out: 2 + - name: "strict_increase" + in: + nums: [1, 2, 3, 4, 5] + out: 6 + - name: "valley_then_increase" + in: + nums: [5, 4, 5, 6, 7] + out: 3 + - name: "alternating_peaks" + in: + nums: [1, 5, 3, 4, 2, 6] + out: 0 + - name: "prefix_plateau" + in: + nums: [2, 2, 3, 4, 5, 1] + out: 2 + - name: "local_only" + in: + nums: [1, 4, 2, 3, 5] + out: 1 + - name: "high_middle_with_tail" + in: + nums: [10, 20, 30, 25, 40, 50] + out: 4 + - name: "three_peak" + in: + nums: [1, 100, 2] + out: 0 + - name: "three_valley" + in: + nums: [100, 1, 100] + out: 0 + - name: "short_alternating" + in: + nums: [1, 2, 1, 2, 1] + out: 0 + - name: "long_increase" + in: + nums: [3, 5, 7, 9, 11, 13] + out: 8 + - name: "long_decrease" + in: + nums: [13, 11, 9, 7, 5, 3] + out: 0 + - name: "two_rises" + in: + nums: [1, 3, 5, 4, 6, 8, 7, 9] + out: 4 + - name: "sawtooth_low" + in: + nums: [2, 1, 3, 2, 4, 3, 5] + out: 0 + - name: "low_prefix_then_rise" + in: + nums: [4, 1, 2, 3, 5, 6] + out: 4 + - name: "rise_with_dip" + in: + nums: [1, 4, 7, 6, 8, 10] + out: 4 + - name: "dip_then_rise" + in: + nums: [10, 8, 6, 7, 9, 11] + out: 2 + - name: "rises_with_dips" + in: + nums: [1, 2, 4, 3, 5, 7, 6] + out: 4 + - name: "decreasing_seven" + in: + nums: [7, 6, 5, 4, 3, 2, 1] + out: 0 + - name: "alternating_extremes" + in: + nums: [1, 10, 2, 9, 3, 8, 4, 7, 5] + out: 0 + - name: "repeated_saw" + in: + nums: [2, 3, 1, 4, 2, 5, 3, 6] + out: 0 + - name: "duplicate_ranks" + in: + nums: [1, 1, 2, 2, 3, 3, 4] + out: 0 + - name: "decreasing_duplicates" + in: + nums: [4, 4, 3, 3, 2, 2, 1] + out: 0 + - name: "small_waves" + in: + nums: [1, 2, 3, 2, 3, 4, 3, 4] + out: 2 + - name: "large_jumps" + in: + nums: [6, 1, 5, 2, 4, 3, 7] + out: 0 + - name: "duplicate_middle" + in: + nums: [1, 3, 2, 2, 4, 1, 5] + out: 0 + - name: "mixed_seven" + in: + nums: [2, 5, 4, 6, 3, 7, 1] + out: 0 + - name: "near_max_peak" + in: + nums: [1, 100000, 99999, 100000] + out: 0 + - name: "near_max_valley" + in: + nums: [99999, 100000, 1] + out: 0 + - name: "generated_small" + seed: 201201 + in: + nums: + gen: "array" + len: + gen: "int" + min: 3 + max: 30 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_medium" + seed: 201202 + in: + nums: + gen: "array" + len: + gen: "int" + min: 100 + max: 500 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_large_a" + seed: 201203 + in: + nums: + gen: "array" + len: 50000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_large_b" + seed: 201204 + in: + nums: + gen: "array" + len: 100000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" + - name: "generated_large_c" + seed: 201205 + in: + nums: + gen: "array" + len: + gen: "int" + min: 90000 + max: 100000 + of: + gen: "int" + min: 1 + max: 100000 + distinct: false + sorted: false + elemType: "int" diff --git a/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.cpp b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.cpp new file mode 100644 index 00000000..785c2ad1 --- /dev/null +++ b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int sumOfBeauties(vector& nums) { + int n = nums.size(); + vector prefix(n), suffix(n); + prefix[0] = nums[0]; + suffix[n-1] = nums[n-1]; + for (int i = 1; i < n; i++) { + prefix[i] = max(nums[i-1], prefix[i-1]); + } + for (int i = n-2; i >= 0; i--) { + suffix[i] = min(nums[i+1], suffix[i+1]); + } + int ans = 0; + for (int i = 1; i < n-1; i++) { + if (prefix[i] < nums[i] && nums[i] < suffix[i]) { + ans += 2; + } else if (nums[i-1] < nums[i] && nums[i] < nums[i+1]) { + ans += 1; + } + } + return ans; + } +}; diff --git a/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.cs b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.cs new file mode 100644 index 00000000..778e7890 --- /dev/null +++ b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.cs @@ -0,0 +1,24 @@ +public class Solution { + public int SumOfBeauties(int[] nums) { + int n = nums.Length; + int[] prefix = new int[n]; + int[] suffix = new int[n]; + prefix[0] = nums[0]; + suffix[n-1] = nums[n-1]; + for (int i = 1; i < n; i++) { + prefix[i] = Math.Max(nums[i-1], prefix[i-1]); + } + for (int i = n-2; i >= 0; i--) { + suffix[i] = Math.Min(nums[i+1], suffix[i+1]); + } + int ans = 0; + for (int i = 1; i < n-1; i++) { + if (prefix[i] < nums[i] && nums[i] < suffix[i]) { + ans += 2; + } else if (nums[i-1] < nums[i] && nums[i] < nums[i+1]) { + ans += 1; + } + } + return ans; + } +} diff --git a/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.dart b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.dart new file mode 100644 index 00000000..cdf11762 --- /dev/null +++ b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.dart @@ -0,0 +1,24 @@ +class Solution { + int sumOfBeauties(List nums) { + int n = nums.length; + List prefix = List.filled(n, 0); + List suffix = List.filled(n, 0); + prefix[0] = nums[0]; + suffix[n-1] = nums[n-1]; + for (int i = 1; i < n; i++) { + prefix[i] = (nums[i-1] > prefix[i-1]) ? nums[i-1] : prefix[i-1]; + } + for (int i = n-2; i >= 0; i--) { + suffix[i] = (nums[i+1] < suffix[i+1]) ? nums[i+1] : suffix[i+1]; + } + int ans = 0; + for (int i = 1; i < n-1; i++) { + if (prefix[i] < nums[i] && nums[i] < suffix[i]) { + ans += 2; + } else if (nums[i-1] < nums[i] && nums[i] < nums[i+1]) { + ans += 1; + } + } + return ans; + } +} diff --git a/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.go b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.go new file mode 100644 index 00000000..7d217edb --- /dev/null +++ b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.go @@ -0,0 +1,30 @@ +func sumOfBeauties(nums []int) int { + n := len(nums) + prefix := make([]int, n) + suffix := make([]int, n) + prefix[0] = nums[0] + suffix[n-1] = nums[n-1] + for i := 1; i < n; i++ { + if nums[i-1] > prefix[i-1] { + prefix[i] = nums[i-1] + } else { + prefix[i] = prefix[i-1] + } + } + for i := n-2; i >= 0; i-- { + if nums[i+1] < suffix[i+1] { + suffix[i] = nums[i+1] + } else { + suffix[i] = suffix[i+1] + } + } + ans := 0 + for i := 1; i < n-1; i++ { + if prefix[i] < nums[i] && nums[i] < suffix[i] { + ans += 2 + } else if nums[i-1] < nums[i] && nums[i] < nums[i+1] { + ans += 1 + } + } + return ans +} diff --git a/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.java b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.java new file mode 100644 index 00000000..d60cdd08 --- /dev/null +++ b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.java @@ -0,0 +1,24 @@ +class Solution { + public int sumOfBeauties(int[] nums) { + int n = nums.length; + int[] prefix = new int[n]; + int[] suffix = new int[n]; + prefix[0] = nums[0]; + suffix[n-1] = nums[n-1]; + for (int i = 1; i < n; i++) { + prefix[i] = Math.max(nums[i-1], prefix[i-1]); + } + for (int i = n-2; i >= 0; i--) { + suffix[i] = Math.min(nums[i+1], suffix[i+1]); + } + int ans = 0; + for (int i = 1; i < n-1; i++) { + if (prefix[i] < nums[i] && nums[i] < suffix[i]) { + ans += 2; + } else if (nums[i-1] < nums[i] && nums[i] < nums[i+1]) { + ans += 1; + } + } + return ans; + } +} diff --git a/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.kt b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.kt new file mode 100644 index 00000000..703046b3 --- /dev/null +++ b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.kt @@ -0,0 +1,24 @@ +class Solution { + fun sumOfBeauties(nums: IntArray): Int { + val n = nums.size + val prefix = IntArray(n) + val suffix = IntArray(n) + prefix[0] = nums[0] + suffix[n-1] = nums[n-1] + for (i in 1 until n) { + prefix[i] = maxOf(nums[i-1], prefix[i-1]) + } + for (i in n-2 downTo 0) { + suffix[i] = minOf(nums[i+1], suffix[i+1]) + } + var ans = 0 + for (i in 1 until n-1) { + if (prefix[i] < nums[i] && nums[i] < suffix[i]) { + ans += 2 + } else if (nums[i-1] < nums[i] && nums[i] < nums[i+1]) { + ans += 1 + } + } + return ans + } +} diff --git a/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.py b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.py new file mode 100644 index 00000000..add43c3c --- /dev/null +++ b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.py @@ -0,0 +1,23 @@ +class Solution: + def sumOfBeauties(self, nums: List[int]) -> int: + n = len(nums) + + prefix = [0] * n + suffix = [0] * n + + prefix[0] = nums[0] + suffix[n - 1] = nums[n - 1] + + for i in range(1, n): + prefix[i] = max(nums[i - 1], prefix[i - 1]) + + for i in range(n - 2, -1, -1): + suffix[i] = min(nums[i + 1], suffix[i + 1]) + + ans = 0 + for i in range(1, n - 1): + if prefix[i] < nums[i] < suffix[i]: + ans += 2 + elif nums[i - 1] < nums[i] < nums[i + 1]: + ans += 1 + return ans diff --git a/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.py2 b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.py2 new file mode 100644 index 00000000..5e841ed6 --- /dev/null +++ b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def sumOfBeauties(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + n = len(nums) + prefix = [0]*n + suffix = [0]*n + prefix[0] = nums[0] + suffix[n-1] = nums[n-1] + for i in range(1, n): + prefix[i] = max(nums[i-1], prefix[i-1]) + for i in range(n-2, -1, -1): + suffix[i] = min(nums[i+1], suffix[i+1]) + ans = 0 + for i in range(1, n-1): + if prefix[i] < nums[i] < suffix[i]: + ans += 2 + elif nums[i-1] < nums[i] < nums[i+1]: + ans += 1 + return ans diff --git a/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.rb b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.rb new file mode 100644 index 00000000..fea8e671 --- /dev/null +++ b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.rb @@ -0,0 +1,24 @@ +# @param {Integer[]} nums +# @return {Integer} +def sum_of_beauties(nums) + n = nums.length + prefix = Array.new(n, 0) + suffix = Array.new(n, 0) + prefix[0] = nums[0] + suffix[n-1] = nums[n-1] + (1...n).each do |i| + prefix[i] = [nums[i-1], prefix[i-1]].max + end + (n-2).downto(0) do |i| + suffix[i] = [nums[i+1], suffix[i+1]].min + end + ans = 0 + (1...n-1).each do |i| + if prefix[i] < nums[i] && nums[i] < suffix[i] + ans += 2 + elsif nums[i-1] < nums[i] && nums[i] < nums[i+1] + ans += 1 + end + end + ans +end diff --git a/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.rs b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.rs new file mode 100644 index 00000000..061b7245 --- /dev/null +++ b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn sum_of_beauties(nums: Vec) -> i32 { + let n = nums.len(); + let mut prefix = vec![0; n]; + let mut suffix = vec![0; n]; + prefix[0] = nums[0]; + suffix[n-1] = nums[n-1]; + for i in 1..n { + prefix[i] = nums[i-1].max(prefix[i-1]); + } + for i in (0..n-1).rev() { + suffix[i] = nums[i+1].min(suffix[i+1]); + } + let mut ans = 0; + for i in 1..n-1 { + if prefix[i] < nums[i] && nums[i] < suffix[i] { + ans += 2; + } else if nums[i-1] < nums[i] && nums[i] < nums[i+1] { + ans += 1; + } + } + ans + } +} diff --git a/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.swift b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.swift new file mode 100644 index 00000000..41ceaa74 --- /dev/null +++ b/tests/2001-2500/2012. sum-of-beauty-in-the-array/sol.swift @@ -0,0 +1,24 @@ +class Solution { + func sumOfBeauties(_ nums: [Int]) -> Int { + let n = nums.count + var prefix = [Int](repeating: 0, count: n) + var suffix = [Int](repeating: 0, count: n) + prefix[0] = nums[0] + suffix[n-1] = nums[n-1] + for i in 1..= 0; i--) { + suffix[i] = Math.min(nums[i + 1], suffix[i + 1]); + } + let ans = 0; + for (let i = 1; i < n - 1; i++) { + if (prefix[i] < nums[i] && nums[i] < suffix[i]) { + ans += 2; + } else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) { + ans += 1; + } + } + return ans; +} diff --git a/tests/2001-2500/2014. longest-subsequence-repeated-k-times/manifest.yaml b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/manifest.yaml new file mode 100644 index 00000000..16b0d7a0 --- /dev/null +++ b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/manifest.yaml @@ -0,0 +1,267 @@ +entry: + id: 2014 + title: "longest-subsequence-repeated-k-times" + params: + s: + type: string + k: + type: int + call: + cpp: "Solution().longestSubsequenceRepeatedK({s}, {k})" + rust: "Solution::longest_subsequence_repeated_k({s}, {k})" + python3: "Solution().longestSubsequenceRepeatedK({s}, {k})" + python2: "Solution().longestSubsequenceRepeatedK({s}, {k})" + ruby: "longest_subsequence_repeated_k({s}, {k})" + java: "new Solution().longestSubsequenceRepeatedK({s}, {k})" + csharp: "new Solution().LongestSubsequenceRepeatedK({s}, {k})" + kotlin: "Solution().longestSubsequenceRepeatedK({s}, {k})" + go: "longestSubsequenceRepeatedK({s}, {k})" + dart: "Solution().longestSubsequenceRepeatedK({s}, {k})" + swift: "Solution().longestSubsequenceRepeatedK({s}, {k})" + typescript: "longestSubsequenceRepeatedK({s}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 512 + +oracle: + python3: + call: "Checker().longestSubsequenceRepeatedK(s, k, {result})" + checker: | + class Checker: + def longestSubsequenceRepeatedK(self, s, k, result): + if not isinstance(result, str): + return False + def repeated(candidate): + if not candidate: + return True + pos = 0 + completed = 0 + for ch in s: + if ch == candidate[pos]: + pos += 1 + if pos == len(candidate): + pos = 0 + completed += 1 + if completed == k: + return True + return False + if not repeated(result): + return False + best = result + counts = {ch: s.count(ch) // k for ch in set(s)} + limit = min(len(s) // k, 8) + candidates = [""] + best_candidate = "" + for _ in range(limit): + candidates = [prefix + ch for prefix in candidates for ch in "abcdefghijklmnopqrstuvwxyz" if repeated(prefix + ch)] + if not candidates: + break + best_candidate = max(candidates, key=lambda x: (len(x), x)) + expected = best_candidate + return result == expected + +seed: 2014 + +tests: + - name: "example_letsleetcode" + in: + s: "letsleetcode" + k: 2 + out: "let" + - name: "example_bb" + in: + s: "bb" + k: 2 + out: "b" + - name: "example_ab" + in: + s: "ab" + k: 2 + out: "" + - name: "single_repeated_letter" + in: + s: "aaaaaa" + k: 3 + out: "aa" + - name: "lexicographic_tie" + in: + s: "ababab" + k: 2 + out: "ba" + - name: "descending_letters" + in: + s: "zyxzyx" + k: 2 + out: "zyx" + - name: "no_character_enough" + in: + s: "abc" + k: 3 + out: "" + - name: "two_distinct_pairs" + in: + s: "aabb" + k: 2 + out: "b" + - name: "lexicographically_larger_pair" + in: + s: "zzayzay" + k: 2 + out: "zay" + - name: "repeated_noncontiguous" + in: + s: "baxbax" + k: 2 + out: "bax" + - name: "interleaved_letters" + in: + s: "abcabcabc" + k: 3 + out: "abc" + - name: "same_counts_order_matters" + in: + s: "acbacb" + k: 2 + out: "acb" + - name: "large_k_one_letter" + in: + s: "" + k: 2 + out: "" + - name: "alternating" + in: + s: "abababab" + k: 4 + out: "ab" + - name: "four_letter_blocks" + in: + s: "abcdabcd" + k: 2 + out: "abcd" + - name: "lexicographic_choice" + in: + s: "cabacaba" + k: 2 + out: "caba" + - name: "sparse_high_letter" + in: + s: "azazaz" + k: 3 + out: "az" + - name: "duplicates_break_order" + in: + s: "aababa" + k: 2 + out: "ba" + - name: "minimum_length" + in: + s: "aa" + k: 2 + out: "a" + - name: "long_uniform" + in: + s: "bbbbbbbbbbbbbbbbbbbb" + k: 5 + out: "bbbb" + - name: "long_pattern" + in: + s: "xyzxyzxyzxyz" + k: 4 + out: "xyz" + - name: "many_unused_letters" + in: + s: "qwertyqwerty" + k: 2 + out: "qwerty" + - name: "reverse_pattern" + in: + s: "cbacba" + k: 2 + out: "cba" + - name: "mixed_runs" + in: + s: "aaabbbccc" + k: 3 + out: "c" + - name: "five_repetitions" + in: + s: "abcabcabcabcabc" + k: 5 + out: "abc" + - name: "only_one_repeatable" + in: + s: "abac" + k: 2 + out: "a" + - name: "high_frequency_tail" + in: + s: "abczzzzabc" + k: 2 + out: "abc" + - name: "alternating_three" + in: + s: "abcabc" + k: 2 + out: "abc" + - name: "large_uniform_two" + in: + s: "cccccccccccccccccccccccc" + k: 2 + out: "cccccccccccc" + - name: "four_repetitions" + in: + s: "abcdabcdabcdabcd" + k: 4 + out: "abcd" + - name: "empty_result_large_k" + in: + s: "abcdefghijklmnop" + k: 16 + out: "" + - name: "generator_small" + seed: 101 + in: + s: + gen: "str" + len: + gen: "int" + min: 2 + max: 15 + alphabet: "abc" + k: 2 + - name: "generator_medium" + seed: 102 + in: + s: + gen: "str" + len: 31 + alphabet: "abcd" + k: 4 + - name: "generator_uniform_stress" + seed: 103 + in: + s: + gen: "str" + len: 1000 + alphabet: "a" + k: 125 + - name: "generator_binary_stress" + seed: 104 + in: + s: + gen: "str" + len: 1000 + alphabet: "ab" + k: 125 + - name: "generator_large_k_stress" + seed: 105 + in: + s: + gen: "str" + len: 1999 + alphabet: "abcde" + k: 250 diff --git a/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.cpp b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.cpp new file mode 100644 index 00000000..16a412f0 --- /dev/null +++ b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + string longestSubsequenceRepeatedK(string s, int k) { + auto isK = [&](const string& sub, const string& t, int k) { + int count = 0; + int i = 0; + for (char ch : t) { + if (i < sub.size() && ch == sub[i]) { + i++; + if (i == sub.size()) { + i = 0; + count++; + if (count == k) return true; + } + } + } + return false; + }; + + string res = ""; + queue q; + q.push(""); + while (!q.empty()) { + string curr = q.front(); + q.pop(); + for (char ch = 'a'; ch <= 'z'; ch++) { + string nxt = curr + ch; + if (isK(nxt, s, k)) { + res = nxt; + q.push(nxt); + } + } + } + return res; + } +}; diff --git a/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.cs b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.cs new file mode 100644 index 00000000..87c7875c --- /dev/null +++ b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.cs @@ -0,0 +1,36 @@ +using System.Collections.Generic; + +public class Solution { + public string LongestSubsequenceRepeatedK(string s, int k) { + bool IsK(string sub, string t, int k) { + int count = 0; + int i = 0; + foreach (char ch in t) { + if (i < sub.Length && ch == sub[i]) { + i++; + if (i == sub.Length) { + i = 0; + count++; + if (count == k) return true; + } + } + } + return false; + } + + string res = ""; + Queue q = new Queue(); + q.Enqueue(""); + while (q.Count > 0) { + string curr = q.Dequeue(); + for (char ch = 'a'; ch <= 'z'; ch++) { + string nxt = curr + ch; + if (IsK(nxt, s, k)) { + res = nxt; + q.Enqueue(nxt); + } + } + } + return res; + } +} diff --git a/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.dart b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.dart new file mode 100644 index 00000000..311a98cb --- /dev/null +++ b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.dart @@ -0,0 +1,33 @@ +class Solution { + String longestSubsequenceRepeatedK(String s, int k) { + bool isK(String sub, String t, int k) { + int count = 0; + int i = 0; + for (int idx = 0; idx < t.length; idx++) { + if (i < sub.length && t[idx] == sub[i]) { + i++; + if (i == sub.length) { + i = 0; + count++; + if (count == k) return true; + } + } + } + return false; + } + + String res = ""; + List q = [""]; + while (q.isNotEmpty) { + String curr = q.removeAt(0); + for (int c = 97; c <= 122; c++) { + String nxt = curr + String.fromCharCode(c); + if (isK(nxt, s, k)) { + res = nxt; + q.add(nxt); + } + } + } + return res; + } +} diff --git a/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.go b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.go new file mode 100644 index 00000000..80356d01 --- /dev/null +++ b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.go @@ -0,0 +1,34 @@ +func longestSubsequenceRepeatedK(s string, k int) string { + isK := func(sub string, t string) bool { + count := 0 + i := 0 + for _, ch := range t { + if i < len(sub) && byte(ch) == sub[i] { + i++ + if i == len(sub) { + i = 0 + count++ + if count == k { + return true + } + } + } + } + return false + } + + res := "" + q := []string{""} + for len(q) > 0 { + curr := q[0] + q = q[1:] + for ch := 'a'; ch <= 'z'; ch++ { + nxt := curr + string(ch) + if isK(nxt, s) { + res = nxt + q = append(q, nxt) + } + } + } + return res +} diff --git a/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.java b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.java new file mode 100644 index 00000000..3bc84cd8 --- /dev/null +++ b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.java @@ -0,0 +1,36 @@ +import java.util.*; + +class Solution { + private boolean isK(String sub, String t, int k) { + int count = 0; + int i = 0; + for (char ch : t.toCharArray()) { + if (i < sub.length() && ch == sub.charAt(i)) { + i++; + if (i == sub.length()) { + i = 0; + count++; + if (count == k) return true; + } + } + } + return false; + } + + public String longestSubsequenceRepeatedK(String s, int k) { + String res = ""; + Queue q = new LinkedList<>(); + q.offer(""); + while (!q.isEmpty()) { + String curr = q.poll(); + for (char ch = 'a'; ch <= 'z'; ch++) { + String nxt = curr + ch; + if (isK(nxt, s, k)) { + res = nxt; + q.offer(nxt); + } + } + } + return res; + } +} diff --git a/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.kt b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.kt new file mode 100644 index 00000000..ad1aded8 --- /dev/null +++ b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.kt @@ -0,0 +1,34 @@ +class Solution { + fun longestSubsequenceRepeatedK(s: String, k: Int): String { + fun isK(sub: String, t: String, k: Int): Boolean { + var count = 0 + var i = 0 + for (ch in t) { + if (i < sub.length && ch == sub[i]) { + i++ + if (i == sub.length) { + i = 0 + count++ + if (count == k) return true + } + } + } + return false + } + + var res = "" + val q = ArrayDeque() + q.add("") + while (q.isNotEmpty()) { + val curr = q.removeFirst() + for (ch in 'a'..'z') { + val nxt = curr + ch + if (isK(nxt, s, k)) { + res = nxt + q.add(nxt) + } + } + } + return res + } +} diff --git a/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.py b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.py new file mode 100644 index 00000000..dd5ef72c --- /dev/null +++ b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.py @@ -0,0 +1,24 @@ +class Solution: + def longestSubsequenceRepeatedK(self, s: str, k: int) -> str: + def isK(sub: str, t: str, k: int) -> bool: + count = i = 0 + for ch in t: + if i < len(sub) and ch == sub[i]: + i += 1 + if i == len(sub): + i = 0 + count += 1 + if count == k: + return True + return False + + res = "" + q = deque([""]) + while q: + curr = q.popleft() + for ch in map(chr, range(ord("a"), ord("z") + 1)): + nxt = curr + ch + if isK(nxt, s, k): + res = nxt + q.append(nxt) + return res diff --git a/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.py2 b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.py2 new file mode 100644 index 00000000..ad96e2be --- /dev/null +++ b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.py2 @@ -0,0 +1,30 @@ +class Solution(object): + def longestSubsequenceRepeatedK(self, s, k): + """ + :type s: str + :type k: int + :rtype: str + """ + def isK(sub, t, k): + count = 0 + i = 0 + for ch in t: + if i < len(sub) and ch == sub[i]: + i += 1 + if i == len(sub): + i = 0 + count += 1 + if count == k: + return True + return False + + res = "" + q = [""] + while q: + curr = q.pop(0) + for ch in map(chr, range(ord('a'), ord('z') + 1)): + nxt = curr + ch + if isK(nxt, s, k): + res = nxt + q.append(nxt) + return res diff --git a/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.rb b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.rb new file mode 100644 index 00000000..a1cfdaed --- /dev/null +++ b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.rb @@ -0,0 +1,34 @@ +# @param {String} s +# @param {Integer} k +# @return {String} +def longest_subsequence_repeated_k(s, k) + def is_k(sub, t, k) + count = 0 + i = 0 + t.each_char do |ch| + if i < sub.length && ch == sub[i] + i += 1 + if i == sub.length + i = 0 + count += 1 + return true if count == k + end + end + end + false + end + + res = "" + q = [""] + while !q.empty? + curr = q.shift + ('a'..'z').each do |ch| + nxt = curr + ch + if is_k(nxt, s, k) + res = nxt + q << nxt + end + end + end + res +end diff --git a/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.rs b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.rs new file mode 100644 index 00000000..8a02eddb --- /dev/null +++ b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.rs @@ -0,0 +1,36 @@ +impl Solution { + pub fn longest_subsequence_repeated_k(s: String, k: i32) -> String { + fn is_k(sub: &str, t: &str, k: usize) -> bool { + let sub_chars: Vec = sub.chars().collect(); + let mut count = 0; + let mut i = 0; + for ch in t.chars() { + if i < sub_chars.len() && ch == sub_chars[i] { + i += 1; + if i == sub_chars.len() { + i = 0; + count += 1; + if count == k { + return true; + } + } + } + } + false + } + + let mut res = String::new(); + let mut q: std::collections::VecDeque = std::collections::VecDeque::from([String::new()]); + while let Some(curr) = q.pop_front() { + for c in 97u8..=122u8 { + let mut nxt = curr.clone(); + nxt.push(c as char); + if is_k(&nxt, &s, k as usize) { + res = nxt.clone(); + q.push_back(nxt); + } + } + } + res + } +} diff --git a/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.swift b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.swift new file mode 100644 index 00000000..89aace09 --- /dev/null +++ b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.swift @@ -0,0 +1,37 @@ +class Solution { + func longestSubsequenceRepeatedK(_ s: String, _ k: Int) -> String { + func isK(_ sub: String, _ t: String, _ k: Int) -> Bool { + let subArr = Array(sub) + let tArr = Array(t) + var count = 0 + var i = 0 + for ch in tArr { + if i < subArr.count && ch == subArr[i] { + i += 1 + if i == subArr.count { + i = 0 + count += 1 + if count == k { + return true + } + } + } + } + return false + } + + var res = "" + var q: [String] = [""] + while !q.isEmpty { + let curr = q.removeFirst() + for c in 97...122 { + let nxt = curr + String(UnicodeScalar(c)!) + if isK(nxt, s, k) { + res = nxt + q.append(nxt) + } + } + } + return res + } +} diff --git a/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.ts b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.ts new file mode 100644 index 00000000..9d546d6e --- /dev/null +++ b/tests/2001-2500/2014. longest-subsequence-repeated-k-times/sol.ts @@ -0,0 +1,31 @@ +function longestSubsequenceRepeatedK(s: string, k: number): string { + function isK(sub: string, t: string, k: number): boolean { + let count = 0; + let i = 0; + for (const ch of t) { + if (i < sub.length && ch === sub[i]) { + i++; + if (i === sub.length) { + i = 0; + count++; + if (count === k) return true; + } + } + } + return false; + } + + let res = ""; + const q: string[] = [""]; + while (q.length > 0) { + const curr = q.shift()!; + for (let c = 97; c <= 122; c++) { + const nxt = curr + String.fromCharCode(c); + if (isK(nxt, s, k)) { + res = nxt; + q.push(nxt); + } + } + } + return res; +} diff --git a/tests/2001-2500/2016. maximum-difference-between-increasing-elements/manifest.yaml b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/manifest.yaml new file mode 100644 index 00000000..50e61db0 --- /dev/null +++ b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/manifest.yaml @@ -0,0 +1,265 @@ +entry: + id: 2016 + title: "maximum-difference-between-increasing-elements" + params: + nums: + type: array + items: + type: int + call: + cpp: "Solution().maximumDifference({nums})" + rust: "Solution::maximum_difference({nums})" + python3: "Solution().maximumDifference({nums})" + python2: "Solution().maximumDifference({nums})" + ruby: "maximum_difference({nums})" + java: "new Solution().maximumDifference({nums})" + csharp: "new Solution().MaximumDifference({nums})" + kotlin: "Solution().maximumDifference({nums})" + go: "maximumDifference({nums})" + dart: "Solution().maximumDifference({nums})" + swift: "Solution().maximumDifference({nums})" + typescript: "maximumDifference({nums})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().maximumDifference(nums, {result})" + checker: | + class Checker: + def maximumDifference(self, nums, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + best = -1 + minimum = nums[0] + for value in nums[1:]: + if value > minimum: + best = max(best, value - minimum) + else: + minimum = value + return result == best + +seed: 2016 + +tests: + - name: "example_1" + in: + nums: [7, 1, 5, 4] + out: 4 + - name: "example_2_no_increase" + in: + nums: [9, 4, 3, 2] + out: -1 + - name: "example_3" + in: + nums: [1, 5, 2, 10] + out: 9 + - name: "minimum_length_increase" + in: + nums: [1, 2] + out: 1 + - name: "minimum_length_decrease" + in: + nums: [2, 1] + out: -1 + - name: "equal_values" + in: + nums: [5, 5, 5, 5] + out: -1 + - name: "increase_at_end" + in: + nums: [8, 7, 6, 1, 20] + out: 19 + - name: "increase_at_start" + in: + nums: [1, 100, 3, 2] + out: 99 + - name: "minimum_replaced_multiple_times" + in: + nums: [10, 1, 2, 0, 9] + out: 9 + - name: "small_positive_steps" + in: + nums: [1, 2, 3, 4, 5] + out: 4 + - name: "strictly_decreasing" + in: + nums: [10, 9, 8, 7, 6, 5] + out: -1 + - name: "late_best_pair" + in: + nums: [20, 3, 8, 2, 4, 15] + out: 13 + - name: "early_minimum_then_plateau" + in: + nums: [1, 1, 1, 7] + out: 6 + - name: "large_values_two" + in: + nums: [1000000000, 1, 999999999] + out: 999999998 + - name: "large_values_in_order" + in: + nums: [1, 500000000, 1000000000] + out: 999999999 + - name: "large_equal_then_increase" + in: + nums: [1000000000, 999999999, 999999999, 1000000000] + out: 1 + - name: "negative_result_avoided" + in: + nums: [6, 4, 5, 3, 2, 1] + out: 1 + - name: "alternating_values" + in: + nums: [5, 1, 6, 2, 7, 3, 8] + out: 7 + - name: "multiple_record_highs" + in: + nums: [4, 6, 5, 9, 3, 12] + out: 9 + - name: "minimum_at_middle" + in: + nums: [20, 15, 1, 2, 3, 4] + out: 3 + - name: "minimum_at_last_no_pair" + in: + nums: [4, 3, 2, 1] + out: -1 + - name: "single_record_after_drop" + in: + nums: [100, 50, 40, 41] + out: 1 + - name: "duplicate_minimum" + in: + nums: [3, 1, 1, 10] + out: 9 + - name: "duplicate_maximum" + in: + nums: [1, 10, 10, 2] + out: 9 + - name: "large_drop_then_gain" + in: + nums: [500000000, 400000000, 300000000, 1, 999999999] + out: 999999998 + - name: "long_small_pattern" + in: + nums: [9, 2, 8, 1, 7, 3, 6, 4, 5] + out: 6 + - name: "strictly_increasing_large_gap" + in: + nums: [2, 4, 8, 16, 32, 64] + out: 62 + - name: "all_values_near_limit" + in: + nums: [999999990, 999999991, 999999995, 1000000000] + out: 10 + - name: "best_before_final_drop" + in: + nums: [2, 50, 3, 40, 1] + out: 48 + - name: "smallest_value_reappears" + in: + nums: [4, 2, 9, 2, 8] + out: 7 + - name: "no_increase_with_duplicates" + in: + nums: [7, 6, 6, 5, 5, 4] + out: -1 + - name: "best_pair_not_global_extremes" + in: + nums: [8, 3, 7, 2, 6, 1, 5] + out: 4 + - name: "value_one_to_limit" + in: + nums: [1, 2, 1000000000] + out: 999999999 + - name: "three_values_drop_then_rise" + in: + nums: [100, 1, 2] + out: 1 + - name: "repeated_high_low" + in: + nums: [10, 2, 9, 1, 8, 0, 7] + out: 7 + - name: "late_equal_minimum" + in: + nums: [5, 10, 3, 3, 9] + out: 6 + - name: "generated_small" + seed: 201601 + in: + nums: + gen: "array" + len: + gen: "int" + min: 2 + max: 20 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + - name: "generated_medium" + seed: 201602 + in: + nums: + gen: "array" + len: + gen: "int" + min: 100 + max: 300 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + - name: "generated_max_length" + seed: 201603 + in: + nums: + gen: "array" + len: 1000 + of: + gen: "int" + min: 1 + max: 1000000000 + distinct: false + sorted: false + - name: "generated_near_max_values" + seed: 201604 + in: + nums: + gen: "array" + len: + gen: "int" + min: 700 + max: 1000 + of: + gen: "int" + min: 999000000 + max: 1000000000 + distinct: false + sorted: false + - name: "generated_small_value_range" + seed: 201605 + in: + nums: + gen: "array" + len: + gen: "int" + min: 500 + max: 1000 + of: + gen: "int" + min: 1 + max: 100 + distinct: false + sorted: false diff --git a/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.cpp b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.cpp new file mode 100644 index 00000000..f1791960 --- /dev/null +++ b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int maximumDifference(vector& nums) { + int minVal = nums[0]; + int maxDiff = -1; + for (int i = 1; i < nums.size(); i++) { + if (nums[i] > minVal) { + maxDiff = max(maxDiff, nums[i] - minVal); + } else { + minVal = nums[i]; + } + } + return maxDiff; + } +}; diff --git a/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.cs b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.cs new file mode 100644 index 00000000..170e1b81 --- /dev/null +++ b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.cs @@ -0,0 +1,14 @@ +public class Solution { + public int MaximumDifference(int[] nums) { + int minVal = nums[0]; + int maxDiff = -1; + for (int i = 1; i < nums.Length; i++) { + if (nums[i] > minVal) { + maxDiff = Math.Max(maxDiff, nums[i] - minVal); + } else { + minVal = nums[i]; + } + } + return maxDiff; + } +} diff --git a/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.dart b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.dart new file mode 100644 index 00000000..12069a4b --- /dev/null +++ b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.dart @@ -0,0 +1,14 @@ +class Solution { + int maximumDifference(List nums) { + int minVal = nums[0]; + int maxDiff = -1; + for (int i = 1; i < nums.length; i++) { + if (nums[i] > minVal) { + maxDiff = maxDiff > nums[i] - minVal ? maxDiff : nums[i] - minVal; + } else { + minVal = nums[i]; + } + } + return maxDiff; + } +} diff --git a/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.go b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.go new file mode 100644 index 00000000..90c99ee8 --- /dev/null +++ b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.go @@ -0,0 +1,14 @@ +func maximumDifference(nums []int) int { + minVal := nums[0] + maxDiff := -1 + for i := 1; i < len(nums); i++ { + if nums[i] > minVal { + if nums[i]-minVal > maxDiff { + maxDiff = nums[i] - minVal + } + } else { + minVal = nums[i] + } + } + return maxDiff +} diff --git a/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.java b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.java new file mode 100644 index 00000000..65753d68 --- /dev/null +++ b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.java @@ -0,0 +1,14 @@ +class Solution { + public int maximumDifference(int[] nums) { + int minVal = nums[0]; + int maxDiff = -1; + for (int i = 1; i < nums.length; i++) { + if (nums[i] > minVal) { + maxDiff = Math.max(maxDiff, nums[i] - minVal); + } else { + minVal = nums[i]; + } + } + return maxDiff; + } +} diff --git a/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.kt b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.kt new file mode 100644 index 00000000..5b41c356 --- /dev/null +++ b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun maximumDifference(nums: IntArray): Int { + var minVal = nums[0] + var maxDiff = -1 + for (i in 1 until nums.size) { + if (nums[i] > minVal) { + maxDiff = maxOf(maxDiff, nums[i] - minVal) + } else { + minVal = nums[i] + } + } + return maxDiff + } +} diff --git a/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.py b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.py new file mode 100644 index 00000000..2dea0d05 --- /dev/null +++ b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.py @@ -0,0 +1,12 @@ +class Solution: + def maximumDifference(self, nums: List[int]) -> int: + min_val = nums[0] + max_diff = -1 + + for i in range(1, len(nums)): + if nums[i] > min_val: + max_diff = max(max_diff, nums[i] - min_val) + else: + min_val = nums[i] + + return max_diff diff --git a/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.py2 b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.py2 new file mode 100644 index 00000000..1ddecd2d --- /dev/null +++ b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.py2 @@ -0,0 +1,14 @@ +class Solution(object): + def maximumDifference(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + min_val = nums[0] + max_diff = -1 + for i in range(1, len(nums)): + if nums[i] > min_val: + max_diff = max(max_diff, nums[i] - min_val) + else: + min_val = nums[i] + return max_diff diff --git a/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.rb b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.rb new file mode 100644 index 00000000..392ae7f7 --- /dev/null +++ b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.rb @@ -0,0 +1,14 @@ +# @param {Integer[]} nums +# @return {Integer} +def maximum_difference(nums) + min_val = nums[0] + max_diff = -1 + (1...nums.length).each do |i| + if nums[i] > min_val + max_diff = [max_diff, nums[i] - min_val].max + else + min_val = nums[i] + end + end + max_diff +end diff --git a/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.rs b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.rs new file mode 100644 index 00000000..3fe35529 --- /dev/null +++ b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.rs @@ -0,0 +1,14 @@ +impl Solution { + pub fn maximum_difference(nums: Vec) -> i32 { + let mut min_val = nums[0]; + let mut max_diff = -1; + for i in 1..nums.len() { + if nums[i] > min_val { + max_diff = max_diff.max(nums[i] - min_val); + } else { + min_val = nums[i]; + } + } + max_diff + } +} diff --git a/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.swift b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.swift new file mode 100644 index 00000000..7e871176 --- /dev/null +++ b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.swift @@ -0,0 +1,14 @@ +class Solution { + func maximumDifference(_ nums: [Int]) -> Int { + var minVal = nums[0] + var maxDiff = -1 + for i in 1.. minVal { + maxDiff = max(maxDiff, nums[i] - minVal) + } else { + minVal = nums[i] + } + } + return maxDiff + } +} diff --git a/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.ts b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.ts new file mode 100644 index 00000000..47fa20fa --- /dev/null +++ b/tests/2001-2500/2016. maximum-difference-between-increasing-elements/sol.ts @@ -0,0 +1,12 @@ +function maximumDifference(nums: number[]): number { + let minVal = nums[0]; + let maxDiff = -1; + for (let i = 1; i < nums.length; i++) { + if (nums[i] > minVal) { + maxDiff = Math.max(maxDiff, nums[i] - minVal); + } else { + minVal = nums[i]; + } + } + return maxDiff; +} diff --git a/tests/2001-2500/2017. grid-game/manifest.yaml b/tests/2001-2500/2017. grid-game/manifest.yaml new file mode 100644 index 00000000..0a847b92 --- /dev/null +++ b/tests/2001-2500/2017. grid-game/manifest.yaml @@ -0,0 +1,271 @@ +entry: + id: 2017 + title: "grid-game" + params: + grid: + type: array + items: + type: array + items: + type: int + call: + cpp: "Solution().gridGame({grid})" + rust: "Solution::grid_game({grid})" + python3: "Solution().gridGame({grid})" + python2: "Solution().gridGame({grid})" + ruby: "grid_game({grid})" + java: "new Solution().gridGame({grid})" + csharp: "new Solution().GridGame({grid})" + kotlin: "Solution().gridGame({grid})" + go: "gridGame({grid})" + dart: "Solution().gridGame({grid})" + swift: "Solution().gridGame({grid})" + typescript: "gridGame({grid})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().gridGame(grid, {result})" + checker: | + class Checker: + def gridGame(self, grid, result): + if not isinstance(grid, list) or len(grid) != 2: + return False + if not all(isinstance(row, list) for row in grid): + return False + if len(grid[0]) != len(grid[1]) or not grid[0]: + return False + top = sum(grid[0]) + bottom = 0 + expected = float("inf") + for i, value in enumerate(grid[0]): + top -= value + expected = min(expected, max(top, bottom)) + bottom += grid[1][i] + return result == expected + +seed: 2017 + +tests: + - name: "example-one" + in: + grid: + - [2, 5, 4] + - [1, 5, 1] + out: 4 + - name: "example-two" + in: + grid: + - [3, 3, 1] + - [8, 5, 2] + out: 4 + - name: "example-three" + in: + grid: + - [1, 3, 1, 15] + - [1, 3, 3, 1] + out: 7 + - name: "single-column-small" + in: + grid: + - [1] + - [1] + out: 0 + - name: "single-column-maximum" + in: + grid: + - [100000] + - [100000] + out: 0 + - name: "two-equal-columns" + in: + grid: + - [1, 1] + - [1, 1] + out: 1 + - name: "two-columns-rising" + in: + grid: + - [1, 2] + - [3, 4] + out: 2 + - name: "two-columns-reversed" + in: + grid: + - [4, 1] + - [1, 4] + out: 1 + - name: "top-heavy-edge" + in: + grid: + - [5, 1, 1] + - [1, 1, 5] + out: 1 + - name: "bottom-heavy-edge" + in: + grid: + - [1, 1, 5] + - [5, 1, 1] + out: 5 + - name: "uniform-ten" + in: + grid: + - [10, 10, 10] + - [10, 10, 10] + out: 10 + - name: "top-middle-spike" + in: + grid: + - [1, 100, 1] + - [100, 1, 100] + out: 100 + - name: "bottom-middle-spike" + in: + grid: + - [100, 1, 100] + - [1, 100, 1] + out: 100 + - name: "alternating-four" + in: + grid: + - [2, 8, 2, 8] + - [8, 2, 8, 2] + out: 10 + - name: "descending-top" + in: + grid: + - [9, 8, 7, 6, 5] + - [1, 2, 3, 4, 5] + out: 6 + - name: "ascending-top" + in: + grid: + - [1, 2, 3, 4, 5] + - [9, 8, 7, 6, 5] + out: 12 + - name: "zero-valued-cells" + in: + grid: + - [5, 0, 5] + - [0, 5, 0] + out: 5 + - name: "zero-valued-bottom" + in: + grid: + - [0, 5, 0] + - [5, 0, 5] + out: 5 + - name: "symmetric-peaks" + in: + grid: + - [7, 1, 9, 1, 7] + - [2, 8, 2, 8, 2] + out: 10 + - name: "symmetric-peaks-reversed" + in: + grid: + - [2, 8, 2, 8, 2] + - [7, 1, 9, 1, 7] + out: 10 + - name: "late-top-drop" + in: + grid: + - [6, 6, 1, 1] + - [1, 1, 6, 6] + out: 2 + - name: "early-top-drop" + in: + grid: + - [1, 1, 6, 6] + - [6, 6, 1, 1] + out: 12 + - name: "equal-end-peaks" + in: + grid: + - [10, 1, 1, 1, 10] + - [1, 1, 1, 1, 10] + out: 4 + - name: "bottom-end-peak" + in: + grid: + - [1, 1, 1, 1, 10] + - [10, 1, 1, 1, 1] + out: 11 + - name: "mixed-six" + in: + grid: + - [3, 1, 4, 1, 5, 9] + - [2, 6, 5, 3, 5, 8] + out: 14 + - name: "top-left-block" + in: + grid: + - [9, 9, 1, 1, 1, 1] + - [1, 1, 9, 9, 9, 9] + out: 3 + - name: "bottom-left-block" + in: + grid: + - [1, 1, 9, 9, 9, 9] + - [9, 9, 1, 1, 1, 1] + out: 19 + - name: "alternating-six" + in: + grid: + - [20, 1, 20, 1, 20, 1] + - [1, 20, 1, 20, 1, 20] + out: 22 + - name: "alternating-six-reversed" + in: + grid: + - [1, 20, 1, 20, 1, 20] + - [20, 1, 20, 1, 20, 1] + out: 41 + - name: "mixed-seven" + in: + grid: + - [12, 3, 4, 5, 6, 7, 8] + - [8, 7, 6, 5, 4, 3, 12] + out: 21 + - name: "mixed-seven-reversed" + in: + grid: + - [8, 7, 6, 5, 4, 3, 12] + - [12, 3, 4, 5, 6, 7, 8] + out: 19 + - name: "alternating-eight" + in: + grid: + - [1, 2, 1, 2, 1, 2, 1, 2] + - [2, 1, 2, 1, 2, 1, 2, 1] + out: 6 + - name: "outer-top-peaks" + in: + grid: + - [50, 1, 1, 1, 1, 1, 50] + - [1, 1, 1, 1, 1, 1, 1] + out: 6 + - name: "outer-bottom-peak" + in: + grid: + - [1, 1, 1, 1, 1, 1, 50] + - [50, 1, 1, 1, 1, 1, 1] + out: 52 + - name: "maximum-values-left" + in: + grid: + - [100000, 1, 1, 1, 1] + - [1, 1, 1, 1, 100000] + out: 2 + - name: "maximum-values-right" + in: + grid: + - [1, 1, 1, 1, 100000] + - [100000, 1, 1, 1, 1] + out: 100001 diff --git a/tests/2001-2500/2017. grid-game/sol.cpp b/tests/2001-2500/2017. grid-game/sol.cpp new file mode 100644 index 00000000..1aa4f68e --- /dev/null +++ b/tests/2001-2500/2017. grid-game/sol.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + long long gridGame(vector>& grid) { + long long minResult = LLONG_MAX; + long long row1Sum = 0; + for (int val : grid[0]) { + row1Sum += val; + } + long long row2Sum = 0; + + for (int i = 0; i < grid[0].size(); i++) { + row1Sum -= grid[0][i]; + minResult = min(minResult, max(row1Sum, row2Sum)); + row2Sum += grid[1][i]; + } + + return minResult; + } +}; diff --git a/tests/2001-2500/2017. grid-game/sol.cs b/tests/2001-2500/2017. grid-game/sol.cs new file mode 100644 index 00000000..8a680917 --- /dev/null +++ b/tests/2001-2500/2017. grid-game/sol.cs @@ -0,0 +1,18 @@ +public class Solution { + public long GridGame(int[][] grid) { + long minResult = long.MaxValue; + long row1Sum = 0; + foreach (int val in grid[0]) { + row1Sum += val; + } + long row2Sum = 0; + + for (int i = 0; i < grid[0].Length; i++) { + row1Sum -= grid[0][i]; + minResult = Math.Min(minResult, Math.Max(row1Sum, row2Sum)); + row2Sum += grid[1][i]; + } + + return minResult; + } +} diff --git a/tests/2001-2500/2017. grid-game/sol.dart b/tests/2001-2500/2017. grid-game/sol.dart new file mode 100644 index 00000000..bced79a4 --- /dev/null +++ b/tests/2001-2500/2017. grid-game/sol.dart @@ -0,0 +1,18 @@ +class Solution { + int gridGame(List> grid) { + int minResult = 1 << 60; + int row1Sum = grid[0].fold(0, (a, b) => a + b); + int row2Sum = 0; + + for (int i = 0; i < grid[0].length; i++) { + row1Sum -= grid[0][i]; + int currentMax = row1Sum > row2Sum ? row1Sum : row2Sum; + if (currentMax < minResult) { + minResult = currentMax; + } + row2Sum += grid[1][i]; + } + + return minResult; + } +} diff --git a/tests/2001-2500/2017. grid-game/sol.go b/tests/2001-2500/2017. grid-game/sol.go new file mode 100644 index 00000000..6ea22b6d --- /dev/null +++ b/tests/2001-2500/2017. grid-game/sol.go @@ -0,0 +1,22 @@ +func gridGame(grid [][]int) int64 { + minResult := int64(math.MaxInt64) + row1Sum := int64(0) + for _, val := range grid[0] { + row1Sum += int64(val) + } + row2Sum := int64(0) + + for i := 0; i < len(grid[0]); i++ { + row1Sum -= int64(grid[0][i]) + currentMax := row1Sum + if row2Sum > currentMax { + currentMax = row2Sum + } + if currentMax < minResult { + minResult = currentMax + } + row2Sum += int64(grid[1][i]) + } + + return minResult +} diff --git a/tests/2001-2500/2017. grid-game/sol.java b/tests/2001-2500/2017. grid-game/sol.java new file mode 100644 index 00000000..352c6420 --- /dev/null +++ b/tests/2001-2500/2017. grid-game/sol.java @@ -0,0 +1,18 @@ +class Solution { + public long gridGame(int[][] grid) { + long minResult = Long.MAX_VALUE; + long row1Sum = 0; + for (int val : grid[0]) { + row1Sum += val; + } + long row2Sum = 0; + + for (int i = 0; i < grid[0].length; i++) { + row1Sum -= grid[0][i]; + minResult = Math.min(minResult, Math.max(row1Sum, row2Sum)); + row2Sum += grid[1][i]; + } + + return minResult; + } +} diff --git a/tests/2001-2500/2017. grid-game/sol.kt b/tests/2001-2500/2017. grid-game/sol.kt new file mode 100644 index 00000000..af8ac635 --- /dev/null +++ b/tests/2001-2500/2017. grid-game/sol.kt @@ -0,0 +1,15 @@ +class Solution { + fun gridGame(grid: Array): Long { + var minResult = Long.MAX_VALUE + var row1Sum = grid[0].sum().toLong() + var row2Sum = 0L + + for (i in grid[0].indices) { + row1Sum -= grid[0][i] + minResult = minOf(minResult, maxOf(row1Sum, row2Sum)) + row2Sum += grid[1][i] + } + + return minResult + } +} diff --git a/tests/2001-2500/2017. grid-game/sol.py b/tests/2001-2500/2017. grid-game/sol.py new file mode 100644 index 00000000..c7227950 --- /dev/null +++ b/tests/2001-2500/2017. grid-game/sol.py @@ -0,0 +1,12 @@ +class Solution: + def gridGame(self, grid: List[List[int]]) -> int: + min_result = float("inf") + row1_sum = sum(grid[0]) + row2_sum = 0 + + for i in range(len(grid[0])): + row1_sum -= grid[0][i] + min_result = min(min_result, max(row1_sum, row2_sum)) + row2_sum += grid[1][i] + + return min_result diff --git a/tests/2001-2500/2017. grid-game/sol.py2 b/tests/2001-2500/2017. grid-game/sol.py2 new file mode 100644 index 00000000..c6f79a70 --- /dev/null +++ b/tests/2001-2500/2017. grid-game/sol.py2 @@ -0,0 +1,16 @@ +class Solution(object): + def gridGame(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + min_result = float('inf') + row1_sum = sum(grid[0]) + row2_sum = 0 + + for i in range(len(grid[0])): + row1_sum -= grid[0][i] + min_result = min(min_result, max(row1_sum, row2_sum)) + row2_sum += grid[1][i] + + return min_result diff --git a/tests/2001-2500/2017. grid-game/sol.rb b/tests/2001-2500/2017. grid-game/sol.rb new file mode 100644 index 00000000..e62857b1 --- /dev/null +++ b/tests/2001-2500/2017. grid-game/sol.rb @@ -0,0 +1,15 @@ +# @param {Integer[][]} grid +# @return {Integer} +def grid_game(grid) + min_result = Float::INFINITY + row1_sum = grid[0].sum + row2_sum = 0 + + (0...grid[0].length).each do |i| + row1_sum -= grid[0][i] + min_result = [min_result, [row1_sum, row2_sum].max].min + row2_sum += grid[1][i] + end + + min_result +end diff --git a/tests/2001-2500/2017. grid-game/sol.rs b/tests/2001-2500/2017. grid-game/sol.rs new file mode 100644 index 00000000..4f7791c3 --- /dev/null +++ b/tests/2001-2500/2017. grid-game/sol.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn grid_game(grid: Vec>) -> i64 { + let mut min_result = i64::MAX; + let mut row1_sum: i64 = grid[0].iter().map(|&x| x as i64).sum(); + let mut row2_sum: i64 = 0; + + for i in 0..grid[0].len() { + row1_sum -= grid[0][i] as i64; + let current_max = row1_sum.max(row2_sum); + min_result = min_result.min(current_max); + row2_sum += grid[1][i] as i64; + } + + min_result + } +} diff --git a/tests/2001-2500/2017. grid-game/sol.swift b/tests/2001-2500/2017. grid-game/sol.swift new file mode 100644 index 00000000..4ac97a71 --- /dev/null +++ b/tests/2001-2500/2017. grid-game/sol.swift @@ -0,0 +1,16 @@ +class Solution { + func gridGame(_ grid: [[Int]]) -> Int { + var minResult = Int.max + var row1Sum = grid[0].reduce(0, +) + var row2Sum = 0 + + for i in 0.. a + b, 0); + let row2Sum = 0; + + for (let i = 0; i < grid[0].length; i++) { + row1Sum -= grid[0][i]; + minResult = Math.min(minResult, Math.max(row1Sum, row2Sum)); + row2Sum += grid[1][i]; + } + + return minResult; +} diff --git a/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/manifest.yaml b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/manifest.yaml new file mode 100644 index 00000000..d93f2ea5 --- /dev/null +++ b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/manifest.yaml @@ -0,0 +1,380 @@ +entry: + id: 2018 + title: "check-if-word-can-be-placed-in-crossword" + params: + board: + type: array + items: + type: array + items: + type: char + word: + type: string + call: + cpp: "Solution().placeWordInCrossword({board}, {word})" + rust: "Solution::place_word_in_crossword({board}, {word})" + python3: "Solution().placeWordInCrossword({board}, {word})" + python2: "Solution().placeWordInCrossword({board}, {word})" + ruby: "place_word_in_crossword({board}, {word})" + java: "new Solution().placeWordInCrossword({board}, {word})" + csharp: "new Solution().PlaceWordInCrossword({board}, {word})" + kotlin: "Solution().placeWordInCrossword({board}, {word})" + go: "placeWordInCrossword({board}, {word})" + dart: "Solution().placeWordInCrossword({board}, {word})" + swift: "Solution().placeWordInCrossword({board}, {word})" + typescript: "placeWordInCrossword({board}, {word})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().placeWordInCrossword(board, word, {result})" + checker: | + class Checker: + def placeWordInCrossword(self, board, word, result): + if not isinstance(result, bool): + return False + m = len(board) + n = len(board[0]) if m else 0 + def fits(chars): + if len(chars) != len(word): + return False + return all(a == ' ' or a == b for a, b in zip(chars, word)) + possible = False + for row in board: + start = 0 + for i in range(n + 1): + if i == n or row[i] == '#': + segment = row[start:i] + possible = possible or fits(segment) or fits(segment[::-1]) + start = i + 1 + for col in range(n): + start = 0 + for i in range(m + 1): + if i == m or board[i][col] == '#': + segment = [board[j][col] for j in range(start, i)] + possible = possible or fits(segment) or fits(segment[::-1]) + start = i + 1 + return result == possible + +seed: 2018 + +tests: + - name: "example_vertical" + in: + board: + - ["#", " ", "#"] + - [" ", " ", "#"] + - ["#", "c", " "] + word: "abc" + out: true + - name: "example_blocked_boundary" + in: + board: + - [" ", "#", "a"] + - [" ", "#", "c"] + - [" ", "#", "a"] + word: "ac" + out: false + - name: "example_reverse_horizontal" + in: + board: + - ["#", " ", "#"] + - [" ", " ", "#"] + - ["#", " ", "c"] + word: "ca" + out: true + - name: "single_empty_cell" + in: + board: + - [" "] + word: "a" + out: true + - name: "single_matching_cell" + in: + board: + - ["z"] + word: "z" + out: true + - name: "single_mismatch_cell" + in: + board: + - ["z"] + word: "a" + out: false + - name: "single_blocked_cell" + in: + board: + - ["#"] + word: "a" + out: false + - name: "horizontal_all_empty" + in: + board: + - [" ", " ", " ", " "] + word: "code" + out: true + - name: "horizontal_reverse_match" + in: + board: + - ["e", "d", "o", "c"] + word: "code" + out: true + - name: "horizontal_wrong_letters" + in: + board: + - ["c", "o", "x", "e"] + word: "code" + out: false + - name: "horizontal_split_by_block" + in: + board: + - [" ", " ", "#", " ", " "] + word: "ab" + out: true + - name: "horizontal_boundary_extra_cell" + in: + board: + - [" ", "a", "b", " "] + word: "ab" + out: false + - name: "horizontal_exact_segment_with_letters" + in: + board: + - ["#", "c", " ", "d", "#"] + word: "cad" + out: true + - name: "horizontal_partial_match" + in: + board: + - ["#", "c", " ", "x", "#"] + word: "cat" + out: false + - name: "vertical_all_empty" + in: + board: + - [" "] + - [" "] + - [" "] + word: "sun" + out: true + - name: "vertical_reverse_match" + in: + board: + - ["n"] + - ["u"] + - ["s"] + word: "sun" + out: true + - name: "vertical_wrong_letter" + in: + board: + - ["s"] + - ["x"] + - ["n"] + word: "sun" + out: false + - name: "vertical_split_by_block" + in: + board: + - [" ", "#"] + - [" ", "#"] + - ["#", " "] + word: "go" + out: true + - name: "vertical_extra_above" + in: + board: + - [" "] + - ["a"] + - ["b"] + - [" "] + word: "ab" + out: false + - name: "vertical_exact_letters" + in: + board: + - ["#", "c"] + - ["#", "a"] + - ["#", "t"] + word: "cat" + out: true + - name: "vertical_repeated_letters" + in: + board: + - ["#", "a", "#"] + - ["#", " ", "#"] + - ["#", "a", "#"] + word: "aaa" + out: true + - name: "two_dimensional_choice" + in: + board: + - ["#", "#", "#", "#", "#"] + - ["#", " ", " ", " ", "#"] + - ["#", "#", "#", "#", "#"] + word: "yes" + out: true + - name: "two_dimensional_no_fit" + in: + board: + - ["#", "#", "#", "#"] + - ["#", " ", " ", "#"] + - ["#", "#", "#", "#"] + word: "abc" + out: false + - name: "letter_matches_forward" + in: + board: + - ["#", "h", "e", " ", "#"] + word: "hello" + out: false + - name: "letter_matches_reverse" + in: + board: + - ["#", "o", "l", "l", "e", "h", "#"] + word: "hello" + out: true + - name: "isolated_letter_segment" + in: + board: + - ["a", "#", " ", "#", "b"] + word: "a" + out: true + - name: "word_longer_than_all_segments" + in: + board: + - [" ", "#", " ", "#", " "] + word: "aa" + out: false + - name: "full_row_letters" + in: + board: + - ["a", "b", "c", "d", "e"] + word: "abcde" + out: true + - name: "full_column_letters" + in: + board: + - ["a", "#"] + - ["b", "#"] + - ["c", "#"] + word: "abc" + out: true + - name: "full_row_mismatch" + in: + board: + - ["a", "b", "x", "d", "e"] + word: "abcde" + out: false + - name: "adjacent_parallel_letters_allowed" + in: + board: + - ["#", " ", " ", "#"] + - ["#", "a", "b", "#"] + - ["#", " ", " ", "#"] + word: "ab" + out: true + - name: "parallel_neighbor_does_not_break_horizontal" + in: + board: + - ["#", " ", " ", "#"] + - ["#", "x", "y", "#"] + - ["#", " ", " ", "#"] + word: "xy" + out: true + - name: "blocked_crossing" + in: + board: + - ["#", " ", "#"] + - [" ", "#", " "] + - ["#", " ", "#"] + word: "aa" + out: false + - name: "long_static_row" + in: + board: + - ["#", " ", " ", " ", " ", " ", " ", " ", " ", " ", "#"] + word: "abcdefghi" + out: true + - name: "long_static_column" + in: + board: + - ["#"] + - [" "] + - [" "] + - [" "] + - [" "] + - [" "] + - [" "] + - [" "] + - [" "] + - [" "] + - ["#"] + word: "abcdefghi" + out: true + - name: "generated_short_word" + in: + board: + - [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "] + word: + gen: "str" + len: + gen: "int" + min: 1 + max: 10 + alphabet: "abcd" + seed: 20181 + - name: "generated_short_word_2" + in: + board: + - [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "] + word: + gen: "str" + len: + gen: "int" + min: 1 + max: 10 + alphabet: "xy" + seed: 20182 + - name: "generated_short_word_3" + in: + board: + - [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "] + word: + gen: "str" + len: + gen: "int" + min: 1 + max: 10 + alphabet: "mno" + seed: 20183 + - name: "generated_short_word_4" + in: + board: + - [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "] + word: + gen: "str" + len: + gen: "int" + min: 1 + max: 10 + alphabet: "az" + seed: 20184 + - name: "generated_short_word_5" + in: + board: + - [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "] + word: + gen: "str" + len: + gen: "int" + min: 1 + max: 10 + alphabet: "qrst" + seed: 20185 diff --git a/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.cpp b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.cpp new file mode 100644 index 00000000..aa3dba87 --- /dev/null +++ b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.cpp @@ -0,0 +1,52 @@ +class Solution { +public: + bool placeWordInCrossword(vector>& board, string word) { + auto can_place = [](const vector& segment, const string& w) { + if (segment.size() != w.size()) return false; + for (size_t i = 0; i < segment.size(); ++i) { + if (segment[i] != ' ' && segment[i] != w[i]) return false; + } + return true; + }; + + int m = board.size(), n = board[0].size(); + string reversed_word = word; + reverse(reversed_word.begin(), reversed_word.end()); + + for (auto& row : board) { + vector seg; + for (char c : row) { + if (c == '#') { + if (!seg.empty()) { + if (can_place(seg, word) || can_place(seg, reversed_word)) return true; + seg.clear(); + } + } else { + seg.push_back(c); + } + } + if (!seg.empty()) { + if (can_place(seg, word) || can_place(seg, reversed_word)) return true; + } + } + + for (int j = 0; j < n; ++j) { + vector seg; + for (int i = 0; i < m; ++i) { + char c = board[i][j]; + if (c == '#') { + if (!seg.empty()) { + if (can_place(seg, word) || can_place(seg, reversed_word)) return true; + seg.clear(); + } + } else { + seg.push_back(c); + } + } + if (!seg.empty()) { + if (can_place(seg, word) || can_place(seg, reversed_word)) return true; + } + } + return false; + } +}; diff --git a/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.cs b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.cs new file mode 100644 index 00000000..7d067702 --- /dev/null +++ b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.cs @@ -0,0 +1,31 @@ +public class Solution { + public bool PlaceWordInCrossword(char[][] board, string word) { + bool CanPlace(string segment, string w) { + if (segment.Length != w.Length) return false; + for (int i = 0; i < segment.Length; i++) { + if (segment[i] != ' ' && segment[i] != w[i]) return false; + } + return true; + } + + int m = board.Length, n = board[0].Length; + string reversedWord = new string(word.Reverse().ToArray()); + + foreach (var row in board) { + string rowStr = new string(row); + foreach (var part in rowStr.Split('#')) { + if (!string.IsNullOrEmpty(part) && (CanPlace(part, word) || CanPlace(part, reversedWord))) return true; + } + } + + for (int j = 0; j < n; j++) { + char[] col = new char[m]; + for (int i = 0; i < m; i++) col[i] = board[i][j]; + string colStr = new string(col); + foreach (var part in colStr.Split('#')) { + if (!string.IsNullOrEmpty(part) && (CanPlace(part, word) || CanPlace(part, reversedWord))) return true; + } + } + return false; + } +} diff --git a/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.dart b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.dart new file mode 100644 index 00000000..49297987 --- /dev/null +++ b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.dart @@ -0,0 +1,30 @@ +class Solution { + bool placeWordInCrossword(List> board, String word) { + bool canPlace(String segment, String w) { + if (segment.length != w.length) return false; + for (int i = 0; i < segment.length; i++) { + if (segment[i] != ' ' && segment[i] != w[i]) return false; + } + return true; + } + + int m = board.length, n = board[0].length; + String reversedWord = word.split('').reversed.join(); + + for (var row in board) { + var parts = row.join().split('#'); + for (var part in parts) { + if (part.isNotEmpty && (canPlace(part, word) || canPlace(part, reversedWord))) return true; + } + } + + for (int j = 0; j < n; j++) { + var col = List.generate(m, (i) => board[i][j]).join(); + var parts = col.split('#'); + for (var part in parts) { + if (part.isNotEmpty && (canPlace(part, word) || canPlace(part, reversedWord))) return true; + } + } + return false; + } +} diff --git a/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.go b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.go new file mode 100644 index 00000000..0f4ea24b --- /dev/null +++ b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.go @@ -0,0 +1,62 @@ +func placeWordInCrossword(board [][]byte, word string) bool { + canPlace := func(segment string, w string) bool { + if len(segment) != len(w) { + return false + } + for i := 0; i < len(segment); i++ { + if segment[i] != ' ' && segment[i] != w[i] { + return false + } + } + return true + } + + m, n := len(board), len(board[0]) + revWord := reverseString(word) + + for _, row := range board { + parts := splitString(string(row), '#') + for _, part := range parts { + if part != "" && (canPlace(part, word) || canPlace(part, revWord)) { + return true + } + } + } + + for j := 0; j < n; j++ { + col := make([]byte, m) + for i := 0; i < m; i++ { + col[i] = board[i][j] + } + parts := splitString(string(col), '#') + for _, part := range parts { + if part != "" && (canPlace(part, word) || canPlace(part, revWord)) { + return true + } + } + } + return false +} + +func reverseString(s string) string { + runes := []rune(s) + for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { + runes[i], runes[j] = runes[j], runes[i] + } + return string(runes) +} + +func splitString(s string, sep byte) []string { + var parts []string + var sb strings.Builder + for i := 0; i < len(s); i++ { + if s[i] == sep { + parts = append(parts, sb.String()) + sb.Reset() + } else { + sb.WriteByte(s[i]) + } + } + parts = append(parts, sb.String()) + return parts +} diff --git a/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.java b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.java new file mode 100644 index 00000000..29023d43 --- /dev/null +++ b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.java @@ -0,0 +1,30 @@ +class Solution { + public boolean placeWordInCrossword(char[][] board, String word) { + java.util.function.BiPredicate canPlace = (segment, w) -> { + if (segment.length() != w.length()) return false; + for (int i = 0; i < segment.length(); i++) { + char c = segment.charAt(i); + if (c != ' ' && c != w.charAt(i)) return false; + } + return true; + }; + + int m = board.length, n = board[0].length; + String reversedWord = new StringBuilder(word).reverse().toString(); + + for (char[] row : board) { + for (String part : new String(row).split("#")) { + if (!part.isEmpty() && (canPlace.test(part, word) || canPlace.test(part, reversedWord))) return true; + } + } + + for (int j = 0; j < n; j++) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < m; i++) sb.append(board[i][j]); + for (String part : sb.toString().split("#")) { + if (!part.isEmpty() && (canPlace.test(part, word) || canPlace.test(part, reversedWord))) return true; + } + } + return false; + } +} diff --git a/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.kt b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.kt new file mode 100644 index 00000000..ee529f36 --- /dev/null +++ b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.kt @@ -0,0 +1,31 @@ +class Solution { + fun placeWordInCrossword(board: Array, word: String): Boolean { + fun canPlace(segment: String, w: String): Boolean { + if (segment.length != w.length) return false + for (i in segment.indices) { + if (segment[i] != ' ' && segment[i] != w[i]) return false + } + return true + } + + val m = board.size + val n = board[0].size + val reversedWord = word.reversed() + + for (row in board) { + val parts = row.joinToString("").split("#") + for (part in parts) { + if (part.isNotEmpty() && (canPlace(part, word) || canPlace(part, reversedWord))) return true + } + } + + for (j in 0 until n) { + val col = (0 until m).map { board[it][j] }.joinToString("") + val parts = col.split("#") + for (part in parts) { + if (part.isNotEmpty() && (canPlace(part, word) || canPlace(part, reversedWord))) return true + } + } + return false + } +} diff --git a/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.py b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.py new file mode 100644 index 00000000..8e031ef9 --- /dev/null +++ b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.py @@ -0,0 +1,32 @@ +class Solution(object): + def placeWordInCrossword(self, board, word): + """ + :type board: List[List[str]] + :type word: str + :rtype: bool + """ + + def can_place(segment, word): + if len(segment) != len(word): + return False + for c1, c2 in zip(segment, word): + if c1 != " " and c1 != c2: + return False + return True + + m, n = len(board), len(board[0]) + reversed_word = word[::-1] + + for row in board: + parts = "".join(row).split("#") + for part in parts: + if can_place(part, word) or can_place(part, reversed_word): + return True + + for col in zip(*board): + parts = "".join(col).split("#") + for part in parts: + if can_place(part, word) or can_place(part, reversed_word): + return True + + return False diff --git a/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.py2 b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.py2 new file mode 100644 index 00000000..f9219413 --- /dev/null +++ b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.py2 @@ -0,0 +1,31 @@ +class Solution(object): + def placeWordInCrossword(self, board, word): + """ + :type board: List[List[str]] + :type word: str + :rtype: bool + """ + def can_place(segment, word): + if len(segment) != len(word): + return False + for c1, c2 in zip(segment, word): + if c1 != ' ' and c1 != c2: + return False + return True + + m, n = len(board), len(board[0]) + reversed_word = word[::-1] + + for row in board: + parts = ''.join(row).split('#') + for part in parts: + if can_place(part, word) or can_place(part, reversed_word): + return True + + for col in zip(*board): + parts = ''.join(col).split('#') + for part in parts: + if can_place(part, word) or can_place(part, reversed_word): + return True + + return False diff --git a/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.rb b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.rb new file mode 100644 index 00000000..498701d9 --- /dev/null +++ b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.rb @@ -0,0 +1,29 @@ +# @param {Character[][]} board +# @param {String} word +# @return {Boolean} +def place_word_in_crossword(board, word) + can_place = ->(segment, w) do + return false if segment.length != w.length + segment.chars.each_with_index.all? { |c, i| c == ' ' || c == w[i] } + end + + m, n = board.length, board[0].length + reversed_word = word.reverse + + board.each do |row| + parts = row.join.split('#') + parts.each do |part| + return true if can_place.call(part, word) || can_place.call(part, reversed_word) + end + end + + (0...n).each do |j| + col = (0...m).map { |i| board[i][j] }.join + parts = col.split('#') + parts.each do |part| + return true if can_place.call(part, word) || can_place.call(part, reversed_word) + end + end + + false +end diff --git a/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.rs b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.rs new file mode 100644 index 00000000..e8359baa --- /dev/null +++ b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.rs @@ -0,0 +1,52 @@ +impl Solution { + pub fn place_word_in_crossword(board: Vec>, word: String) -> bool { + fn can_place(segment: &Vec, word: &str) -> bool { + let chars: Vec = word.chars().collect(); + if segment.len() != chars.len() { return false; } + for i in 0..segment.len() { + if segment[i] != ' ' && segment[i] != chars[i] { return false; } + } + true + } + + let m = board.len(); + let n = board[0].len(); + let reversed_word: String = word.chars().rev().collect(); + + for row in &board { + let mut seg: Vec = Vec::new(); + for &c in row { + if c == '#' { + if !seg.is_empty() { + if can_place(&seg, &word) || can_place(&seg, &reversed_word) { return true; } + seg.clear(); + } + } else { + seg.push(c); + } + } + if !seg.is_empty() { + if can_place(&seg, &word) || can_place(&seg, &reversed_word) { return true; } + } + } + + for j in 0..n { + let mut seg: Vec = Vec::new(); + for i in 0..m { + let c = board[i][j]; + if c == '#' { + if !seg.is_empty() { + if can_place(&seg, &word) || can_place(&seg, &reversed_word) { return true; } + seg.clear(); + } + } else { + seg.push(c); + } + } + if !seg.is_empty() { + if can_place(&seg, &word) || can_place(&seg, &reversed_word) { return true; } + } + } + false + } +} diff --git a/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.swift b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.swift new file mode 100644 index 00000000..27b28e9c --- /dev/null +++ b/tests/2001-2500/2018. check-if-word-can-be-placed-in-crossword/sol.swift @@ -0,0 +1,53 @@ +class Solution { + func placeWordInCrossword(_ board: [[Character]], _ word: String) -> Bool { + func canPlace(_ segment: [Character], _ w: String) -> Bool { + if segment.count != w.count { return false } + let chars = Array(w) + for i in 0.. { + if (segment.length !== w.length) return false; + for (let i = 0; i < segment.length; i++) { + if (segment[i] !== " " && segment[i] !== w[i]) return false; + } + return true; + }; + + const m = board.length, + n = board[0].length; + const reversedWord = word.split("").reverse().join(""); + + for (let row of board) { + const parts = row.join("").split("#"); + for (let part of parts) { + if (part && (canPlace(part, word) || canPlace(part, reversedWord))) + return true; + } + } + + for (let j = 0; j < n; j++) { + let col = ""; + for (let i = 0; i < m; i++) col += board[i][j]; + const parts = col.split("#"); + for (let part of parts) { + if (part && (canPlace(part, word) || canPlace(part, reversedWord))) + return true; + } + } + return false; +} diff --git a/tests/2001-2500/2019. the-score-of-students-solving-math-expression/manifest.yaml b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/manifest.yaml new file mode 100644 index 00000000..a4a3feb0 --- /dev/null +++ b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/manifest.yaml @@ -0,0 +1,245 @@ +entry: + id: 2019 + title: "the-score-of-students-solving-math-expression" + params: + s: + type: string + answers: + type: array + items: + type: int + call: + cpp: "Solution().scoreOfStudents({s}, {answers})" + rust: "Solution::score_of_students({s}, {answers})" + python3: "Solution().scoreOfStudents({s}, {answers})" + python2: "Solution().scoreOfStudents({s}, {answers})" + ruby: "score_of_students({s}, {answers})" + java: "new Solution().scoreOfStudents({s}, {answers})" + csharp: "new Solution().ScoreOfStudents({s}, {answers})" + kotlin: "Solution().scoreOfStudents({s}, {answers})" + go: "scoreOfStudents({s}, {answers})" + dart: "Solution().scoreOfStudents({s}, {answers})" + swift: "Solution().scoreOfStudents({s}, {answers})" + typescript: "scoreOfStudents({s}, {answers})" + +judge: + type: "exact" + +limits: + time_ms: 500 + memory_mb: 300 + +oracle: + python3: + call: "Checker().scoreOfStudents(s, answers, {result})" + checker: | + from functools import lru_cache + + class Checker: + def scoreOfStudents(self, s, answers, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + values = [int(s[i]) for i in range(0, len(s), 2)] + ops = [s[i] for i in range(1, len(s), 2)] + + @lru_cache(None) + def solve(lo, hi): + if lo == hi: + return {values[lo]} + out = set() + for mid in range(lo, hi): + for left in solve(lo, mid): + for right in solve(mid + 1, hi): + value = left + right if ops[mid] == "+" else left * right + if value <= 1000: + out.add(value) + return out + + correct = values[0] + for i, op in enumerate(ops): + if op == "*": + correct *= values[i + 1] + else: + correct += values[i + 1] + possible = solve(0, len(values) - 1) + expected = sum(5 if x == correct else 2 if x in possible else 0 for x in answers) + return result == expected + +seed: 2019 + +tests: + - name: "example_one" + in: + s: "7+3*1*2" + answers: [20, 13, 42] + out: 7 + - name: "example_two" + in: + s: "3+5*2" + answers: [13, 0, 10, 13, 13, 16, 16] + out: 19 + - name: "example_three" + in: + s: "6+0*1" + answers: [12, 9, 6, 4, 8, 6] + out: 10 + - name: "single_add" + in: + s: "1+2" + answers: [3, 0, 1, 2] + out: 5 + - name: "single_multiply" + in: + s: "8*9" + answers: [72, 71, 0] + out: 5 + - name: "zero_product" + in: + s: "6+0*1" + answers: [6, 6, 0, 7] + out: 10 + - name: "all_additions" + in: + s: "1+2+3+4+5" + answers: [15, 10, 0, 15, 14] + out: 10 + - name: "all_multiplications" + in: + s: "1*2*3*4*5" + answers: [120, 119, 0, 24] + out: 5 + - name: "mixed_one" + in: + s: "2+3*4+5" + answers: [19, 25, 45, 0, 14] + out: 9 + - name: "mixed_two" + in: + s: "9*1+2*3" + answers: [15, 33, 27, 0, 11] + out: 7 + - name: "nested_alternatives" + in: + s: "1+2*3+4" + answers: [11, 21, 13, 15, 10] + out: 11 + - name: "large_sum" + in: + s: "9+9+9+9+9+9+9+9" + answers: [72, 0, 71, 72] + out: 10 + - name: "large_product" + in: + s: "2*2*2*2*2*2*2*2" + answers: [256, 255, 128, 0] + out: 5 + - name: "leading_zero" + in: + s: "0+1*2+3" + answers: [5, 6, 3, 0] + out: 5 + - name: "zero_addition" + in: + s: "4*0+7*2" + answers: [14, 0, 28, 7] + out: 5 + - name: "ones" + in: + s: "1+1*1+1" + answers: [3, 4, 2, 0] + out: 7 + - name: "many_students" + in: + s: "2+3*4" + answers: [14, 14, 14, 20, 20, 20, 99, 0, 12, 12] + out: 21 + - name: "ambiguous_a" + in: + s: "2*3+4*5" + answers: [26, 50, 46, 70, 10] + out: 11 + - name: "ambiguous_b" + in: + s: "1+2+3*4" + answers: [15, 24, 21, 10, 0] + out: 9 + - name: "alternating_short" + in: + s: "3*2+1*4" + answers: [10, 24, 13, 8] + out: 5 + - name: "alternating_long" + in: + s: "1+2*3+4*5+6" + answers: [33, 51, 45, 105, 0] + out: 7 + - name: "max_target" + in: + s: "9*9+9*1" + answers: [90, 810, 810, 99, 0] + out: 5 + - name: "all_zero" + in: + s: "0*0+0*0" + answers: [0, 1, 2, 0] + out: 10 + - name: "all_nines_product" + in: + s: "9*9*9" + answers: [729, 81, 0, 729] + out: 10 + - name: "four_operands" + in: + s: "5+4*3+2" + answers: [19, 27, 45, 17, 0] + out: 7 + - name: "five_operands" + in: + s: "5*4+3*2+1" + answers: [27, 31, 50, 41, 0] + out: 5 + - name: "six_operands" + in: + s: "2+4*2+3*1" + answers: [13, 21, 18, 0, 10] + out: 5 + - name: "repeated_zero" + in: + s: "7*0+8*0+9" + answers: [9, 0, 16, 72, 17] + out: 7 + - name: "small_values" + in: + s: "1+2*1+2" + answers: [5, 6, 7, 4, 0] + out: 7 + - name: "balanced_expression" + in: + s: "3*3+2*2+1" + answers: [14, 25, 19, 23, 0] + out: 7 + - name: "deep_expression" + in: + s: "1+2*3+4*5+6*7+8" + answers: [69, 105, 153, 41, 0] + out: 2 + - name: "duplicate_correct" + in: + s: "4+5*2" + answers: [14, 14, 14, 19, 19, 0] + out: 15 + - name: "duplicate_wrong" + in: + s: "2+6*3" + answers: [24, 24, 24, 8, 0] + out: 6 + - name: "boundary_answer" + in: + s: "9*9+9" + answers: [90, 99, 81, 1000, 0] + out: 5 + - name: "long_valid_expression" + in: + s: "1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1" + answers: [16, 15, 0, 16] + out: 10 diff --git a/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.cpp b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.cpp new file mode 100644 index 00000000..0056782c --- /dev/null +++ b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.cpp @@ -0,0 +1,68 @@ +class Solution { +public: + int scoreOfStudents(string s, vector& answers) { + unordered_map> memo; + + function(int,int)> dp = [&](int lo, int hi) -> unordered_set { + string key = to_string(lo) + "," + to_string(hi); + if (memo.count(key)) return memo[key]; + if (lo + 1 == hi) { + unordered_set tmp = {s[lo] - '0'}; + memo[key] = tmp; + return tmp; + } + unordered_set result; + for (int mid = lo + 1; mid < hi; mid += 2) { + auto left = dp(lo, mid); + auto right = dp(mid + 1, hi); + for (int x : left) { + for (int y : right) { + if (s[mid] == '+' && x + y <= 1000) { + result.insert(x + y); + } else if (s[mid] == '*' && x * y <= 1000) { + result.insert(x * y); + } + } + } + } + memo[key] = result; + return result; + }; + + // evaluate target with precedence + vector nums; + vector ops; + for (char c : s) { + if (isdigit(c)) { + nums.push_back(c - '0'); + } else if (c == '+' || c == '*') { + while (!ops.empty() && precedence(ops.back()) >= precedence(c)) { + apply(nums, ops); + } + ops.push_back(c); + } + } + while (!ops.empty()) apply(nums, ops); + int target = nums.back(); + + auto cand = dp(0, s.size()); + int score = 0; + for (int x : answers) { + if (x == target) score += 5; + else if (cand.count(x)) score += 2; + } + return score; + } + +private: + int precedence(char c) { + return c == '*' ? 2 : 1; + } + + void apply(vector& nums, vector& ops) { + int b = nums.back(); nums.pop_back(); + int a = nums.back(); nums.pop_back(); + char op = ops.back(); ops.pop_back(); + nums.push_back(op == '+' ? a + b : a * b); + } +}; diff --git a/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.cs b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.cs new file mode 100644 index 00000000..40f9c849 --- /dev/null +++ b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.cs @@ -0,0 +1,67 @@ +public class Solution { + private string s; + private Dictionary<(int,int), HashSet> memo; + + private HashSet Fn(int lo, int hi) { + var key = (lo, hi); + if (memo.ContainsKey(key)) return memo[key]; + if (lo + 1 == hi) { + var tmp = new HashSet { s[lo] - '0' }; + memo[key] = tmp; + return tmp; + } + var result = new HashSet(); + for (int mid = lo + 1; mid < hi; mid += 2) { + foreach (int x in Fn(lo, mid)) { + foreach (int y in Fn(mid + 1, hi)) { + if (s[mid] == '+' && x + y <= 1000) { + result.Add(x + y); + } else if (s[mid] == '*' && x * y <= 1000) { + result.Add(x * y); + } + } + } + } + memo[key] = result; + return result; + } + + public int ScoreOfStudents(string s, int[] answers) { + this.s = s; + this.memo = new Dictionary<(int,int), HashSet>(); + + // target evaluation with precedence + var nums = new Stack(); + var ops = new Stack(); + for (int i = 0; i < s.Length; i++) { + char c = s[i]; + if (char.IsDigit(c)) { + nums.Push(c - '0'); + } else if (c == '+' || c == '*') { + while (ops.Count > 0 && Precedence(ops.Peek()) >= Precedence(c)) { + Apply(nums, ops); + } + ops.Push(c); + } + } + while (ops.Count > 0) Apply(nums, ops); + int target = nums.Peek(); + + var cand = Fn(0, s.Length); + int score = 0; + foreach (int x in answers) { + if (x == target) score += 5; + else if (cand.Contains(x)) score += 2; + } + return score; + } + + private int Precedence(char c) => c == '*' ? 2 : 1; + + private void Apply(Stack nums, Stack ops) { + int b = nums.Pop(); + int a = nums.Pop(); + char op = ops.Pop(); + nums.Push(op == '+' ? a + b : a * b); + } +} diff --git a/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.dart b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.dart new file mode 100644 index 00000000..395a960e --- /dev/null +++ b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.dart @@ -0,0 +1,63 @@ +class Solution { + int scoreOfStudents(String s, List answers) { + final memo = >{}; + + Set fn(int lo, int hi) { + final key = '$lo,$hi'; + if (memo.containsKey(key)) return memo[key]!; + if (lo + 1 == hi) { + final tmp = {int.parse(s[lo])}; + memo[key] = tmp; + return tmp; + } + final ans = {}; + for (int mid = lo + 1; mid < hi; mid += 2) { + for (final x in fn(lo, mid)) { + for (final y in fn(mid + 1, hi)) { + if (s[mid] == '+' && x + y <= 1000) { + ans.add(x + y); + } else if (s[mid] == '*' && x * y <= 1000) { + ans.add(x * y); + } + } + } + } + memo[key] = ans; + return ans; + } + + // evaluate target with precedence + final nums = []; + final ops = []; + for (int i = 0; i < s.length; i++) { + final c = s[i]; + if (RegExp(r'[0-9]').hasMatch(c)) { + nums.add(int.parse(c)); + } else if (c == '+' || c == '*') { + while (ops.isNotEmpty && precedence(ops.last) >= precedence(c)) { + apply(nums, ops); + } + ops.add(c); + } + } + while (ops.isNotEmpty) apply(nums, ops); + final target = nums.last; + + final cand = fn(0, s.length); + int score = 0; + for (final x in answers) { + if (x == target) score += 5; + else if (cand.contains(x)) score += 2; + } + return score; + } + + int precedence(String c) => c == '*' ? 2 : 1; + + void apply(List nums, List ops) { + final b = nums.removeLast(); + final a = nums.removeLast(); + final op = ops.removeLast(); + nums.add(op == '+' ? a + b : a * b); + } +} diff --git a/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.go b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.go new file mode 100644 index 00000000..98bc5450 --- /dev/null +++ b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.go @@ -0,0 +1,81 @@ +func scoreOfStudents(s string, answers []int) int { + memo := make(map[[2]int]map[int]bool) + + var fn func(lo, hi int) map[int]bool + fn = func(lo, hi int) map[int]bool { + key := [2]int{lo, hi} + if val, ok := memo[key]; ok { + return val + } + if lo+1 == hi { + res := map[int]bool{int(s[lo]-'0'): true} + memo[key] = res + return res + } + res := make(map[int]bool) + for mid := lo + 1; mid < hi; mid += 2 { + for x := range fn(lo, mid) { + for y := range fn(mid+1, hi) { + if s[mid] == '+' && x+y <= 1000 { + res[x+y] = true + } else if s[mid] == '*' && x*y <= 1000 { + res[x*y] = true + } + } + } + } + memo[key] = res + return res + } + + // evaluate target with precedence + nums := []int{} + ops := []byte{} + for i := 0; i < len(s); i++ { + c := s[i] + if c >= '0' && c <= '9' { + nums = append(nums, int(c-'0')) + } else if c == '+' || c == '*' { + for len(ops) > 0 && precedence(ops[len(ops)-1]) >= precedence(c) { + apply(&nums, &ops) + } + ops = append(ops, c) + } + } + for len(ops) > 0 { + apply(&nums, &ops) + } + target := nums[len(nums)-1] + + cand := fn(0, len(s)) + score := 0 + for _, x := range answers { + if x == target { + score += 5 + } else if cand[x] { + score += 2 + } + } + return score +} + +func precedence(c byte) int { + if c == '*' { + return 2 + } + return 1 +} + +func apply(nums *[]int, ops *[]byte) { + b := (*nums)[len(*nums)-1] + *nums = (*nums)[:len(*nums)-1] + a := (*nums)[len(*nums)-1] + *nums = (*nums)[:len(*nums)-1] + op := (*ops)[len(*ops)-1] + *ops = (*ops)[:len(*ops)-1] + if op == '+' { + *nums = append(*nums, a+b) + } else { + *nums = append(*nums, a*b) + } +} diff --git a/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.java b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.java new file mode 100644 index 00000000..5f7cb65d --- /dev/null +++ b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.java @@ -0,0 +1,73 @@ +import java.util.*; + +class Solution { + private String s; + private Map> memo; + + private Set fn(int lo, int hi) { + String key = lo + "," + hi; + if (memo.containsKey(key)) return memo.get(key); + if (lo + 1 == hi) { + Set tmp = new HashSet<>(); + tmp.add(s.charAt(lo) - '0'); + memo.put(key, tmp); + return tmp; + } + Set ans = new HashSet<>(); + for (int mid = lo + 1; mid < hi; mid += 2) { + for (int x : fn(lo, mid)) { + for (int y : fn(mid + 1, hi)) { + if (s.charAt(mid) == '+' && x + y <= 1000) { + ans.add(x + y); + } else if (s.charAt(mid) == '*' && x * y <= 1000) { + ans.add(x * y); + } + } + } + } + memo.put(key, ans); + return ans; + } + + public int scoreOfStudents(String s, int[] answers) { + this.s = s; + this.memo = new HashMap<>(); + int target = 0; + // Evaluate expression respecting precedence + // Simple approach: use a stack + Stack nums = new Stack<>(); + Stack ops = new Stack<>(); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (Character.isDigit(c)) { + nums.push(c - '0'); + } else if (c == '+' || c == '*') { + while (!ops.isEmpty() && precedence(ops.peek()) >= precedence(c)) { + apply(nums, ops.pop()); + } + ops.push(c); + } + } + while (!ops.isEmpty()) apply(nums, ops.pop()); + target = nums.pop(); + + Set cand = fn(0, s.length()); + int score = 0; + for (int x : answers) { + if (x == target) score += 5; + else if (cand.contains(x)) score += 2; + } + return score; + } + + private int precedence(char c) { + return c == '*' ? 2 : 1; + } + + private void apply(Stack nums, char op) { + int b = nums.pop(); + int a = nums.pop(); + if (op == '+') nums.push(a + b); + else nums.push(a * b); + } +} diff --git a/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.kt b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.kt new file mode 100644 index 00000000..4a7029a1 --- /dev/null +++ b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.kt @@ -0,0 +1,60 @@ +class Solution { + fun scoreOfStudents(s: String, answers: IntArray): Int { + val memo = HashMap, Set>() + + fun fn(lo: Int, hi: Int): Set { + val key = Pair(lo, hi) + memo[key]?.let { return it } + if (lo + 1 == hi) { + val tmp = mutableSetOf(s[lo] - '0') + memo[key] = tmp + return tmp + } + val ans = mutableSetOf() + var mid = lo + 1 + while (mid < hi) { + for (x in fn(lo, mid)) { + for (y in fn(mid + 1, hi)) { + if (s[mid] == '+' && x + y <= 1000) ans.add(x + y) + else if (s[mid] == '*' && x * y <= 1000) ans.add(x * y) + } + } + mid += 2 + } + memo[key] = ans + return ans + } + + // evaluate target respecting precedence + val nums = java.util.ArrayDeque() + val ops = java.util.ArrayDeque() + for (i in s.indices) { + val c = s[i] + if (c.isDigit()) nums.addLast(c - '0') + else if (c == '+' || c == '*') { + while (ops.isNotEmpty() && precedence(ops.peekLast()) >= precedence(c)) { + apply(nums, ops.pollLast()) + } + ops.addLast(c) + } + } + while (ops.isNotEmpty()) apply(nums, ops.pollLast()) + val target = nums.pollLast() + + val cand = fn(0, s.length) + var score = 0 + for (x in answers) { + if (x == target) score += 5 + else if (cand.contains(x)) score += 2 + } + return score + } + + private fun precedence(c: Char): Int = if (c == '*') 2 else 1 + + private fun apply(nums: java.util.ArrayDeque, op: Char) { + val b = nums.pollLast() + val a = nums.pollLast() + if (op == '+') nums.addLast(a + b) else nums.addLast(a * b) + } +} diff --git a/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.py b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.py new file mode 100644 index 00000000..f0f965a8 --- /dev/null +++ b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.py @@ -0,0 +1,27 @@ +class Solution: + def scoreOfStudents(self, s: str, answers: List[int]) -> int: + + @cache + def fn(lo, hi): + """Return possible answers of s[lo:hi].""" + if lo + 1 == hi: + return {int(s[lo])} + ans = set() + for mid in range(lo + 1, hi, 2): + for x in fn(lo, mid): + for y in fn(mid + 1, hi): + if s[mid] == "+" and x + y <= 1000: + ans.add(x + y) + elif s[mid] == "*" and x * y <= 1000: + ans.add(x * y) + return ans + + target = eval(s) + cand = fn(0, len(s)) + ans = 0 + for x in answers: + if x == target: + ans += 5 + elif x in cand: + ans += 2 + return ans diff --git a/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.py2 b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.py2 new file mode 100644 index 00000000..4ce321e2 --- /dev/null +++ b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.py2 @@ -0,0 +1,36 @@ +class Solution(object): + def scoreOfStudents(self, s, answers): + """ + :type s: str + :type answers: List[int] + :rtype: int + """ + memo = {} + def fn(lo, hi): + key = (lo, hi) + if key in memo: + return memo[key] + if lo + 1 == hi: + result = set([int(s[lo])]) + memo[key] = result + return result + ans = set() + for mid in range(lo + 1, hi, 2): + for x in fn(lo, mid): + for y in fn(mid + 1, hi): + if s[mid] == '+' and x + y <= 1000: + ans.add(x + y) + elif s[mid] == '*' and x * y <= 1000: + ans.add(x * y) + memo[key] = ans + return ans + + target = eval(s) + cand = fn(0, len(s)) + ans = 0 + for x in answers: + if x == target: + ans += 5 + elif x in cand: + ans += 2 + return ans diff --git a/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.rb b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.rb new file mode 100644 index 00000000..b7f0032f --- /dev/null +++ b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.rb @@ -0,0 +1,38 @@ +# @param {String} s +# @param {Integer[]} answers +# @return {Integer} +def score_of_students(s, answers) + memo = {} + + fn = lambda do |lo, hi| + return [s[lo].to_i] if lo + 1 == hi + return memo[[lo, hi]] if memo.key?([lo, hi]) + ans = [] + mid = lo + 1 + while mid < hi + fn.call(lo, mid).each do |x| + fn.call(mid + 1, hi).each do |y| + if s[mid] == '+' && x + y <= 1000 + ans << (x + y) unless ans.include?(x + y) + elsif s[mid] == '*' && x * y <= 1000 + ans << (x * y) unless ans.include?(x * y) + end + end + end + mid += 2 + end + memo[[lo, hi]] = ans + end + + target = eval(s) + cand = fn.call(0, s.length) + score = 0 + answers.each do |x| + if x == target + score += 5 + elsif cand.include?(x) + score += 2 + end + end + score +end diff --git a/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.rs b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.rs new file mode 100644 index 00000000..b0f2a797 --- /dev/null +++ b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.rs @@ -0,0 +1,80 @@ +impl Solution { + pub fn score_of_students(s: String, answers: Vec) -> i32 { + use std::collections::HashMap; + use std::collections::HashSet; + + let s_chars: Vec = s.chars().collect(); + let mut memo: HashMap<(usize, usize), HashSet> = HashMap::new(); + + fn dp(chars: &Vec, lo: usize, hi: usize, memo: &mut HashMap<(usize, usize), HashSet>) -> HashSet { + if let Some(val) = memo.get(&(lo, hi)) { + return val.clone(); + } + if lo + 1 == hi { + let val = chars[lo].to_digit(10).unwrap() as i32; + let mut set = HashSet::new(); + set.insert(val); + memo.insert((lo, hi), set.clone()); + return set; + } + let mut result = HashSet::new(); + let mut mid = lo + 1; + while mid < hi { + let left = dp(chars, lo, mid, memo); + let right = dp(chars, mid + 1, hi, memo); + for &x in &left { + for &y in &right { + if chars[mid] == '+' && x + y <= 1000 { + result.insert(x + y); + } else if chars[mid] == '*' && x * y <= 1000 { + result.insert(x * y); + } + } + } + mid += 2; + } + memo.insert((lo, hi), result.clone()); + result + } + + // evaluate target respecting precedence + let mut nums: Vec = Vec::new(); + let mut ops: Vec = Vec::new(); + for &c in &s_chars { + if c.is_digit(10) { + nums.push(c.to_digit(10).unwrap() as i32); + } else if c == '+' || c == '*' { + while !ops.is_empty() && Self::precedence(ops[ops.len()-1]) >= Self::precedence(c) { + Self::apply(&mut nums, &mut ops); + } + ops.push(c); + } + } + while !ops.is_empty() { + Self::apply(&mut nums, &mut ops); + } + let target = nums[nums.len()-1]; + + let cand = dp(&s_chars, 0, s_chars.len(), &mut memo); + let mut score = 0; + for x in answers { + if x == target { + score += 5; + } else if cand.contains(&x) { + score += 2; + } + } + score + } + + fn precedence(c: char) -> i32 { + if c == '*' { 2 } else { 1 } + } + + fn apply(nums: &mut Vec, ops: &mut Vec) { + let b = nums.pop().unwrap(); + let a = nums.pop().unwrap(); + let op = ops.pop().unwrap(); + nums.push(if op == '+' { a + b } else { a * b }); + } +} diff --git a/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.swift b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.swift new file mode 100644 index 00000000..56012b24 --- /dev/null +++ b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.swift @@ -0,0 +1,71 @@ +class Solution { + func scoreOfStudents(_ s: String, _ answers: [Int]) -> Int { + var memo = [String: Set]() + + func fn(_ lo: Int, _ hi: Int) -> Set { + let key = "\(lo),\(hi)" + if let cached = memo[key] { return cached } + let chars = Array(s) + if lo + 1 == hi { + let val = Int(String(chars[lo]))! + memo[key] = [val] + return [val] + } + var result = Set() + var mid = lo + 1 + while mid < hi { + let left = fn(lo, mid) + let right = fn(mid + 1, hi) + for x in left { + for y in right { + if chars[mid] == "+" && x + y <= 1000 { + result.insert(x + y) + } else if chars[mid] == "*" && x * y <= 1000 { + result.insert(x * y) + } + } + } + mid += 2 + } + memo[key] = result + return result + } + + // evaluate target with precedence + var nums = [Int]() + var ops = [Character]() + let chars = Array(s) + for i in 0..= precedence(c) { + apply(&nums, &ops) + } + ops.append(c) + } + } + while !ops.isEmpty { apply(&nums, &ops) } + let target = nums.last! + + let cand = fn(0, s.count) + var score = 0 + for x in answers { + if x == target { score += 5 } + else if cand.contains(x) { score += 2 } + } + return score + } + + private func precedence(_ c: Character) -> Int { + return c == "*" ? 2 : 1 + } + + private func apply(_ nums: inout [Int], _ ops: inout [Character]) { + let b = nums.removeLast() + let a = nums.removeLast() + let op = ops.removeLast() + nums.append(op == "+" ? a + b : a * b) + } +} diff --git a/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.ts b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.ts new file mode 100644 index 00000000..2dec9eef --- /dev/null +++ b/tests/2001-2500/2019. the-score-of-students-solving-math-expression/sol.ts @@ -0,0 +1,66 @@ +function scoreOfStudents(s: string, answers: number[]): number { + const memo = new Map>(); + + function fn(lo: number, hi: number): Set { + const key = `${lo},${hi}`; + if (memo.has(key)) return memo.get(key)!; + if (lo + 1 === hi) { + const val = new Set([parseInt(s[lo])]); + memo.set(key, val); + return val; + } + const result = new Set(); + for (let mid = lo + 1; mid < hi; mid += 2) { + for (const x of fn(lo, mid)) { + for (const y of fn(mid + 1, hi)) { + if (s[mid] === "+" && x + y <= 1000) { + result.add(x + y); + } else if (s[mid] === "*" && x * y <= 1000) { + result.add(x * y); + } + } + } + } + memo.set(key, result); + return result; + } + + // evaluate target with precedence + const nums: number[] = []; + const ops: string[] = []; + for (let i = 0; i < s.length; i++) { + const c = s[i]; + if (c >= "0" && c <= "9") { + nums.push(parseInt(c)); + } else if (c === "+" || c === "*") { + while ( + ops.length > 0 && + precedence(ops[ops.length - 1]) >= precedence(c) + ) { + apply(nums, ops); + } + ops.push(c); + } + } + while (ops.length > 0) apply(nums, ops); + const target = nums[nums.length - 1]; + + const cand = fn(0, s.length); + let score = 0; + for (const x of answers) { + if (x === target) score += 5; + else if (cand.has(x)) score += 2; + } + return score; +} + +function precedence(c: string): number { + return c === "*" ? 2 : 1; +} + +function apply(nums: number[], ops: string[]) { + const b = nums.pop()!; + const a = nums.pop()!; + const op = ops.pop()!; + nums.push(op === "+" ? a + b : a * b); +} diff --git a/tests/2001-2500/2022. convert-1d-array-into-2d-array/manifest.yaml b/tests/2001-2500/2022. convert-1d-array-into-2d-array/manifest.yaml new file mode 100644 index 00000000..6100c0a5 --- /dev/null +++ b/tests/2001-2500/2022. convert-1d-array-into-2d-array/manifest.yaml @@ -0,0 +1,1205 @@ +entry: + id: 2022 + title: "convert-1d-array-into-2d-array" + params: + original: + type: array + items: + type: int + m: + type: int + n: + type: int + call: + cpp: "Solution().construct2DArray({original}, {m}, {n})" + rust: "Solution::construct2_d_array({original}, {m}, {n})" + python3: "Solution().construct2DArray({original}, {m}, {n})" + python2: "Solution().construct2DArray({original}, {m}, {n})" + ruby: "construct2_d_array({original}, {m}, {n})" + java: "new Solution().construct2DArray({original}, {m}, {n})" + csharp: "new Solution().Construct2DArray({original}, {m}, {n})" + kotlin: "Solution().construct2DArray({original}, {m}, {n})" + go: "construct2DArray({original}, {m}, {n})" + dart: "Solution().construct2DArray({original}, {m}, {n})" + swift: "Solution().construct2DArray({original}, {m}, {n})" + typescript: "construct2DArray({original}, {m}, {n})" + +judge: + type: "exact" + +limits: + time_ms: 200 + memory_mb: 300 + +oracle: + python3: + call: "Checker().construct2DArray(original, m, n, {result})" + checker: | + class Checker: + def construct2DArray(self, original, m, n, result): + if not isinstance(result, list): + return False + if m * n != len(original): + return result == [] + if len(result) != m: + return False + return all(isinstance(row, list) and len(row) == n and + row == original[i * n:(i + 1) * n] + for i, row in enumerate(result)) + +seed: 2022 + +tests: + - name: "example_two_by_two" + in: + original: [1, 2, 3, 4] + m: 2 + n: 2 + out: + - [1, 2] + - [3, 4] + + - name: "example_one_by_three" + in: + original: [1, 2, 3] + m: 1 + n: 3 + out: + - [1, 2, 3] + + - name: "example_impossible" + in: + original: [1, 2] + m: 1 + n: 1 + out: [] + + - name: "single_element" + in: + original: [7] + m: 1 + n: 1 + out: + - [7] + + - name: "single_row_five" + in: + original: [5, 4, 3, 2, 1] + m: 1 + n: 5 + out: + - [5, 4, 3, 2, 1] + + - name: "five_rows_single_column" + in: + original: [5, 4, 3, 2, 1] + m: 5 + n: 1 + out: + - [5] + - [4] + - [3] + - [2] + - [1] + + - name: "three_by_four" + in: + original: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + m: 3 + n: 4 + out: + - [1, 2, 3, 4] + - [5, 6, 7, 8] + - [9, 10, 11, 12] + + - name: "four_by_three" + in: + original: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120] + m: 4 + n: 3 + out: + - [10, 20, 30] + - [40, 50, 60] + - [70, 80, 90] + - [100, 110, 120] + + - name: "negative_not_allowed_but_positive_bounds" + in: + original: [1, 100000, 99999, 2] + m: 2 + n: 2 + out: + - [1, 100000] + - [99999, 2] + + - name: "repeated_values" + in: + original: [8, 8, 8, 8, 8, 8] + m: 2 + n: 3 + out: + - [8, 8, 8] + - [8, 8, 8] + + - name: "alternating_values" + in: + original: [1, 100000, 1, 100000, 1, 100000] + m: 3 + n: 2 + out: + - [1, 100000] + - [1, 100000] + - [1, 100000] + + - name: "impossible_too_many_elements" + in: + original: [1, 2, 3, 4, 5, 6, 7] + m: 2 + n: 3 + out: [] + + - name: "impossible_too_few_elements" + in: + original: [1, 2, 3, 4, 5] + m: 2 + n: 3 + out: [] + + - name: "mismatch_one_dimension" + in: + original: [9, 8, 7, 6] + m: 4 + n: 2 + out: [] + + - name: "large_values_two_by_two" + in: + original: [99998, 99999, 100000, 1] + m: 2 + n: 2 + out: + - [99998, 99999] + - [100000, 1] + + - name: "six_by_two" + in: + original: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8] + m: 6 + n: 2 + out: + - [3, 1] + - [4, 1] + - [5, 9] + - [2, 6] + - [5, 3] + - [5, 8] + + - name: "two_by_six" + in: + original: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8] + m: 2 + n: 6 + out: + - [3, 1, 4, 1, 5, 9] + - [2, 6, 5, 3, 5, 8] + + - name: "seven_by_three" + in: + original: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + ] + m: 7 + n: 3 + out: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + - [10, 11, 12] + - [13, 14, 15] + - [16, 17, 18] + - [19, 20, 21] + + - name: "three_by_seven" + in: + original: + [ + 21, + 20, + 19, + 18, + 17, + 16, + 15, + 14, + 13, + 12, + 11, + 10, + 9, + 8, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + ] + m: 3 + n: 7 + out: + - [21, 20, 19, 18, 17, 16, 15] + - [14, 13, 12, 11, 10, 9, 8] + - [7, 6, 5, 4, 3, 2, 1] + + - name: "eight_by_four" + in: + original: + [ + 1, + 3, + 5, + 7, + 9, + 11, + 13, + 15, + 17, + 19, + 21, + 23, + 25, + 27, + 29, + 31, + 33, + 35, + 37, + 39, + 41, + 43, + 45, + 47, + 49, + 51, + 53, + 55, + 57, + 59, + 61, + 63, + ] + m: 8 + n: 4 + out: + - [1, 3, 5, 7] + - [9, 11, 13, 15] + - [17, 19, 21, 23] + - [25, 27, 29, 31] + - [33, 35, 37, 39] + - [41, 43, 45, 47] + - [49, 51, 53, 55] + - [57, 59, 61, 63] + + - name: "nine_by_two" + in: + original: [9, 8, 7, 6, 5, 4, 3, 2, 1, 10, 20, 30, 40, 50, 60, 70, 80, 90] + m: 9 + n: 2 + out: + - [9, 8] + - [7, 6] + - [5, 4] + - [3, 2] + - [1, 10] + - [20, 30] + - [40, 50] + - [60, 70] + - [80, 90] + + - name: "ten_by_one" + in: + original: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + m: 10 + n: 1 + out: + - [10] + - [9] + - [8] + - [7] + - [6] + - [5] + - [4] + - [3] + - [2] + - [1] + + - name: "one_by_ten" + in: + original: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + m: 1 + n: 10 + out: + - [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + + - name: "zeros_not_allowed_use_minimum" + in: + original: [1, 1, 2, 2, 3, 3] + m: 2 + n: 3 + out: + - [1, 1, 2] + - [2, 3, 3] + + - name: "prime_sequence" + in: + original: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37] + m: 3 + n: 4 + out: + - [2, 3, 5, 7] + - [11, 13, 17, 19] + - [23, 29, 31, 37] + + - name: "product_boundary_100" + in: + original: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + 63, + 64, + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + 99, + 100, + ] + m: 10 + n: 10 + out: + - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] + - [21, 22, 23, 24, 25, 26, 27, 28, 29, 30] + - [31, 32, 33, 34, 35, 36, 37, 38, 39, 40] + - [41, 42, 43, 44, 45, 46, 47, 48, 49, 50] + - [51, 52, 53, 54, 55, 56, 57, 58, 59, 60] + - [61, 62, 63, 64, 65, 66, 67, 68, 69, 70] + - [71, 72, 73, 74, 75, 76, 77, 78, 79, 80] + - [81, 82, 83, 84, 85, 86, 87, 88, 89, 90] + - [91, 92, 93, 94, 95, 96, 97, 98, 99, 100] + + - name: "product_boundary_120" + in: + original: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + 63, + 64, + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 91, + 92, + 93, + 94, + 95, + 96, + 97, + 98, + 99, + 100, + 101, + 102, + 103, + 104, + 105, + 106, + 107, + 108, + 109, + 110, + 111, + 112, + 113, + 114, + 115, + 116, + 117, + 118, + 119, + 120, + ] + m: 12 + n: 10 + out: + - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + - [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] + - [21, 22, 23, 24, 25, 26, 27, 28, 29, 30] + - [31, 32, 33, 34, 35, 36, 37, 38, 39, 40] + - [41, 42, 43, 44, 45, 46, 47, 48, 49, 50] + - [51, 52, 53, 54, 55, 56, 57, 58, 59, 60] + - [61, 62, 63, 64, 65, 66, 67, 68, 69, 70] + - [71, 72, 73, 74, 75, 76, 77, 78, 79, 80] + - [81, 82, 83, 84, 85, 86, 87, 88, 89, 90] + - [91, 92, 93, 94, 95, 96, 97, 98, 99, 100] + - [101, 102, 103, 104, 105, 106, 107, 108, 109, 110] + - [111, 112, 113, 114, 115, 116, 117, 118, 119, 120] + + - name: "impossible_large_product" + in: + original: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + m: 40000 + n: 40000 + out: [] + + - name: "max_element_single" + in: + original: [100000] + m: 1 + n: 1 + out: + - [100000] + + - name: "max_elements_four" + in: + original: [100000, 100000, 100000, 100000] + m: 2 + n: 2 + out: + - [100000, 100000] + - [100000, 100000] + + - name: "twelve_by_one" + in: + original: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23] + m: 12 + n: 1 + out: + - [1] + - [3] + - [5] + - [7] + - [9] + - [11] + - [13] + - [15] + - [17] + - [19] + - [21] + - [23] + + - name: "one_by_twelve" + in: + original: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23] + m: 1 + n: 12 + out: + - [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23] + + - name: "sixteen_by_four" + in: + original: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + 63, + 64, + ] + m: 16 + n: 4 + out: + - [1, 2, 3, 4] + - [5, 6, 7, 8] + - [9, 10, 11, 12] + - [13, 14, 15, 16] + - [17, 18, 19, 20] + - [21, 22, 23, 24] + - [25, 26, 27, 28] + - [29, 30, 31, 32] + - [33, 34, 35, 36] + - [37, 38, 39, 40] + - [41, 42, 43, 44] + - [45, 46, 47, 48] + - [49, 50, 51, 52] + - [53, 54, 55, 56] + - [57, 58, 59, 60] + - [61, 62, 63, 64] + + - name: "impossible_product_near_match" + in: + original: [1, 2, 3, 4, 5, 6, 7, 8, 9] + m: 2 + n: 5 + out: [] + + - name: "twenty_by_three" + in: + original: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + ] + m: 20 + n: 3 + out: + - [1, 2, 3] + - [4, 5, 6] + - [7, 8, 9] + - [10, 11, 12] + - [13, 14, 15] + - [16, 17, 18] + - [19, 20, 21] + - [22, 23, 24] + - [25, 26, 27] + - [28, 29, 30] + - [31, 32, 33] + - [34, 35, 36] + - [37, 38, 39] + - [40, 41, 42] + - [43, 44, 45] + - [46, 47, 48] + - [49, 50, 51] + - [52, 53, 54] + - [55, 56, 57] + - [58, 59, 60] + + - name: "twenty_by_three_impossible" + in: + original: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + ] + m: 20 + n: 3 + out: [] + + - name: "thirty_by_two" + in: + original: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + ] + m: 30 + n: 2 + out: + - [1, 2] + - [3, 4] + - [5, 6] + - [7, 8] + - [9, 10] + - [11, 12] + - [13, 14] + - [15, 16] + - [17, 18] + - [19, 20] + - [21, 22] + - [23, 24] + - [25, 26] + - [27, 28] + - [29, 30] + - [31, 32] + - [33, 34] + - [35, 36] + - [37, 38] + - [39, 40] + - [41, 42] + - [43, 44] + - [45, 46] + - [47, 48] + - [49, 50] + - [51, 52] + - [53, 54] + - [55, 56] + - [57, 58] + - [59, 60] + + - name: "thirty_by_two_impossible" + in: + original: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + ] + m: 30 + n: 2 + out: [] + + - name: "forty_by_one" + in: + original: + [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + ] + m: 40 + n: 1 + out: + - [1] + - [2] + - [3] + - [4] + - [5] + - [6] + - [7] + - [8] + - [9] + - [10] + - [11] + - [12] + - [13] + - [14] + - [15] + - [16] + - [17] + - [18] + - [19] + - [20] + - [21] + - [22] + - [23] + - [24] + - [25] + - [26] + - [27] + - [28] + - [29] + - [30] + - [31] + - [32] + - [33] + - [34] + - [35] + - [36] + - [37] + - [38] + - [39] + - [40] diff --git a/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.cpp b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.cpp new file mode 100644 index 00000000..5c7bfb09 --- /dev/null +++ b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + vector> construct2DArray(vector& original, int m, int n) { + int k = original.size(); + if (m * n != k) return {}; + vector> ans(m, vector(n)); + int idx = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + ans[i][j] = original[idx++]; + } + } + return ans; + } +}; diff --git a/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.cs b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.cs new file mode 100644 index 00000000..07ffa4eb --- /dev/null +++ b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.cs @@ -0,0 +1,14 @@ +public class Solution { + public int[][] Construct2DArray(int[] original, int m, int n) { + int k = original.Length; + if (m * n != k) return new int[0][]; + int[][] ans = new int[m][]; + for (int i = 0; i < m; i++) { + ans[i] = new int[n]; + for (int j = 0; j < n; j++) { + ans[i][j] = original[i * n + j]; + } + } + return ans; + } +} diff --git a/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.dart b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.dart new file mode 100644 index 00000000..ac65a1fa --- /dev/null +++ b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.dart @@ -0,0 +1,14 @@ +class Solution { + List> construct2DArray(List original, int m, int n) { + int k = original.length; + if (m * n != k) return []; + List> ans = List.generate(m, (_) => List.filled(n, 0)); + int idx = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + ans[i][j] = original[idx++]; + } + } + return ans; + } +} diff --git a/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.go b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.go new file mode 100644 index 00000000..3cfe7580 --- /dev/null +++ b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.go @@ -0,0 +1,16 @@ +func construct2DArray(original []int, m int, n int) [][]int { + k := len(original) + if m*n != k { + return [][]int{} + } + ans := make([][]int, m) + idx := 0 + for i := 0; i < m; i++ { + ans[i] = make([]int, n) + for j := 0; j < n; j++ { + ans[i][j] = original[idx] + idx++ + } + } + return ans +} diff --git a/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.java b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.java new file mode 100644 index 00000000..825f34d2 --- /dev/null +++ b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.java @@ -0,0 +1,14 @@ +class Solution { + public int[][] construct2DArray(int[] original, int m, int n) { + int k = original.length; + if (m * n != k) return new int[0][0]; + int[][] ans = new int[m][n]; + int idx = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + ans[i][j] = original[idx++]; + } + } + return ans; + } +} diff --git a/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.kt b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.kt new file mode 100644 index 00000000..640479b4 --- /dev/null +++ b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.kt @@ -0,0 +1,14 @@ +class Solution { + fun construct2DArray(original: IntArray, m: Int, n: Int): Array { + val k = original.size + if (m * n != k) return emptyArray() + val ans = Array(m) { IntArray(n) } + var idx = 0 + for (i in 0 until m) { + for (j in 0 until n) { + ans[i][j] = original[idx++] + } + } + return ans + } +} diff --git a/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.py b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.py new file mode 100644 index 00000000..615c5ce5 --- /dev/null +++ b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.py @@ -0,0 +1,14 @@ +class Solution: + def construct2DArray(self, original, m, n): + k = len(original) + if m * n != k: + return [] + ans = [] + idx = 0 + while idx < k: + temp = [] + for _ in range(n): + temp.append(original[idx]) + idx += 1 + ans.append(temp) + return ans diff --git a/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.py2 b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.py2 new file mode 100644 index 00000000..f57bfe4a --- /dev/null +++ b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.py2 @@ -0,0 +1,20 @@ +class Solution(object): + def construct2DArray(self, original, m, n): + """ + :type original: List[int] + :type m: int + :type n: int + :rtype: List[List[int]] + """ + k = len(original) + if m * n != k: + return [] + ans = [] + idx = 0 + while idx < k: + temp = [] + for _ in range(n): + temp.append(original[idx]) + idx += 1 + ans.append(temp) + return ans diff --git a/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.rb b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.rb new file mode 100644 index 00000000..9af826ed --- /dev/null +++ b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.rb @@ -0,0 +1,19 @@ +# @param {Integer[]} original +# @param {Integer} m +# @param {Integer} n +# @return {Integer[][]} +def construct2_d_array(original, m, n) + k = original.length + return [] if m * n != k + ans = [] + idx = 0 + while idx < k + temp = [] + n.times do + temp << original[idx] + idx += 1 + end + ans << temp + end + ans +end diff --git a/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.rs b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.rs new file mode 100644 index 00000000..b064eec2 --- /dev/null +++ b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn construct2_d_array(original: Vec, m: i32, n: i32) -> Vec> { + let k = original.len() as i32; + if m * n != k { + return Vec::new(); + } + let mut ans = vec![vec![0; n as usize]; m as usize]; + let mut idx = 0; + for i in 0..m as usize { + for j in 0..n as usize { + ans[i][j] = original[idx]; + idx += 1; + } + } + ans + } +} diff --git a/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.swift b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.swift new file mode 100644 index 00000000..b6a6bb80 --- /dev/null +++ b/tests/2001-2500/2022. convert-1d-array-into-2d-array/sol.swift @@ -0,0 +1,15 @@ +class Solution { + func construct2DArray(_ original: [Int], _ m: Int, _ n: Int) -> [[Int]] { + let k = original.count + if m * n != k { return [] } + var ans = Array(repeating: Array(repeating: 0, count: n), count: m) + var idx = 0 + for i in 0.. new Array(n).fill(0)); + let idx = 0; + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + ans[i][j] = original[idx++]; + } + } + return ans; +} diff --git a/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/manifest.yaml b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/manifest.yaml new file mode 100644 index 00000000..04b90335 --- /dev/null +++ b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/manifest.yaml @@ -0,0 +1,385 @@ +entry: + id: 2023 + title: "number-of-pairs-of-strings-with-concatenation-equal-to-target" + params: + nums: + type: array + items: + type: string + target: + type: string + call: + cpp: "Solution().numOfPairs({nums}, {target})" + rust: "Solution::num_of_pairs({nums}, {target})" + python3: "Solution().numOfPairs({nums}, {target})" + python2: "Solution().numOfPairs({nums}, {target})" + ruby: "num_of_pairs({nums}, {target})" + java: "new Solution().numOfPairs({nums}, {target})" + csharp: "new Solution().NumOfPairs({nums}, {target})" + kotlin: "Solution().numOfPairs({nums}, {target})" + go: "numOfPairs({nums}, {target})" + dart: "Solution().numOfPairs({nums}, {target})" + swift: "Solution().numOfPairs({nums}, {target})" + typescript: "numOfPairs({nums}, {target})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().numOfPairs(nums, target, {result})" + checker: | + class Checker: + def numOfPairs(self, nums, target, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + expected = 0 + for i in range(len(nums)): + for j in range(len(nums)): + if i != j and nums[i] + nums[j] == target: + expected += 1 + return result == expected + +seed: 2023 + +tests: + - name: example-one + in: + nums: ["777", "7", "77", "77"] + target: "7777" + out: 4 + judge: + type: "exact" + - name: example-two + in: + nums: ["123", "4", "12", "34"] + target: "1234" + out: 2 + judge: + type: "exact" + - name: example-three + in: + nums: ["1", "1", "1"] + target: "11" + out: 6 + judge: + type: "exact" + - name: no-pair + in: + nums: ["1", "2", "3"] + target: "12" + out: 1 + judge: + type: "exact" + - name: no-concatenation + in: + nums: ["12", "34", "56"] + target: "12345" + out: 0 + judge: + type: "exact" + - name: two-identical + in: + nums: ["5", "5"] + target: "55" + out: 2 + judge: + type: "exact" + - name: repeated-three + in: + nums: ["12", "12", "12", "12"] + target: "1212" + out: 12 + judge: + type: "exact" + - name: ordered-pairs + in: + nums: ["1", "23", "12", "3"] + target: "123" + out: 2 + judge: + type: "exact" + - name: prefix-only + in: + nums: ["12", "1", "2", "21"] + target: "121" + out: 2 + judge: + type: "exact" + - name: suffix-missing + in: + nums: ["9", "99", "999"] + target: "9999" + out: 2 + judge: + type: "exact" + - name: different-splits + in: + nums: ["1", "23", "123", "2", "3"] + target: "123" + out: 1 + judge: + type: "exact" + - name: length-two-split + in: + nums: ["10", "20", "30", "1020"] + target: "1020" + out: 1 + judge: + type: "exact" + - name: long-single-pair + in: + nums: ["1234567890", "9876543210", "12345678909876543210"] + target: "12345678909876543210" + out: 1 + judge: + type: "exact" + - name: many-decoys + in: + nums: ["1", "2", "4", "8", "16", "32"] + target: "48" + out: 1 + judge: + type: "exact" + - name: repeated-left + in: + nums: ["1", "1", "1", "23", "123"] + target: "123" + out: 3 + judge: + type: "exact" + - name: repeated-right + in: + nums: ["12", "3", "3", "3", "0"] + target: "123" + out: 3 + judge: + type: "exact" + - name: one-digit-zero-free + in: + nums: ["2", "3", "4", "5"] + target: "45" + out: 1 + judge: + type: "exact" + - name: long-target-no-split + in: + nums: ["1", "11", "111", "1111"] + target: "111111" + out: 2 + judge: + type: "exact" + - name: same-value-and-other-split + in: + nums: ["9", "9", "99", "999", "9999"] + target: "9999" + out: 4 + judge: + type: "exact" + - name: target-shorter-than-items + in: + nums: ["123", "12", "1", "2"] + target: "12" + out: 1 + judge: + type: "exact" + - name: all-distinct-pairs + in: + nums: ["11", "22", "33", "44", "55", "66"] + target: "1122" + out: 1 + judge: + type: "exact" + - name: target-with-large-digits + in: + nums: ["8", "9", "89", "98", "0"] + target: "898" + out: 2 + judge: + type: "exact" + - name: four-way-split + in: + nums: ["1", "2", "12", "3", "23", "123", "1234"] + target: "123" + out: 2 + judge: + type: "exact" + - name: duplicate-long + in: + nums: ["12345", "67890", "12345", "67890", "1"] + target: "1234567890" + out: 4 + judge: + type: "exact" + - name: no-leading-zero-data + in: + nums: ["10", "20", "1020", "2", "0"] + target: "1020" + out: 1 + judge: + type: "exact" + - name: maximal-count-small-alphabet + in: + nums: ["3", "3", "3", "3", "3", "3", "3", "3"] + target: "33" + out: 56 + judge: + type: "exact" + - name: asymmetric-order + in: + nums: ["123", "4", "1234", "12", "34", "1", "234"] + target: "1234" + out: 3 + judge: + type: "exact" + - name: nested-prefixes + in: + nums: ["1", "12", "123", "1234", "2", "23", "234"] + target: "1234" + out: 1 + judge: + type: "exact" + - name: target-length-one-impossible + in: + nums: ["1", "2", "3", "4"] + target: "1" + out: 0 + judge: + type: "exact" + - name: target-length-one-digit-pairs + in: + nums: ["1", "1", "2", "2", "3"] + target: "11" + out: 2 + judge: + type: "exact" + - name: large-number-strings + in: + nums: + [ + "99999999999999999999", + "88888888888888888888", + "99999999999999999999", + "88888888888888888888", + ] + target: "9999999999999999999988888888888888888888" + out: 4 + judge: + type: "exact" + - name: decoy-target-prefix + in: + nums: ["123", "456", "123456", "12", "345", "6"] + target: "123456" + out: 1 + judge: + type: "exact" + - name: duplicate-both-halves + in: + nums: ["45", "45", "67", "67", "4567", "4", "567"] + target: "4567" + out: 5 + judge: + type: "exact" + - name: all-unequal + in: + nums: ["7", "8", "78", "87", "9", "98"] + target: "789" + out: 1 + judge: + type: "exact" + - name: mixed-length-repetitions + in: + nums: ["2", "2", "22", "22", "222", "222"] + target: "2222" + out: 10 + judge: + type: "exact" + - name: generated-short-random + in: + nums: + gen: "array" + len: 100 + of: + gen: "str" + len: 1 + alphabet: "123456789" + elemType: "string" + target: + gen: "str" + len: 2 + alphabet: "123456789" + judge: + type: "exact" + seed: 101 + - name: generated-medium-random + in: + nums: + gen: "array" + len: 100 + of: + gen: "str" + len: 10 + alphabet: "123456789" + elemType: "string" + target: + gen: "str" + len: 20 + alphabet: "123456789" + judge: + type: "exact" + seed: 102 + - name: generated-long-random + in: + nums: + gen: "array" + len: 100 + of: + gen: "str" + len: 100 + alphabet: "123456789" + elemType: "string" + target: + gen: "str" + len: 100 + alphabet: "123456789" + judge: + type: "exact" + seed: 103 + - name: generated-single-digit-heavy + in: + nums: + gen: "array" + len: 100 + of: + gen: "str" + len: 1 + alphabet: "19" + elemType: "string" + target: + gen: "str" + len: 2 + alphabet: "19" + judge: + type: "exact" + seed: 104 + - name: generated-varied-lengths + in: + nums: + gen: "array" + len: 100 + of: + gen: "str" + len: 50 + alphabet: "123456789" + elemType: "string" + target: + gen: "str" + len: 50 + alphabet: "123456789" + judge: + type: "exact" + seed: 105 diff --git a/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.cpp b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.cpp new file mode 100644 index 00000000..30e68a79 --- /dev/null +++ b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int numOfPairs(vector& nums, string target) { + unordered_map freq; + for (const string& num : nums) { + freq[num]++; + } + + int totalCnt = 0; + + for (const string& num : nums) { + if (target.rfind(num, 0) == 0) { + string remain = target.substr(num.length()); + + if (remain == num) { + totalCnt += freq[remain] - 1; + } else { + totalCnt += freq[remain]; + } + } + } + + return totalCnt; + } +}; diff --git a/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.cs b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.cs new file mode 100644 index 00000000..5d428331 --- /dev/null +++ b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.cs @@ -0,0 +1,24 @@ +public class Solution { + public int NumOfPairs(string[] nums, string target) { + var freq = new Dictionary(); + foreach (var num in nums) { + freq[num] = freq.GetValueOrDefault(num, 0) + 1; + } + + int totalCnt = 0; + + foreach (var num in nums) { + if (target.StartsWith(num)) { + string remain = target.Substring(num.Length); + + if (remain == num) { + totalCnt += freq.GetValueOrDefault(remain, 0) - 1; + } else { + totalCnt += freq.GetValueOrDefault(remain, 0); + } + } + } + + return totalCnt; + } +} diff --git a/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.dart b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.dart new file mode 100644 index 00000000..05158704 --- /dev/null +++ b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.dart @@ -0,0 +1,24 @@ +class Solution { + int numOfPairs(List nums, String target) { + Map freq = {}; + for (var num in nums) { + freq[num] = (freq[num] ?? 0) + 1; + } + + int totalCnt = 0; + + for (var num in nums) { + if (target.startsWith(num)) { + String remain = target.substring(num.length); + + if (remain == num) { + totalCnt += (freq[remain] ?? 0) - 1; + } else { + totalCnt += freq[remain] ?? 0; + } + } + } + + return totalCnt; + } +} diff --git a/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.go b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.go new file mode 100644 index 00000000..6ab0cc8c --- /dev/null +++ b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.go @@ -0,0 +1,22 @@ +func numOfPairs(nums []string, target string) int { + freq := make(map[string]int) + for _, num := range nums { + freq[num]++ + } + + totalCnt := 0 + + for _, num := range nums { + if strings.HasPrefix(target, num) { + remain := target[len(num):] + + if remain == num { + totalCnt += freq[remain] - 1 + } else { + totalCnt += freq[remain] + } + } + } + + return totalCnt +} diff --git a/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.java b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.java new file mode 100644 index 00000000..72259e3a --- /dev/null +++ b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.java @@ -0,0 +1,24 @@ +class Solution { + public int numOfPairs(String[] nums, String target) { + Map freq = new HashMap<>(); + for (String num : nums) { + freq.put(num, freq.getOrDefault(num, 0) + 1); + } + + int totalCnt = 0; + + for (String num : nums) { + if (target.startsWith(num)) { + String remain = target.substring(num.length()); + + if (remain.equals(num)) { + totalCnt += freq.getOrDefault(remain, 0) - 1; + } else { + totalCnt += freq.getOrDefault(remain, 0); + } + } + } + + return totalCnt; + } +} diff --git a/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.kt b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.kt new file mode 100644 index 00000000..d126fc7a --- /dev/null +++ b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.kt @@ -0,0 +1,21 @@ +class Solution { + fun numOfPairs(nums: Array, target: String): Int { + val freq = nums.groupingBy { it }.eachCount() + + var totalCnt = 0 + + for (num in nums) { + if (target.startsWith(num)) { + val remain = target.substring(num.length) + + if (remain == num) { + totalCnt += (freq[remain] ?: 0) - 1 + } else { + totalCnt += freq[remain] ?: 0 + } + } + } + + return totalCnt + } +} diff --git a/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.py b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.py new file mode 100644 index 00000000..8227333c --- /dev/null +++ b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.py @@ -0,0 +1,24 @@ +from collections import Counter + + +class Solution(object): + def numOfPairs(self, nums, target): + """ + :type nums: List[str] + :type target: str + :rtype: int + """ + num_2_freq = Counter(nums) + + total_cnt = 0 + + for num in nums: + if target.startswith(num): + remain = target[len(num) :] + + if remain == num: + total_cnt += num_2_freq[remain] - 1 + else: + total_cnt += num_2_freq[remain] + + return total_cnt diff --git a/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.py2 b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.py2 new file mode 100644 index 00000000..a48cc00e --- /dev/null +++ b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.py2 @@ -0,0 +1,22 @@ +class Solution(object): + def numOfPairs(self, nums, target): + """ + :type nums: List[str] + :type target: str + :rtype: int + """ + from collections import Counter + num_2_freq = Counter(nums) + + total_cnt = 0 + + for num in nums: + if target.startswith(num): + remain = target[len(num):] + + if remain == num: + total_cnt += num_2_freq[remain] - 1 + else: + total_cnt += num_2_freq[remain] + + return total_cnt diff --git a/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.rb b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.rb new file mode 100644 index 00000000..0e24f76e --- /dev/null +++ b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.rb @@ -0,0 +1,22 @@ +# @param {String[]} nums +# @param {String} target +# @return {Integer} +def num_of_pairs(nums, target) + freq = nums.tally + + total_cnt = 0 + + nums.each do |num| + if target.start_with?(num) + remain = target[num.length..] + + if remain == num + total_cnt += freq[remain] - 1 + else + total_cnt += freq[remain].to_i + end + end + end + + total_cnt +end diff --git a/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.rs b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.rs new file mode 100644 index 00000000..2376b0ac --- /dev/null +++ b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn num_of_pairs(nums: Vec, target: String) -> i32 { + use std::collections::HashMap; + + let mut freq: HashMap<&str, i32> = HashMap::new(); + for num in &nums { + *freq.entry(num).or_insert(0) += 1; + } + + let mut total_cnt = 0; + + for num in &nums { + if target.starts_with(num.as_str()) { + let remain = &target[num.len()..]; + + if remain == num { + total_cnt += freq.get(remain).unwrap_or(&0) - 1; + } else { + total_cnt += freq.get(remain).unwrap_or(&0); + } + } + } + + total_cnt + } +} diff --git a/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.swift b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.swift new file mode 100644 index 00000000..404d9a5e --- /dev/null +++ b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.swift @@ -0,0 +1,25 @@ +class Solution { + func numOfPairs(_ nums: [String], _ target: String) -> Int { + var freq: [String: Int] = [:] + for num in nums { + freq[num, default: 0] += 1 + } + + var totalCnt = 0 + + let targetChars = Array(target) + for num in nums { + if target.hasPrefix(num) { + let remain = String(targetChars[num.count...]) + + if remain == num { + totalCnt += (freq[remain] ?? 0) - 1 + } else { + totalCnt += freq[remain] ?? 0 + } + } + } + + return totalCnt + } +} diff --git a/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.ts b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.ts new file mode 100644 index 00000000..88ed5793 --- /dev/null +++ b/tests/2001-2500/2023. number-of-pairs-of-strings-with-concatenation-equal-to-target/sol.ts @@ -0,0 +1,22 @@ +function numOfPairs(nums: string[], target: string): number { + const freq: Record = {}; + for (const num of nums) { + freq[num] = (freq[num] || 0) + 1; + } + + let totalCnt = 0; + + for (const num of nums) { + if (target.startsWith(num)) { + const remain = target.substring(num.length); + + if (remain === num) { + totalCnt += (freq[remain] || 0) - 1; + } else { + totalCnt += freq[remain] || 0; + } + } + } + + return totalCnt; +} diff --git a/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/manifest.yaml b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/manifest.yaml new file mode 100644 index 00000000..1915f15b --- /dev/null +++ b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/manifest.yaml @@ -0,0 +1,264 @@ +entry: + id: 2024 + title: "maximize-the-confusion-of-an-exam" + params: + answerKey: + type: string + k: + type: int + call: + cpp: "Solution().maxConsecutiveAnswers({answerKey}, {k})" + rust: "Solution::max_consecutive_answers({answerKey}, {k})" + python3: "Solution().maxConsecutiveAnswers({answerKey}, {k})" + python2: "Solution().maxConsecutiveAnswers({answerKey}, {k})" + ruby: "max_consecutive_answers({answerKey}, {k})" + java: "new Solution().maxConsecutiveAnswers({answerKey}, {k})" + csharp: "new Solution().MaxConsecutiveAnswers({answerKey}, {k})" + kotlin: "Solution().maxConsecutiveAnswers({answerKey}, {k})" + go: "maxConsecutiveAnswers({answerKey}, {k})" + dart: "Solution().maxConsecutiveAnswers({answerKey}, {k})" + swift: "Solution().maxConsecutiveAnswers({answerKey}, {k})" + typescript: "maxConsecutiveAnswers({answerKey}, {k})" + +judge: + type: "exact" + +limits: + time_ms: 2000 + memory_mb: 256 + +oracle: + python3: + call: "Checker().maxConsecutiveAnswers(answerKey, k, {result})" + checker: | + class Checker: + def maxConsecutiveAnswers(self, answerKey, k, result): + if not isinstance(result, int) or isinstance(result, bool): + return False + best = 0 + for target in ("T", "F"): + left = 0 + changes = 0 + for right, ch in enumerate(answerKey): + if ch != target: + changes += 1 + while changes > k: + if answerKey[left] != target: + changes -= 1 + left += 1 + best = max(best, right - left + 1) + return result == best + +seed: 2024 + +tests: + - name: example-1 + in: + answerKey: "TTFF" + k: 2 + out: 4 + - name: example-2 + in: + answerKey: "TFFT" + k: 1 + out: 3 + - name: example-3 + in: + answerKey: "TTFTTFTT" + k: 1 + out: 5 + - name: one-t + in: + answerKey: "T" + k: 1 + out: 1 + - name: one-f + in: + answerKey: "F" + k: 1 + out: 1 + - name: two-opposite-k1 + in: + answerKey: "TF" + k: 1 + out: 2 + - name: all-t + in: + answerKey: "TTTTTTTT" + k: 1 + out: 8 + - name: all-f + in: + answerKey: "FFFFFFFF" + k: 3 + out: 8 + - name: alternating-short + in: + answerKey: "TFTFTF" + k: 1 + out: 3 + - name: alternating-k2 + in: + answerKey: "TFTFTFTF" + k: 2 + out: 5 + - name: alternating-kall + in: + answerKey: "TFTFTFTF" + k: 8 + out: 8 + - name: single-mismatch-middle + in: + answerKey: "TTTFTTT" + k: 1 + out: 7 + - name: two-mismatches + in: + answerKey: "TTFTFTTT" + k: 1 + out: 5 + - name: long-t-run + in: + answerKey: "TTTTTFTTTTT" + k: 1 + out: 11 + - name: long-f-run + in: + answerKey: "FFFFFTFFFFF" + k: 1 + out: 11 + - name: balanced-k1 + in: + answerKey: "TTFFTTFF" + k: 1 + out: 3 + - name: balanced-k2 + in: + answerKey: "TTFFTTFF" + k: 2 + out: 6 + - name: alternating-nine + in: + answerKey: "TFTFTFTFT" + k: 3 + out: 7 + - name: mostly-t + in: + answerKey: "TTTTFTTFTTTT" + k: 2 + out: 12 + - name: mostly-f + in: + answerKey: "FFFFTFFTFFFF" + k: 2 + out: 12 + - name: runs-k1 + in: + answerKey: "TTFFFTTFFF" + k: 1 + out: 4 + - name: runs-k3 + in: + answerKey: "TTFFFTTFFF" + k: 3 + out: 9 + - name: short-blocks + in: + answerKey: "TFFTTFTTFF" + k: 2 + out: 6 + - name: sparse-t + in: + answerKey: "FTFFFFTFFFFF" + k: 1 + out: 10 + - name: sparse-f + in: + answerKey: "TFT" + k: 1 + out: 3 + - name: alternating-twelve + in: + answerKey: "TFTFTFTFTFTF" + k: 4 + out: 9 + - name: k-near-length + in: + answerKey: "TFTFFTTF" + k: 7 + out: 8 + - name: alternating-sixteen-k5 + in: + answerKey: "TFTFTFTFTFTFTFTF" + k: 5 + out: 11 + - name: alternating-sixteen-k6 + in: + answerKey: "TFTFTFTFTFTFTFTF" + k: 6 + out: 13 + - name: two-runs + in: + answerKey: "TTTTFFFFFFFF" + k: 2 + out: 10 + - name: three-runs + in: + answerKey: "TTTFFF" + k: 1 + out: 4 + - name: repeated-pattern + in: + answerKey: "TTFTTFTTFTTFT" + k: 2 + out: 8 + - name: long-alternating-static + in: + answerKey: "TFTFTFTFTFTFTFTFTFTF" + k: 2 + out: 5 + - name: boundary-k-one + in: + answerKey: "FFTTFFTTFFTT" + k: 1 + out: 3 + - name: boundary-k-length + in: + answerKey: "FTFTTFTF" + k: 8 + out: 8 + - name: generated-balanced + in: + answerKey: + gen: "str" + len: 50000 + alphabet: "TF" + k: 1 + - name: generated-k-quarter + in: + answerKey: + gen: "str" + len: 50000 + alphabet: "TF" + k: 12500 + - name: generated-k-half + in: + answerKey: + gen: "str" + len: 50000 + alphabet: "TF" + k: 25000 + - name: generated-k-large + in: + answerKey: + gen: "str" + len: 50000 + alphabet: "TF" + k: 40000 + - name: generated-k-max + in: + answerKey: + gen: "str" + len: 50000 + alphabet: "TF" + k: 50000 diff --git a/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.cpp b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.cpp new file mode 100644 index 00000000..572ce295 --- /dev/null +++ b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + int maxConsecutiveAnswers(string answerKey, int k) { + int l = 0; + int r = 0; + int falseCnt = 0; + int trueCnt = 0; + int result = 0; + int n = answerKey.size(); + while (r < n) { + if (answerKey[r] == 'T') { + trueCnt++; + } + if (answerKey[r] == 'F') { + falseCnt++; + } + while (trueCnt > k && falseCnt > k) { + if (answerKey[l] == 'T') { + trueCnt--; + } + if (answerKey[l] == 'F') { + falseCnt--; + } + l++; + } + result = max(result, r - l + 1); + r++; + } + return result; + } +}; diff --git a/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.cs b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.cs new file mode 100644 index 00000000..2297224f --- /dev/null +++ b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.cs @@ -0,0 +1,30 @@ +public class Solution { + public int MaxConsecutiveAnswers(string answerKey, int k) { + int l = 0; + int r = 0; + int falseCnt = 0; + int trueCnt = 0; + int result = 0; + int n = answerKey.Length; + while (r < n) { + if (answerKey[r] == 'T') { + trueCnt++; + } + if (answerKey[r] == 'F') { + falseCnt++; + } + while (trueCnt > k && falseCnt > k) { + if (answerKey[l] == 'T') { + trueCnt--; + } + if (answerKey[l] == 'F') { + falseCnt--; + } + l++; + } + result = Math.Max(result, r - l + 1); + r++; + } + return result; + } +} diff --git a/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.dart b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.dart new file mode 100644 index 00000000..53079c9a --- /dev/null +++ b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.dart @@ -0,0 +1,30 @@ +class Solution { + int maxConsecutiveAnswers(String answerKey, int k) { + int l = 0; + int r = 0; + int falseCnt = 0; + int trueCnt = 0; + int result = 0; + int n = answerKey.length; + while (r < n) { + if (answerKey[r] == 'T') { + trueCnt++; + } + if (answerKey[r] == 'F') { + falseCnt++; + } + while (trueCnt > k && falseCnt > k) { + if (answerKey[l] == 'T') { + trueCnt--; + } + if (answerKey[l] == 'F') { + falseCnt--; + } + l++; + } + result = result > (r - l + 1) ? result : (r - l + 1); + r++; + } + return result; + } +} diff --git a/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.go b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.go new file mode 100644 index 00000000..32a0926b --- /dev/null +++ b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.go @@ -0,0 +1,30 @@ +func maxConsecutiveAnswers(answerKey string, k int) int { + l := 0 + r := 0 + falseCnt := 0 + trueCnt := 0 + result := 0 + n := len(answerKey) + for r < n { + if answerKey[r] == 'T' { + trueCnt++ + } + if answerKey[r] == 'F' { + falseCnt++ + } + for trueCnt > k && falseCnt > k { + if answerKey[l] == 'T' { + trueCnt-- + } + if answerKey[l] == 'F' { + falseCnt-- + } + l++ + } + if r-l+1 > result { + result = r - l + 1 + } + r++ + } + return result +} diff --git a/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.java b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.java new file mode 100644 index 00000000..57cbdc81 --- /dev/null +++ b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.java @@ -0,0 +1,30 @@ +class Solution { + public int maxConsecutiveAnswers(String answerKey, int k) { + int l = 0; + int r = 0; + int falseCnt = 0; + int trueCnt = 0; + int result = 0; + int n = answerKey.length(); + while (r < n) { + if (answerKey.charAt(r) == 'T') { + trueCnt++; + } + if (answerKey.charAt(r) == 'F') { + falseCnt++; + } + while (trueCnt > k && falseCnt > k) { + if (answerKey.charAt(l) == 'T') { + trueCnt--; + } + if (answerKey.charAt(l) == 'F') { + falseCnt--; + } + l++; + } + result = Math.max(result, r - l + 1); + r++; + } + return result; + } +} diff --git a/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.kt b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.kt new file mode 100644 index 00000000..cc5fa1b3 --- /dev/null +++ b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.kt @@ -0,0 +1,30 @@ +class Solution { + fun maxConsecutiveAnswers(answerKey: String, k: Int): Int { + var l = 0 + var r = 0 + var falseCnt = 0 + var trueCnt = 0 + var result = 0 + val n = answerKey.length + while (r < n) { + if (answerKey[r] == 'T') { + trueCnt++ + } + if (answerKey[r] == 'F') { + falseCnt++ + } + while (trueCnt > k && falseCnt > k) { + if (answerKey[l] == 'T') { + trueCnt-- + } + if (answerKey[l] == 'F') { + falseCnt-- + } + l++ + } + result = maxOf(result, r - l + 1) + r++ + } + return result + } +} diff --git a/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.py b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.py new file mode 100644 index 00000000..fc1893db --- /dev/null +++ b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.py @@ -0,0 +1,22 @@ +class Solution: + def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int: + l = 0 + r = 0 + falseCnt = 0 + trueCnt = 0 + result = 0 + n = len(answerKey) + while r < n: + if answerKey[r] == "T": + trueCnt += 1 + if answerKey[r] == "F": + falseCnt += 1 + while trueCnt > k and falseCnt > k: + if answerKey[l] == "T": + trueCnt -= 1 + if answerKey[l] == "F": + falseCnt -= 1 + l += 1 + result = max(result, r - l + 1) + r += 1 + return result diff --git a/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.py2 b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.py2 new file mode 100644 index 00000000..d6624a93 --- /dev/null +++ b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.py2 @@ -0,0 +1,27 @@ +class Solution(object): + def maxConsecutiveAnswers(self, answerKey, k): + """ + :type answerKey: str + :type k: int + :rtype: int + """ + l = 0 + r = 0 + falseCnt = 0 + trueCnt = 0 + result = 0 + n = len(answerKey) + while r < n: + if answerKey[r] == 'T': + trueCnt += 1 + if answerKey[r] == 'F': + falseCnt += 1 + while trueCnt > k and falseCnt > k: + if answerKey[l] == 'T': + trueCnt -= 1 + if answerKey[l] == 'F': + falseCnt -= 1 + l += 1 + result = max(result, r - l + 1) + r += 1 + return result diff --git a/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.rb b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.rb new file mode 100644 index 00000000..23492ca8 --- /dev/null +++ b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.rb @@ -0,0 +1,31 @@ +# @param {String} answer_key +# @param {Integer} k +# @return {Integer} +def max_consecutive_answers(answer_key, k) + l = 0 + r = 0 + false_cnt = 0 + true_cnt = 0 + result = 0 + n = answer_key.length + while r < n + if answer_key[r] == 'T' + true_cnt += 1 + end + if answer_key[r] == 'F' + false_cnt += 1 + end + while true_cnt > k && false_cnt > k + if answer_key[l] == 'T' + true_cnt -= 1 + end + if answer_key[l] == 'F' + false_cnt -= 1 + end + l += 1 + end + result = [result, r - l + 1].max + r += 1 + end + result +end diff --git a/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.rs b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.rs new file mode 100644 index 00000000..203b9b57 --- /dev/null +++ b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.rs @@ -0,0 +1,31 @@ +impl Solution { + pub fn max_consecutive_answers(answer_key: String, k: i32) -> i32 { + let chars: Vec = answer_key.chars().collect(); + let mut l = 0; + let mut r = 0; + let mut false_cnt = 0; + let mut true_cnt = 0; + let mut result = 0; + let n = chars.len(); + while r < n { + if chars[r] == 'T' { + true_cnt += 1; + } + if chars[r] == 'F' { + false_cnt += 1; + } + while true_cnt > k && false_cnt > k { + if chars[l] == 'T' { + true_cnt -= 1; + } + if chars[l] == 'F' { + false_cnt -= 1; + } + l += 1; + } + result = result.max((r - l + 1) as i32); + r += 1; + } + result + } +} diff --git a/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.swift b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.swift new file mode 100644 index 00000000..d030c47f --- /dev/null +++ b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.swift @@ -0,0 +1,31 @@ +class Solution { + func maxConsecutiveAnswers(_ answerKey: String, _ k: Int) -> Int { + let chars = Array(answerKey) + var l = 0 + var r = 0 + var falseCnt = 0 + var trueCnt = 0 + var result = 0 + let n = chars.count + while r < n { + if chars[r] == "T" { + trueCnt += 1 + } + if chars[r] == "F" { + falseCnt += 1 + } + while trueCnt > k && falseCnt > k { + if chars[l] == "T" { + trueCnt -= 1 + } + if chars[l] == "F" { + falseCnt -= 1 + } + l += 1 + } + result = max(result, r - l + 1) + r += 1 + } + return result + } +} diff --git a/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.ts b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.ts new file mode 100644 index 00000000..8bfbb17e --- /dev/null +++ b/tests/2001-2500/2024. maximize-the-confusion-of-an-exam/sol.ts @@ -0,0 +1,28 @@ +function maxConsecutiveAnswers(answerKey: string, k: number): number { + let l = 0; + let r = 0; + let falseCnt = 0; + let trueCnt = 0; + let result = 0; + const n = answerKey.length; + while (r < n) { + if (answerKey[r] === "T") { + trueCnt++; + } + if (answerKey[r] === "F") { + falseCnt++; + } + while (trueCnt > k && falseCnt > k) { + if (answerKey[l] === "T") { + trueCnt--; + } + if (answerKey[l] === "F") { + falseCnt--; + } + l++; + } + result = Math.max(result, r - l + 1); + r++; + } + return result; +} From 104f9ee8d6bcd4679aa6413894085dee2e1923bb Mon Sep 17 00:00:00 2001 From: Andrey Litvitski Date: Sat, 15 Aug 2026 04:37:39 +0300 Subject: [PATCH 02/12] lil more --- .../1535. find-the-winner-of-an-array-game/manifest.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/1501-2000/1535. find-the-winner-of-an-array-game/manifest.yaml b/tests/1501-2000/1535. find-the-winner-of-an-array-game/manifest.yaml index 7a483a25..83499f95 100644 --- a/tests/1501-2000/1535. find-the-winner-of-an-array-game/manifest.yaml +++ b/tests/1501-2000/1535. find-the-winner-of-an-array-game/manifest.yaml @@ -119,7 +119,7 @@ tests: in: arr: [999999, 1, 500000, 1000000] k: 2 - out: 1000000 + out: 999999 - name: minimum-value-one in: arr: [1, 100, 2, 99] From 26dfaac8751a7f6df8d93e62d8d83526d45e46f4 Mon Sep 17 00:00:00 2001 From: Andrey Litvitski Date: Sun, 16 Aug 2026 03:04:37 +0300 Subject: [PATCH 03/12] lil more --- .../1535. find-the-winner-of-an-array-game/manifest.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/1501-2000/1535. find-the-winner-of-an-array-game/manifest.yaml b/tests/1501-2000/1535. find-the-winner-of-an-array-game/manifest.yaml index 83499f95..5845e8f9 100644 --- a/tests/1501-2000/1535. find-the-winner-of-an-array-game/manifest.yaml +++ b/tests/1501-2000/1535. find-the-winner-of-an-array-game/manifest.yaml @@ -139,7 +139,7 @@ tests: in: arr: [2, 6, 1, 5, 3, 4, 7] k: 5 - out: 7 + out: 6 - name: k-equals-one in: arr: [11, 4, 9, 2, 8] From abedecda0f5b6e6d2270fb0b7f9ae5de2f23ab66 Mon Sep 17 00:00:00 2001 From: Andrey Litvitski Date: Sun, 16 Aug 2026 03:28:46 +0300 Subject: [PATCH 04/12] lil more --- .../1563. stone-game-v/manifest.yaml | 48 +++++++++++++------ 1 file changed, 33 insertions(+), 15 deletions(-) diff --git a/tests/1501-2000/1563. stone-game-v/manifest.yaml b/tests/1501-2000/1563. stone-game-v/manifest.yaml index 1e21ade7..79f6da95 100644 --- a/tests/1501-2000/1563. stone-game-v/manifest.yaml +++ b/tests/1501-2000/1563. stone-game-v/manifest.yaml @@ -36,23 +36,41 @@ oracle: if not isinstance(result, int) or isinstance(result, bool): return False n = len(stoneValue) - pref = [0] + prefix = [0] for value in stoneValue: - pref.append(pref[-1] + value) - dp = [[0] * (n + 1) for _ in range(n + 1)] - for length in range(2, n + 1): + prefix.append(prefix[-1] + value) + dp = [[0] * n for _ in range(n)] + left_best = [[0] * n for _ in range(n)] + right_best = [[0] * n for _ in range(n)] + for length in range(1, n + 1): for left in range(n - length + 1): - right = left + length - best = 0 - for mid in range(left + 1, right): - a = pref[mid] - pref[left] - b = pref[right] - pref[mid] - if a <= b: - best = max(best, a + dp[left][mid]) - if b <= a: - best = max(best, b + dp[mid][right]) - dp[left][right] = best - return result == dp[0][n] + right = left + length - 1 + total = prefix[right + 1] - prefix[left] + if left < right: + lo, hi, split = left, right - 1, left - 1 + while lo <= hi: + mid = (lo + hi) // 2 + if 2 * (prefix[mid + 1] - prefix[left]) <= total: + split = mid + lo = mid + 1 + else: + hi = mid - 1 + if split >= left: + dp[left][right] = left_best[left][split] + lo, hi, first = left + 1, right, right + 1 + while lo <= hi: + mid = (lo + hi) // 2 + if 2 * (prefix[mid] - prefix[left]) >= total: + first = mid + hi = mid - 1 + else: + lo = mid + 1 + if first <= right: + dp[left][right] = max(dp[left][right], right_best[first][right]) + score = total + dp[left][right] + left_best[left][right] = max(score, left_best[left][right - 1] if right > left else 0) + right_best[left][right] = max(score, right_best[left + 1][right] if left < right else 0) + return result == dp[0][n - 1] seed: 1563 From 1033e018b540bc17e205390cf8e6e91fadf70093 Mon Sep 17 00:00:00 2001 From: Andrey Litvitski Date: Sun, 16 Aug 2026 20:38:19 +0300 Subject: [PATCH 05/12] lil more --- .../sol.py | 32 +++++++++---------- .../sol.rb | 15 ++++----- 2 files changed, 22 insertions(+), 25 deletions(-) diff --git a/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.py b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.py index f046567f..ad54747e 100644 --- a/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.py +++ b/tests/1501-2000/1707. maximum-xor-with-an-element-from-array/sol.py @@ -1,29 +1,33 @@ class Solution(object): def maximizeXor(self, nums, queries): - trie = [[-1, -1]] + child_zero = [-1] + child_one = [-1] def insert(num): node = 0 - for i in range(31, -1, -1): + for i in range(30, -1, -1): bit = (num >> i) & 1 - if trie[node][bit] == -1: - trie[node][bit] = len(trie) - trie.append([-1, -1]) - node = trie[node][bit] + children = child_one if bit else child_zero + if children[node] == -1: + children[node] = len(child_zero) + child_zero.append(-1) + child_one.append(-1) + node = children[node] def maxor(num): - if trie[0][0] == -1 and trie[0][1] == -1: + if child_zero[0] == -1 and child_one[0] == -1: return -1 node = 0 ans = 0 - for i in range(31, -1, -1): + for i in range(30, -1, -1): bit = (num >> i) & 1 opp = 1 - bit - if trie[node][opp] != -1: + opposite = child_one if opp else child_zero + if opposite[node] != -1: ans |= 1 << i - node = trie[node][opp] + node = opposite[node] else: - node = trie[node][bit] + node = (child_one if bit else child_zero)[node] return ans nums.sort() @@ -41,9 +45,3 @@ def maxor(num): idx += 1 res[i] = maxor(x) return res - - """ - :type nums: List[int] - :type queries: List[List[int]] - :rtype: List[int] - """ diff --git a/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.rb b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.rb index 39847444..43e03388 100644 --- a/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.rb +++ b/tests/1501-2000/1957. delete-characters-to-make-fancy-string/sol.rb @@ -1,21 +1,20 @@ # @param {String} s # @return {String} def make_fancy_string(s) - return "" if s.empty? - result = s[0] - last = s[0] - count = 1 + result = String.new + last = nil + count = 0 - (1...s.length).each do |i| - if s[i] != last - last = s[i] + s.each_char do |char| + if char != last + last = char count = 0 end count += 1 next if count > 2 - result += s[i] + result << char end result From 192fdd2f4b69ccfbfc66943bac8f51f775a3da76 Mon Sep 17 00:00:00 2001 From: Andrey Litvitski Date: Sun, 16 Aug 2026 22:53:32 +0300 Subject: [PATCH 06/12] lil more --- .../sol.py | 16 +--------------- .../sol.py2 | 15 +-------------- 2 files changed, 2 insertions(+), 29 deletions(-) diff --git a/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py index 7fffc7b6..13f6e665 100644 --- a/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py +++ b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py @@ -1,17 +1,3 @@ class Solution: def getMinDistance(self, nums: list[int], target: int, start: int) -> int: - - if nums[start] == target: - return 0 - - n = len(nums) - d = 1 - - while True: - if start - d >= 0 and nums[start - d] == target: - return d - - if start + d < n and nums[start + d] == target: - return d - - d += 1 + return min(abs(index - start) for index, value in enumerate(nums) if value == target) diff --git a/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py2 b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py2 index a412b43a..5d8d9a74 100644 --- a/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py2 +++ b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py2 @@ -6,17 +6,4 @@ class Solution(object): :type start: int :rtype: int """ - if nums[start] == target: - return 0 - - n = len(nums) - d = 1 - - while True: - if start - d >= 0 and nums[start - d] == target: - return d - - if start + d < n and nums[start + d] == target: - return d - - d += 1 + return min(abs(index - start) for index, value in enumerate(nums) if value == target) From 2ba97845ea45b4e7011244b1264da7706a173909 Mon Sep 17 00:00:00 2001 From: Andrey Litvitski Date: Sun, 16 Aug 2026 23:49:50 +0300 Subject: [PATCH 07/12] lil more --- .../1848. minimum-distance-to-the-target-element/sol.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py index 13f6e665..bf36db0d 100644 --- a/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py +++ b/tests/1501-2000/1848. minimum-distance-to-the-target-element/sol.py @@ -1,3 +1,5 @@ class Solution: def getMinDistance(self, nums: list[int], target: int, start: int) -> int: - return min(abs(index - start) for index, value in enumerate(nums) if value == target) + return min( + abs(index - start) for index, value in enumerate(nums) if value == target + ) From cf7f8e7ec909dcb6c8d36422b20ecfb45a236768 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 16 Aug 2026 03:15:00 +0000 Subject: [PATCH 08/12] update problems counter --- .badges/problems.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.badges/problems.json b/.badges/problems.json index 67737254..834ebb51 100644 --- a/.badges/problems.json +++ b/.badges/problems.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, "label": "problems", - "message": "1043", + "message": "1k", "color": "FFA116" } From fc63d5d128d03a10d0922a59f1e18f8e3a367f0c Mon Sep 17 00:00:00 2001 From: Andrey Litvitski Date: Mon, 17 Aug 2026 01:45:35 +0300 Subject: [PATCH 09/12] fix runner variable collisions --- core/Core/Test/Runner.hs | 114 +++++++++++++++++++-------------------- runtimes/python2/main.py | 3 +- runtimes/python3/main.py | 1 - 3 files changed, 56 insertions(+), 62 deletions(-) diff --git a/core/Core/Test/Runner.hs b/core/Core/Test/Runner.hs index 484c569f..ddf42b18 100644 --- a/core/Core/Test/Runner.hs +++ b/core/Core/Test/Runner.hs @@ -352,110 +352,110 @@ buildMainSnippet lang idx prelude callExpr = T.unlines ( ["fmt.Println(" <> quotedMarker <> ")"] ++ prelude - ++ [ "cur" <> suffix <> " := time.Now().UnixNano() / 1_000_000", - "a" <> suffix <> " := " <> callExpr, - "now" <> suffix <> " := time.Now().UnixNano() / 1_000_000", - "fmt.Println(now" <> suffix <> " - cur" <> suffix <> ")", - "fmt.Println(toJson(a" <> suffix <> "))" + ++ [ "openleetcode_timer_start_" <> suffix <> " := time.Now().UnixNano() / 1_000_000", + "openleetcode_result_" <> suffix <> " := " <> callExpr, + "openleetcode_timer_end_" <> suffix <> " := time.Now().UnixNano() / 1_000_000", + "fmt.Println(openleetcode_timer_end_" <> suffix <> " - openleetcode_timer_start_" <> suffix <> ")", + "fmt.Println(toJson(openleetcode_result_" <> suffix <> "))" ] ) TypeScript -> T.unlines ( ["console.log(" <> quotedMarker <> ");"] ++ prelude - ++ [ "const _start" <> suffix <> " = Date.now();", - "const _a" <> suffix <> " = " <> callExpr <> ";", - "const _end" <> suffix <> " = Date.now();", - "console.log(String(_end" <> suffix <> " - _start" <> suffix <> "));", - "console.log(toJson(_a" <> suffix <> "));" + ++ [ "const openleetcode_timer_start_" <> suffix <> " = Date.now();", + "const openleetcode_result_" <> suffix <> " = " <> callExpr <> ";", + "const openleetcode_timer_end_" <> suffix <> " = Date.now();", + "console.log(String(openleetcode_timer_end_" <> suffix <> " - openleetcode_timer_start_" <> suffix <> "));", + "console.log(toJson(openleetcode_result_" <> suffix <> "));" ] ) Dart -> T.unlines ( ["print(" <> quotedMarker <> ");"] ++ prelude - ++ [ "final start" <> suffix <> " = Stopwatch()..start();", - "final a" <> suffix <> " = " <> callExpr <> ";", - "start" <> suffix <> ".stop();", - "print(start" <> suffix <> ".elapsedMilliseconds);", - "print(toJson(a" <> suffix <> "));" + ++ [ "final openleetcode_timer_" <> suffix <> " = Stopwatch()..start();", + "final openleetcode_result_" <> suffix <> " = " <> callExpr <> ";", + "openleetcode_timer_" <> suffix <> ".stop();", + "print(openleetcode_timer_" <> suffix <> ".elapsedMilliseconds);", + "print(toJson(openleetcode_result_" <> suffix <> "));" ] ) Cpp -> T.unlines ( ["cout << " <> quotedMarker <> " << \"\\n\";"] ++ prelude - ++ [ "auto start" <> suffix <> " = chrono::steady_clock::now();", - "auto a" <> suffix <> " = " <> callExpr <> ";", - "auto end" <> suffix <> " = chrono::steady_clock::now();", - "cout << chrono::duration_cast(end" <> suffix <> " - start" <> suffix <> ").count() << \"\\n\";", - "cout << toJson(a" <> suffix <> ") << \"\\n\";" + ++ [ "auto openleetcode_timer_start_" <> suffix <> " = chrono::steady_clock::now();", + "auto openleetcode_result_" <> suffix <> " = " <> callExpr <> ";", + "auto openleetcode_timer_end_" <> suffix <> " = chrono::steady_clock::now();", + "cout << chrono::duration_cast(openleetcode_timer_end_" <> suffix <> " - openleetcode_timer_start_" <> suffix <> ").count() << \"\\n\";", + "cout << toJson(openleetcode_result_" <> suffix <> ") << \"\\n\";" ] ) CSharp -> T.unlines ( ["Console.WriteLine(" <> quotedMarker <> ");"] ++ prelude - ++ [ "var sw" <> suffix <> " = Stopwatch.StartNew();", - "var a" <> suffix <> " = " <> callExpr <> ";", - "sw" <> suffix <> ".Stop();", - "Console.WriteLine(sw" <> suffix <> ".ElapsedMilliseconds);", - "Console.WriteLine(ToJson(a" <> suffix <> "));" + ++ [ "var openleetcode_timer_" <> suffix <> " = Stopwatch.StartNew();", + "var openleetcode_result_" <> suffix <> " = " <> callExpr <> ";", + "openleetcode_timer_" <> suffix <> ".Stop();", + "Console.WriteLine(openleetcode_timer_" <> suffix <> ".ElapsedMilliseconds);", + "Console.WriteLine(ToJson(openleetcode_result_" <> suffix <> "));" ] ) Java -> T.unlines ( ["System.out.println(" <> quotedMarker <> ");"] ++ prelude - ++ [ "long cur" <> suffix <> " = System.currentTimeMillis();", - "var a" <> suffix <> " = " <> callExpr <> ";", - "long now" <> suffix <> " = System.currentTimeMillis();", - "System.out.println(now" <> suffix <> " - cur" <> suffix <> ");", - "System.out.println(Json.toJson(a" <> suffix <> "));" + ++ [ "long openleetcode_timer_start_" <> suffix <> " = System.currentTimeMillis();", + "var openleetcode_result_" <> suffix <> " = " <> callExpr <> ";", + "long openleetcode_timer_end_" <> suffix <> " = System.currentTimeMillis();", + "System.out.println(openleetcode_timer_end_" <> suffix <> " - openleetcode_timer_start_" <> suffix <> ");", + "System.out.println(Json.toJson(openleetcode_result_" <> suffix <> "));" ] ) Kotlin -> T.unlines ( ["println(" <> quotedMarker <> ")"] ++ prelude - ++ [ "val cur" <> suffix <> " = System.currentTimeMillis()", - "val a" <> suffix <> " = " <> callExpr, - "val now" <> suffix <> " = System.currentTimeMillis()", - "println(now" <> suffix <> " - cur" <> suffix <> ")", - "println(Json.toJson(a" <> suffix <> "))" + ++ [ "val openleetcode_timer_start_" <> suffix <> " = System.currentTimeMillis()", + "val openleetcode_result_" <> suffix <> " = " <> callExpr, + "val openleetcode_timer_end_" <> suffix <> " = System.currentTimeMillis()", + "println(openleetcode_timer_end_" <> suffix <> " - openleetcode_timer_start_" <> suffix <> ")", + "println(Json.toJson(openleetcode_result_" <> suffix <> "))" ] ) Rust -> T.unlines ( ["println!(\"" <> marker idx <> "\");"] ++ prelude - ++ [ "let start" <> suffix <> " = Instant::now();", - "let result" <> suffix <> " = " <> callExpr <> ";", - "let duration" <> suffix <> " = start" <> suffix <> ".elapsed();", - "println!(\"{}\", duration" <> suffix <> ".as_millis());", - "println!(\"{}\", to_json(&result" <> suffix <> "));" + ++ [ "let openleetcode_timer_start_" <> suffix <> " = Instant::now();", + "let openleetcode_result_" <> suffix <> " = " <> callExpr <> ";", + "let openleetcode_duration_" <> suffix <> " = openleetcode_timer_start_" <> suffix <> ".elapsed();", + "println!(\"{}\", openleetcode_duration_" <> suffix <> ".as_millis());", + "println!(\"{}\", to_json(&openleetcode_result_" <> suffix <> "));" ] ) Ruby -> T.unlines ( ["puts " <> quotedMarker] ++ prelude - ++ [ "start" <> suffix <> " = (Time.now.to_f * 1000).to_i", - "a" <> suffix <> " = " <> callExpr, - "finish" <> suffix <> " = (Time.now.to_f * 1000).to_i", - "puts(finish" <> suffix <> " - start" <> suffix <> ")", - "puts to_json(a" <> suffix <> ")" + ++ [ "openleetcode_timer_start_" <> suffix <> " = (Time.now.to_f * 1000).to_i", + "openleetcode_result_" <> suffix <> " = " <> callExpr, + "openleetcode_timer_end_" <> suffix <> " = (Time.now.to_f * 1000).to_i", + "puts(openleetcode_timer_end_" <> suffix <> " - openleetcode_timer_start_" <> suffix <> ")", + "puts to_json(openleetcode_result_" <> suffix <> ")" ] ) Swift -> T.unlines ( ["print(" <> quotedMarker <> ")"] ++ prelude - ++ [ "let start" <> suffix <> " = Int(Date().timeIntervalSince1970 * 1000)", - "let result" <> suffix <> " = " <> callExpr, - "let end" <> suffix <> " = Int(Date().timeIntervalSince1970 * 1000)", - "print(end" <> suffix <> " - start" <> suffix <> ")", - "print(toJson(result" <> suffix <> "))" + ++ [ "let openleetcode_timer_start_" <> suffix <> " = Int(Date().timeIntervalSince1970 * 1000)", + "let openleetcode_result_" <> suffix <> " = " <> callExpr, + "let openleetcode_timer_end_" <> suffix <> " = Int(Date().timeIntervalSince1970 * 1000)", + "print(openleetcode_timer_end_" <> suffix <> " - openleetcode_timer_start_" <> suffix <> ")", + "print(toJson(openleetcode_result_" <> suffix <> "))" ] ) Default -> error "Unsupported" @@ -466,17 +466,13 @@ buildMainSnippet lang idx prelude callExpr = T.unlines ( ["print(" <> quotedMarker <> ")"] ++ prelude - ++ [ "_start_" <> suffix <> " = int(" <> pythonTimeExpr <> " * 1000)", - "_a_" <> suffix <> " = " <> callExpr, - "_end_" <> suffix <> " = int(" <> pythonTimeExpr <> " * 1000)", - "print(_end_" <> suffix <> " - _start_" <> suffix <> ")", - "print(to_json(_a_" <> suffix <> "))" + ++ [ "openleetcode_timer_start_" <> suffix <> " = int(time.time() * 1000)", + "openleetcode_result_" <> suffix <> " = " <> callExpr, + "openleetcode_timer_end_" <> suffix <> " = int(time.time() * 1000)", + "print(openleetcode_timer_end_" <> suffix <> " - openleetcode_timer_start_" <> suffix <> ")", + "print(to_json(openleetcode_result_" <> suffix <> "))" ] ) - pythonTimeExpr = - case lang of - Python2 -> "_time.time()" - _ -> "time.time()" parseMainBatchOutput :: [PreparedCase] -> Text -> IO (M.Map Int MainCaseOutput) parseMainBatchOutput cases stdoutText = diff --git a/runtimes/python2/main.py b/runtimes/python2/main.py index 339a3ac1..018236e5 100644 --- a/runtimes/python2/main.py +++ b/runtimes/python2/main.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- import sys -import time as _time +import time import math import heapq import bisect @@ -9,7 +9,6 @@ import re import operator import string -import datetime as _dt import collections import json from functools import * diff --git a/runtimes/python3/main.py b/runtimes/python3/main.py index 2d766516..5cee806f 100644 --- a/runtimes/python3/main.py +++ b/runtimes/python3/main.py @@ -13,7 +13,6 @@ import decimal import fractions import statistics -import datetime as _dt import json from typing import * From 802aeca96cb2a7e8045064c2416d0e5ddaad7692 Mon Sep 17 00:00:00 2001 From: Andrey Litvitski Date: Mon, 17 Aug 2026 02:12:09 +0300 Subject: [PATCH 10/12] bones - vpn --- runtimes/python2/main.py | 4 ++++ runtimes/python3/main.py | 7 +++++-- runtimes/rust/main.rs | 8 ++++---- runtimes/typescript/main.ts | 3 +-- 4 files changed, 14 insertions(+), 8 deletions(-) diff --git a/runtimes/python2/main.py b/runtimes/python2/main.py index 018236e5..ccb8a1e6 100644 --- a/runtimes/python2/main.py +++ b/runtimes/python2/main.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- import sys +import array import time import math import heapq @@ -9,12 +10,15 @@ import re import operator import string +import datetime import collections import json +import sortedcontainers from functools import * from collections import * from heapq import * from bisect import * +from sortedcontainers import SortedDict, SortedList, SortedSet sys.setrecursionlimit(10**6) diff --git a/runtimes/python3/main.py b/runtimes/python3/main.py index 5cee806f..dc79a253 100644 --- a/runtimes/python3/main.py +++ b/runtimes/python3/main.py @@ -1,6 +1,7 @@ from __future__ import annotations import sys +import array import math import heapq import bisect @@ -13,12 +14,14 @@ import decimal import fractions import statistics +import datetime import json +import sortedcontainers from typing import * from collections import * -from dataclasses import asdict, is_dataclass -from functools import cache, lru_cache +from dataclasses import * +from functools import * from heapq import * from bisect import * from sortedcontainers import SortedDict, SortedList, SortedSet diff --git a/runtimes/rust/main.rs b/runtimes/rust/main.rs index 531ed4f6..de846e6f 100644 --- a/runtimes/rust/main.rs +++ b/runtimes/rust/main.rs @@ -5,12 +5,12 @@ pub struct Solution; use std::time::Instant; use std::rc::Rc; use std::cell::RefCell; -use std::cmp::{max as _max, min as _min, Ordering as _Ordering, Reverse as _Reverse}; +use std::cmp::*; use std::collections::*; use std::fs; -use itertools::Itertools as _Itertools; -use rand::prelude as _rand_prelude; -use regex::Regex as _Regex; +use itertools::*; +use rand::prelude::*; +use regex::*; ${IMPORTS} diff --git a/runtimes/typescript/main.ts b/runtimes/typescript/main.ts index 82f43d0e..8bce0c1a 100644 --- a/runtimes/typescript/main.ts +++ b/runtimes/typescript/main.ts @@ -1,6 +1,5 @@ import * as fs from "fs"; -import * as __lodash_runtime from "lodash"; -void __lodash_runtime; +import * as _ from "lodash"; type _TEST_INPUT_ = { val: any }; const _TEST_: Record> = JSON.parse( From e64a301713826248bd495b9fb60c7408d4dc63b5 Mon Sep 17 00:00:00 2001 From: Andrey Litvitski Date: Mon, 17 Aug 2026 02:50:41 +0300 Subject: [PATCH 11/12] lil fix --- runtimes/rust/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtimes/rust/main.rs b/runtimes/rust/main.rs index de846e6f..418a708c 100644 --- a/runtimes/rust/main.rs +++ b/runtimes/rust/main.rs @@ -8,7 +8,7 @@ use std::cell::RefCell; use std::cmp::*; use std::collections::*; use std::fs; -use itertools::*; +use itertools::Itertools as _; use rand::prelude::*; use regex::*; From 4c218a6c724e92737ebc812ff074a9c00e90d725 Mon Sep 17 00:00:00 2001 From: Andrey Litvitski Date: Mon, 17 Aug 2026 04:50:31 +0300 Subject: [PATCH 12/12] lil more --- runtimes/go/utilities.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/runtimes/go/utilities.go b/runtimes/go/utilities.go index ef68d27a..7c970f61 100644 --- a/runtimes/go/utilities.go +++ b/runtimes/go/utilities.go @@ -415,7 +415,16 @@ func encodeValue(v reflect.Value, seen map[uintptr]bool) string { return "null" } if v.Type().Elem().Kind() == reflect.Uint8 { - return jsonQuote(bytesHex(v.Bytes())) + var sb strings.Builder + sb.WriteByte('[') + for i, b := range v.Bytes() { + if i > 0 { + sb.WriteByte(',') + } + sb.WriteString(jsonQuote(string([]byte{b}))) + } + sb.WriteByte(']') + return sb.String() } return encodeArray(v, seen) case reflect.Array: